Michael
Michael

Reputation: 42100

Sliding window minimum algorithm

This is a homework problem. Let A[] is an array of integers and integer K -- window size. Generate array M of minimums seen in a window as it slides over A. I found an article with a solution for this problem but did not understand why it has O(n) complexity. Can anybody explain it to me?

Upvotes: 5

Views: 5370

Answers (1)

JPvdMerwe
JPvdMerwe

Reputation: 3363

This tends to catch people out. You would think it would take O(N^2) time since you reason adding takes O(N) time and you have O(N) elements. However, realise each element can only be added once and removed once. So in total it takes O(N) to slide over the whole array A.

This yields an amortised efficiency of O(1) every time you move the sliding window on by one element. In other words, the average time it takes to move the sliding window by one element is O(1).

Upvotes: 9

Related Questions