Python 0071.py
class Solution:
def simplifyPath(self, path: str) -> str:
parts = path.split("/")
again = True
while again:
again = False
for i in range(len(parts)):
if parts[i] == "" or parts[i] == ".":
del parts[i]
again = True
break
if parts[i] == "..":
del parts[i]
if i > 0:
del parts[i-1]
again = True
break
return "/" + "/".join(parts)
Difficulty
and has an acceptance rate of about 51% (2+ million submissions).
Typical patterns to solve this problem:
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method simplifyPath. The method receives a Unix-style file system path as a string and returns its canonical form. The algorithm works by tokenising the input, iteratively removing redundant or special components, and finally rebuilding the cleaned path.
Detailed Walkthrough
Tokenising the Input
The first operation splits the raw path on the slash character, producing a list that may contain empty strings, single dots, double dots, and ordinary directory names.
parts = path.split("/")
At this stage, a path such as "/a//b/./c/../" becomes ['', 'a', '', 'b', '.', 'c', '..', '']. The list preserves the order of components while exposing the elements that need to be examined.
Iterative Cleanup Loop
A while loop drives the cleanup process. The loop continues as long as a modification occurs during a pass, indicated by the again flag.
again = True
while again:
again = False
for i in range(len(parts)):
# removal logic follows
The loop structure ensures that after each deletion the algorithm restarts scanning from the beginning, guaranteeing that newly adjacent elements are re-evaluated.
Removing Empty and Current-Directory Tokens
Inside the loop, the first conditional checks for empty strings ("") and single dots ("."). Both represent no-op components in a Unix path. When such a token is found, it is removed from the list, the again flag is set, and the loop breaks to restart the scan.
if parts[i] == "" or parts[i] == ".":
del parts[i]
again = True
break
This step handles cases where the input contains multiple consecutive slashes or explicit references to the current directory.
Handling Parent-Directory Tokens
The second conditional deals with double dots (".."). When encountered, the algorithm deletes the ".." token itself. If there is a preceding component (i.e., i > 0), that preceding component is also removed, effectively moving one level up in the directory hierarchy. After performing the deletions, the again flag is set and the loop breaks.
if parts[i] == "..":
del parts[i]
if i > 0:
del parts[i-1]
again = True
break
This logic correctly processes attempts to navigate to a parent directory, including edge cases where ".." appears at the beginning of the path (no preceding component to remove) or follows a series of deletions that may shift indices.
Reconstructing the Canonical Path
When the cleanup loop finishes-meaning no further deletions are possible-the remaining tokens represent the simplified directory hierarchy. The method joins these tokens with slashes and prefixes a leading slash to produce the final canonical path.
return "/" + "/".join(parts)
If all tokens have been removed, the join operation yields an empty string, and the method returns "/", representing the root directory.
Edge Cases Addressed
The algorithm gracefully handles several special situations:
- Paths that start or end with one or more slashes, which generate leading or trailing empty strings after splitting.
- Multiple consecutive slashes, which also produce empty strings that are eliminated.
- Explicit references to the current directory (
"."), which are ignored. - Parent-directory references (
"..") at the root level, where no preceding component exists; the code simply discards the".."without attempting to remove a non-existent parent. - Paths that consist solely of special tokens, resulting in an empty
partslist and a final output of"/".
Performance Optimizations Observed
The implementation performs in-place modifications of the parts list using the del statement. By mutating the original list rather than constructing new intermediate structures, the algorithm reduces auxiliary memory usage.
The early-exit break inside the for loop prevents unnecessary iteration over the remainder of the list once a modification is made. Coupled with the again flag, this approach limits the amount of work performed per pass, as the loop restarts only when a change has occurred.
Overall, the design balances simplicity with a modest amount of work reduction by avoiding full rescans after each deletion and by operating directly on the token list.
ELI5 - Simplified Explanation
Think of this code like a tiny robot that is tidying up a messy pile of address blocks. Imagine those blocks are written on paper slips separated by slashes. The robot looks through the stack one by one to make sure every direction makes sense.
When the robot finds a slip that is empty or just a single dot, it knows that means to stay right where it is, so it tosses that slip away. If the robot finds two dots in a row,, that is a special instruction to go back one step. When that happens, the robot removes the instruction for two dots and also deletes the step that came right before it, as if it is undoing a move.
The robot keeps checking the whole stack over and over again from the beginning. It continues doing this until it finds that nothing else needs to be deleted or changed. Once the stack is perfectly clean, the robot puts all the remaining slips back together with slashes in between to show the final path.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| Krazune | Java | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| Krazune | Java | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 309: Best Time to Buy and Sell Stock with Cooldown
- problem 516: Longest Palindromic Subsequence
- problem 673: Number of Longest Increasing Subsequence
- problem 712: Minimum ASCII Delete Sum for Two Strings
- problem 714: Best Time to Buy and Sell Stock with Transaction Fee
- problem 740: Delete and Earn
- problem 931: Minimum Falling Path Sum
- problem 2483: Minimum Penalty for a Shop
- problem 188: Best Time to Buy and Sell Stock IV
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality