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] <= 104
  • 1 <= 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:

  1. Initializing variables j, i, and max takes constant time, O(1).

  2. The while loop runs nums.length - k + 1 times. This is because the loop starts from index i = 0 and goes up to index i = nums.length - k, since you’re considering subarrays of length k. So, the loop runs approximately nums.length - k times.

  3. Inside the loop, you’re using the slice method, which takes O(k) time, and then you’re using the sort method, which takes O(k * log(k)) time (since you’re sorting a subarray of length k).

  4. Pushing an element into the max array 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.