
Sponsored
Sponsored
In this approach, we use two pointers starting at the beginning of the array. One pointer, called 'i', iterates over each element of the array, while the second pointer, called 'j', records the position of where to insert a new element that is not equal to 'val'. Whenever we encounter an element not equal to 'val', we place it at the position pointed by 'j' and increment 'j'. The final value of 'j' will give us the length of the modified array where elements are not equal to 'val'.
Time Complexity: O(n), where n is the length of nums.
Space Complexity: O(1), in-place manipulation of the array.
1#include <vector>
2
3int removeElement(std::vector<int>& nums, int val) {
4 int j = 0;
5 for (int i = 0; i < nums.size(); i++) {
6 if (nums[i] != val) {
7 nums[j++] = nums[i];
8 }
9 }
10 return j;
11}This C++ solution similarly uses two pointers. It modifies the array in place, moving elements not equal to 'val' to the front.
This method uses a two-pointer technique but in a different manner. Here, one pointer (i) starts from the beginning and the other pointer (end) starts from the end of the array. As long as i <= end, we check each element. If nums[i] equals val, we swap it with the element at nums[end] and decrement end. If not, increment i. This ensures that values to be removed accumulate at the end of the array, and relevant values are compacted at the front.
Time Complexity: O(n), where n is the size of nums.
Space Complexity: O(1), swaps happen within nums.
1Using swapping, this Python function streamlines removal of 'val'. Being linear time, it lines up non-targets by reusing available space.