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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code