Skip to content

Update simplify-path.md First Python Solution to be O(n) in the Worst…#5523

Open
AnonymousAnion wants to merge 1 commit intoneetcode-gh:mainfrom
AnonymousAnion:patch-1
Open

Update simplify-path.md First Python Solution to be O(n) in the Worst…#5523
AnonymousAnion wants to merge 1 commit intoneetcode-gh:mainfrom
AnonymousAnion:patch-1

Conversation

@AnonymousAnion
Copy link

… Case

The first proposed Python solution is O(n^2) due to the use of naive string concatenation e.g. cur += c. Don't forget that strings are immutable so naive concatenation is an O(n) operation and since this is within a for loop that is O(n) the overall solution becomes O(n^2). This would occur in the worst case of a very long named single directory. Therefore, the second solution should be strongly preferred!

I've added a simple fix to make the first Python solution O(n) by ensuring the string uses the pythonic way of string building by appending to a list then joining. This makes the python solution consistent with the C++, Java, etc. implementations.

Important

Please make sure the file name is lowercase and a duplicate file does not already exist before merging.

… Case

The first proposed Python solution is O(n^2) due to the use of naive string concatenation e.g. cur += c. Don't forget that strings are immutable so naive concatenation is an O(n) operation and since this is within a for loop that is O(n) the overall solution becomes O(n^2). This would occur in the worst case of a very long named single directory. Therefore, the second solution should be strongly preferred!

I've added a simple fix to make the first Python solution O(n) by ensuring the string uses the pythonic way of string building by appending to a list then joining.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant