MediumStringStack

Simplify Path

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now