Skip to content
DSA Patterns
Menu
Language
Stack ParsingLC #712 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time 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

Path segments are a stack. .. pops, . and empty tokens are skipped, and any other token pushes. Join the survivors with one leading /.

Reflection

  • .. pops one segment, and must not pop when you are already at the root. . and the empty piece from // never go on the stack.
  • ... is a directory name, not a parent. A trailing / does not change the result.
  • An empty stack answers /. The result always starts with /.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Unix path /a/./b/../../c/. Split on /; stack holds real segments.

a
0
.
1
b
2
..
3
..
4
c
5
Key:CurrentActive rangeMatchSettledEliminated