Opening the reading…
Opening the reading…
GAME THEORY › LEVEL I
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 →Raze can mark only odd-numbered positions, while Breach can mark only even-numbered positions. Therefore, neither player can remove a position belonging to the other player's group. The game lasts until exactly one position remains, so the only question is which group contains that unavoidable survivor.
When n is odd, there is one more odd-numbered position than even-numbered positions. Breach can mark every even position, while Raze cannot mark all odd positions, so the final position is an odd-numbered one. Raze can choose which odd position to leave, and wins if at least one such digit is odd.
When n is even, the two groups have the same size, but Raze moves one more time because the total number of moves is odd. Raze removes every odd-numbered position, leaving an even-numbered position for the final move. Breach can choose which even position survives, so Breach wins if any even-numbered position contains an even digit.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The scan visits only one parity group, which contains at most n positions, and each visited character is converted and checked once. It stops early when a winning digit is found, so no position is processed more than once. |
| Space | O(1) extra | The algorithm stores only n, the loop index, and a few scalar values. The input string is not counted as working memory, and there is no returned collection to exclude; the bound stays constant even in the worst case when the scan reaches its last candidate. |
#include <string>
using namespace std;
class Solution {
public:
int digitGame(string s) {
int n = static_cast<int>(s.size());
if (n % 2 == 1) {
for (int i = 0; i < n; i += 2) {
if ((s[i] - '0') % 2 == 1) {
return 1;
}
}
return 2;
}
for (int i = 1; i < n; i += 2) {
if ((s[i] - '0') % 2 == 0) {
return 2;
}
}
return 1;
}
};The loop starts at index 0 for odd n because index 0 represents position 1, an odd-numbered position. It starts at index 1 for even n because index 1 represents position 2, an even-numbered position. The character expression s[i] - '0' converts the decimal character to its numeric digit value, so the parity test matches the winning rule exactly.