Mark Elements That Repeat Later
viaLeetCode
Problem Transform an array in place: element becomes 1 if the SAME value appears again LATER in the array, else 0.
Input / Output
- Input: int array. Output: 0/1 array per the rule.
Constraints
- n up to 10^5; O(n) expected.
Example
- [1,2,1,3,2] → [1,1,0,0,0] (the first 1 and first 2 repeat later; last occurrences and 3 do not).
Expected approach
- Right-to-left sweep with a seen-set: for i from n−1 down: result[i] = seen.contains(a[i]) ? 1 : 0; then add a[i]. One pass, O(n)/O(n) — the direction insight ("later" = already-seen when scanning backwards) is the whole question. Left-to-right alternative: precompute last-occurrence index per value, then result[i] = (lastIndex[a[i]] > i). In-place value overwriting requires saving originals (or the backward sweep order) — the standard trap.
asked …