
Problem Statement
In this problem, you are provided with an integer array named nums
and an integer val
. Your task is to remove all occurrences of val
from the array nums
in an in-place manner. The goal is not just to remove these elements but to also return the size of the array after the removals, denoted as k
. The array size k
corresponds to the count of elements in the array nums
that are not equal to val
. The elements post the k
index in the array do not matter and can be any values, hence representing a flexible part of the array not checked by the judge post solution submission.
For the solution to be accepted, change the array nums
such that:
- The first
k
elements contain only those elements that are not equal toval
. - The elements in
nums
beyond the firstk
positions can be any values and are irrelevant to the solution's correctness.
The output, besides the shortened array, is the integer k
, which is the number of elements in the modified array nums
that are not equal to val
.
Examples
Example 1
Input:
nums = [3,2,2,3], val = 3
Output:
2, nums = [2,2,_,_]
Explanation:
Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2
Input:
nums = [0,1,2,2,3,0,4,2], val = 2
Output:
5, nums = [0,1,4,0,3,_,_,_]
Explanation:
Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
Approach and Intuition
Given the problem requirements and constraints, we can frame our approach with the following steps:
- Initialize a counter
k
at 0 which will keep track of all non-val
elements encountered. - Traverse the list
nums
. For each element:- If it is not equal to
val
, place it at the indexk
of the array and incrementk
by 1. This ensures that all non-val
elements are collected from the start of the array. - If it is equal to
val
, simply skip it. That way, the element isn't placed in the firstk
elements ofnums
.
- If it is not equal to
This results in an array where the first k
positions hold the required values, and positions from k
onwards being irrelevant. The value of k
itself represents the number of valid elements and is the required return value.
Using the given examples:
- For
nums = [3,2,2,3], val = 3
, the process will skip all '3's and bring all '2's to the front, resulting innums = [2,2,_,_]
andk = 2
. - For
nums = [0,1,2,2,3,0,4,2], val = 2
, all elements except '2' are shifted to the start givingnums = [0,1,4,0,3,_,_,_]
andk = 5
.
This approach ensures an efficient, in-place modification with a time complexity of O(n) where n is the number of elements in nums
, and the space complexity is O(1), as we do not use any additional significant space.
Solutions
- C++
- Java
- C
- JavaScript
- Python
class Solution {
public:
int deleteElement(vector<int>& elements, int target) {
int index = 0;
int length = elements.size();
while (index < length) {
if (elements[index] == target) {
elements[index] = elements[length - 1];
length--;
} else {
index++;
}
}
return length;
}
};
The provided C++ solution defines a method deleteElement
that efficiently removes all instances of a specified target
value from a given vector of integers elements
. The function operates by using a two-pointer approach where:
- One pointer,
index
, iterates through the vector from the beginning. - Instead of resizing the vector whenever a target element is found, the code swaps the target element with the last non-processed element in the vector and reduces the vector's effective size (
length
).
As a result, each encounter with the target does not require shifting elements, making the overall operation more efficient, especially for larger data sets.
The main features of this function are:
- It loops through the vector up to the current
length
, decrementinglength
whenever a target element is found. - It performs an in-place modification by swapping elements, thus avoiding the creation of a new array.
- The function returns the new length of the vector after all target values have been removed.
The solution leverages efficiency in terms of space by modifying the input array directly without using additional storage, and in terms of time by reducing unnecessary movements of elements.
class Solution {
public int deleteValue(int[] array, int target) {
int k = 0;
int size = array.length;
while (k < size) {
if (array[k] == target) {
array[k] = array[size - 1];
size--;
} else {
k++;
}
}
return size;
}
}
The Java solution presented focuses on removing a specified target value from an array, termed as deleteValue
method in the Solution
class. Follow this method to tackle the given problem:
- Initialize an integer
k
to 0 to act as a pointer while traversing the array and maintain the size of the array withsize
. - Use a
while
loop to iterate through the array untilk
is less thansize
. - Inside the loop, check if the current element at index
k
equals the target value.- If it does, replace the current element with the last element in the active region of the array and decrement
size
. - If it does not, increment
k
to continue checking the next element.
- If it does, replace the current element with the last element in the active region of the array and decrement
- The loop exits when all elements have been checked, resulting in
size
representing the new length of the array after all instances of the target have been removed. - Return
size
, which now indicates how many elements remain in the modified array without the target values.
This approach ensures the array is modified in place, reducing the need for additional memory, and it efficiently handles scenarios where the target value appears multiple times or not at all.
int eraseElement(int* arr, int length, int value) {
int index = 0;
int newLength = length;
while (index < newLength) {
if (arr[index] == value) {
arr[index] = arr[newLength - 1];
newLength--;
} else {
index++;
}
}
return newLength;
}
This solution presents a C language function eraseElement
that takes three parameters: a pointer to an integer array arr
, the length of the array length
, and the integer value
to be removed from the array. The function iterates through the given array, and each occurrence of the specified value is removed by replacing it with the last element in the array, which effectively decreases the array's length each time a matching value is found. The iteration continues until all elements of the array have been checked. Once finished, the function returns the new length of the modified array.
Here's what happens throughout the code execution:
- Initialize
index
to 0 to start checking the array from the beginning. - Set
newLength
equal tolength
as the initial modified length of the array. - Use a
while
loop to iterate over the array elements untilindex
is less thannewLength
. - In each iteration, check if the current element equals
value
.- If it does, move the last element in the array to the current index and reduce
newLength
by one. - If it does not match, increment
index
to continue with the next element.
- If it does, move the last element in the array to the current index and reduce
- The loop continues until each element has been inspected or moved if needed.
- After completing the iterations, the function returns the new length of the array which denotes the count of remaining elements after the specified value has been removed.
This method allows the array to be modified in-place without using additional memory (aside from loop control variables), providing an efficient way to remove elements.
var filterArray = function (elements, value) {
let index = 0;
let length = elements.length;
while (index < length) {
if (elements[index] == value) {
elements[index] = elements[length - 1];
length--;
} else {
index++;
}
}
return length;
};
This solution defines a JavaScript function filterArray
designed to remove specified elements from an array. The function takes two arguments: elements
(the array from which to remove elements) and value
(the value of the elements to remove). Here's how the function operates:
- Initialize
index
to 0 to track the current position in the array andlength
to the total number of elements in the array. - Use a while loop to iterate through the array until
index
is less thanlength
. - Within the loop, check if the current element (at
index
) is equal tovalue
. If true:- Replace the element at the current index with the element at the last valid index (
length - 1
). - Decrement
length
to effectively reduce the array size by one.
- Replace the element at the current index with the element at the last valid index (
- If the current element does not match
value
, incrementindex
to move to the next element. - Finally, after the loop completes, the function returns
length
, representing the new size of the array with the specified elements removed.
This approach modifies the array in place without using extra space for another array, which makes it efficient in terms of space complexity. Use this function to clean arrays quickly, removing all occurrences of a specific value while maintaining the array's remaining elements' order up to the new length.
class Solution:
def delete_value(self, elements: List[int], target: int) -> int:
index = 0
size = len(elements)
while index < size:
if elements[index] == target:
elements[index] = elements[size - 1]
size -= 1
else:
index += 1
return size
The provided Python solution demonstrates a method to remove all occurrences of a specified element (target
) from an array (elements
) in-place and returns the new length of the array after removal. The delete_value
function uses a two-pointer approach:
- Initialize an
index
to track the current position in the array andsize
to keep track of the effective length of the array. - Iterate through the array with the
index
pointer. If the element atindex
matchestarget
, replace it with the last element in the effective part of the list and reducesize
. This avoids shifting all elements and achieves the removal in O(1) time complexity for each replacement. - If the element does not match, simply move
index
forward. - At the completion of the loop,
size
indicates the new length of the array, which does not contain thetarget
element.
This approach ensures efficient removal of the specified element with minimal space usage since the operations modify the array in place. The return value gives the number of remaining elements.
No comments yet.