Simplify Path
Problem
Given an absolute Unix-style path, return its canonical form.
- . → current directory (skip)
- .. → parent directory (pop one)
- // (and more) collapse to a single /
- anything else is a directory name
The result starts with /, has no trailing / (except the root itself), and contains no . or ...
Constraints
- 1 ≤ path.length ≤ 3000
- Always starts with
/ ...(three or more dots) is a regular directory name, not a special token
Approach — Stack
This is a Stack problem. The idea: scan the input once, pushing work onto a stack and popping when the top can be resolved, so the stack always reflects what's still open. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class Solution:
def simplifyPath(self, path):
st = []
for part in path.split('/'):
if part == '' or part == '.':
continue
if part == '..':
if st:
st.pop()
else:
st.append(part)
return '/' + '/'.join(st)
Java
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public String simplifyPath(String path) {
// Initialize a stack
Deque<String> stack = new ArrayDeque<>();
String[] components = path.split("/");
// Split the input string on "/" as the delimiter
// and process each portion one by one
for (String directory : components) {
// A no-op for a "." or an empty string
if (directory.equals(".") || directory.isEmpty()) {
continue;
} else if (directory.equals("..")) {
// If the current component is a "..", then
// we pop an entry from the stack if it's non-empty
if (!stack.isEmpty()) {
stack.pop();
}
} else {
// Finally, a legitimate directory name, so we add it
// to our stack
stack.push(directory);
}
}
// Stich together all the directory names together
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, "/" + stack.pop());
}
return result.length() == 0 ? "/" : result.toString();
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Simplify Path interactively → ← All solutions