Problem
Given an absolute Unix-style path, return the simplified canonical path. A canonical path starts with a slash, has no trailing slash unless it is the root, and contains no "." or ".." segments.
Original: LeetCode 71: Simplify Path.
Examples
Example 1
`path = "/home/"``"/home"`Example 2
`path = "/home//foo/"``"/home/foo"`Example 3
`path = "/home/user/Documents/../Pictures"``"/home/user/Pictures"`Example 4
`path = "/../"``"/"`Example 5
`path = "/.../a/../b/c/../d/./"``"/.../b/d"`Constraints
1 <= path.length <= 3000pathconsists of English letters, digits, period'.', slash'/'or'_'.pathis a valid absolute Unix path.
Hints
Hint 1
".." moves to the parent, and stays at the root if you are already there. Three or more dots, such as "...", are a literal directory name. Consecutive slashes are one separator.
Hint 2
A path with parent references is stack-based parsing: push directories and pop on "..".
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. There is no slower algorithm that is useful here; the work is to get the rules right while you scan once.
Optimal. Split on '/', ignore empty parts and ".", pop on "..", and push everything else. Join with a leading slash.
Alternative. You can scan character by character instead of splitting, which avoids an intermediate array but is easier to get wrong.
Complexity
- Time
- O(n)
O(n) time and O(n) space, where n is the length of the path.
- Space
- O(n)
Code
def simplify_path(path: str) -> str:
stack: list[str] = []
for part in path.split("/"):
if part in ("", "."):
continue
if part == "..":
if stack:
stack.pop()
else:
stack.append(part)
return "/" + "/".join(stack)
if __name__ == "__main__":
assert simplify_path("/home/") == "/home"
assert simplify_path("/home//foo/") == "/home/foo"
assert simplify_path("/home/user/Documents/../Pictures") == "/home/user/Pictures"
assert simplify_path("/../") == "/"
assert simplify_path("/.../a/../b/c/../d/./") == "/.../b/d"
print("ok")import java.util.ArrayDeque;
public class SimplifyPath {
static String simplifyPath(String path) {
var stack = new ArrayDeque<String>();
for (var part : path.split("/")) {
if (part.isEmpty() || part.equals(".")) continue;
if (part.equals("..")) {
if (!stack.isEmpty()) stack.removeLast();
} else {
stack.addLast(part);
}
}
if (stack.isEmpty()) return "/";
var out = new StringBuilder();
for (var part : stack) out.append('/').append(part);
return out.toString();
}
public static void main(String[] args) {
if (!simplifyPath("/home/").equals("/home")) throw new AssertionError();
if (!simplifyPath("/home//foo/").equals("/home/foo")) throw new AssertionError();
if (!simplifyPath("/home/user/Documents/../Pictures").equals("/home/user/Pictures")) throw new AssertionError();
if (!simplifyPath("/../").equals("/")) throw new AssertionError();
if (!simplifyPath("/.../a/../b/c/../d/./").equals("/.../b/d")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "/home/" becomes "/home", "/home//foo/" becomes "/home/foo", "/home/user/Documents/../Pictures" becomes "/home/user/Pictures", "/../" becomes "/", and "/.../a/../b/c/../d/./" becomes "/.../b/d".
- ".." at the root does not go above "/".
Follow-ups
- The same stack walk works for a relative path if you also keep the current working directory on the stack.
Interview script
"I split on slashes and use a stack of directory names. I ignore empty parts and '.', I pop on '..', and I treat any other token, including '...', as a real name. Then I join what remains, or return '/' if the stack is empty."
Source: LeetCode 71: Simplify Path Source: Java SE 17 API: ArrayDeque
Sources (2)
- LeetCode 71: Simplify Pathleetcode.com
- Java SE 17 API: ArrayDequedocs.oracle.com