Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That would still require O(n) space (to store the list of elements to keep or remove) so why not simply use the regular `reject` ?


No, before sliding elements, you set a local variable "dirty" to true. You iterate over all elements and keep the ones that are not rejected by moving them at the end of the current max index. When you code finishes normally, dirty is set to false.

You have an "ensure" block (finally) protecting the code which handles the cases where dirty is true (moving all the remaining elements after the current max). Then you truncate the array.


Because you're saving the O(N) time copy...

iirc, Ruby's array doesn't expose the distinction between length and capacity, but internally it may decide to amortize the cost of such copies. For example, if reject only removes a small % of elements, it may choose not to shrink capacity.


You're not saving the O(N) time copy, just replacing it with an O(N) slide.

(That's assuming you copy at all, instead of simply updating the reference.)


I meant O(N) space, as you said "That would still require O(n) space" - but a slide does not require additional space.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: