Simplify Path
Given a string path, which is an absolute path to a file or directory in a Unix-style file system, convert it to the simplified canonical path. A single period '.' refers to the current directory, a double period '..' moves up one level, and multiple consecutive slashes are treated as a single slash. The canonical path must start with a single slash and must not end with a slash (unless it is the root).
- 1 <= path.length <= 3000
- path consists of English letters, digits, period, slash, or underscore
- path is a valid absolute Unix path (starts with '/')
path = "/home/""/home"path = "/../""/"path = "/home//foo/""/home/foo"When you are navigating through folders on a computer, you are building a history of where you have been. If you go into folder A, then B, and then hit "..", you are not just deleting text—you are undoing your last move and jumping back to A.
This Undo behavior is why a Stack is the perfect data structure for simplifying file paths. A Stack remembers the sequence of your deeper dives and allows you to pop the most recent directory the moment it gets cancelled by a ".." command.
- Splitting the Noise: First, we ignore all the extra slashes. By splitting the path by "/", we get a clean list of individual commands: folder names, dots ("."), or double-dots ("..").
- Filtering the Segments:
- Folder Name: This is a deep dive. Push it onto the Stack.
- "." (Current Dir): This does nothing. Ignore it.
- ".." (Parent Dir): This is the undo button. Pop the most recent folder off the Stack. If you are already at the root, ignore it (you cannot go higher than home!).
- The Final Assembly: After processing all segments, the folders remaining in the Stack represent your final, direct path. Just join them back together with slashes!
stack = []
segments = path.SPLIT('/')
FOR each part in segments:
IF part is ".." :
IF stack is NOT empty:
stack.POP()
ELSE IF part is empty OR part is "." :
CONTINUE
ELSE:
stack.PUSH(part)
RETURN "/" + stack.JOIN('/')Unix-style traversal logic with Stack
Mental Model
- Breadcrumb Trail: The stack acts as a breadcrumb trail of your location.
- Backtracking: `..` means "go back", modeled by `stack.pop()`.
Canonical Path Rules
1. Always start with `/`. 2. Single `/` between directories. 3. No trailing `/`. 4. Remove `.` and handling `..`. The stack approach handles all these naturally.