Simplify Path

You are given an absolute Unix-style path that starts with a slash. Return its simplified canonical form. A single period `.` means the current directory, a double period `..` moves up to the parent directory, and several consecutive slashes count as one. Any other name, including names made only of periods such as `...`, is a regular directory name. The canonical path starts with one slash, separates directory names with exactly one slash, does not end with a slash (unless it is the root `/`), and contains no `.` or `..` parts.

30:00

Simplify Path
medium
Free written solution
Topics
Companies

You are given an absolute Unix-style path that starts with a slash. Return its simplified canonical form. A single period . means the current directory, a double period .. moves up to the parent directory, and several consecutive slashes count as one. Any other name, including names made only of periods such as ..., is a regular directory name.

The canonical path starts with one slash, separates directory names with exactly one slash, does not end with a slash (unless it is the root /), and contains no . or .. parts.

Example 1:
Input: {"path":"/home/"}
Output: /home
Constraints:
  • 1≤path.length≤30001 \leq \text{path.length} \leq 3000

  • path consists of English letters, digits, period ., slash / or underscore _.

  • path is a valid absolute Unix path.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"path":"/home/"}

path split on "/" (3 parts)

 
/
home
/
 

pushed

".." popped

ignored

Split "/home/" on "/" into 3 parts and start at the root with an empty folder stack.

current part

·

split on "/"

Each part between slashes is one instruction.

ignored so far: 0

folder stack (deepest on top)

/ root

depth 0

current directory

/

Variables
VariableValue
stack[]
cwd/
DepthFunction Call
Stack empty
0/4