Prefix State Map
Algorithm
Pseudo Code
int ans = 0; // the length of the optimal subarray
int state = 0; // assume the initial state is 0
unordered_map<int, int> m{{0, -1}}; // let -1 be the index of state `0`.
for (int i = 0; i < A.size(); ++i) {
state = nextState(state, A[i]); // update state using A[i]
int prefixState = getPrefixState(state); // based on problem description, we can compute a prefix state using the current state.
ans = max(ans, i - m[prefixState]); // Use `min` if we are looking for the shortest subarray.
m[state] = min(m[state], i); // Use `max` if we are looking for the shortest subarray.
}Problems
Last updated