71. Simplify Path 🗺️
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Stack
, String
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 systems:
A single period '.'
signifies the current directory.
A double period '..'
denotes moving up one directory level.
Multiple slashes '//'
are interpreted as a single slash '/'
.
The simplified canonical path should:
Start with a single slash '/'
.
Separate directories with a single slash '/'
.
Not end with a slash '/'
(unless it is the root directory).
Exclude any single or double periods.
🔹 Example 1:
Input:
Output:
🔹 Example 2:
Input:
Output:
🔹 Example 3:
Input:
Output:
🔹 Example 4:
Input:
Output:
🔹 Example 5:
Input:
Output:
1 <= path.length <= 3000
path
consists of English letters, digits, period '.'
, slash '/'
, or underscore '_'
.
path
is a valid absolute Unix path.
To solve the problem, a stack can be used to process directory names:
Split the path by '/'
to handle each component.
Ignore empty strings, '.'
, and handle '..'
by popping the stack (if not empty).
Push valid directory names onto the stack.
Construct the canonical path by joining stack elements with '/'
.
Splitting the Path:
Split the path into components by '/'
to isolate directories, '.'
, and '..'
.
Using a Stack:
Push valid directory names onto the stack.
Pop the stack for '..'
to move up a directory level.
Ignore '.'
and empty components.
Constructing the Canonical Path:
Join stack elements with '/'
to create the simplified path.
If the stack is empty, return '/'
as the root directory.
O(n): Where n
is the length of the input path
. Each component is processed once.
O(n): In the worst case, the stack contains all components of the path.
You can find the full solution .