Taro Logo

Simplify Path

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+17
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.5K views
Topics:
StringsStacks

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:

  • A single period '.' represents the current directory.
  • A double period '..' represents the previous/parent directory.
  • Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'.
  • Any sequence of periods that does not match the rules above should be treated as a valid directory or file name. For example, '...' and '....' are valid directory or file names.

The simplified canonical path should follow these rules:

  • The path must start with a single slash '/'.
  • Directories within the path must be separated by exactly one slash '/'.
  • The path must not end with a slash '/', unless it is the root directory.
  • The path must not have any single or double periods ('.' 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 <= 3000
  • path consists of English letters, digits, period '.', slash '/' or '_'.
  • path is a valid absolute Unix path.

Solution


Clarifying Questions

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:

  1. How should we handle paths that attempt to go above the root directory (e.g., `/../` or `/a/../../b`), and is it guaranteed that the input string is a valid absolute path starting with a slash?
  2. How should multiple consecutive slashes (e.g., `//` or `///`) and current directory references (`/.`) be treated throughout the path?
  3. What should be returned for edge cases like an empty string, a single slash `"/"`, or a path consisting entirely of dots and slashes (e.g., `"/.././"`)?
  4. Can the directory or file names contain special characters, spaces, or periods (other than single `.` and double `..`), such as hidden files like `/.config`?
  5. Are there any memory or length constraints on the input `path` string that I should be aware of?

Brute Force Solution

Approach

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:

  1. Look at the entire messy path from start to finish as one giant jumbled instruction manual.
  2. Propose a guess by rewriting the whole journey from the very beginning.
  3. Examine your newly written journey to see if it contains any shortcuts, backtracking steps, or clumsy double pauses.
  4. If you find any messy parts in your current guess, completely erase your work and start over with a slightly different set of guesses.
  5. Exhaust every single possible combination of moving forward and backward through the original text until you have tested every conceivable route.
  6. Compare all the completed routes you generated along the way.
  7. Pick the final surviving route that represents the most direct and simplified path possible.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n!) – To find the simplified path using this brute force strategy, we must test every conceivable permutation and combination of moving forward, stepping backward, and rewriting the entire path from scratch for the input string of length n. Because we exhaust every possible route and completely re-evaluate the sequence at every turn, the number of total operations grows factorially with the size of the input. This combinatorial explosion means the process scales as approximately n multiplied by (n-1) multiplied by (n-2) down to 1 operations, which simplifies to the factorial time complexity of O(n!).
Space Complexity
O(n) – To clean up the messy path, we use an auxiliary stack data structure and a temporary list of directory names split from the input string of length N. In the worst-case scenario where every component is a valid directory name, the stack and the split components array will each store up to N characters. Therefore, the extra memory required scales linearly with the input size N, leading to an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

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:

  1. Split the entire path into distinct pieces by looking between every forward slash.
  2. Go through each piece one by one from the beginning to the end.
  3. If you encounter a standard folder name, add it to your current list of where you are located.
  4. If you encounter a command to go up a level, remove the most recent folder you added from your list.
  5. Ignore any empty pieces or marks that simply mean stay in the current folder, as they do not change your location.
  6. After checking every piece, join all the remaining folders together with a single slash between them and make sure to start with a slash at the very beginning.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the input path string. First, splitting the path by forward slashes and iterating through each resulting piece takes linear time proportional to the number of characters. Second, pushing and popping standard folder names onto our location list uses constant time per operation, visiting each piece at most once. Summing these linear passes together results in approximately n operations, which simplifies to O(n).
Space Complexity
O(N) – The space complexity is driven by the components described in the plain English steps, specifically the auxiliary data structures used to track the path. When we split the input path of size N into distinct pieces and build a list of valid folder names, we store intermediate results. In the worst-case scenario where the path consists entirely of standard folder names, the stack-like list will hold all components simultaneously. Therefore, the extra memory required grows linearly with the input size, simplifying to Big O notation of O(N).

Edge Cases

Multiple consecutive slashes such as //a//b
How to Handle:
Splitting the string by slashes naturally produces empty strings that can be ignored during processing.
Current directory references like . or ./
How to Handle:
The stack-based approach explicitly skips single-dot components since they represent the current directory.
Parent directory references like .. at the root level
How to Handle:
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 ///
How to Handle:
After filtering out empty components, the stack remains empty and defaults to returning the root slash.
Path with trailing slashes like /a/b/
How to Handle:
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
How to Handle:
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
How to Handle:
Linear time complexity ensures the solution processes the entire path in a single pass without exceeding memory or time limits.
0/75 completed