Simplify Path - Problem

Imagine you're building a Unix terminal navigation system that needs to clean up messy file paths! ๐Ÿ—‚๏ธ

You're given an absolute path for a Unix-style file system (always starting with '/'), and your job is to transform it into its simplified canonical form.

Unix Path Rules:

  • '.' = current directory (ignore it)
  • '..' = go back to parent directory
  • '///' = treat multiple slashes as single '/'
  • '...' or '.abc' = valid directory names

Canonical Path Rules:

  • Must start with single '/'
  • Directories separated by exactly one '/'
  • No trailing '/' (except root)
  • No '.' or '..' components

Examples:
"/home//foo/" โ†’ "/home/foo"
"/a/./b/../../c/" โ†’ "/c"
"/../" โ†’ "/"

Input & Output

example_1.py โ€” Basic Path
$ Input: "/home/"
โ€บ Output: "/home"
๐Ÿ’ก Note: Trailing slash is removed, but the directory remains
example_2.py โ€” Complex Navigation
$ Input: "/a/./b/../../c/"
โ€บ Output: "/c"
๐Ÿ’ก Note: '.' is ignored, '..' goes back to parent, so we go: /a โ†’ /a/b โ†’ /a โ†’ / โ†’ /c
example_3.py โ€” Root Edge Case
$ Input: "/../"
โ€บ Output: "/"
๐Ÿ’ก Note: Cannot go above root directory, so '..' from root stays at root

Constraints

  • 1 โ‰ค path.length โ‰ค 3000
  • path consists of English letters, digits, period '.', slash '/' or underscore '_'
  • path is a valid absolute Unix path

Visualization

Tap to expand
Unix Path Simplification ProcessInput Path: /home/../var/./log/../wwwStep-by-step processing:Start with empty stack: []Process 'home' โ†’ push to stack: [home]Process '..' โ†’ pop from stack: []Process 'var' โ†’ push to stack: [var]Process '.' โ†’ ignore: [var]Process 'log' โ†’ push to stack: [var, log]Process '..' โ†’ pop from stack: [var]Process 'www' โ†’ push to stack: [var, www]Result: /var/wwwStack VisualizationwwwvarFinal Stack State
Understanding the Visualization
1
Parse Path
Split the path into individual components separated by '/'
2
Stack Processing
Use a stack to track your current location in the directory tree
3
Handle Components
Push directories, ignore '.', pop on '..' operations
4
Build Result
Join the final stack contents to create the canonical path
Key Takeaway
๐ŸŽฏ Key Insight: A stack naturally models the directory hierarchy - pushing when going deeper into directories and popping when going back to parent directories with '..' operations.
Asked in
Facebook 45 Microsoft 38 Amazon 32 Google 28
125.0K Views
High Frequency
~18 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen