Simplify Path

Medium · Stack & Monotonic Stack · about 15 minutes

Asked at Meta, Amazon, Google, Microsoft, Bloomberg, Snowflake, Datadog, CrowdStrike, Elastic, Rubrik, Glean, Akamai.

Given an absolute Unix-style path (starting with '/'), return its simplified canonical form:

  • "." means the current directory and ".." the parent (at the root, ".." stays at the root),
  • several consecutive slashes count as one,
  • any other name, such as "...", is a normal directory name.

The canonical path starts with a single '/', separates directories by single slashes, and has no trailing slash (except the root "/" itself).