Tidy a file path with . and .. parts

Stacks and queues Mid-level Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
print("/a//b/./../c/".split("/"))

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A ['', 'a', '', 'b', '.', '..', 'c', '']

Right: each slash splits, so repeated and trailing slashes give empty strings.

Empty strings from the split are just skipped by the stack walk, which is why splitting is the easy first step.

Why not the others?
  • B ['a', 'b', '.', '..', 'c']. split keeps empty strings between neighbouring slashes.
  • C ['/a', '/b', '/.', '/..', '/c']. The separator is removed, not kept.

30-second answer

Split on '/', and walk the parts with a stack of folder names. Skip empty parts and '.'; on '..' pop if the stack is not empty; otherwise push the part. Join the stack with '/' and add the leading slash. O(n) time and space.

Practise saying it · 30 s. No recording, just a timer

Explain how to tidy a path with a stack.

Say your answer out loud, then check which of these points you covered:

  • Split on slash
  • Skip '' and '.', pop on '..'
  • Join with leading slash

Deep dive

Splitting on '/' turns repeated slashes into empty strings, which are simply skipped.

'..' at the root stays at the root.

Names like '...' are ordinary folder names.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def tidy_path(path: str) -> str:
    folders: list[str] = []
    for part in path.split("/"):
        if part == "..":
            if folders:
                folders.pop()
        elif part and part != ".":
            folders.append(part)
    return "/" + "/".join(folders)

Common mistakes

  • Treating '...' as a special part.
  • Returning an empty string instead of '/' for the root.

Senior take & follow-ups

List the edge cases (double slash, '..' at root, '...') before coding.

Follow-up questions

Think of your answer first, then open the hint.

  1. What about relative paths?

    Show hint

    Then leading '..' parts must be kept instead of dropped.

  2. How does Python do this?

    Show hint

    posixpath.normpath handles most cases, but it keeps a leading '//' and does not resolve symbolic links.

What each operation costs: Stack · Queue · Deque

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.