InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Simplify Path

medium Original ↗ 00:00

Problem

Given an absolute Unix-style file path (a string starting with /), reduce it to its canonical form:

  • A single dot . means “current directory” — it disappears.
  • A double dot .. means “go up one directory” — it removes the previous directory name (at the root it does nothing).
  • Multiple consecutive slashes collapse into one.
  • Any other run of characters between slashes — including names like ... or a..b — is a legitimate directory name and must be kept verbatim.

The canonical path must start with exactly one /, use single slashes between names, not end with a trailing slash (unless the whole path is just /), and contain no . or .. components.

Examples

Example 1

Input: path = "/home//foo/./" Output: "/home/foo" Explanation: the double slash collapses, . is dropped, and the trailing slash is removed.

Example 2

Input: path = "/a/b/../../c/" Output: "/c" Explanation: the first .. cancels b, the second cancels a, leaving only c.

Example 3

Input: path = "/../.../up" Output: "/.../up" Explanation: .. at the root is a no-op, and ... is an ordinary directory name, not a “go up twice.”

Constraints

  • 1 <= path.length <= 3000
  • path consists of letters, digits, ., /, and _, and begins with /.
  • A single linear pass is expected — O(n) time.

Think about it first

Hint 1 Split the path on `/`. What do the empty pieces produced by `//` and by the leading slash correspond to?
Hint 2 `..` undoes the most recently entered directory. Which data structure gives you constant-time "undo the most recent thing"?
Hint 3 Walk the split components with a stack: skip `""` and `"."`; pop (if non-empty) on `".."`; push anything else. The answer is `"/" + "/".join(stack)`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug