Sponsored
Sponsored
Description: Use two pointers, or indices - one starting at 0 and the other at 'n'. For each 'I' in the string, assign the lowest available number and increment the 'low' index. For each 'D', assign the highest available number and decrement the 'high' index. This approach efficiently fills the permutation array by maximizing the immediate decision at each step.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), excluding the output array.
1#include <stdio.h>
2#include <stdlib.h>
3
4int* diStringMatch(char * s, int* returnSize){
5 int n = strlen(s);
6 int* result = (int*)malloc((n + 1) * sizeof(int));
7 int low = 0, high = n, i;
8 for(i = 0; i < n; ++i) {
9 result[i] = s[i] == 'I' ? low++ : high--;
10 }
11 result[n] = low; // or result[n] = high since low == high
12 *returnSize = n + 1;
13 return result;
14}
This C solution uses a two-pointer approach. It initializes 'low' and 'high' to track the currently available smallest and largest numbers. As it iterates through the string 's', it assigns numbers based on whether 'I' or 'D' is encountered, thereby constructing the permutation.
Description: The Greedy Character Matching approach involves tracking two dynamic bounds, 'low' and 'high', to determine at every step what the current optimal choice for our permutation should be. By iterating over the string 's', for every 'I', append the current lowest available integer and increment it. For 'D', add the current highest integer and decrement it, ensuring the correct permutation ordering through direct engagement with the constraints.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), discounting the result storage.
1 public int[] DiStringMatch(string s) {
int n = s.Length;
int[] result = new int[n + 1];
int low = 0, high = n;
for (int i = 0; i < n; i++) {
result[i] = s[i] == 'I' ? low++ : high--;
}
result[n] = low;
return result;
}
}
By consistently applying the lowest and highest number logic within bounds decisions, this C# code gracefully establishes perm through greed-coupled character handling and placement.