From 7fcf1b1c90b516bd8c4bdb05e0927ab7fd9cd39b Mon Sep 17 00:00:00 2001 From: Liam Tomson-Moylan Date: Wed, 25 Feb 2026 02:31:52 -0600 Subject: [PATCH] Update simplify-path.md First Python Solution to be O(n) in the Worst 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. --- articles/simplify-path.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/articles/simplify-path.md b/articles/simplify-path.md index 75f4e016f..f57c573cb 100644 --- a/articles/simplify-path.md +++ b/articles/simplify-path.md @@ -30,18 +30,19 @@ A Unix-style path can contain special directory references: `.` means the curren class Solution: def simplifyPath(self, path: str) -> str: stack = [] - cur = "" + cur = [] for c in path + "/": if c == "/": + cur = "".join(cur) if cur == "..": if stack: stack.pop() elif cur != "" and cur != ".": stack.append(cur) - cur = "" + cur = [] else: - cur += c + cur.append(c) return "/" + "/".join(stack) ```