The optimal solution uses the two-pointer technique to modify the array in-place. One pointer traverses the array, while another pointer keeps track of the position where the next valid element should be placed.
Whenever an element different from the target value is encountered, it is copied to the current insertion position and the insertion pointer is incremented. After processing all elements, the insertion pointer represents the new length of the modified array.
This approach satisfies the in-place requirement and avoids allocating additional memory.
Java Solution:
public class RemoveElement {
public static int removeElement(int[] nums, int valueToRemove) {
int insertPosition = 0;
for (int currentIndex = 0; currentIndex < nums.length; currentIndex++) {
if (nums[currentIndex] != valueToRemove) {
nums[insertPosition] = nums[currentIndex];
insertPosition++;
}
}
return insertPosition;
}
public static void main(String[] args) {
int[] nums = {3, 2, 2, 3};
int valueToRemove = 3;
int newLength = removeElement(nums, valueToRemove);
System.out.println("New Length: " + newLength);
System.out.print("Modified Array: ");
for (int index = 0; index < newLength; index++) {
System.out.print(nums[index] + " ");
}
}
}Output: New Length: 2 Modified Array: 2 2
Time Complexity: O(n), where n is the number of elements in the array since each element is visited exactly once.
Space Complexity: O(1), as the array is modified in-place without using additional storage.
Key Interview Points: • The two-pointer technique is commonly used for in-place array modification problems. • Only the first newLength elements are considered valid after the operation. • The values beyond the returned length are irrelevant and do not need to be updated. • A common follow-up question is to remove duplicates from a sorted array using a similar approach.