LeetCode 942: DI String Match Solution
Master LeetCode problem 942 (DI String Match), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
942. DI String Match
Problem Explanation
Explanation:
To solve this problem, we can start by observing that the permutation is always [0, 1, 2, ..., n] in ascending order. The given string s determines whether the next number in the permutation should be the current minimum or maximum available number.
We can iterate through the string s and maintain two pointers, one pointing to the minimum number available and the other pointing to the maximum number available. If we encounter an 'I', we pick the minimum number available, and if we encounter a 'D', we pick the maximum number available.
Solution Code
class Solution {
public int[] diStringMatch(String s) {
int n = s.length();
int[] perm = new int[n + 1];
int min = 0, max = n;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'I') {
perm[i] = min++;
} else {
perm[i] = max--;
}
}
perm[n] = min; // or max, as they are equal at this point
return perm;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 942 (DI String Match)?
This page provides optimized solutions for LeetCode problem 942 (DI String Match) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 942 (DI String Match)?
The time complexity for LeetCode 942 (DI String Match) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 942 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 942 in Java, C++, or Python.