Skip to main content

55. Simplify Path

mediumAsked at Ola

Simplify 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 <= 3000
  • path consists of English letters, digits, period '.', slash '/' or '_'
  • path is a valid absolute Unix path

Examples

Example 1

Input
path = "/home/"
Output
"/home"

Example 2

Input
path = "/a/./b/../../c/"
Output
"/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; messy

Tradeoff:

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.

Output

Press Run or Cmd+Enter to execute

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 →