Simplify Path Medium 0 attempts
LeetCode ↗

Simplify Path

Medium StringHash Table LeetCode

You're given an absolute path in a Unix-style file system. Convert it into its canonical (simplified) form.

Along the way: a "." segment means stay in the current directory and can be dropped, a ".." segment means step up to the parent directory, consecutive slashes collapse into one, and a trailing slash gets stripped. The simplified path always begins with exactly one "/".

Input Format
Implement simplifyPath(path). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

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
Test Cases (2)
Case 1
Args: ["/home/"] Expected: "/home"
Case 2
Args: ["/../.../a/./"] Expected: "/.../a"

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.

Saved in this browser only. Private to you.

JavaScript