In-Place Removal of Specific Array Values

The objective is to modify an integer array by removing all instances of a specific value directly within the original memory space. The function must return the new length of the array after removal.

Constraints and Mechanics

The solution must adhere to strict space complexity requirements:

  • O(1) Extra Space: No additional arrays or data structures are permitted.
  • In-Place Modification: The input array must be altered directly.
  • Order Irrelevance: The relative order of remaining elements does not need to be preserved.
  • Ignored Tail: Elements beyond the returned new length are irrelevant.

Since arrays are passed by reference in many languages, modifying the content within the function reflects on the caller's side. The returned integer indicates how many elements at the beginning of the array are valid.

Example Scenarios

  1. Input: [3, 2, 2, 3], Target: 3

    • Result: Length 2, Valid content [2, 2].
    • Elements beyond index 1 are ignored.
  2. Input: [0, 1, 2, 2, 3, 0, 4, 2], Target: 2

    • Result: Length 5, Valid content [0, 1, 3, 0, 4] (order may vary).

Algorithmic Approach

The optimal strategy utilizes a two-pointer technique. One pointer tracks the position for writing valid elements, while the other iterates through the array to read elements.

  1. Initialize a write pointer at the start of the array.
  2. Iterate through each element using a read pointer.
  3. If the current element does not match the target value, copy it to the write pointer's position and increment the write pointer.
  4. If it matches, skip the copy operation.
  5. The final position of the write pointer represents the new length.

Implementation

The following Java implementation demonstrates this logic using a while loop structure to manage iteration explicitly.

public class ArrayModifier {
    public int removeTargetValue(int[] data, int target) {
        int writePosition = 0;
        int readPosition = 0;
        
        while (readPosition < data.length) {
            if (data[readPosition] != target) {
                data[writePosition] = data[readPosition];
                writePosition++;
            }
            readPosition++;
        }
        
        return writePosition;
    }
}

This approach ensures linear time complexity O(n) while maintaining constant space complexity O(1).

Tags: Arrays two-pointers in-place-algorithm java data-structures

Posted on Wed, 03 Jun 2026 17:23:48 +0000 by jordy