Simplify Path
Medium
Topics
Given an absolute Unix-style path path, return its simplified canonical path. Handle . (current), .. (parent), and redundant slashes.
Example 1
parts
result
Splitting on
/ makes the rest mechanical: . and empty parts are dropped, .. pops, and anything else pushes. Popping an empty stack must be a no-op, since the root has no parent. Result: /home.Chips are the path components before and after simplification.
Input: path = "/home/" Output: "/home"
Example 2
parts
result
Input: path = "/../" Output: "/"
Example 3
parts
result
Input: path = "/a/./b/../../c/" Output: "/c"
Constraints
- 1 <= path.length <= 3000
- path begins with a single slash.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Split on / and the path becomes a list of segments, most of which are directory names to keep. Three segment kinds are special: the empty string (from a doubled or trailing slash) and . are both no-ops, and .. pops the previous directory.
A stack of kept segments makes the whole thing one pass. The leading slash is restored at the end, and because the path is absolute, a .. at the root is simply ignored rather than an error.
Approach
- Split the path on
/. - Skip empty segments and
.. - On
.., pop if the stack is non-empty. - Otherwise push the segment.
- Return
/joined with the stack.
Dry Run
"/home/" -> "/home" trailing slash gives an empty segment
"/../" -> "/" .. at the root is ignored
"/home//foo/" -> "/home/foo" the doubled slash gives an empty segment
"/a/./b/../../c/" -> "/c" . skipped, then two pops
"/..." -> "/..." three dots is an ordinary name
"/a/../../b" -> "/b" the second .. pops nothingComplexity
- Time — O(n): the split is linear and each segment is handled once.
- Space — O(n) for the segment list and the stack.
Common Pitfalls
- Treating
...or any longer run of dots as a parent reference. Only exactly..is special;...is a legal directory name, and this is the case most often missed. - Popping on
..without checking the stack, which throws at the root. On an absolute path the root has no parent, so the operation is a no-op. - Hand-rolling the slash handling with an index walk and getting the doubled-slash case wrong. Splitting and discarding empty segments handles redundant and trailing slashes in one rule.
- Joining without the leading
/, or emitting a trailing one. The canonical form starts with exactly one slash and ends without one, except for the root itself which is just/. - Returning the empty string when everything pops. The root is
/, which the"/" + join(...)form produces for free.
Full Solution — all languages
class Solution:
def simplifyPath(self, s):
stack = []
for part in s.split("/"):
if part == "" or part == ".":
continue
if part == "..":
if stack: stack.pop()
else:
stack.append(part)
return "/" + "/".join(stack)import java.util.*;
class Solution {
public String simplifyPath(String s) {
Deque<String> stack = new ArrayDeque<>();
for (String part : s.split("/")) {
if (part.isEmpty() || part.equals(".")) continue;
if (part.equals("..")) {
if (!stack.isEmpty()) stack.pollLast();
} else stack.addLast(part);
}
StringBuilder sb = new StringBuilder();
for (String p : stack) sb.append('/').append(p);
return sb.length() == 0 ? "/" : sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string simplifyPath(string s) {
vector<string> stack;
stringstream ss(s);
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 res;
for (auto& p : stack) res += "/" + p;
return res.empty() ? "/" : res;
}
};/**
* @param {string} s
* @return {string}
*/ var simplifyPath = function(s) {
const stack = [];
for (const part of s.split('/')) {
if (part === '' || part === '.') continue;
if (part === '..') {
if (stack.length) stack.pop();
} else stack.push(part);
}
return '/' + stack.join('/');
};