
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 <stdio.h>
2
3int removeElement(int* nums, int numsSize, int val) {
4 int j = 0;
5 for (int i = 0; i < numsSize; i++) {
6 if (nums[i] != val) {
7 nums[j++] = nums[i];
8 }
9 }
10 return j;
11}This C solution uses two pointers. The 'i' pointer traverses the entire array, while 'j' records the positions to insert non-'val' elements. Elements equal to 'val' are ignored, effectively 'removing' them.
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.
1
This C solution uses an in-place swapping mechanism to manage elements. When the desired element is found, it is swapped with the back-most unchecked item, expanding backward.