Problem description

You are given a string that represents an absolute path in a Unix-style file system, always beginning with a single slash. The path may contain redundant elements: a single period refers to the current directory, a double period refers to the parent directory, and repeated slashes act as a single separator.

Transform the path into its canonical form. The canonical path starts with exactly one slash, joins directory names with a single slash between them, never ends with a trailing slash unless it is the root, and contains no period or double-period components.

Return the simplified canonical path as a string.

Example 1

Input: path = "/home//foo/"

Output: "/home/foo"

Multiple slashes collapse into one and the trailing slash is removed, leaving two real directories.

Example 2

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

Output: "/c"

The '.' is ignored, and each '..' cancels the most recent directory, so a and b are removed before c is appended.

Constraints

  • 1 <= path.length <= 3000
  • path consists of English letters, digits, period '.', slash '/' or underscore '_'.
  • path is a valid absolute Unix path.

After the pattern

Now solve one you haven't seen.

Canonical Store Locator is our own problem on the technique behind Simplify Path: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free