-1

I know that the time complexity of the sliding window algorithm is o(N) but what is the time complexity of a variable-sized sliding window algorithm.

For eg-

array = [1,2,3,4,5,6]

when size of sliding window is = 1 window - [1], [2], [3], [4], [5], [6]

when size of sliding window is = 2 window - [1,2], [2,3], [3,4], [4,5], [5,6]

when size of sliding window is = 3 window - [1,2,3], [2,3,4], [3,4,5], [4,5,6]

and so on ...

window size will range from 1 to n (valid values for window size). If creating a single-window costs O(N) then creating N windows will cost O(N^2)?

  • 1
    Is the variable for the window size also a parameter? Looks like O(n) regardless. The question is: how many times do you visit `array[i]` for any `i`? The answer is 2 in all window sizes, once when pushed onto the head of the window, one when dequeued from the tail. – ggorlen Apr 05 '21 at 18:51
  • 3
    The algorithm that uses the sliding window will be O(n) regardless of the size of the sliding window. – user3386109 Apr 05 '21 at 18:53
  • window size will range from 1 to n (valid values for a window). If creating a single-window costs O(N) then creating N windows will cost O(N^2)? – Manasvin Sharma Apr 05 '21 at 18:56
  • If you want to make a window of size `n` then you get a single sliding window. Why would it be `O(n^2)`? – VLAZ Apr 05 '21 at 19:01
  • @VLAZ No, the size of the window varies from 1 to n (both inclusive). – Manasvin Sharma Apr 05 '21 at 19:02
  • 1
    Yes, but for an array of size `n`, a sliding window of size `n` is...one window. That contains the entire array. – VLAZ Apr 05 '21 at 19:03
  • Which "the" sliding window algorithm are you referring to ? A sliding median filter (for instance) does not have O(N) complexity. –  Apr 05 '21 at 19:56

1 Answers1

1

Running a sliding window across an array is O(n) regardless of the size of the window.

The head pointer and tail pointers increase monotonically for all window sizes. In contrast, a typical nested loop quadratic algorithm runs the inner index j from i to n for every outer index i.

The assumption here is that you're not doing any extra work besides the deque offers and polls (which are constant time for each i) such as looping over the window for every i.

If you're creating n windows from 1 to n, you're back to the classical nested-loop quadratic algorithm, O(n^2).

ggorlen
  • 44,755
  • 7
  • 76
  • 106