Simplify Path solution explained

Simplify Path gives you an absolute Unix-style path that may contain repeated slashes, single dots and double dots, and asks for its shortest canonical form. Split the path on slashes, push each real folder name onto a stack, ignore empty parts and ".", pop on ".." when the stack is not empty, and join what is left with single slashes after a leading one. It runs in O(n) time.

By Published 6 min read

Restating the problem

The input is a string that starts with a slash and describes a location in a Unix-like file system. Inside it, a single dot means "this folder", two dots mean "the parent folder", and several slashes in a row count as one. Any other sequence of characters between slashes is a folder name, even if it is made of dots, such as "...". Return the simplified absolute path: it begins with exactly one slash, names are separated by single slashes, it does not end with a slash (unless it is the root itself), and it contains no "." or ".." parts.

"/docs//drafts/./old/../final/"  ->  "/docs/drafts/final"
"/../../srv"                      ->  "/srv"       (cannot go above the root)
"/notes/.../todo/.."              ->  "/notes/..."  ("..." is a folder name)
"/var/./"                         ->  "/var"
"/"                               ->  "/"
Paths made up for this page, with the canonical form

What it tests

Simplify Path is a parsing problem dressed as a file system question. Interviewers want to see that you split the input into tokens before reasoning about it, that you recognize ".." as an undo operation on a stack, and that you handle the boring cases cleanly: empty parts from double slashes, ".." at the root, and names that only look special.

Slow but sure: rewrite until nothing changes

A natural first idea is to edit the string itself: collapse double slashes, delete "/./", and replace "/name/../" with "/", repeating until no rule applies. It works, but each pass rescans the string and a path with many nested ".." parts needs many passes, so it is quadratic. It is still useful as an independent check in tests.

import re


def simplify_path_slow(path):
    p = path + "/"
    while True:
        q = p.replace("//", "/").replace("/./", "/")
        q = re.sub(r"/(?!\.\.?/)[^/]+/\.\./", "/", q, count=1)
        if q.startswith("/../"):
            q = q[3:]
        if q == p:
            break
        p = q
    return p.rstrip("/") or "/"
Python: apply one rewrite at a time until the string stops changing. O(n squared).

The lookahead in the pattern stops it from treating "." or ".." itself as the folder name being cancelled. Names such as "..." or ".x" still match, which is correct.

The stack solution

Splitting on "/" turns the path into a list of parts. Double slashes and the leading and trailing slashes produce empty strings, which you skip. A "." is also skipped. A ".." removes the most recent folder if there is one. Everything else is a folder to enter, so you push it. The stack now holds the folders from the root down, and joining them gives the answer.

def simplify_path(path):
    stack = []
    for part in path.split("/"):
        if part == "" or part == ".":
            continue
        if part == "..":
            if stack:
                stack.pop()
        else:
            stack.append(part)
    return "/" + "/".join(stack)
Python: split, push names, pop on ".."
function simplifyPath(path) {
  const stack = [];
  for (const part of path.split("/")) {
    if (part === "" || part === ".") continue;
    if (part === "..") {
      if (stack.length) stack.pop();
    } else {
      stack.push(part);
    }
  }
  return "/" + stack.join("/");
}
JavaScript: the same loop

When the stack is empty, joining gives an empty string and the result is "/", so the root needs no special case. In JavaScript, calling pop on an empty array just returns undefined, but the explicit length check makes the root rule visible to the reader.

Tracing the first example

"/docs//drafts/./old/../final/" split on "/"
PartActionStack after
"" (before the first slash)skip(empty)
docspushdocs
"" (double slash)skipdocs
draftspushdocs, drafts
.skipdocs, drafts
oldpushdocs, drafts, old
..pop olddocs, drafts
finalpushdocs, drafts, final
"" (trailing slash)skipdocs, drafts, final
"/docs//drafts/./old/../final/" split on "/". Scroll sideways on a small screen.

Complexity

n is the length of the path
ApproachTimeExtra space
Rewrite until stableO(n squared) in the worst caseO(n)
Split and stackO(n)O(n) for the parts and the stack
n is the length of the path. Scroll sideways on a small screen.

Inputs that catch bugs

  • The root alone, "/", and the root written as "///": both return "/".
  • More ".." parts than folders, such as "/../../srv": extra pops at the root are ignored.
  • Names made of dots, like "..." or "....": push them as folders.
  • Hidden-file style names like ".config": a normal folder.
  • A trailing ".." with no slash after it, as in "/notes/.../todo/..".

Common mistakes

  • Treating any part that starts with a dot as special, which breaks "..." and ".config".
  • Popping on ".." without checking for an empty stack, which crashes in Python.
  • Building the answer with a trailing slash, or returning an empty string for the root.
  • Using string replace for "/../" in one pass, which misses cases created by an earlier replacement.
  • Handing the job to a library path function in the interview. Some keep a double leading slash, and the interviewer wants your logic anyway.

Variations

  • Relative paths with a current folder: start the stack with the current folder's parts and process the relative path on top.
  • Windows-style paths: split on backslashes and keep the drive letter as a fixed first part that ".." cannot remove.
  • Symbolic links: when a part is a link, replace it with the parts of its target and continue; watch for cycles.
  • Longest file path in a text listing: a different stack over folder depths, in Longest Absolute File Path.

How to explain it out loud

Fictional example

Turning the rules into operations
Candidate
I will split on slashes, so double slashes and the edges become empty strings I can skip.
Candidate
Each remaining part is an instruction: a dot means stay, two dots mean go up, anything else means go into that folder. Going up undoes the last go-into, which is a stack pop.
Interviewer
What about ".." at the root, or a folder called three dots?
Candidate
At the root I just ignore the pop. Three dots is not one of the two special tokens, so it is an ordinary name. At the end I join the stack with slashes and put one in front, which also gives "/" for an empty stack.

Two more parsing-with-a-stack problems sit in this batch: Basic Calculator II evaluates an expression string, and Exclusive Time of Functions parses log lines into a call stack. The classic warm-up for all of them is Valid Parentheses.

Rehearsing it with Natively

This is a problem where interviewers listen for the edge cases you name before you code. Natively, on a Mac or Windows computer, can read the path rules from a screenshot during a mock round, suggest the split-and-stack plan, and transcribe your answer so you can see afterwards whether you raised the root and the three-dot name on your own. More on this in Natively for coding practice.

Questions people ask

How do you solve Simplify Path?

Split the path on slashes. Skip empty parts and single dots, pop the stack on a double dot if it is not empty, and push every other part. Join the stack with slashes after a leading slash.

What does ".." do at the root in Simplify Path?

Nothing. You cannot go above the root, so a double dot with an empty stack is ignored.

Is "..." a special part in Simplify Path?

No. Only a single dot and a double dot are special. Three or more dots, or names like .config, are ordinary folder names.

What is the time complexity of Simplify Path?

O(n) for a path of length n: one split and one pass over the parts, with O(n) space for the stack.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP