Stacks and Queues Matching and cancelling
201. Simplify Path
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...,..aand.bare 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/"
"/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/../.."
"/"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"
"/.../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.
Constraints
1 ≤ path.length ≤ 105pathholds only English letters, digits,'.','_'and'/'pathstarts with'/'
Clarifying questions
What you would ask an interviewer before writing any code.