Ctrl K

Tidy a Folder Route

Medium
A user typed an absolute path route into a file manager's address bar; it always starts with a slash /. Reduce it to its short canonical form. How a path is read: - . is the current folder and can simply be skipped; - .. moves up to the parent folder; at the root there is nowhere to go, so .. does nothing there; - several slashes in a row (//, ///) count as one; - any other run of dots, such as ... or ...., is an ordinary folder name. The canonical path starts with a single /, separates folders with exactly one slash, has no trailing slash (unless the whole path is the root /), and contains no . or .. steps. Return it as a string.
Example 1
route="/docs//drafts/./final/" → '/docs/drafts/final'

The double slash collapses, . means "stay here", and the trailing slash is dropped.

Example 2
route="/music/rock/../jazz/.." → '/music'

We step back from rock into music, enter jazz, then step back up again, leaving /music.

Example 3
route="/../../.../x" → '/.../x'

You cannot climb above the root, and ... is just an ordinary folder name.

Constraints
  • 1 ≤ len(route) ≤ 3000
  • route consists of English letters, digits, ., / and _
  • route starts with /
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFour-Operation Calculator MediumEvery Letter Once MediumChecking a Tree Record With Hash Marks MediumLongest Path to a File MediumExpand Repeat Brackets Medium
loading Python…
Input
route="/docs//drafts/./final/"
Expected
'/docs/drafts/final'

Run checks the first 3 tests in your browser. Submit checks all 201 tests on the server, hidden ones included.