Canonicalize an Absolute Unix-Style Path With Dot and Double-Dot Segments
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Convert an absolute Unix-style file path into its canonical form by collapsing repeated slashes, dropping single-dot segments, resolving double-dot segments against the parent directory, and treating other dot sequences as ordinary names. It tests careful string parsing and edge cases such as the root directory.
Constraints
- 1 <= len(path) <= 3000
- path consists of English letters, digits, '.', '/', and '_'.
- path is a valid absolute Unix path and starts with '/'.
Examples
Input: ('/home//foo/',)
Expected Output: '/home/foo'
Explanation: Source example 1: the double slash collapses and the trailing slash is removed.
Input: ('/../',)
Expected Output: '/'
Explanation: Source example 2: moving up from the root stays at the root.
Hints
- Only a component that is exactly '.' or exactly '..' is special; '...', '.a', 'a..' and similar pieces are ordinary names.
- A '..' cancels only the most recently kept name, and has no effect once you are back at the root.
- Repeated slashes and a trailing slash never contribute a component of their own, so the answer depends only on the non-empty pieces between slashes.