In-place Operations

Basic Algorithms
≈ 2 min read

Changing data without an additional array

An operation is called in-place when the main result is produced directly inside the original data structure, while the amount of extra memory does not grow with the input size. For an array, this usually means rearranging or overwriting its elements instead of creating a second array of the same length.

A classic example is reversing an array. We can swap symmetric elements while moving from the edges toward the center.

int left = 0;
int right = numbers.length - 1;

while (left < right) {
    int temp = numbers[left];
    numbers[left] = numbers[right];
    numbers[right] = temp;

    left++;
    right--;
}

The algorithm runs in O(n) time and uses O(1) extra space: regardless of the array size, only a few variables are needed.

Overwriting can be safe

To modify an array in place, it is important to understand which old values are no longer needed. For example, if every negative number must be replaced with zero, the old value can be overwritten immediately after the check.

for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] < 0) {
        numbers[i] = 0;
    }
}

But not every problem should be forced into an in-place solution. Sometimes a separate array makes the code simpler or is required by the problem — for example, when the original data must remain unchanged.

In-place does not mean "no memory at all." Local variables such as left, right, and temp are fine. What matters is that extra space remains O(1) instead of growing with n.