Simplify Path
Asked at OpenAI
Problem
Given a Unix-style absolute file path, simplify it by resolving dots, double dots, and multiple slashes. The simplified path must be absolute, start with a single slash, and have no trailing slash unless it is the root directory.
Asked At
| Company | Difficulty | |
|---|---|---|
| OpenAI | MEDIUM | View all OpenAI questions → |
How to Think About It
Split the path by "/" delimiter to get individual components
Use a stack to process each component sequentially
Push valid directory names onto the stack
Pop from stack when encountering ".." (go up one directory)
Ignore "." and empty components, join stack with "/" for result
Optimal Approach
Split the path by "/" to get components. Use a stack to track directory names. For each component: if it is "." or empty, skip; if it is "..", pop from stack if non-empty; otherwise push the component onto the stack. Join the stack with "/" and prepend a leading slash to form the simplified absolute path.
What Trips People Up in Real Interviews
Clarify how to handle edge cases like multiple consecutive slashes
Explain that ".." at root level should not go above root
Discuss why a stack is natural for this directory traversal problem
Mention the importance of not adding trailing slashes
Consider how the solution handles paths like "/../" or "/./"
Solution Code
def simplifyPath(path):
stack = []
for component in path.split("/"):
if component == "..":
if stack:
stack.pop()
elif component and component != ".":
stack.append(component)
return "/" + "/".join(stack)Frequently Asked Questions
What is the Simplify Path problem?
Given a Unix-style absolute file path, simplify it by resolving dots, double dots, and multiple slashes. The simplified path must be absolute, start with a single slash, and have no trailing slash unless it is the root directory.
How do you solve Simplify Path?
The optimal approach is described in detail above, including step-by-step walkthroughs, complexity analysis, and solution code in Python. Scroll up to the "Optimal Approach" section.
What companies ask Simplify Path?
Simplify Path is asked at OpenAI. It is a medium difficulty problem.
What are common mistakes on Simplify Path?
- Clarify how to handle edge cases like multiple consecutive slashes
- Explain that ".." at root level should not go above root
- Discuss why a stack is natural for this directory traversal problem
- Mention the importance of not adding trailing slashes
- Consider how the solution handles paths like "/../" or "/./"