27. Remove Element
Explanation
To solve this problem, we can use a two-pointer approach where one pointer iterates through the array while the other pointer keeps track of the next position to overwrite when the element needs to be removed. We iterate through the array, and whenever we encounter an element equal to the given value, we skip it. If the element is not equal to the given value, we copy it to the position indicated by the second pointer. This way, we effectively remove the specified value from the array in-place.
Algorithm
- Initialize two pointers
i
andk
at the start of the array. - Iterate through the array using pointer
i
. - If
nums[i]
is equal toval
, skip this element. - If
nums[i]
is not equal toval
, copynums[i]
tonums[k]
and incrementk
. - Continue this process until
i
reaches the end of the array. - Return the value of
k
as the length of the modified array.
Time Complexity
The time complexity of this algorithm is O(n), where n is the number of elements in the input array nums
.
Space Complexity
The algorithm has a space complexity of O(1) as it modifies the input array in-place without using any extra space.
class Solution {
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[k] = nums[i];
k++;
}
}
return k;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.