Simplify Path
Master this topic with zero to advance depth.
Simplify Path
Given a Unix-style absolute path, simplify it to its canonical form.
Visual Representation
path = "/home//foo/../bar/"
Tokens: ["home", "", "foo", "..", "bar"]
1. "home": Valid name. Push. Stack: ["home"]
2. "": Empty. Skip.
3. "foo": Valid name. Push. Stack: ["home", "foo"]
4. "..": Parent dir. Pop. Stack: ["home"]
5. "bar": Valid name. Push. Stack: ["home", "bar"]
Canonical Path: "/home/bar"Examples
Level I: Iterative Stack Processing (Natural Approach)
Intuition
Split the path by '/' into parts. Maintain a list acting as a stack: push valid directory names, pop for '..', skip '.' and empty parts. Join the stack with '/' prefixed by '/'.
Level II: Recursive Path Reduction
Intuition
Instead of using an explicit stack, we can process the path string repeatedly by removing the most 'reducible' parts. For example, replacing /./ with / and /directory_name/../ with /. This is less efficient but helpful for understanding the underlying LIFO structure of the path.
Level III: Optimal (Stack Tokenization)
Intuition
Split the path by / and process each component. A stack maintains the valid directory structure. .. removes the last added directory, while . or empty strings are ignored. Any other string is a valid directory to be pushed.
Detailed Dry Run
| Part | Action | Stack Content |
|---|---|---|
| "home" | Push | ["home"] |
| "foo" | Push | ["home", "foo"] |
| ".." | Pop | ["home"] |
| "bar" | Push | ["home", "bar"] |
⚠️ Common Pitfalls & Tips
Multiple slashes become one. .. at the root keeps you at the root. The trailing slash should be removed unless it's the root itself.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.