Given an array of N elements, A[0 .. N - 1], Produce an array B such that:
B[i] = min (A[i], A[i+1], ..., A[i+K-1]).
(The array B will have exactly (N-k+1) elements.
Time complexity should be better than O(N*k)
I was thinking of using minheap… but heapify will increase the complexity
Also brute force is O(n*k)
Also space complexity s’d be less than equal to O(k)
Here’s an example
Input:
A={ 2,1,3,2,5,7,1}, N=7,k=3
Output:
B={1,1,2,2,1}
To solve the problem, you can use queue in which push_rear(), pop_front() and get_min() are all constant time operations.
Push first
kelements from the arrayAto this queue. Then continue filling the queue from the arrayA, while popping elements from it and appending minimum values to the arrayB.Time complexity is
O(N). Space complexity isO(k).