55. Simplify Path
mediumAsked at OlaSimplify a Unix-style absolute path.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string path representing an absolute path on a Unix-style file system, convert it to the simplified canonical path. Handle '.', '..', and multiple slashes.
Constraints
1 <= path.length <= 3000path consists of English letters, digits, period '.', slash '/' or '_'path is a valid absolute Unix path
Examples
Example 1
path = "/home/""/home"Example 2
path = "/a/./b/../../c/""/c"Approaches
1. Regex passes
Repeatedly collapse slashes, single dots, and double dots until stable.
- Time
- O(n^2)
- Space
- O(n)
while (path.includes('//')) path = path.replace(/\/+/g,'/');
// repeated replace; messyTradeoff:
2. Stack of directory names
Split by '/'; push non-empty/non-dot names; pop on '..'. Join with '/'.
- Time
- O(n)
- Space
- O(n)
function simplifyPath(path) {
const stack = [];
for (const part of path.split('/')) {
if (part === '' || part === '.') continue;
if (part === '..') stack.pop();
else stack.push(part);
}
return '/' + stack.join('/');
}Tradeoff:
Ola-specific tips
Ola uses this to test string-tokenization fluency; tie it to canonicalizing a chained dispatch hop trail into the smallest representable route.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Simplify Path and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →