Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Stack & Queue

Simplify a Unix Path

Medium · Stack & Queue · Asked at Meta, Amazon, Microsoft, Google

Simplify an absolute Unix-style path:

Print the canonical path: it starts with a single /, directories are separated by single /, and there is no trailing / (unless the path is just /).

Input

A single line with the path (starts with /).

Output

The simplified path.

Constraints

Split on /, then use a stack of names: skip empty parts and ., pop on .., push anything else. Join the stack with /.

Example 1

Input

/home/

Output

/home

Example 2

Input

/a/./b/../../c/

Output

/c

Example 3

Input

/../

Output

/

Hints

  1. Split the path on "/" — empty pieces come from repeated slashes.
  2. The directories you are inside form a stack.
  3. "." does nothing, ".." pops, anything else (even "...") is pushed.

Approach

Split by '/', and for every piece: skip it if empty or ".", pop the stack (if not empty) for "..", otherwise push the name. The answer is "/" followed by the stack joined with "/" — which is just "/" when the stack is empty.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string path, part;
    cin >> path;
    vector<string> st;
    stringstream ss(path);
    while (getline(ss, part, '/')) {
        if (part.empty() || part == ".") continue;
        if (part == "..") {
            if (!st.empty()) st.pop_back();
        } else st.push_back(part);
    }
    string out;
    for (auto &p : st) out += "/" + p;
    cout << (out.empty() ? "/" : out) << "\n";
    return 0;
}

Python solution

path = input().strip()
st = []
for part in path.split("/"):
    if part in ("", "."):
        continue
    if part == "..":
        if st:
            st.pop()
    else:
        st.append(part)
print("/" + "/".join(st))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String path = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
        ArrayDeque<String> st = new ArrayDeque<>();
        for (String part : path.split("/")) {
            if (part.isEmpty() || part.equals(".")) continue;
            if (part.equals("..")) {
                if (!st.isEmpty()) st.pollLast();
            } else st.addLast(part);
        }
        StringBuilder sb = new StringBuilder();
        for (String p : st) sb.append('/').append(p);
        System.out.println(sb.length() == 0 ? "/" : sb.toString());
    }
}

Solve Simplify a Unix Path online · All practice problems