5

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?

2

1 Answer 1

9

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.