mediumStackStringStack

Simplify Path

mediumTime: O(n)Space: O(n)

Recognize the pattern

simplify Unix pathhandle . and .. and //stack for directory hierarchy

Brute force idea

Not applicable — stack IS the natural approach.

Better approach

Split by '/'. For each part: '.' = skip, '..' = pop, '' = skip, else push. Join with '/' prefix. O(n).

Key invariant

The stack represents root-to-current path. '..' = go up (pop). Valid names = go deeper (push).

Watch out for

Popping empty stack on '..' — stay at root (don't pop).

Stack Pattern