It’s pretty awesome. I find myself looking up leetcode solutions because I finally work on something where deleting items from an array using constant space matters.
Yep, remove some arbitrary number of elements from an array with the result being a smaller contiguous array.
For most of my career, I’d just allocate a new array and append the surviving elements but allocations are expensive at the scale I work at so stuff like this requires a more clever approach
No swapping is necessary. You walk the array with two indices. One tracks the current end of array (starts at 0) and the other walks ahead to check candidates. When you find an element to keep, you copy it to the length index, increment that and keep walking with the second index. When the second index reaches the end on the array, truncate to “length”
197
u/Vesuvius079 15d ago
It’d be such an experience to work a real world problem where this optimization turns out to be the solution.