KatInterview

Normalize a Filesystem Location String

Stacks & QueuesAuto-graded · 23 test cases
MediumAuto-gradedStacks & Queuesstackstring-parsingsimulation

Last updated

Reduce an absolute Unix-style path to its canonical form by resolving repeated slashes, current-directory and parent-directory segments, using a stack.

Normalize a Filesystem Location String

You are given a string location that describes an absolute location in a Unix-style file system. Produce the shortest equivalent form of that location, called its canonical form.

How to read the input

The string always begins with /. Treat it as a series of segments separated by slashes, and interpret each segment as follows:

  • A segment that is exactly . means "stay in the current directory". It contributes nothing to the result.
  • A segment that is exactly .. means "go up to the parent directory". If you are already at the root, you stay at the root.
  • Several slashes in a row (such as // or ///) count as one single separator, so they produce no empty segments.
  • Every other segment is a regular name and is kept as is. This includes segments made of three or more dots (like ...) and names that merely begin with dots (like .cfg or ..x). Only the exact strings . and .. are special.

Format of the result

The returned string must satisfy all of the following:

  • It begins with exactly one /.
  • Consecutive names are separated by exactly one /.
  • It does not end with /, unless the whole result is just the root /.
  • It contains no . or .. segments.

Task

Implement the function so that it returns the canonical form of location.

Constraints

  • 1 <= len(location) <= 3000
  • location contains only English letters, digits, ., /, and _.
  • location is a valid absolute path (it starts with /).

Examples

Example 1

Input: normalize_location('/home//foo/')

Output: '/home/foo'

Example 2

Input: normalize_location('/../')

Output: '/'

Example 3

Input: normalize_location('/.../a/../b/c/../d/./')

Output: '/.../b/d'

Hints

Hint 1

Break the string apart on the slash character and look at the pieces one by one. Think about which pieces are empty and what they mean.

Hint 2

Keep a stack of the directory names you are currently inside. Going up with `..` undoes the most recent descent, which is last-in, first-out behavior.

Hint 3

Compare each piece to `.` and `..` with exact equality, not a prefix check. Guard the pop so `..` at the root does nothing, and build the answer as a leading slash plus the names joined by slashes.