71. Simplify Path
Asked at 21Meta84Microsoft46Amazon44Bloomberg42Google37Snowflake67Roblox55Patreon100Tinkoff86Grab76Visa75Capital One71Arista Networks71OpenAI63Upstart61TikTok58Oracle58ServiceNow55Yandex46Nvidia39Uber35
Problem
Convert an absolute Unix-style path to its canonical form: . means the current directory, .. goes up one level (staying at the root if already there), repeated slashes count as one, and any other name (including ...) is a directory. The result starts with a single /, has single slashes between names and no trailing slash.
Example: "/home//foo/" → "/home/foo"; "/../" → "/"; "/a/./b/../../c/" → "/c"
Split on /. Skip "" and "."; ".." pops; anything else pushes. Join with /.
Complexity: O(n).
class Solution:
def simplifyPath(self, path: str) -> str:
st = []
for part in path.split("/"):
if part == "..":
if st:
st.pop()
elif part and part != ".":
st.append(part)
return "/" + "/".join(st)
assert Solution().simplifyPath("/home/") == "/home"
assert Solution().simplifyPath("/../") == "/"
assert Solution().simplifyPath("/home//foo/") == "/home/foo"
assert Solution().simplifyPath("/a/./b/../../c/") == "/c"
class Solution {
public String simplifyPath(String path) {
Deque<String> st = new ArrayDeque<>();
for (String p : path.split("/")) {
if (p.equals("..")) { if (!st.isEmpty()) st.pollLast(); }
else if (!p.isEmpty() && !p.equals(".")) st.addLast(p);
}
return "/" + String.join("/", st);
}
}
func simplifyPath(path string) string {
st := []string{}
for _, part := range strings.Split(path, "/") {
switch part {
case "..":
if len(st) > 0 {
st = st[:len(st)-1]
}
case "", ".":
default:
st = append(st, part)
}
}
return "/" + strings.Join(st, "/")
}