← Back to index
MediumTypeScript2 min read

Simplify Path

normalize unix-style file paths by handling . and .. components using a stack.

stackstring

Problem link

View on LeetCode

Solutions in this repo

  • TypeScript../simplify-path/solution.tsTypeScript solution

split the path by "/" and process each component. empty strings and "." are ignored. ".." pops from the stack (goes up one directory). everything else gets pushed onto the stack.

at the end, join the stack with "/" and prepend "/" for the root. the stack naturally handles nested directory navigation.

edge cases

  • multiple slashes: split handles them as empty strings
  • ".." at root: stack.pop() on empty stack is safe (no-op)
  • trailing slash: gets split as empty string, ignored

complexity

O(n) time to split and process, O(n) space for the stack. straightforward linear solution.