Arrays & Hashing · Pattern 7 of 26
In-place transformations
Reuse the input as your memory. Values in 1..n can mark "seen" by flipping the sign at an index; a matrix can store its own flags in its first row and column.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- O(1) extra space is required
- Values are in the range 1..n (they can be used as indexes)
- Update a matrix based on its old state
The template
// values are in 1..n: mark "seen" by making nums[value - 1] negative
List<Integer> findDuplicatesList(int[] nums) {
List<Integer> out = new ArrayList<>();
for (int x : nums) {
int i = Math.abs(x) - 1;
if (nums[i] < 0) out.add(i + 1); // already marked: seen twice
else nums[i] = -nums[i];
}
return out;
}
int[] findDuplicates(int[] nums) {
return findDuplicatesList(nums).stream().mapToInt(Integer::intValue).toArray();
} def find_duplicates(nums): # values are in 1..n
out = []
for x in nums:
i = abs(x) - 1
if nums[i] < 0:
out.append(i + 1) # already marked: seen twice
else:
nums[i] = -nums[i] # mark value i + 1 as seen
return out // values are in 1..n: mark "seen" by making nums[value - 1] negative
vector<int> findDuplicates(vector<int>& nums) {
vector<int> out;
for (int x : nums) {
int i = abs(x) - 1;
if (nums[i] < 0) out.push_back(i + 1); // already marked: seen twice
else nums[i] = -nums[i];
}
return out;
} // values are in 1..n: mark "seen" by making nums[value - 1] negative
function findDuplicates(nums) {
const out = [];
for (const x of nums) {
const i = Math.abs(x) - 1;
if (nums[i] < 0) out.push(i + 1); // already marked: seen twice
else nums[i] = -nums[i];
}
return out;
} The variations
-
1Mark with signs or with the index itself
When values fit in 1..n, the array is its own hash set: flip a sign, or swap each value into its home index (cyclic sort), then scan for the first mismatch.
Now you solve -
2Use the matrix to store its own flags
Keep "this row/column has a zero" in the first row and column (and one extra variable). For Game of Life, encode old and new state in two bits of each cell.
Now you solve- Game of Life Medium Stuck? solution
-
3Rotate by transpose and reverse
Rotating 90° clockwise = transpose, then reverse each row. No extra matrix.
Mistakes to avoid
- Reading
nums[i]after you flipped its sign: always useabs. - Setting matrix cells to zero while still scanning, which spreads zeros. Record flags first, apply them after.
- For first missing positive, forgetting to ignore values ≤ 0 or > n.
Lesson done
Next: Merge sort, and counting while you merge →Mark it done once you can write the template from memory and you have solved the worked examples yourself.