Simplify Path

Clean up a Unix file path by removing extra slashes, single dots and the steps that go back up.

On Unix systems such as Linux and macOS, the place of a file is written as a path like /home/foo. Each name in it is a directory (a folder), inside the directory named before it. A path that starts with a slash is an absolute path: the first slash stands for the top directory, called the root.

Given an absolute path as a string path, return its simplified form, following these rules:

The simplified form starts with a single slash, separates directory names with single slashes, and has no slash at the end.

Example 1
Input: path = "/home/"
Output: "/home"
Example 2
Input: path = "/../"
Output: "/"
Example 3
Input: path = "/home//foo/"
Output: "/home/foo"
Example 4
Input: path = "/a/./b/../../c/"
Output: "/c"
Solution

The Idea

If you have used a terminal, you have probably typed cd .. to go up one folder. A path can hold the same moves written inline. Reading "/a/./b/../../c/" from left to right is like following directions: go into a, stay where you are, go into b, go up, go up again, go into c. You end up in /c, which is the answer to Example 4.

The single dots and the extra slashes are easy, because they never move you anywhere. The real question is the "..". When one turns up, which directory does it take you out of?

Always the one you entered most recently and have not left yet. The first ".." leaves b, the last directory entered. The second one leaves a, because b is already gone. Look at the picture below.

The path /a/./b/../../c/ split into the parts "", a, ., b, .., .., c. Empty parts and the dot are skipped, names are pushed onto the stack, and each .. pops the top name. The stack ends holding only c.

The row labelled "part" holds the pieces between the slashes, read left to right. The first piece is empty, because nothing comes before the first slash. Below each part, the row labelled "action" says what it does, and the bottom row, labelled "directories we are inside", shows where we are after it.

Follow the bottom row. a is added, the dot changes nothing, and b goes on top of a. The first ".." takes away b, the top one, and the second takes away a. Then c is added, and c alone is left: the path /c.

A pile where you only ever add to the top and take from the top is called a stack. Adding is called push and taking the top away is called pop. A directory name is pushed, and each ".." pops the name that was pushed last.

Solution Approach

Turning that idea into code means settling three things: how to break the path into parts, what each part does to the stack, and how to build the simplified path from what is left on it.

Breaking the path into parts

How do we get the parts out of the string? Java's String.split("/") cuts a string at every slash and returns the pieces in an array. Two slashes in a row have nothing between them, so they give an empty piece, and so does the leading slash. A slash at the end gives no piece at all, because split drops empty pieces at the end of the array.

So every extra slash turns into an empty string, and skipping empty strings is all it takes to treat several slashes as one.

What each part does to the stack

Which parts change the stack? Empty parts and "." are skipped. A ".." pops the top name, but only if the stack has one: an empty stack means we are at the root, and going up from the root does nothing. Every other part is a directory name and is pushed, even "...", which only looks like a special part.

Building the simplified path

Which order should the names come out in? The bottom of the stack holds the outermost directory, so the path is written from the bottom up, each name with a slash before it. If the stack is empty, the answer is the root, "/".

A plain stack only lets us take from the top, which would give the names backwards. Java's ArrayDeque helps here. It is a double-ended queue, a list that can add and remove at both ends. Its push and pop work at the front, which acts as the top of the stack. Its pollLast removes from the other end, the bottom.

Java Solution

The method simplifyPath works in these steps:

  1. First, create the stack, dirs, as an ArrayDeque<String>. It holds the directories we are inside.
  2. Split path with path.split("/"), and loop over the pieces, calling each one part.
  3. If part is empty or ".", skip it with continue.
  4. If part is "..", pop the top name from dirs, but only when dirs is not empty.
  5. Otherwise part is a directory name, so push it onto dirs.
  6. After the loop, build the answer in a StringBuilder named result. A second loop takes names from the bottom of dirs with pollLast() and appends each one after a slash.
  7. Return "/" if result is still empty, and the text in result otherwise.

The main method runs the four examples, a path with more ".." parts than directories, the name "...", a path full of extra slashes and dots, and the root on its own.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class SimplifyPath {

    public static String simplifyPath(String path) {
        Deque<String> dirs = new ArrayDeque<>();
        for (String part : path.split("/")) {
            if (part.isEmpty() || part.equals(".")) {
                continue;                       // from "//" or "."
            }
            if (part.equals("..")) {
                if (!dirs.isEmpty()) {
                    dirs.pop();                 // go up one level; at the root nothing happens
                }
            } else {
                dirs.push(part);
            }
        }
        StringBuilder result = new StringBuilder();
        while (!dirs.isEmpty()) {
            result.append('/').append(dirs.pollLast());   // bottom of the stack first
        }
        return result.length() == 0 ? "/" : result.toString();
    }

    public static void main(String[] args) {
        String[] paths = {
            "/home/", "/../", "/home//foo/", "/a/./b/../../c/",
            "/a/../../b", "/...", "/a//b////c/d//././/..", "/"
        };
        for (String path : paths) {
            System.out.println(path + " -> " + simplifyPath(path));
        }
    }
}

Running it prints:

Output
/home/ -> /home
/../ -> /
/home//foo/ -> /home/foo
/a/./b/../../c/ -> /c
/a/../../b -> /b
/... -> /...
/a//b////c/d//././/.. -> /a/b/c
/ -> /

Each line shows a path, an arrow, and its simplified form. Look at /a/../../b -> /b. The first ".." pops a, and the second finds the stack empty, so it does nothing, just like cd .. at the root. Then b is pushed.

The line /... -> /... keeps its three dots, because only one or two dots have a special meaning. In /a//b////c/d//././/.. -> /a/b/c, the empty parts and single dots are all skipped, and the final ".." pops d.

The isEmpty() check before pop() matters. ArrayDeque.pop() on an empty deque throws an exception. Without the check, the input "/../" from the second line stops the program with a java.util.NoSuchElementException instead of printing /.

The original implementation, SimplifyPath.java, is on GitHub.

Complexity

The work is one split of the path, one push or pop per part, and one pass to write the answer.

  • Time: O(n) for a path of n characters. split reads each character once, each name is pushed at most once and popped at most once, and the final loop writes at most n characters.
  • Space: O(n). The array of parts from split and the names on the stack are pieces of the path, so together they hold at most its n characters.

The same "push, then pop on a step back" idea solves Removing Stars From a String.