Skip to problem
←

Simplify Path

Medium 0 attempts

Given an absolute Unix-style path, return its canonical form using these rules:

  • An exact . segment means the current directory and is ignored.
  • An exact .. segment removes the last directory, if one exists. You cannot move above the root.
  • Repeated slashes act as one separator.
  • Every other segment is a literal directory name. For example, ..., ..hidden, and a..b are ordinary names.

The result starts with exactly one slash, uses one slash between directory names, and has no trailing slash unless it is the root /. Preserve the spelling and case of directory names. This is a string-processing task; no filesystem access or symbolic-link resolution is needed.

Function contract

Implement simplifyPath(path).

Output: Return the canonical absolute path as a string. The root directory is represented by "/".

Example 1

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

Example 2

Input
path = "/../.../a/./"
Output
"/.../a"
Constraints
  • 1 <= path.length <= 3000
  • path consists of English letters, digits, period, slash, or underscore
  • path is an absolute path and starts with /
Topics

Split the path by "/" and process each component using a stack. Skip empty strings and ".". For "..", pop the stack (if non-empty). Everything else gets pushed. Join the remaining stack elements with "/" at the end.

javascript
function simplifyPath(path) {
  const stack = [];
  const parts = path.split('/');

  for (const part of parts) {
    if (part === '' || part === '.') continue;
    if (part === '..') {
      stack.pop();
    } else {
      stack.push(part);
    }
  }

  return '/' + stack.join('/');
}

Time: O(n) where n is the length of the path string. Space: O(n) for the stack in the worst case.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript