#942

DI String Match

Easy
ArrayTwo PointersStringGreedyTwo PointersGreedy
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 approach uses a greedy strategy to construct the permutation directly based on the 'I' and 'D' characters in the string. We can maintain two pointers to fill in the permutation efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array perm of size n + 1 with values from 0 to n.
  2. 2Step 2: Use two pointers: one starting from the beginning (left) and one from the end (right) of the array.
  3. 3Step 3: Iterate through the string s: if s[i] is 'I', assign perm[left] to the result and increment left; if 'D', assign perm[right] to the result and decrement right.
solution.py14 lines
1def diStringMatch(s):
2    n = len(s)
3    perm = list(range(n + 1))
4    left, right = 0, n
5    result = []
6    for char in s:
7        if char == 'I':
8            result.append(perm[left])
9            left += 1
10        else:
11            result.append(perm[right])
12            right -= 1
13    result.append(perm[left])  # Add the last element
14    return result

Complexity note: The time complexity is O(n) because we only make a single pass through the string s and fill the result array in linear time. The space complexity is O(n) due to the result array.

  • 1The 'I' and 'D' characters dictate the order of the numbers directly.
  • 2Using two pointers allows us to fill the permutation efficiently without generating all possibilities.

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