Search code examples
pythonfunctioninputargumentspep8

Is it bad practice to modify function input arguments?


I've been solving problems on Leetcode.

I noticed that it's often easy to reduce the space complexity from O(n) to O(1) by solving the problem "in place" --- that is, by updating the input list instead of returning a new list.

However, I suspect that modifying the input may be a bad practice.

I found an example of someone saying as much (see comment at bottom): https://leetcode.com/problems/circular-array-loop/discuss/94183/simple-on-solution-with-o1-space-complexity

So, is it truly the case that modifying arguments is a bad practice? Why is that the case?

Thank you.


Solution

    • If you're prepping for interviews, please don't do this
    • If you're learning algorithms/data structures/CS, please don't do this
    • If you're into competitive programming, please do this :)

    Some people treat O(1) space as "extra space", whereas other people treat it as the memory you end up using irrespective of allocations. I think the former is an example of overfitting yourself to a metric, because in practice, you are still using O(n) memory; it's just not yours, and it's now a lot harder to debug (especially if you're clobbering & reference arguments). Allocating a copy of the space you "steal" puts your places the space complexity of your algorithm O(2 * n) which is still O(n).

    This same debate comes up whenever people ask about whether call stack counts for space complexity for solutions involving recursion. It's still memory even if you didn't explicitly allocate it: you can still TLE/MLE if you use too much of it.


    Regarding my facetious quip at the beginning of the answer: no interviewer will praise the added complexity of modifying a function's arguments, especially considering hidden state is what causes production codebases to rot. Furthermore, a lot of folks who get into algorithms tend to worry too much about the difference between a 100ms vs a 50ms solution, despite the server having so much variance that some days an equivalent solution may register 300ms, and premature optimizations take away from the art of code kata (I've been there myself).

    However, with most things in life, we wrap around at the very high end and once you start playing with strict OJs like DMOJ, CodeForces, etc., people start doing ridiculous stuff where the time limits are razor-thin and every little bit of optimization could actually potentially win you a contest.