DSA · Stack · #163
Simplify Path
Module 45 · difficulty 3/5·⏱ 30:00starts on first keystroke
Given an absolute path `path` for a Unix-style file system, transform it into its **simplified canonical path**. In a Unix-style file system a single period `.` refers to the current directory, a double period `..` refers to the parent directory, and any sequence of multiple consecutive slashes (e.g. `//`) is treated as a single slash `/`. For this problem, any other sequence of periods (e.g. `...`) is treated as a valid directory/file name. The canonical path must: - Start with a single slash `/`. - Have exactly one slash between two directory names. - Not end with a trailing slash (unless it is the root). - Not contain any `.` or `..` components. Implement `simplifyPath(path)` returning the canonical path as a string.
Examples
path = "/home/"→"/home"— The trailing slash is removed.path = "/../"→"/"— Going up from root stays at root.path = "/home//foo/"→"/home/foo"— Multiple consecutive slashes collapse into one.
Constraints
- · 1 <= path.length <= 3000
- · path consists of English letters, digits, '.', '/', and '_'.
- · path is a valid absolute Unix path, beginning with '/'.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.