All problems
0351MediumStringStack

Canonical Store Locator

Tracked in this browser only
Write code

Trains the technique from

LeetCode 71Simplify Path

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

An artifact store addresses every folder with a locator that begins at the root, written as /. A locator is a run of pieces separated by /, and the store reads it like this:

  • a piece of . means stay where you are;
  • a piece of .. means step back to the folder that contains the current one, and at the root it does nothing at all;
  • any other piece is a folder name, and names may contain letters, digits, underscores and even runs of dots such as ..., which are ordinary names and not steps;
  • separators may be doubled up, and // behaves exactly like /.

The canonical form of a locator starts with /, puts exactly one / between consecutive folder names, and never ends with / unless it is the root by itself. Given path, return its canonical form.

Examples

Example 1

Input
path = "/store//alpha/"
Output
"/store/alpha"

The doubled separator collapses to one and the trailing separator is dropped, leaving the two folder names in place.

Example 2

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

`.` leaves the position alone, the first `..` undoes `b` and the second undoes `a`, so only `c` is left below the root.

Example 3

Input
path = "/_x/y/.._/.."
Output
"/_x/y"

`.._` is an ordinary folder name, so it is entered like any other, and the final `..` steps back out of it.

Example 4

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

A piece of three dots is a folder name, so the canonical form keeps it.

Constraints

  • 1 <= path.length <= 3000
  • path holds English letters, digits, '.', '/' and '_' only.
  • path is a valid absolute locator, so it starts with '/'.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def simplify_path(path: str) -> str:
Java
public String simplifyPath(String path)
September 7
Apply