Coding Interview PatternsSimplify Path
MediumStacks
Simplify Path
Explanation & Solution
Description
Given an absolute path for a Unix-style file system, which begins with a slash '/', transform this path into its simplified canonical path.
In Unix-style file system context, a single period '.' signifies the current directory, a double period '..' denotes moving up one directory level, and multiple consecutive slashes such as '//' are interpreted as a single slash. In this problem, treat sequences of periods not covered by the previous rules (like '...') as valid names for files or directories.
The simplified canonical path should adhere to the following rules:
- It must start with a single slash
'/'. - Directories within the path must be separated by exactly one slash
'/'. - It must not end with a slash
'/', unless it's the root directory. - It must not include any single or double periods used to denote current or parent directories.
Input: path = "/home/"
Output: "/home"
Constraints
1 <= path.length <= 3000pathconsists of English letters, digits, period'.', slash'/'or underscore'_'pathis a valid absolute Unix path
Approach
Stacks pattern
1. Split the Path
- Split the path string by
'/'to get individual components - This handles multiple consecutive slashes naturally (they become empty strings)
2. Process Each Component
- Empty string or `'.'`: Skip — these don't change the directory
- `'..'`: Pop from the stack (go up one directory), if stack is non-empty
- Anything else: Push onto the stack as a valid directory name
3. Reconstruct the Path
- Join the stack elements with
'/'and prepend a leading'/' - If the stack is empty, the result is just
'/'(root)
Key Insight
- The stack naturally models directory navigation — pushing for descent, popping for ascent
- Splitting by
'/'and filtering edge cases makes the logic clean and linear - Time: O(n), Space: O(n)