InterviewPrepKit

Home / Coding / Stack

Simplify Path

medium Original ↗
Solving tips
  • Tokenize first: split on '/', then each component is one decision, with '..' meaning 'undo the most recent directory' which is a stack pop.
  • Skip empty strings (from // and the leading /) and '.'; push everything else, including tricky names like '...' and 'a..b' which are ordinary directories.
  • Guard the pop: '..' at the root (empty stack) must be a silent no-op, not an error.
  • Build the answer as '/' + '/'.join(stack), which naturally yields '/' for an empty stack; target O(n) time and O(n) space.

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 "undo the most recent thing" for free?
Hint 3 Walk the split components with a stack: skip `""` and `"."`; pop (if non-empty) on `".."`; push anything else. The answer is `"/" + "/".join(stack)`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.