Simplify Path

MediumStackstack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given path, an absolute Unix-style path that always begins with '/'. Convert it to its canonical form and return it. Rules: consecutive slashes act as one; a . segment means the current directory and is dropped; a .. segment moves up to the parent directory (at the root it stays at the root). Any other segment is a directory name, including names made only of dots such as .... The canonical path starts with a single '/', has one slash between names, and has no trailing slash (except for the root "/" itself).

Examples

Input: path = "/home/"
Output: "/home"
The trailing slash is removed.
Input: path = "/a/./b/../../c/"
Output: "/c"
Enter a, stay, enter b, go up twice back to root, then enter c.
Input: path = "/../"
Output: "/"
Going up from the root stays at the root.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More stack problems