Simplify Path
Medium · Stack · Explanation and code example
Stack - II
How it works
Instead of processing character by character, we can split the path by / to get all the directory names at once. This simplifies the logic since we directly work with directory names rather than building them up. The same stack-based approach applies: push valid directories and pop on ...
Steps
- Split the path string by
/to get an array of parts. - For each part:
- If it equals
.., pop from thestack(if not empty). - If it is a valid directory name (not empty and not
.), push it onto thestack.
- If it equals
- Join the
stackwith/and prepend a leading/to return the simplified path.
Complexity
- Time complexity:
O(n) - Space complexity:
O(n)
Things to watch for
Popping from an Empty Stack on ".."
When encountering .., you should only pop from the stack if it is non-empty. Attempting to pop from an empty stack causes runtime errors in some languages, and logically, going to the parent of the root directory should simply stay at the root. Forgetting this check leads to crashes or incorrect path construction.
Treating "." and ".." as Valid Directory Names
The single dot . means "current directory" and should be ignored, while .. means "parent directory" and triggers a pop operation. A common mistake is pushing these onto the stack as if they were regular directory names, resulting in paths like /home/./user/../.. instead of the simplified /home.
Not Handling Multiple Consecutive Slashes
Paths like //home///user should be treated the same as /home/user. When splitting by / or processing character by character, multiple consecutive slashes produce empty strings. Failing to skip these empty strings can result in incorrect behavior or extra slashes in the output.
Python code example
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
paths = path.split("/")
for cur in paths:
if cur == "..":
if stack:
stack.pop()
elif cur != "" and cur != ".":
stack.append(cur)
return "/" + "/".join(stack)
C++ code example
class Solution {
public:
string simplifyPath(string path) {
vector<string> stack;
string cur;
stringstream ss(path);
while (getline(ss, cur, '/')) {
if (cur.empty()) continue;
if (cur == "..") {
if (!stack.empty()) stack.pop_back();
} else if (!cur.empty() && cur != ".") {
stack.push_back(cur);
}
}
string result = "/";
for (int i = 0; i < stack.size(); ++i) {
if (i > 0) result += "/";
result += stack[i];
}
return result;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.