Efficient Solutions for Common Array Manipulation Problems
Merging Two Sorted Arrays
Approach:
Use two pointers starting from the end of both arrays and fill the result array from the end to avoid overwriting.
Implementation:
class ArrayMerger {
public void combineSortedArrays(int[] primary, int size1, int[] secondary, int size2) {
int position = primary.length - 1;
int ptr1 = size1 - 1, ptr2 = size2 - 1;
while (ptr1 >= 0 && ptr2 >= 0) {
if (primary[ptr1] > secondary[ptr2]) {
primary[position--] = primary[ptr1--];
} else {
primary[position--] = secondary[ptr2--];
}
}
while (ptr1 >= 0) primary[position--] = primary[ptr1--];
while (ptr2 >= 0) primary[position--] = secondary[ptr2--];
}
}
Removing Specific Elements
Approach:
Miantain two pointers where one traverses the array while the other builds the result by skipping unwanted values.
Implementation:
class ElementRemover {
public int filterElements(int[] data, int target) {
int resultIndex = 0;
for (int current : data) {
if (current != target) {
data[resultIndex++] = current;
}
}
return resultIndex;
}
}
Eliminating Duplicates from Sorted Array
Approach:
Use two pointers to track unique elements, comparing each element with its predecessor.
Implementation:
class DuplicateHandler {
public int removeDuplicates(int[] sortedData) {
if (sortedData.length == 0) return 0;
int uniqueCount = 1;
for (int i = 1; i < sortedData.length; i++) {
if (sortedData[i] != sortedData[i-1]) {
sortedData[uniqueCount++] = sortedData[i];
}
}
return uniqueCount;
}
}
Handling Duplicates with Limited Occurrences
Approach:
Allow up to two duplicates by comparing elements with the one two positions back in the result array.
Implementation:
class LimitedDuplicateHandler {
public int removeExcessDuplicates(int[] nums) {
if (nums.length <= 2) return nums.length;
int validIndex = 2;
for (int j = 2; j < nums.length; j++) {
if (nums[j] != nums[validIndex-2]) {
nums[validIndex++] = nums[j];
}
}
return validIndex;
}
}
Finding the Dominant Element
Approach:
The majority element will always be at the middle position in a sorted array.
Implementation:
class MajorityFinder {
public int findDominantElement(int[] elements) {
Arrays.sort(elements);
return elements[elements.length / 2];
}
}
Rotating Array Elements
Approach:
Reverse the entire array, then reverse the first k elements and the remaining elements separately.
Implementation:
class ArrayRotator {
public void circularShift(int[] arr, int rotations) {
rotations %= arr.length;
reverseSegment(arr, 0, arr.length - 1);
reverseSegment(arr, 0, rotations - 1);
reverseSegment(arr, rotations, arr.length - 1);
}
private void reverseSegment(int[] array, int start, int end) {
while (start < end) {
int temp = array[start];
array[start++] = array[end];
array[end--] = temp;
}
}
}