Mediumstack-parsing
Simplify Path
Problem (restated)
Convert an absolute Unix path to its simplified canonical form (no ., .., or redundant /).
Intuition
Split on /. Stack holds real segments; .. pops; empty and . are ignored.
Approaches
Segment stack
Tested onlyTime O(n)Space O(n)
Idea. Process each token left-to-right; rejoin with a single leading /.
Walkthrough. “/a/./b/../../c/” → stack ends as [“c”] → “/c”.
Trade-offs. Root /.. stays / because pop is a no-op on empty stack.
Solution
export function simplifyPath(path: string): string {
const stack: string[] = [];
for (const part of path.split("/")) {
if (part === "" || part === ".") continue;
if (part === "..") {
if (stack.length) stack.pop();
} else {
stack.push(part);
}
}
return "/" + stack.join("/");
}
export function simplifyPath(path: string): string {
const stack: string[] = [];
for (const part of path.split("/")) {
if (part === "" || part === ".") continue;
if (part === "..") {
if (stack.length) stack.pop();
} else {
stack.push(part);
}
}
return "/" + stack.join("/");
}
Template connection
Stack parsing of nested/path structure.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?