DI String Match

easy greedy two pointers string

Problem

A permutation perm of the integers in the range [0, n] is encoded by a string s of length n where s[i] == 'I' means perm[i] < perm[i+1] and s[i] == 'D' means perm[i] > perm[i+1]. Given such a string s, reconstruct and return any permutation perm that matches it. There is always at least one valid answer.

Inputs = "IDID"
Output[0, 4, 1, 3, 2]
n = 4, so the permutation uses 0..4. Each 'I' rises and each 'D' falls: 0<4, 4>1, 1<3, 3>2.

def di_string_match(s):
    low, high = 0, len(s)
    perm = []
    for ch in s:
        if ch == 'I':
            perm.append(low)
            low += 1
        else:
            perm.append(high)
            high -= 1
    perm.append(low)
    return perm
function diStringMatch(s) {
  let low = 0, high = s.length;
  const perm = [];
  for (const ch of s) {
    if (ch === 'I') {
      perm.push(low);
      low++;
    } else {
      perm.push(high);
      high--;
    }
  }
  perm.push(low);
  return perm;
}
class Solution {
    public int[] diStringMatch(String s) {
        int low = 0, high = s.length();
        int[] perm = new int[s.length() + 1];
        int idx = 0;
        for (char ch : s.toCharArray()) {
            if (ch == 'I') perm[idx++] = low++;
            else perm[idx++] = high--;
        }
        perm[idx] = low;
        return perm;
    }
}
vector<int> diStringMatch(string s) {
    int low = 0, high = (int)s.size();
    vector<int> perm;
    for (char ch : s) {
        if (ch == 'I') perm.push_back(low++);
        else perm.push_back(high--);
    }
    perm.push_back(low);
    return perm;
}
Time: O(n) Space: O(n)