loading

Simplify Path — Step-by-Step Visualization

mediumLeetCode #71StringStack

Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. The canonical path should have no double slashes, no '.' components, and '..' goes up one level.

Algorithm Pattern

Stack-Based Path Parsing

Key Idea

Push directories onto stack, pop on '..', ignore '.' and empty parts.

Step-by-Step Approach

  1. Split path by '/'
  2. Skip empty strings and '.'
  3. On '..', pop from stack if non-empty
  4. Otherwise push directory name
  5. Join stack with '/'

Common Gotchas

  • Splitting by '/' can produce empty strings from double slashes — skip them.
  • '..' at the root level should be ignored (don't pop an empty stack).

Related Problems