Simplify Path (LeetCode 71): Solution and Explanation
Given an absolute Unix path such as /a/./b/../../c/, return its canonical form: one leading slash, single slashes between folder names, no trailing slash, and no . or .. parts.
Intuition
Read the path the way a shell would: as a list of moves. Splitting on / turns the string into parts, and each part is an instruction. An empty part (from // or a slash at either end) and . both mean stay where you are. .. means go back up one folder. Anything else, even ..., means enter a folder with that name.
Going up always cancels the most recent folder you entered that has not been cancelled yet. Last in, first out is exactly what a stack gives you, so keep the folders you are inside on a stack.
When the parts run out, the stack lists the folders from the root down to where you ended up. Joining them with single slashes and putting one slash in front gives the canonical path, and an empty stack gives just /.
Approach: Stack of folder names
- Split
pathon/. - For each part: if it is empty or
., skip it. - If it is
.., pop the top folder if the stack is not empty. At the root there is nothing to pop, so nothing happens. - Otherwise push the part as a folder name.
- Return
/followed by the stack joined with/.
Step-by-step example
path = "/home/"
- Splitting on
/gives three parts:"","home"and"". - The first part is empty because the path starts with a slash. Skip it.
homeis a folder name, so push it. The stack is[home].- The last part is empty because of the trailing slash. Skip it.
- Join the stack and add the leading slash: the answer is
"/home".
Code: Python, Java, C++
1class Solution:
2 def simplifyPath(self, path: str) -> str:
3 stack = []
4 for part in path.split('/'):
5 if part == '' or part == '.':
6 continue
7 if part == '..':
8 if stack:
9 stack.pop()
10 else:
11 stack.append(part)
12 return '/' + '/'.join(stack)1class Solution {
2 public String simplifyPath(String path) {
3 Deque<String> stack = new ArrayDeque<>();
4 for (String part : path.split("/")) {
5 if (part.isEmpty() || part.equals(".")) {
6 continue;
7 }
8 if (part.equals("..")) {
9 if (!stack.isEmpty()) {
10 stack.pollLast();
11 }
12 } else {
13 stack.addLast(part);
14 }
15 }
16 StringBuilder sb = new StringBuilder();
17 for (String dir : stack) {
18 sb.append('/').append(dir);
19 }
20 return sb.length() == 0 ? "/" : sb.toString();
21 }
22}1class Solution {
2public:
3 string simplifyPath(string path) {
4 vector<string> stack;
5 stringstream ss(path);
6 string part;
7 while (getline(ss, part, '/')) {
8 if (part.empty() || part == ".") {
9 continue;
10 }
11 if (part == "..") {
12 if (!stack.empty()) {
13 stack.pop_back();
14 }
15 } else {
16 stack.push_back(part);
17 }
18 }
19 string result;
20 for (const string& dir : stack) {
21 result += "/" + dir;
22 }
23 return result.empty() ? "/" : result;
24 }
25};Time and space complexity
O(n)
Splitting reads each character once, each part is pushed or popped at most once, and the final join copies each kept character once.
O(n)
The list of parts and the stack together hold at most every character of the path.
Other approaches
Scan characters without split (time O(n), space O(n))
Walk the string with an index, read one part at a time between slashes, and apply the same push, pop or skip rule. It avoids building the list of parts up front but needs careful index handling.
Rewrite the string until it stops changing (time O(n^2), space O(n))
Repeatedly replace // with /, remove /./, and collapse /name/../. It mirrors how you might simplify by hand, but every pass rescans the string, so deep paths take quadratic time and the edge cases are easy to miss.
Common mistakes
- Treating
...or..aas special. Only the exact parts.and..have meaning; everything else is a folder name. - Popping on
..when the stack is empty. Going up from the root stays at the root. - Returning an empty string when every folder was cancelled. The answer must be
/. - Building the answer with a trailing slash, or forgetting the leading one.
Frequently asked questions
Why is a stack the right structure for Simplify Path?
Each .. undoes the most recent folder that is still open, which is last in, first out. A stack pushes folders as you enter them and pops the latest one when you go up.
What does .. do at the root?
Nothing. The root has no parent, so the path stays at / and the stack stays empty.
Why do empty parts appear after splitting?
A leading slash, a trailing slash or two slashes in a row each leave an empty string between separators. They carry no folder name, so they are skipped like ..
What is the time complexity of Simplify Path?
O(n) time and O(n) space, where n is the length of the path. Every part is pushed or popped at most once.