Quick Overview

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

Normalize a file path

Company: Bridge.Xyz

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

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.

Quick Answer: 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 (ignored at the root). - 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 `/` Note: tokens like `...` or `.....` are NOT special — they are valid directory names and must be kept. Example: - Input: `/a//b/./c/../d/` - Output: `/a/b/d`

Constraints

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

Examples

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

Expected Output: /a/b/d

Explanation: Collapse '//' to one slash, drop '.', and '..' removes 'c'; trailing slash trimmed.

Input: /

Expected Output: /

Explanation: Root path stays as a single slash.

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 '/'.

Loading coding console...