Skip to content
ΣDSA Patterns
Menu
Language

Stack Parsing

Guide 2 of 6 · Path 2 of 6

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

Tested only
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

Stack parsing of nested/path structure.

Reflection