algoadvance

You are given a string s that consists only of the characters 'I' (increase) and 'D' (decrease). Assume that s has a length n. You need to find a permutation perm of the integers from 0 to n such that for all i:

Clarifying Questions

  1. Input Constraints
    • Is the input string guaranteed to have only characters ‘I’ and ‘D’?
      • Yes, the problem guarantees this constraint.
    • What is the range for the length n?
      • The length can be up to 10,000, as per typical LeetCode problem constraints.
  2. Output Expectations
    • Should the output be any valid permutation that satisfies the condition?
      • Yes, any valid permutation meeting the criteria is acceptable.

Strategy

To solve this problem, we can use a two-pointer technique. Start with the smallest and largest possible numbers, and place them based on the characters in the string:

This approach ensures that all conditions are met with a time complexity of O(n).

Code

def diStringMatch(s: str):
    n = len(s)
    low, high = 0, n
    perm = []
    
    for char in s:
        if char == 'I':
            perm.append(low)
            low += 1
        else:
            perm.append(high)
            high -= 1
    
    # Append the last remaining number which should be same for both low and high
    perm.append(low)  # low and high are the same at this point
    
    return perm

# Example Usage
s = "IDID"
print(diStringMatch(s))  # Output should be a valid permutation like [0, 4, 1, 3, 2]

Time Complexity

Try our interview co-pilot at AlgoAdvance.com