Two pointers is the move here and I did get there, but I fumbled around for a bit first thinking about a second array before remembering the space constraint.
Use a two-pointer technique: one pointer (write) tracks the position to place the next valid element, and the other (read) scans through the array. For each element, if it's not the target, write it at the write index and increment write. Finally, return write as the count of remaining elements.
Pro tip: Clarify that the order of the remaining elements doesn't matter, so you can optimize by swapping with the last element when you encounter the target, reducing the number of writes. However, the two-pointer approach is simpler and still O(n).
Restate the problem: remove all instances of a given value in-place, return the new length, and ensure the first k elements contain the valid values. Emphasize O(n) time and O(1) space.
Explain that you'll use two pointers: one for reading through the array and one for writing the next valid element. This avoids extra space and processes each element once.
Initialize write pointer to 0. Iterate read pointer from 0 to n-1. If nums[read] != target, set nums[write] = nums[read] and increment write. After the loop, return write.
State that time complexity is O(n) because each element is visited once, and space is O(1) since only two pointers are used. Mention edge cases: empty array, all elements equal to target, no elements equal to target.
Walk through a small example, such as nums = [3,2,2,3], target = 3, showing how the array transforms and the return value is 2.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.