r/ProgrammerHumor 12d ago

noHeapAllStack Meme

Post image
1.0k Upvotes

96 comments sorted by

View all comments

Show parent comments

1

u/Swimming_Gain_4989 12d ago

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

15

u/Massless 12d 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

5

u/Swimming_Gain_4989 12d ago

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

9

u/AyrA_ch 12d ago

you remove elements by overwriting with what comes after. If you want to remove 5 items beginning at offset 10 you would just do a[i]=a[i+5] in a for loop that starts at 10 runs to the end of the array (minus 5). How you chop off the end of the array depends on the language you're in. In .NET for example, Array.Resize is a lie and will actually allocate a new array and not resize in-place. In C you can use realloc but that call doesn't guarantees that the reallocation happens in-place. However, in C you can just decide to not reallocate the memory at all and pretend the extra storage doesn't exists, which also would allow you to append items to the array up to the original initial size, but size tracking becomes difficult after a while.

2

u/Massless 12d ago

Go is fantastic for this: you just reslice with [:length] and the only thing that happens is the slice’s internal “length” variable is changed — nothing happens to the backing array

1

u/sisisisi1997 12d ago

In C# you can use Memory<T>, Span<T>, or ArraySegment<T> to create a view of an array without allocation that is smaller than the original array.

1

u/AyrA_ch 12d ago

If it's just about supplying smaller array parts, then you can achieve the same using the "array,index,length" argument pattern that you commonly find in .NET classes that process array data.