Simplify Path Visualizer & Step-by-Step Algorithm Solution

Convert an absolute Unix-style file path into its canonical simplified form using a LIFO stack to manage directory navigation, parent traversals, and redundant slashes.

Category: stack | Difficulty: Medium

Tags: Stack, String, Unix Path, Simulation, LeetCode 71

Simplify Path

Path Segments (path.split("/"))
""
0
home
1
""
2
foo
3
""
4
Push / Pop (Top)
(Empty Stack)
Directory Stack
100%
state
path/home//foo/
canonicalPath/
stackDepth0
totalSegments5
segments["", home, "", foo, ""]
Initialization
1/13
Explanation

Start simplifyPath with path = "/home//foo/". Split by '/' into 5 segments.

Source Code
1function simplifyPath(path: string): string {
2 const stack: string[] = [];
3 for (let part of path.split("/")) {
4 if (part === "" || part === ".") continue;
5 if (part === "..") {
6 if (stack.length) stack.pop();
7 } else {
8 stack.push(part);
9 }
10 }
11 return "/" + stack.join("/");
12}