↓Skip to main content
  1. LeetCode/

LeetCode 71: Simplify Path

·2 mins· ·
LeetCode Medium String Stack
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-24

  • Submissions: Runtime Error → Wrong Answer ×4 → Runtime Error ×2 → Wrong Answer ×2 → Accepted → Wrong Answer → Accepted → Wrong Answer → Accepted

Approach
#

Split on / and handle each piece (Stack Template 1):

  • Empty strings (from repeated /) and .: skip.
  • ..: pop if the stack is non-empty; at the root, do nothing.
  • Anything else, including ...: a directory name to push.

The answer is "/" + "/".join(stack), which is exactly "/" for an empty stack.

My Attempts
#

This took 14 submissions:

  • Attempt 1 processed characters backwards with tangled rules for . and /, returning an empty string even for /.
  • With split('/') and a stack, the boundaries got fixed one by one: .. at the root popped an empty stack (IndexError), empty pieces were kept (/ returned //), and . was kept (/. returned /.).
  • Two 2022-11 rewrites each missed one case again, . and the root’s .. (/.. returned /..).

Solution
#

class Solution:
    def simplifyPath(self, path: str) -> str:
        st = []
        for part in path.split("/"):
            if part == "..":
                if st:
                    st.pop()
            elif part and part != ".":
                st.append(part)
        return "/" + "/".join(st)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • split("/") yields empty strings; skip them.
  • Skip ., while ... is a valid name.
  • .. at the root must neither pop an empty stack nor be pushed.

Interview Explanation
#

I split on slashes, skip empty pieces and single dots, pop for double dots unless at the root, push other names, and join with slashes. Time O(n).

Related

LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 43: Multiply Strings
·2 mins
LeetCode Medium Math String Simulation
LeetCode 43 note: num1[i] × num2[j] lands at position i + j + 1; accumulate into an array of length n + m and carry at the end
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list
LeetCode 5: Longest Palindromic Substring
·2 mins
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 note: expand around centers, using each position as an odd and an even center; with interval DP, iterate i from large to small
LeetCode 1047: Remove All Adjacent Duplicates In String
·1 min
LeetCode Easy String Stack
LeetCode 1047 note: if the stack top equals the current character both vanish, otherwise push it; after a removal the new top may cancel with the next character
LeetCode 1021: Remove Outermost Parentheses
·1 min
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 note: track depth instead of a stack; the ‘(’ raising depth from 0 to 1 and the ‘)’ lowering it from 1 to 0 are outermost, everything else stays