Problem 296135 · medium · Phase 02 Linear Data Structures

Canonical Directory Path

stacks · strings · parsing

Given an absolute Unix-style path path (it always starts with /), return its canonical form:

  • a single / separates directories; repeated slashes such as // count as one;
  • . means the current directory and is ignored;
  • .. moves up one directory (moving up from the root stays at the root);
  • the result starts with /, has no trailing / (except when it is the root itself), and contains no . or .. components.

Any other component (including names like ... or .hidden) is an ordinary directory name.

Examples

Input:  path = "/home//foo/"
Output: "/home/foo"

Input:  path = "/a/./b/../../c/"
Output: "/c"

Input:  path = "/../"
Output: "/"

Constraints

  • 1 <= len(path) <= 5000
  • Target: O(n) time

Goals

  • Split a path into components and treat each as a stack operation
  • Handle `.`, `..`, empty components and the root correctly
Starting Python…