◀ THE GRIND — STACK

Simplify Path

MEDIUM✓ CHIP-TIMEDLC #71 — FULL STATEMENT ↗

The drill: Collapse a Unix-style absolute path into its canonical form: '.' does nothing, '..' pops back to the parent (never above root), and repeated slashes squeeze into one.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An absolute Unix-style file path arrives as a string, and the drill is to collapse it into its single canonical form.

A '.' component refers to the current directory and contributes nothing to the result. A '..' component steps up to the parent directory, but stepping up from the root simply stays at the root instead of erroring.

Multiple consecutive slashes collapse into one, and the canonical output always starts with a single leading slash, uses single slashes between directory names, and never ends with a trailing slash unless the whole result is just the root.

EX 01
path = "/gym/"
"/gym"
SINGLE DIRECTORY, TRAILING SLASH
EX 02
path = "/../"
"/"
'..' AT ROOT IS A NO-OP
EX 03
path = "/home//lib//"
"/home/lib"
REPEATED SLASHES SQUEEZE OUT
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Split the path on '/' and look at each token in isolation — most of them are noise. What are the only three token shapes that actually matter?

HINT 2 THE STRUCTURE

A real '..' has to undo the most recently added real directory. That undo-the-most-recent shape is exactly what a stack is built for.

HINT 3 ONE STEP FROM THE ANSWER

Push every non-empty, non-'.' token; pop on '..' only if there's something to pop (root swallows extra '..'s). Join what's left with '/' and prefix it — default to '/' when the stack ends up empty.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE TOKEN STACKPATTERN · TOKEN STACKpath = "/a/./b/../../c/"
a
.
b
..
..
c
STACK (canonical directories)
— empty —
STEP 1

Split the path on '/'. Real names push; '.' does nothing; '..' pops if there's something to pop.

STEP 1 / 10 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/simplify-path.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def simplifyPath(self, path: str) -> str:
        stack = []
        for token in path.split("/"):
            if token == "" or token == ".":
                continue
            elif token == "..":
                if stack:
                    stack.pop()
            else:
                stack.append(token)
        return "/" + "/".join(stack)
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 12 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED