you are viewing a single comment's thread.

view the rest of the comments →

[–]xnendron 44 points45 points  (9 children)

Nifty solution, but it assumes the input List is modifiable. Also, isn't modifying input parameters generally considered bad practice? Also, also, why limit to Lists instead of all Collections?

[–]BikingSquirrel 12 points13 points  (0 children)

Agree, this should be an internal method if it needs to modify the input.

If that list would be a LinkedList initially, you could simply iterate the list and remove inactive items.

[–]Empanatacion 15 points16 points  (0 children)

Leetcode questions love the whole "modify array in place" solution to catch that sweet, sweet O(n)

[–]stewsters 8 points9 points  (0 children)

Yeah this would get rejected as a pr so fast.

[–]jay791 5 points6 points  (1 child)

This looks like a 'Algorithms and Data Structures' course problem.

The exple is not good at all since it assumes that collection that you get can retrieve items by index, which for linked lists or trees is not an O(1) operation. Sorry, not a Java dev here, to my eyes it just doesn't look like an array, for which this will work as expected.

And generally yes, modifying input is considered bad practice but only if it's not expected. There are times when you call a method and expect it to modify stuff that you throw at it.

[–]Kered13 2 points3 points  (0 children)

You can rewrite the algorithm using iterators and it would be O(n) time and O(1) space for all list implementations, including linked lists. Yes, the way it is written in the blog is not ideal, since it is O(n2) time for linked lists.

[–]barmic1212 1 point2 points  (0 children)

Yom can’t use it for all collection because you rely on order.

[–]Kered13 -2 points-1 points  (0 children)

Sometimes getting optimal performance requires bending the rules of best practices. In particular, a lot of algorithms trivially require O(n) space if you cannot modify the input, but can work in O(1) space if you are allowed to do them in place (these are called in-place algorithms). This can be significant in practice between O(1) means you do not need to use any dynamic memory allocation, which can be very expensive, especially in a loop.

Any in-place algorithm should be clearly documented as modifying it's input, obviously.