Home
DSA Patterns
Stack
Simplify Path
Simplify Path (LeetCode 71)
Simplify Path (LeetCode 71): turn a Unix-style absolute path into its canonical form with a stack of directory names: skip empty parts and '.', pop on '..', push names.
Problem Understanding
Simplify Path: given an absolute Unix-style path, return its canonical form. . means the current directory, .. the parent, and any run of slashes counts as one. The result starts with a single /, has no trailing slash, and contains no . or ...
Example: "/home/user/Documents/../Pictures" returns "/home/user/Pictures".
The Intuition: Where Am I Now?
Read the path left to right as a series of moves, keeping a stack of the directories you are inside:
- Empty part or
.: you have not moved; ignore it. Empty parts come from//, the leading/and a trailing/. ..: go up a level; pop, unless you are already at the root.- Anything else: a directory name, even
...; push it.
At the end the stack is the canonical path: join it with / and put a / in front. The same push-and-pop bookkeeping drives Valid Parentheses and Decode String.
Simplify Path Visualization
SPLIT ON '/'
path.split('/')
0
1
2
3
4
5
6
7
8
9
directories (stack, root on the left)
ROOT
depth
0
Answer
:
Split on '/' into 10 parts. The stack holds the directories we are inside
Next
Empty part (from a leading, trailing or doubled slash): ignore it
path
The parts of path.split('/') are on top, with empty parts drawn as "". Below them are the directories on the stack. When .. leaves a directory it turns red for one step. Try Above root to see .. ignored at the root.
Simplify Path Dry Run
Input: "/.../a/../b/c/../d/./"
| Part | Action | Stack after |
|---|---|---|
| "" | ignore | [] |
| ... | push | [...] |
| a | push | [..., a] |
| .. | pop a | [...] |
| b | push | [..., b] |
| c | push | [..., b, c] |
| .. | pop c | [..., b] |
| d | push | [..., b, d] |
| . | ignore | [..., b, d] |
| "" | ignore | [..., b, d] |
Answer: "/.../b/d".
Simplify Path LeetCode Solution
Split, then a stack of names. The C version uses strtok, which already skips empty parts.
Simplify Path Code
1var simplifyPath = function(path) {2 const stack = [];3 for (const part of path.split('/')) {4 if (part === '' || part === '.') continue;5 if (part === '..') {6 stack.pop();7 } else {8 stack.push(part);9 }10 }11 return '/' + stack.join('/');12};
Simplify Path in Python, Java, C++, TypeScript and C
Simplify Path in Python
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for part in path.split('/'):
if part == '' or part == '.':
continue
if part == '..':
if stack:
stack.pop()
else:
stack.append(part)
return '/' + '/'.join(stack)Simplify Path in Java
class Solution {
public String simplifyPath(String path) {
Deque<String> stack = new ArrayDeque<>();
for (String part : path.split("/")) {
if (part.isEmpty() || part.equals(".")) continue;
if (part.equals("..")) {
if (!stack.isEmpty()) stack.pollLast();
} else {
stack.addLast(part);
}
}
return "/" + String.join("/", stack);
}
}Simplify Path in C++
class Solution {
public:
string simplifyPath(string path) {
vector<string> stack;
stringstream ss(path);
string part;
while (getline(ss, part, '/')) {
if (part.empty() || part == ".") continue;
if (part == "..") {
if (!stack.empty()) stack.pop_back();
} else {
stack.push_back(part);
}
}
string ans;
for (const string& s : stack) ans += "/" + s;
return ans.empty() ? "/" : ans;
}
};Simplify Path in TypeScript
function simplifyPath(path: string): string {
const stack: string[] = [];
for (const part of path.split('/')) {
if (part === '' || part === '.') continue;
if (part === '..') {
stack.pop();
} else {
stack.push(part);
}
}
return '/' + stack.join('/');
}Simplify Path in C
char* simplifyPath(char* path) {
int n = strlen(path), top = 0;
char** stack = malloc((n / 2 + 1) * sizeof(char*));
for (char* part = strtok(path, "/"); part; part = strtok(NULL, "/")) {
if (strcmp(part, ".") == 0) continue;
if (strcmp(part, "..") == 0) {
if (top) top--;
} else {
stack[top++] = part;
}
}
char* ans = malloc(n + 2);
int len = 0;
for (int i = 0; i < top; i++) len += sprintf(ans + len, "/%s", stack[i]);
if (len == 0) strcpy(ans, "/");
free(stack);
return ans;
}Edge Cases & Common Mistakes
..at the root: ignore it;"/../"is"/".- Names made of dots:
...is a normal directory name; only.and..are special. - Multiple slashes:
"/a//b"splits into an empty part between the slashes; skip it. - Empty result: join gives an empty string; the answer is
"/", not"". - JavaScript
pop()on an empty array: returnsundefinedand changes nothing, so no guard is needed there.
Summary
Split the path on '/'. Ignore empty parts and '.', pop on '..' when the stack is not empty, and push every other name. Return '/' plus the stack joined with '/'. O(n) time, O(n) space.
More practice: DSA interview questions with answers · patterns cheat sheet
