Resolve a Simplified Absolute File Path

Implement resolvePath

Given an absolute Unix-style file path path, simplify it into its canonical form: collapse multiple consecutive slashes into one, drop every "." segment (it means "stay here"), and resolve every ".." segment by cancelling out the directory segment immediately before it. Since ".." only ever needs to know the single most recently resolved segment — nothing deeper — a stackStackA LIFO (Last In, First Out) structure. Path resolution only ever needs to inspect or cancel the most recently added segment, never anything beneath it, which is exactly what a stack exposes for free. is the natural fit: push real directory names, skip "." entirely, and pop on "..". Rebuilding the resolved path from a string every time "..\" appears works but wastes effort re-deriving something a stack already knows in O(1) — its own top.

Example 1:

Input: path = "/docs//reports/"

Output: "/docs/reports"

Example 2:

Input: path = "/pics/vids/../../gallery"

Output: "/gallery"

Example 3:

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

Output: "/x/z"

+ 6 hidden test cases run on Submit.

Constraints:

  • 1 ≤ path.length ≤ 40
  • path is a valid absolute Unix-style path starting with '/'
  • Path segments are separated by '/', and may include '.' (current directory), '..' (parent directory), multiple consecutive slashes, or ordinary directory names of lowercase letters
  • The simplified path must not end with a trailing '/', unless it is the root "/" itself

path =

/docs//reports/