r/csinterviewproblems • u/zhay • Jan 12 '16
Given an array of n integers, find the minimum value in each subarray of size k.
Example:
Suppose you're given:
array = [5, 2, 8, 4, 6, 9, 10, 1] and k = 3Return:
result = [2, 2, 4, 4, 6, 1]Because:
2 == min(5, 2, 8)
2 == min(2, 8, 4)
4 == min(8, 4, 6)
4 == min(4, 6, 9)
6 == min(6, 9, 10)
1 == min(9, 10, 1)Return minimums in order from left to right.
Easy:
Solve in O(nk) time and O(nk) space (excluding output size in space complexity).
Solve in O(nk) time and O(1) space (excluding output size in space complexity).
Medium:
Solve in O(n lg n) time and O(n) space (excluding output size in space complexity)
Solve in O(n lg k) time and O(k) space (excluding output size in space complexity)
Hard:
Solve in O(n) time and O(n) space (excluding output size in space complexity)
Solve in O(n) time and O(k) space (excluding output size in space complexity)
3
u/naridimh Jan 12 '16
I see an O(Nlog(K)) solution:
It isn't obvious to me how to do this in linear time.
2
u/zhay Jan 13 '16
Since solutions have been posted for the easy and medium tasks, I'll post some solutions for the hard task.
If we can implement a queue that supports min(), enqueue(), and dequeue() in O(1) time, we can accomplish what we want. We enqueue the the first k array values. After that, we repeatedly call max() on the queue and enqueue() on the next value in the array until we've reached the end of the array.
So how do we implement a queue that supports min() quickly? Well, let's start with the easier problem: stack with min(). A stack must support push() and pop(). Let's pretend our stack doesn't have pop(). Well, if we need push() and min(), then min() simply returns the min of all values seen. To implement that, we just have a variable that stores the running minimum. Any time we push a value, we update the minimum if the value we're pushing is smaller than the existing minimum. What happens if we introduce pop()? Well, we don't have a way of discounting the value that was removed from the stack. If we remove the top value of the stack, we can check to see if it is equal to the minimum. If it is equal to the minimum, then we may need to update the minimum (because it could be the only value in the stack equal to the minimum). If it is bigger than the minimum, then we can remove it without updating the minimum. So let's consider the case where it's equal to the minimum. How do we determine if it is the only value equal to the minimum, and how do we determine what the minimum is if that was the last value equal to the minimum? That's simple... we just need the value of the minimum before that value was added. If we know what the minimum was before the value was added, then we know what the minimum is after that value is removed. This tells us that we can just maintain a separate stack of running minimums. When we push a value, if it is less than the previous minimum (defined by the top value of the minimum stack), then we push a new minimum to the minimum stack. Otherwise, we push the previous minimum to the minimum stack. When we pop a value, we remove the top element from the value stack and the minimum stack. To get the minimum, we return the top value in the minimum stack.
OK, so let's try to take that thought process and apply it to a queue with min(). Let's start with a queue that need only support enqueue() and min(). This is the same as a stack with push() and min(). We simply maintain a running minimum. It gets tricky when we try to dequeue() an element. With the stack, we had an auxiliary stack of minimums, and we could revert back to a previous minimum as needed. With queues, we will have an auxiliary queue of minimums. First, let's think about what can happen to the minimum when we enqueue() a value. If the value to enqueue is smaller than the existing minimum, then the minimum will be updated. If the value is bigger than the existing minimum, then the minimum won't be updated. Now, let's think about what happens when we dequeue() a value. With stacks, popping reverted the minimum to a previous minimum. The same is not true of queues. Dequeueing a value does not remove the last value that contributed to the minimum. Instead, dequeueing removes the first value that contributed to the minimum. We need to update the minimum to the minimum of the values that were enqueued after the element that was just dequeued. The best way to gain insight for what to do next is to go through an example:
Suppose we have the following operations:
enqueue(4)
enqueue(2)
enqueue(3)
enqueue(10)
print min()
dequeue()
print min()
dequeue()
print min()
dequeue()
print min()
The values that will be printed are: 2, 2, 3, 10
Let's visualize our queue before dequeuing: [4, 2, 3, 10]
How do we maintain the smallest value to the right of or at the current value? (the is what our auxiliary queue must have)
Well, unfortunately, the smallest value to the right of or at index i can change as new values are enqueued. If the next value that is enqueued is smaller than all of the values in the queue, we will have to update the smallest value to the right of or at i for all i. That doesn't sound like constant time. However, let's go with it anyway.
On enqueue(), we will add the value to enqueue to the end of the auxiliary queue because no values are smaller than it to the right. However, before we can add it, we need to update the values to the left if the new value is smaller than any of them. Whatever values it is smaller than need to be updated to the value that we are enqueueing.
[4, 2, 3, 10]'s auxiliary queue would then be: [2, 2, 3, 10].
Or, with another example:
[1, 5, 4, 3, 2]'s auxiliary queue would be: [1, 2, 2, 2, 2].
Unfortunately, this has a problem: each time we enqueue a value, we have to potentially update each value in the queue. This is too slow!
But let's make an observation: if we update 4 values, we update them all to the same thing: the newly enqueued value. Why can't we just compress those 4 values into a single value? e.g., instead of [2, 1, 1, 1, 1], let's just change it to: [2, 1]. In other words, before adding a value to the end of the auxiliary queue, remove all values from the auxiliary queue that are less than that value. When we add this restriction, that means our queue will store monotonically increasing values. Therefore, the process of removing values less than a given values involves looking from end of the queue (right side) towards the front (left side). As soon as we see a value that is smaller than the value we are going to enqueue, we stop.
Let's think about the run-time here. An enqueue can still take O(n) time. But how many times can it take O(n) time? Well, each value is enqueued and dequeued at most 1 time. Therefore, the amortized cost to enqueue and dequeue an element over O(n) enqueues and dequeues is O(1).
Getting the minimum requires simply returning the front value of the auxiliary queue. On dequeue, we remove the front value of the auxiliary queue if it's equal to the front value of the normal queue.
Let me know if that doesn't make sense :)
2) Use preprocessing
We need a way of finding the minimum over any k-sized subarray in constant time. Let's suppose we can do O(n) preprocessing.
It's trivial to find the minimum for k-sized subarrays whose starting index = 0 mod k... we just find the minimum for the first k values, then find the minimum for the next k values, then find the minimum for the next k values, etc. In other words, we divide the array into k-sized blocks that are disjoint and compute the minimum for each block. What can we do if the subarray we want the minimum for spans two blocks?
For example, suppose we have [4, 5, 6, 9, 7, 6] and k = 3.
Then we can partition it into k-sized blocks: [4, 5, 6][9, 7, 6].
Now let's suppose we want the minimum of [5, 6, 9] (a block that spans two blocks).
The minimum of [5, 6, 9] is the minimum of [5, 6] and [9]. Notice that [5, 6] touches the right side of its block, and [9] touches the left side of its block. Let's focus on the [4, 5, 6] block. We need the minimum of the right 2 values. In general, we need a way of finding the minimum of the right x values of an array. Similarly, for the [9, 7, 6] block, we need the minimum of the left 1 value. In general, we need a way of finding the minimum of the left y values of an array. If we solve one of these general problems, it is trivial to solve the other (just do everything in reverse).
Let's just focus on the latter: finding the minimum value of the left y values in an array (for any y value).
Let's suppose we preprocess the array by maintaining the running minimum from left to right. For example, the running minimums for [7, 3, 9, 4, 2, 1] are [7, 3, 3, 3, 2, 1]. If we want the minimum of the left y values, we just look up the value at index y-1 among the running minimums. For example, the minimum of the left 3 values is the value at index 2, which is 3. This checks out since the minimum of [7, 3, 9] is 3.
OK, so let's turn this into an algorithm:
Break the input array into blocks of size k. Then, preprocess each block by recording the running minimum in that block from left to right, and the running minimum in that block from right to left.
E.g., for [2, 3, 6, 5, 7, 1] with k = 3, you'd have:
left_to_right = [2, 2, 2, 5, 5, 1]
right_to_left = [2, 3, 6, 1, 1, 1]
or if you prefer to visualize them as blocks:
left_to_right = [2, 2, 2][5, 5, 1]
right_to_left = [2, 3, 6][1, 1, 1]
To find the minimum of a window, (left, right), you'd use min(left_to_right[right], right_to_left[left]).
e.g., if window = (1, 3) == [3, 6, 5], then you'd take min(left_to_right(3), right_to_left(1)) == min(5, 3) == 3.
For this specific problem, we could reduce the memory requirement to O(k) by holding only two k-sized blocks in memory at one time.
3) Use a range minimum query
There's a complicated way to find the minimum value in any subrange of an array in O(1) time after O(n) preprocessing. It's not trivial and not something you'd ever do in an interview. That being said, it does exist as a potential solution.
2
u/Herathe Jan 12 '16
Would anyone be able to explain to me in simple terms what time and space my ruby solution would be?
1
u/lavahot Jan 12 '16
Seems to me like there's a solution in O (n) time and O (1) space.
1
u/readoptional Jan 12 '16
C# - assumes arr.length > k
Feedback welcome
2
u/[deleted] Jan 12 '16
C#, only bothered with the quick/easy solution (for right now hopefully):
0
u/[deleted] Jan 12 '16
[deleted] — view deleted comment