The time complexity of the solution for the Sliding Window Maximum problem that uses a deque is O(n), where n is the number of elements in the input array.
Here's why the time complexity is O(n):
-
Initialization: Initializing the deque and processing the first k elements of the array takes O(k) time, which is typically considered a constant factor since k is often much smaller than n.
-
Sliding Window Across Array: As we slide the window across the array from left to right, we iterate through each element of the array exactly once. At each step, we perform the following constant-time operations on the deque:
- Removing indices from the front of the deque.
- Removing indices from the back of the deque.
- Adding the current index to the back of the deque.
Each element of the array is processed once by these operations. Since there are n elements in the array, the total time complexity for sliding the window across the array is O(n).
-
Returning Maximums: After processing the entire array, we return the list of maximum elements for each sliding window. This operation involves retrieving the elements corresponding to the indices at the front of the deque, which takes constant time for each element. Therefore, the time complexity of returning the maximums is also O(n).
Since the overall time complexity of each step is O(n), the total time complexity of the solution is dominated by the sliding window across the array, resulting in a time complexity of O(n). This makes the solution efficient for large arrays and practical for real-world applications where the input size can be significant.