Simplify Path

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an absolute path for a Unix-style file system, which begins with a slash '/', transform this path into its simplified canonical path.

In Unix-style file system context, a single period '.' signifies the current directory, a double period '..' denotes moving up one directory level, and multiple consecutive slashes such as '//' are interpreted as a single slash. In this problem, treat sequences of periods not covered by the previous rules (like '...') as valid names for files or directories.

The simplified canonical path should adhere to the following rules:

  • It must start with a single slash '/'.
  • Directories within the path must be separated by exactly one slash '/'.
  • It must not end with a slash '/', unless it's the root directory.
  • It must not include any single or double periods used to denote current or parent directories.

Examples

Example 1:

Input: path = "/home/"

Output: "/home"

Example 2:

Input: path = "/home//foo/"

Output: "/home/foo"

Example 3:

Input: path = "/home/user/Documents/../Pictures"

Output: "/home/user/Pictures"

Example 4:

Input: path = "/../"

Output: "/"

Constraints

  • 1 <= path.length <= 3000
  • path consists of English letters, digits, period '.', slash '/' or underscore '_'
  • path is a valid absolute Unix path
Source: Stacks pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle