Problem 296135 · medium · Level 02 Linear Data Structures

Tidy a Folder Address

stacks · strings · parsing

A file manager receives a folder address path typed by a user. It always starts at the root /, but it may be untidy. Return the tidy address of the same folder, following these rules:

  • folder names are separated by a single /, and a run of slashes such as // acts like one;
  • the name . means "stay in this folder" and simply disappears;
  • the name .. steps back to the parent folder; at the root there is no parent, so it does nothing;
  • the tidy address begins with /, contains no . or .. names, and does not end with / unless it is the root / itself.

Every other name, even an odd one such as ... or .hidden, is an ordinary folder name.

Examples

Input:  path = "/var///cache//"
Output: "/var/cache"

Input:  path = "/srv/./www/../logs/"
Output: "/srv/logs"

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

Constraints

  • 1 <= len(path) <= 5000
  • Target: O(n) time

Goals

  • Split a path into components and treat each as a stack operation
  • Handle `.`, `..`, empty components and the root correctly
Starting Python…