Opening the reading…
Opening the reading…
2 POINTERS › TWO POINTER ON STRINGS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →At position i, the next comparison only asks whether perm[i] must be smaller or larger than the value at position i + 1. If s[i] is I, using the smallest unused number gives the next position room to be larger. If s[i] is D, using the largest unused number gives the next position room to be smaller.
The unused values always form a continuous range from low to high. Taking low for I removes its smallest value, while taking high for D removes its largest value. Neither choice can make a future comparison impossible: an increase consumes the bottom end and a decrease consumes the top end, so every remaining value stays available for later decisions. After n comparisons, one number remains for the last position.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The loop examines each character once and performs only constant-time assignment and pointer updates. Each character removes exactly one value from the unused interval, so no value or character is processed in a second pass. |
| Space | O(1) extra | The low and high variables use constant working memory. The result array takes O(n) space but is required output and is excluded from the extra-space bound. The bound stays O(1) for every input shape, including all I or all D strings. |
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> diStringMatch(string s) {
int n = static_cast<int>(s.size());
vector<int> perm(n + 1);
int low = 0;
int high = n;
for (int i = 0; i < n; ++i) {
if (s[i] == 'I') {
perm[i] = low++;
} else {
perm[i] = high--;
}
}
perm[n] = low;
return perm;
}
};The key placement is perm[i], not perm[i + 1]. At that moment, the only comparison involving this new value that is already known is s[i], so choosing from the matching endpoint guarantees the required direction toward the still-unfilled next position. The final assignment is separate because there is no character after the last output position; its only valid value is the one left unused.