You are given an absolute path for a Unix-style file system, which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path.
The rules of a Unix-style file system are as follows:
'.' represents the current directory.'..' represents the previous/parent directory.'//' and '///' are treated as a single slash '/'.'...' and '....' are valid directory or file names.The simplified canonical path should follow these rules:
'/'.'/'.'/', unless it is the root directory.'.' and '..') used to denote current or parent directories.Return the simplified canonical path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation:
The trailing slash should be removed.
Example 2:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation:
Multiple consecutive slashes are replaced by a single one.
Example 3:
Input: path = "/home/user/Documents/../Pictures"
Output: "/home/user/Pictures"
Explanation:
A double period ".." refers to the directory up a level (the parent directory).
Example 4:
Input: path = "/../"
Output: "/"
Explanation:
Going one level up from the root directory is not possible.
Example 5:
Input: path = "/.../a/../b/c/../d/./"
Output: "/.../b/d"
Explanation:
"..." is a valid name for a directory in this problem.
Constraints:
1 <= path.length <= 3000path consists of English letters, digits, period '.', slash '/' or '_'.path is a valid absolute Unix path.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are standing at the beginning of a messy file path containing messy shortcuts and distractions. The brute force strategy involves testing every single way to step forward, step backward, and skip around, completely rewriting the entire path from scratch at every single turn until you somehow stumble upon the cleanest possible version.
Here's how the algorithm would work step-by-step:
def simplifyPath(path):
# We must explore all potential routing permutations because brute force tests every route
def generate_all_route_guesses(remaining_segments, current_route_guess):
if not remaining_segments:
return [current_route_guess]
current_segment = remaining_segments[0]
next_segments = remaining_segments[1:]
routes_accumulator = []
if current_segment == ".." or current_segment == "." or current_segment == "":
routes_accumulator.extend(generate_all_route_guesses(next_segments, current_route_guess))
routes_accumulator.extend(generate_all_route_guesses(next_segments, current_route_guess + [current_segment]))
else:
routes_accumulator.extend(generate_all_route_guesses(next_segments, current_route_guess + [current_segment]))
return routes_accumulator
path_segments = path.split("/")
all_route_permutations = generate_all_route_guesses(path_segments, [])
valid_canonical_routes = []
# Filtering is necessary to discard paths that violate Unix directory navigation rules
for route_guess in all_route_permutations:
stack_accumulator = []
is_route_valid = True
for segment in route_guess:
if segment == "..":
if stack_accumulator:
stack_accumulator.pop()
else:
is_route_valid = False
break
elif segment == "." or segment == "":
continue
else:
stack_accumulator.append(segment)
if is_route_valid:
valid_canonical_routes.append(stack_accumulator)
if not valid_canonical_routes:
return "/"
shortest_length = float('inf')
optimal_chosen_route = []
# We compare every surviving route to select the most direct and simplified path
for candidate_route in valid_canonical_routes:
route_length = len(candidate_route)
if route_length <= shortest_length:
shortest_length = route_length
optimal_chosen_route = candidate_route
return "/" + "/".join(optimal_chosen_route)Imagine you are following a set of directions on a scratchpad where you can easily write down or erase your current location. By breaking down the path into individual parts, you can step forward when entering a folder and step backward when hitting a command to go up a level.
Here's how the algorithm would work step-by-step:
def simplify_path(absolute_path): directory_stack = [] # Splitting by slash isolates every component so we can process folder navigation sequentially. for path_component in absolute_path.split('/'): # Going up a directory requires removing the last visited folder to properly track our current depth. if path_component == '..': if directory_stack: directory_stack.pop() elif path_component and path_component != '.': directory_stack.append(path_component) # Rebuilding the path with leading slashes ensures absolute path format and prevents empty output strings. return '/' + '/'.join(directory_stack)| Case | How to Handle |
|---|---|
| Multiple consecutive slashes such as //a//b | Splitting the string by slashes naturally produces empty strings that can be ignored during processing. |
| Current directory references like . or ./ | The stack-based approach explicitly skips single-dot components since they represent the current directory. |
| Parent directory references like .. at the root level | The stack checks if it is empty before popping, preventing out-of-bounds errors when trying to go above the root. |
| Path consisting of only slashes like / or /// | After filtering out empty components, the stack remains empty and defaults to returning the root slash. |
| Path with trailing slashes like /a/b/ | The final string construction joins stack elements with a single slash, naturally stripping any trailing slash except for the root. |
| Directory names containing dots like .foo or ..bar | Valid file and directory names that start with dots are treated as regular directory names rather than navigation commands. |
| Extremely long paths with thousands of nested directories | Linear time complexity ensures the solution processes the entire path in a single pass without exceeding memory or time limits. |