Problem 71

Abstract / Summary

Given a file path with slashes and special symbols simplify it into its shortest form without resolving actual file system operations

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
21 lines | 607 bytes | submitted August 29, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (2+ million submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 parts list 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4.5 | μ = 4.77 | σ = 1.50

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
54 links | 38 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Simplify Path - Stack - Leetcode 71 - Python'
NeetCode 13 mins
Simplify Path - Stack - Leetcode 71 - Python
YouTube video 'Simplify Path | Leetcode - 71 | META | Explanation ➕ Live Coding'
codestorywithMIK 20 mins
Simplify Path | Leetcode - 71 | META | Explanation ➕ Live Coding
YouTube video 'Simplify Path | Leetcode 71 | Stack | Day-14'
Ayushi Sharma 18 mins
Simplify Path | Leetcode 71 | Stack | Day-14
YouTube video 'Simplify Path | simplify path | LeetCode 71 | Stack String | Facebook'
Naresh Gupta 13 mins
Simplify Path | simplify path | LeetCode 71 | Stack String | Facebook
YouTube video 'Simplify Path || Stack || C++/Java/Python || Leetcode - 71'
Aryan Mittal 13 mins
Simplify Path || Stack || C++/Java/Python || Leetcode - 71
YouTube video 'LeetCode 71: Simplify Path Solution in Hindi'
Engineering Digest 9 mins
LeetCode 71: Simplify Path Solution in Hindi
YouTube video 'SIMPLIFY PATH | PYTHON | LEETCODE # 71'
Cracking FAANG 11 mins
SIMPLIFY PATH | PYTHON | LEETCODE # 71
YouTube video 'LeetCode 71 | Simplify Path | Solution Explained (Java + Whiteboard)'
Xavier Elon 7 mins
LeetCode 71 | Simplify Path | Solution Explained (Java + Whiteboard)
YouTube video 'Simplify Path | Leetcode 71'
Coding Decoded 11 mins
Simplify Path | Leetcode 71
YouTube video 'Simplify Path - LeetCode 71 - Python #leetcode'
Deepti Talesra 11 mins
Simplify Path - LeetCode 71 - Python #leetcode
YouTube video '71 || Simplify Path || C++ || Leetcode Daily Challenge'
CodeFreaks 18 mins
71 || Simplify Path || C++ || Leetcode Daily Challenge
YouTube video 'Simplify Path | Leet code 71 | Theory + Python + Java'
Sai Anish Malla 26 mins
Simplify Path | Leet code 71 | Theory + Python + Java
YouTube video 'Simplify Path - LeetCode 71 - JavaScript'
AlgoJS 7 mins
Simplify Path - LeetCode 71 - JavaScript
YouTube video 'Simplify Path - LeetCode 71 - Python Solution'
Code with Carter 6 mins
Simplify Path - LeetCode 71 - Python Solution
YouTube video 'Daily Leetcode #1107: Apr 12, 2023 - 71. Simplify Path'
Programming Live with Larry 5 mins
Daily Leetcode #1107: Apr 12, 2023 - 71. Simplify Path
YouTube video 'Daily Leetcode #311: Feb 05, 2021 - 71. Simplify Path'
Programming Live with Larry 9 mins
Daily Leetcode #311: Feb 05, 2021 - 71. Simplify Path
YouTube video 'Facebook Coding Interview Question | Leetcode 71 | Simplify Path'
WorkWithGoogler 12 mins
Facebook Coding Interview Question | Leetcode 71 | Simplify Path
YouTube video 'Daily Leetcode #713: Mar 14, 2022 - 71. Simplify Path'
Programming Live with Larry 8 mins
Daily Leetcode #713: Mar 14, 2022 - 71. Simplify Path
YouTube video 'Can you simplify a path? (LeetCode 71: Simplify Path)'
Code With Zi 7 mins
Can you simplify a path? (LeetCode 71: Simplify Path)
YouTube video '71. Simplify Path | JavaScript | Stack | LeetCode Daily Challenge'
LeetCodeWithMonu 15 mins
71. Simplify Path | JavaScript | Stack | LeetCode Daily Challenge
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   August 29, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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