The O(n) constraint is where this gets interesting.
Use a sliding window of size k and maintain a counter of how many times the target appears in the current window. Slide the window one step at a time, updating the counter by removing the element leaving the window and adding the new element entering. Whenever the counter is greater than zero, record the current window's start and end indices.
Pro tip: Clarify upfront whether the window size k can be larger than the array or if k is always valid, and mention that the counter approach avoids re-scanning the window, ensuring O(n) time. Also, discuss how you would handle multiple occurrences of the target within a window—the counter naturally handles that.
Compute the count of the target in the first k elements. If the count > 0, add the window [0, k-1] to the result.
For each subsequent position i from k to n-1, remove the element at i-k from the count and add the element at i. This updates the count for the new window [i-k+1, i].
After each slide, if the count of the target in the current window is > 0, append the start index (i-k+1) and end index (i) to the result list.
If k > n or k <= 0, return an empty list. Also consider if the target is not present at all—the result will be empty.
After processing all windows, return the list of index pairs.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.