Skip to the code
cf.
+25 XP

#252 Normalize an Asset Path

medium

A static site builder receives asset paths written by hand, such as /src/./img/../css//main.css, and must turn them into a clean form before looking them up.

Write normalizePath(path) for an absolute path that starts with /. Split it on / into parts. A part . means the current folder and is dropped. A part .. means the parent folder and removes the previous folder, but at the root it does nothing. Empty parts from repeated slashes are dropped. Any other part, including ..., is a folder or file name.

Return the clean path: / followed by the remaining names joined with /. The root alone is /, and the result never ends with / otherwise.

Example 1

Input: path = "/src/./img/../css//main.css"
Output: "/src/css/main.css"

. is dropped, .. removes img, and the double slash is one slash.

Example 2

Input: path = "/../"
Output: "/"

.. at the root does nothing.

Constraints

  • 1 <= path.length <= 3000
  • path starts with / and has letters, digits, ., _, and /.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).