oneby7

Stacks and Queues Matching and cancelling

201. Simplify Path

Medium

You are given path, an absolute path in a Unix-style file system. It starts at the root directory / and lists directory names separated by slashes. Return the simplified form of the path: the shortest path that leads to the same directory.

Read from left to right, the parts between the slashes mean:

  • . is the current directory, so it changes nothing.
  • .. moves up to the parent directory. The root has no parent, so .. at the root stays at the root.
  • Two or more slashes in a row count as one slash.
  • Any other part is the name of a directory to move into. Only a part that is exactly . or .. is special, so ..., ..a and .b are ordinary names.

The simplified path starts with a single /, has exactly one / between two names, and holds no . or .. parts. It does not end with /, unless it is the root itself, /.

Answers are shown in double quotes.

Example 1

Input: path = "/home/./docs//notes/../photos/"

Output: "/home/docs/photos"

Explanation: We go into home, stay put on ., and go into docs (the two slashes count as one). Then we go into notes and back up out of it, so photos is inside docs. The slash at the end is dropped.

Example 2

Input: path = "/../x/../.."

Output: "/"

Explanation: The first .. is at the root, so we stay there. We go into x and back out, and the last .. is at the root again.

Example 3

Input: path = "/.../a/..b/./.c"

Output: "/.../a/..b/.c"

Explanation: ..., ..b and .c are names, because none of them is exactly . or ... Only the lone . is removed.

Check your understanding

Work out the answer for this input before you write any code.

path = "/a/b/../../c/"

Constraints

  • 1 ≤ path.length ≤ 105
  • path holds only English letters, digits, '.', '_' and '/'
  • path starts with '/'

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.