You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
**Input:** nums = [1,3,-1,-3,5,3,6,7], k = 3
**Output:** [3,3,5,5,6,7]
**Explanation:**
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 **3**
1 [3 -1 -3] 5 3 6 7 **3**
1 3 [-1 -3 5] 3 6 7 ** 5**
1 3 -1 [-3 5 3] 6 7 **5**
1 3 -1 -3 [5 3 6] 7 **6**
1 3 -1 -3 5 [3 6 7] **7**
Example 2:
**Input:** nums = [1], k = 1
**Output:** [1]
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 1041 <= k <= nums.length
Naive Approach
- Set: i=0, j=k
- Slice the array into i -> k
- sort in descending
- push[0] into the max array
- i++; j++
let nums = [1,3,-1,-3,5,3,6,7]
function window(nums, k){
let j = k
let i = 0
let max = []
while (j <= nums.length){
let section = nums.slice(i, j)
section.sort((a,b)=>{return b-a})
max.push(section[0])
i++
j++
}
return max
}
console.log(window(nums, 3))This shit is hella slow for larger arrays, So organizing for larger arrays is not really possilbe
Time Complexity
The time complexity of the given function can be analyzed step by step:
-
Initializing variables
j,i, andmaxtakes constant time, O(1). -
The while loop runs
nums.length - k + 1times. This is because the loop starts from indexi = 0and goes up to indexi = nums.length - k, since youâre considering subarrays of lengthk. So, the loop runs approximatelynums.length - ktimes. -
Inside the loop, youâre using the
slicemethod, which takes O(k) time, and then youâre using thesortmethod, which takes O(k * log(k)) time (since youâre sorting a subarray of lengthk). -
Pushing an element into the
maxarray is a constant time operation.
Overall, the time complexity of each iteration of the loop is O(k * log(k)) due to the sorting step.
Since the loop runs approximately nums.length - k times, and each iteration has a time complexity of O(k * log(k)), the total time complexity of the function can be approximated as follows:
Total time complexity â (nums.length - k) * (O(k * log(k)))
Asymptotically, when k is smaller than nums.length, the O(k * log(k)) term dominates, so you can simplify the expression to:
Total time complexity â O((nums.length - k) * k * log(k))
This can be further simplified to: Total time complexity â O(nums.length * k * log(k))
So, the time complexity of the provided function is approximately O(nums.length * k * log(k)) in the worst case.