Problem Description
Given an integer array and a value, remove all occurrences of that value in-place so that the first k elements of the array are the remaining elements that are not equal to the given value. Return k, the count of these elements. The order of the elements can be changed and it does not matter what you leave beyond the first k elements.
Key Insights
- Use a two-pointer approach: one pointer iterates through the array while the other keeps track of the position for the next valid element.
- Modify the array in-place, which ensures constant extra space usage.
- The order of elements is not preserved, which allows swapping elements or simply overwriting the unwanted ones.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
The idea is to maintain a write pointer that indicates where the next valid element (not equal to val) should be placed. Iterate through the array with a read pointer. For every element that is not equal to val, write it to the position indicated by the write pointer and increment the write pointer. Once the loop completes, the write pointer will represent the number of valid elements (k) and the array's first k elements will be the desired result.