Skip to content
Decoder

Simplify Path

Medium

Problem

Given an absolute Unix-style file path path (it starts with /), return its simplified canonical form. The rules:

- . means the current folder and can be dropped. - .. means go up one folder. Going up from the root / stays at the root. - Several slashes in a row, like //, count as one. - Any other name, including ..., is a normal folder name.

The canonical path starts with a single /, separates folder names with single slashes, and has no trailing slash (unless it is just /).

Example 1

Input
"/home/"
Output
"/home"

Example 2

Input
"/home//foo/"
Output
"/home/foo"

Example 3

Input
"/home/user/Documents/../Pictures"
Output
"/home/user/Pictures"

Example 4

Input
"/../"
Output
"/"

Constraints

  • 1 <= path.length <= 3000
  • path contains English letters, digits, ., / and _.
  • path is a valid absolute path.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.