942. DI String Match LeetCode Solution

In this guide, you will get 942. DI String Match LeetCode Solution with the best time and space complexity. The solution to DI String Match problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. DI String Match solution in C++
  4. DI String Match solution in Java
  5. DI String Match solution in Python
  6. Additional Resources
942. DI String Match LeetCode Solution image

Problem Statement of DI String Match

A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

s[i] == ‘I’ if perm[i] perm[i + 1].

Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

Example 1:
Input: s = “IDID”
Output: [0,4,1,3,2]
Example 2:
Input: s = “III”
Output: [0,1,2,3]
Example 3:
Input: s = “DDI”
Output: [3,2,0,1]

Constraints:

1 <= s.length <= 105
s[i] is either 'I' or 'D'.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

942. DI String Match LeetCode Solution in C++

class Solution {
 public:
  vector<int> diStringMatch(string s) {
    vector<int> ans;
    int mn = 0;
    int mx = s.length();

    for (const char c : s)
      ans.push_back(c == 'I' ? mn++ : mx--);
    ans.push_back(mn);

    return ans;
  }
};
/* code provided by PROGIEZ */

942. DI String Match LeetCode Solution in Java

class Solution {
  public int[] diStringMatch(String s) {
    final int n = s.length();
    int[] ans = new int[n + 1];
    int mn = 0;
    int mx = n;

    for (int i = 0; i < n; ++i)
      ans[i] = s.charAt(i) == 'I' ? mn++ : mx--;
    ans[n] = mn;

    return ans;
  }
}
// code provided by PROGIEZ

942. DI String Match LeetCode Solution in Python

class Solution:
  def diStringMatch(self, s: str) -> list[int]:
    ans = []
    mn = 0
    mx = len(s)

    for c in s:
      if c == 'I':
        ans.append(mn)
        mn += 1
      else:
        ans.append(mx)
        mx -= 1

    return ans + [mn]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.