Simplify Path Medium 0 attempts
LeetCode ↗

Simplify Path

Medium StringHash Table LeetCode

Given an absolute Unix-style file path, simplify it to its canonical form.

Rules: "." refers to the current directory, ".." moves up one directory, multiple consecutive slashes are treated as a single slash, and any trailing slash is removed. The result always starts with a single "/".

Examples

Input: path = "/home/"
Output: "/home"
Input: path = "/home//foo/"
Output: "/home/foo"
Input: path = "/a/./b/../../c/"
Output: "/c"
Input: path = "/../"
Output: "/"
Explanation: Can't go above root.

Constraints

  • 1 <= path.length <= 3000
  • path consists of English letters, digits, '.', '/', or '_'.
Sample Input
path = "/home/"
Sample Output
"/home"
Constraints
  • 1 <= path.length <= 3000
  • path consists of English letters, digits, period, slash, or underscore
Test Cases
Case 1
Args: ["/home/"] Expected: "/home"

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.

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