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.

3 variations · 5 problems · 2 with animated walkthroughs

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

In-place Transformations
// 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();
}

The variations

  1. 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.

  2. 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
  3. 3Rotate by transpose and reverse

    Rotating 90° clockwise = transpose, then reverse each row. No extra matrix.

    Worked example Rotate Image Medium Read the solution

Mistakes to avoid

  • Reading nums[i] after you flipped its sign: always use abs.
  • 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.
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.