#71

Simplify Path

Medium
StringStackStackString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to efficiently manage the directory components. This approach processes each component exactly once, making it much faster.

⚙️

Algorithm

4 steps
  1. 1Step 1: Split the input path by '/' to get all components.
  2. 2Step 2: Initialize an empty stack to keep track of valid directory names.
  3. 3Step 3: Iterate through each component and handle '.', '..', and valid directory names.
  4. 4Step 4: After processing all components, join the stack to form the simplified path.
solution.py12 lines
1def simplifyPath(path):
2    parts = path.split('/')
3    stack = []
4    for part in parts:
5        if part == '' or part == '.':
6            continue
7        if part == '..':
8            if stack:
9                stack.pop()
10        else:
11            stack.append(part)
12    return '/' + '/'.join(stack)

Complexity note: The complexity is O(n) because we process each component of the path exactly once, and the space complexity is O(n) due to the stack storing the valid directory names.

  • 1Understanding how to manipulate strings and manage directory structures is crucial.
  • 2Using a stack helps efficiently manage the directory levels.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.