Normalize a Filesystem Location String
Stacks & QueuesAuto-graded · 23 test casesLast 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.cfgor..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) <= 3000locationcontains only English letters, digits,.,/, and_.locationis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the input on / to get a list of pieces, then walk through them while maintaining a stack of directory names that represents the current position relative to the root.
For each piece:
- If it is empty (caused by a leading slash, repeated slashes, or a trailing slash) or exactly
., ignore it, since neither changes the current location. - If it is exactly
.., pop the top of the stack if the stack is not empty. If it is empty we are at the root, and the root's parent is the root, so nothing happens. - Otherwise it is a regular name (this includes
...,.hidden,..a), so push it.
At the end, return "/" followed by the stack entries joined with /. An empty stack yields just "/", which is the root.
Why it is correct
After processing the first k pieces, the stack holds exactly the list of directory names on the path from the root to the location reached by following those k pieces. Initially we are at the root and the stack is empty. Ignored pieces do not move us. A regular name moves us one level down, which is a push. .. moves us one level up, which removes the last name, or does nothing at the root. Since every stack entry is a non-empty regular name, joining them with single slashes after one leading slash gives a result with a single leading slash, single separators, no . or .. components, and no trailing slash except for the root.
Complexity
- Time: O(n), where n is the length of the input. Splitting, the single pass (each piece pushed and popped at most once), and the join are all linear.
- Space: O(n) for the pieces, the stack, and the output.
Reference solution
def normalize_location(location):
names = []
for piece in location.split("/"):
if piece == "" or piece == ".":
continue
if piece == "..":
if names:
names.pop()
else:
names.append(piece)
return "/" + "/".join(names)