Data Structures & AlgorithmsHard
A window with at most K replacements (or at most K zeros) is found with two pointers. Why is it safe for the left pointer to only move forward?
- A. Left pointers must alternate direction to find the best answer.
- B. Extending the window to the right can only make the count of violations larger or equal, so an invalid left end never becomes valid again.
- C. The right pointer always moves at double the speed of the left.
- D. Each window is independent, so the left pointer may reset to zero.
Correct answer: B. Extending the window to the right can only make the count of violations larger or equal, so an invalid left end never becomes valid again.
Violations are monotone in the window's right end, so once a left end is too far left it stays too far left. The left pointer therefore sweeps forward once and the whole process is linear.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- In 'product of array except self', why does a single zero need special handling?
- Why does counting subarrays with sum exactly k, when elements can be NEGATIVE, use a hash map of prefix sums and not a sliding window?
- When counting pairs with a given sum in a sorted array using two pointers, why is sorting essential?
- The 3-sum two-pointer method skips a value when it equals the previous value. Why?
- What is the lexicographically smallest array of length n with positive integers and total sum S (S ≥ n)?
- In the 'minimum swaps to sort a permutation' problem, why is the answer n minus the number of cycles?