Simplify Path
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #71
Convert an absolute Unix-style path into its canonical form: single slashes, no trailing slash, . means the current directory, .. goes up one level (staying at root if already there), and any other name (including ...) is a directory.
Examples
text
"/home/" → "/home"
"/../" → "/"
"/home//foo/" → "/home/foo"
"/a/./b/../../c/" → "/c"
"/.../a/../b/c/../d/./" → "/.../b/d"Hints
- Split by
/and process each part. ..pops from a stack;.and empty parts are ignored.
Approach
Split the path on /. For each token: skip '' and .; on .., pop the stack if it's non-empty; otherwise push the name. The answer is '/' + '/'.join(stack). O(n).
Complexity
Time: O(n). Space: O(n).
Python solution
def simplifyPath(path):
st = []
for part in path.split("/"):
if part in ("", "."):
continue
if part == "..":
if st:
st.pop()
else:
st.append(part)
return "/" + "/".join(st)JavaScript solution
function simplifyPath(path) {
const st = [];
for (const part of path.split('/')) {
if (part === '' || part === '.') continue;
if (part === '..') st.pop(); else st.push(part);
}
return '/' + st.join('/');
}