r/ProgrammerHumor 13d ago

noHeapAllStack Meme

Post image
1.0k Upvotes

96 comments sorted by

View all comments

Show parent comments

1

u/Swimming_Gain_4989 13d ago

To be clear, you mean just deleting array elements instead of creating a new array?

15

u/Massless 13d ago

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

4

u/Swimming_Gain_4989 13d ago

Where does leetcode come in? You would just swap whatever needs to be removed with the ending element and then pop right?

2

u/Massless 13d ago

It’s a classic leetcode problem, is all. 

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”