Code Logo

Simplify Path

Published at23 Jul 2026
Easy 0 views
Like0

Given an absolute Unix-style file path as a string, simplify it to its canonical form. The path starts with / and contains directory names separated by slashes. A single dot . refers to the current directory. A double dot .. refers to the parent directory. Multiple consecutive slashes should be treated as a single slash.

A stack handles this naturally: split the path by slashes, iterate through each part. If the part is .., pop from the stack (go up one directory). If the part is . or empty, skip it. Otherwise, push the part onto the stack (enter the directory). At the end, join the stack with slashes and prepend /.

For example, "/home//foo/" simplifies to "/home/foo". "/a/./b/../../c/" simplifies to "/c".

This problem tests understanding of stack operations in a practical context. The stack-based approach is the standard solution and runs in linear time. It is commonly asked in entry-level interviews to assess fundamental data structure knowledge.

The stack is the natural data structure here because directory navigation follows a LIFO pattern: when you go into a directory you push it, and when you go up with ".." you pop the most recent directory. This directly mirrors how a stack works. Edge cases include paths that try to go above root (which is ignored), empty paths, and paths with only slashes.

Example Input & Output

Example 1
Input
/home/
Output
/home
Explanation

Trailing slash removed.

Example 2
Input
/a/./b/../../c/
Output
/c
Explanation

Navigates up from b to a to root, then to c.

Example 3
Input
/../
Output
/
Explanation

Cannot go above root.

Algorithm Flow

Recommendation Algorithm Flow for Simplify Path
Recommendation Algorithm Flow for Simplify Path

Solution Approach

Split the path by slashes. Use a stack. For each part: if .. and stack not empty, pop. If not . and not empty, push. Join with / and prepend /.

function solution(path) {
  var stack = [];
  var parts = path.split("/");
  for (var i = 0; i < parts.length; i++) {
    var p = parts[i];
    if (p === "..") { if (stack.length) stack.pop(); }
    else if (p !== "." && p !== "") stack.push(p);
  }
  return "/" + stack.join("/");
}

Time O(n), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public String solution(String path) {
        Stack<String> stack = new Stack<>();
        for (String p : path.split("/")) {
            if (p.equals("..")) { if (!stack.isEmpty()) stack.pop(); }
            else if (!p.isEmpty() && !p.equals(".")) stack.push(p);
        }
        return "/" + String.join("/", stack);
    }
}