A Sliding Window Problem

View as PDF

Submit solution

Points: 7
Time limit: 1.0s
Memory limit: 256M

Author:
Problem type

You are given an array of N positive integers. Define a "window" to be a subarray of a fixed size of exactly K elements.

Initially, the window starts off at the leftmost position. Then, it slides right by one index, such that exactly one new element is included in the window and the leftmost element of the window is no longer included within the window. This continues until the window can no longer slide right. For each of these windows, your task is to output the minimum element within the window.

More specifically, you are to output the minimum element across all subarrays of size K, from the leftmost subarray to the rightmost.

Input Specification

The first line will consist of two spaced single integer N and K (1 \le K \le N \le 10^5).

The next line consists of N spaced integers, where the i-th integer is a_i (1 \le a_i \le 10^6).

Output Specification

For each of the windows of size K, output its minimum element on its own line.

Sample Input 1

5 3
1 3 2 5 4

Output for Sample Input 1

1
2
2

Explanation of Output for Sample Input 1

The array given is [1, 3, 2, 5, 4]. The windows slides across as follows:

[1 \; 3 \; 2] \; 5 \; 4 \rightarrow minimum of [1, 3, 2] is 1

1 \; [3 \; 2 \; 5] \; 4 \rightarrow minimum of [3, 2, 5] is 2

1 \; 3 \; [2 \; 5 \; 4] \rightarrow minimum of [2, 5, 4] is 2

Sample Input 2

6 2
2 3 1 4 5 3

Output for Sample Input 2

2
1
1
4
3

Explanation of Output for Sample Input 2

The window slides as follows:

[2 \; 3]\; 1 \; 4 \; 5 \; 3

2 \; [3\; 1] \; 4 \; 5 \; 3

2 \; 3\; [1 \; 4] \; 5 \; 3

2 \; 3\; 1 \; [4 \; 5] \; 3

2 \; 3\; 1 \; 4 \; [5 \; 3]


Comments

There are no comments at the moment.