Loading content...
You are given an integer array nums and an integer val. Your task is to eliminate all occurrences of val from the array in-place, meaning you must modify the original array directly without allocating additional space for another array.
The relative order of elements that remain may be changed—what matters is the count and presence of non-matching elements.
Your function should return k, the number of elements in nums that are not equal to val. After your function executes, the first k positions of the array should contain only elements that are not equal to val. The elements beyond index k-1 are irrelevant and can hold any value.
Validation Criteria:
The solution will be validated as follows:
int[] nums = [...]; // Input array
int val = ...; // Value to filter out
int[] expected = [...]; // Expected elements (excluding val), sorted
int k = filterArrayByValue(nums, val); // Your implementation
assert k == expected.length;
sort(nums, 0, k); // Sort first k elements
for (int i = 0; i < k; i++) {
assert nums[i] == expected[i];
}
If all assertions pass, your solution is correct.
nums = [3,2,2,3]
val = 32The function returns k = 2, indicating that two elements remain after removing all occurrences of 3. The first two positions of nums now contain [2, 2]. The values at positions beyond k are irrelevant (represented as underscores: [2, 2, _, _]).
nums = [0,1,2,2,3,0,4,2]
val = 25The function returns k = 5, meaning five elements remain after filtering out all 2s. The first five positions contain the values 0, 1, 3, 0, and 4 in some order. Elements beyond index 4 are irrelevant: [0, 1, 3, 0, 4, _, _, _].
nums = [1,2,3,4,5]
val = 65Since 6 does not appear in the array, no elements are removed. All 5 elements remain, and the array stays as [1, 2, 3, 4, 5].
Constraints