DSA Factory
Free Stacks and queues lessonsStacks and queues · Stage 4 · Expression evaluation · Step 4

Tidy up a file path

Simplify a file path with dots and double dots by keeping the folders you are inside on a stack, popping one for each step back up. About 12 minutes.

Where you are is a stack

A path describes a walk through folders. Split it at the slashes into pieces. The example path gives: home, an empty piece, foo, two dots, bar, and another empty piece. Each piece is a step.

A folder name goes one level deeper, so push it. Two dots mean go up one level, so pop. An empty piece or a single dot means stay where you are, so do nothing.

Folder name: push it.
Two dots: pop one, if there is one.
In code
parts = "/a//b/".split("/")
# ["", "a", "", "b", ""]
Pieces of the example path after splitting it at the slashes.
home
0
1
foo
2
..
3
bar
4
5
i

home is a folder. Push it. Stack: home.

Move 1 of 6

Build the answer from the stack

Two dots at the very top level have nowhere to go, so they are ignored: only pop when the stack is not empty.

When all the pieces are done, the stack holds the folders from the root to where you ended. Join them with slashes and put one slash at the front. If the stack is empty, the answer is just the root, a single slash.

Two dots at the root: do nothing.
Answer: a slash, then the folders joined with slashes.
In code
stack = ["home", "bar"]
path = "/" + "/".join(stack)
# "/home/bar"
Quick check

What is the simplified form of /a/./b/../../c/?

  1. A/c
  2. B/a/c
  3. C/
Show the answer

/c. Into a, into b, back out of b, back out of a, then into c.

Your problem

Simplify path

You are given an absolute path for a Unix-style file system, starting with a slash. A single dot means the current folder, two dots mean go up one folder (stepping up from the root stays at the root), and multiple slashes in a row count as one. Return the simplified canonical path: it starts with a slash, folders are separated by a single slash, there is no trailing slash (unless it is the root), and it has no dots standing for the current or parent folder.

Example
path = "/home//foo/../bar/" → "/home/bar"

1 ≤ length of path ≤ 3,000 · path has letters, digits, . _ - and / · it starts with /

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve