Simplify Path
Problem Statement
You are given an absolute Unix-style file path path (it always starts with /). Rewrite it in its shortest, canonical form.
The rules of the path:
.means the current folder, so it changes nothing...means the parent folder. At the root/, there is no parent, so you stay at the root.- Several slashes in a row (
//,///) count as one/. - Any other piece is a folder name, including things like
...or..a.
The canonical path starts with a single /, has exactly one / between folder names, does not end with / (unless it is just /), and contains no . or .. pieces.
A string path.
The simplified canonical path as a string.
The trailing slash is dropped.
The double slash counts as one.
.. goes back up from Documents to user, then we enter Pictures.
The root has no parent, so .. keeps us at the root.
... is an ordinary folder name. a is undone by the .. after it, c by the next .., and . changes nothing.
- • 1 ≤ path.length ≤ 3000
- • path contains English letters, digits, '.', '/' and '_'
- • path is a valid absolute Unix path
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Repeatedly collapse "//", remove "/./", and cancel "/name/../" pairs
Skip "" and ".", pop on ".." if not empty, push any other name; join with '/'
Add a / at the end so every name is followed by /. Then keep applying the first rule that matches, searching from the start each time: // → /, /./ → /, a leading /../ → /, and /name/../ → / (where name is not ..). When no rule matches, drop the trailing /.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Stack translate into production architectures and low-level memory mechanics.