Skip to the content

Lesson 118 of 296

Arrays: in-place changes, reversing, rotating

What you will learn

  • What "in place" means
  • Reversing an array with two indexes
  • Rotating an array
  • Removing items in place
  • Product of Array Except Self
On this page

Arrays in memory

An array stores items next to each other in memory, so reading arr[i] is O(1): the computer calculates the position directly. Inserting or deleting in the middle is O(n), because later items must shift.

In place

An algorithm works in place when it changes the input array directly, using only O(1) extra memory. Interviewers often ask "can you do it in place?". Always ask whether you are allowed to change the input.

Swapping two items

TypeScript
function swap<T>(arr: T[], i: number, j: number): void {
  const temp = arr[i]!;
  arr[i] = arr[j]!;
  arr[j] = temp;
}

You can also write [arr[i], arr[j]] = [arr[j], arr[i]] with destructuring.

Reverse in place

Use two indexes: one at the start, one at the end. Swap them, move both towards the middle, stop when they meet.

TypeScript
function reverseInPlace<T>(arr: T[]): T[] {
  let left = 0;
  let right = arr.length - 1;
  while (left < right) {
    const temp = arr[left]!;
    arr[left] = arr[right]!;
    arr[right] = temp;
    left++;
    right--;
  }
  return arr;
}

O(n) time, O(1) space. This "two pointers from both ends" idea returns in Lesson 123.

Rotate an array to the right by k

[1, 2, 3, 4, 5, 6, 7] rotated by 3 becomes [5, 6, 7, 1, 2, 3, 4].

Simple way, O(n) extra space:

TypeScript
function rotateCopy(nums: number[], k: number): number[] {
  const n = nums.length;
  if (n === 0) return [];
  const steps = k % n;
  return [...nums.slice(n - steps), ...nums.slice(0, n - steps)];
}

k % n matters: rotating 7 items by 10 is the same as rotating by 3.

In place with three reversals, O(1) extra space:

  1. Reverse the whole array: [7, 6, 5, 4, 3, 2, 1]
  2. Reverse the first k items: [5, 6, 7, 4, 3, 2, 1]
  3. Reverse the rest: [5, 6, 7, 1, 2, 3, 4]
TypeScript
function reverseRange(nums: number[], start: number, end: number): void {
  while (start < end) {
    const temp = nums[start]!;
    nums[start] = nums[end]!;
    nums[end] = temp;
    start++;
    end--;
  }
}

function rotateInPlace(nums: number[], k: number): void {
  const n = nums.length;
  if (n === 0) return;
  const steps = k % n;
  reverseRange(nums, 0, n - 1);
  reverseRange(nums, 0, steps - 1);
  reverseRange(nums, steps, n - 1);
}

Remove items in place

"Remove every val from nums in place and return the new length." Use a write pointer: copy every item you want to keep to the front.

TypeScript
function removeElement(nums: number[], val: number): number {
  let write = 0;
  for (let read = 0; read < nums.length; read++) {
    if (nums[read] !== val) {
      nums[write] = nums[read]!;
      write++;
    }
  }
  return write;
}

The first write items are the kept ones. O(n) time, O(1) space. The same "read pointer and write pointer" trick removes duplicates from a sorted array and moves zeros to the end.

Product of Array Except Self

Problem (LeetCode 238): return an array where each position holds the product of all other numbers. Do it in O(n) without division.
[1, 2, 3, 4] gives [24, 12, 8, 6].

Brute force: for each index, multiply all the others: O(n²).

Idea: the answer at i = (product of everything left of i) × (product of everything right of i).

  • First pass, left to right: store the product of everything to the left.
  • Second pass, right to left: multiply by a running product of everything to the right.
TypeScript
function productExceptSelf(nums: number[]): number[] {
  const n = nums.length;
  const result = new Array<number>(n).fill(1);

  let leftProduct = 1;
  for (let i = 0; i < n; i++) {
    result[i] = leftProduct;
    leftProduct *= nums[i]!;
  }

  let rightProduct = 1;
  for (let i = n - 1; i >= 0; i--) {
    result[i] = result[i]! * rightProduct;
    rightProduct *= nums[i]!;
  }
  return result;
}

Trace with [1, 2, 3, 4]:

Passresult after the pass
After left pass[1, 1, 2, 6] (products of items on the left)
After right pass[24, 12, 8, 6]

O(n) time, O(1) extra space (the output array does not count).

Why "without division"? Dividing the total product by each number fails when the array contains a zero.

How to say it in an interview

"Array access by index is O(1), but inserting or removing in the middle is O(n). For in-place work I use two pointers: from both ends to reverse, or a read and write pointer to filter. Rotation can be done in place with three reversals, using k modulo n. For product except self I build prefix products from the left and multiply in suffix products from the right, which is O(n) time without division and O(1) extra space."

Key words

WordMeaning
In placeChanging the input directly with O(1) extra memory
SwapExchange two items
Read / write pointerOne index scans, the other marks where to write
Prefix productThe product of all items before an index
Suffix productThe product of all items after an index

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.