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
Trailing slash removed.
Navigates up from b to a to root, then to c.
Cannot go above root.
Algorithm Flow

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 /.
Time O(n), Space O(n).
Best Answers
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);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
