cswork / libraryOpen practice workspace

Coding questions · Bridge

Normalize a file path

This question evaluates string manipulation and parsing skills, specifically understanding Unix-style filesystem path semantics and edge-case normalization.

Given an absolute Unix-style file path as a string, return its canonical normalized form.

Rules:

  • The input always starts with /.
  • A single . means the current directory and should be ignored.
  • A double dot .. means move to the parent directory if possible.
  • Multiple consecutive slashes should be treated as a single slash.
  • The output must:
    • start with exactly one /
    • contain directory names separated by a single slash
    • not end with a trailing slash unless the result is the root path /

Example:

  • Input: /a//b/./c/../d/
  • Output: /a/b/d

Explain your approach and implement the function.

Normalize a Unix File Path

Constraints

  • 1 <= path.length <= 3000
  • path consists of English letters, digits, '.', '/', and '_'
  • path is a valid absolute Unix path beginning with '/'

Hints

  1. Split the path on '/' and process each component left to right with a stack.
  2. Empty strings (from consecutive or trailing slashes) and '.' are no-ops; '..' pops the stack only if it is non-empty.
  3. Tokens like '...' or '..foo' are ordinary directory names — only the exact strings '.' and '..' are special.
  4. Rebuild the answer by joining the stack with '/' and prefixing a single '/'; an empty stack yields the root '/'.