Remove Element easy

Problem Statement

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in-place, you must return the new length of the array after removing all occurrences of val.

Consider the number of elements to be removed as a given, so you can assume that there will always be space for shifting the elements over.

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, 1, 3, 0, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k.

Steps:

  1. Two Pointers: Use two pointers, k (representing the index of the next element to be placed) and i (iterating through the array). Initialize k to 0.

  2. Iteration: Iterate through the array using i.

  3. Comparison: If nums[i] is not equal to val, place nums[i] at index k ( nums[k] = nums[i]) and increment k.

  4. Return: After iterating through the entire array, k will represent the new length of the array containing only elements different from val. Return k.

Explanation:

The algorithm uses a two-pointer approach to efficiently remove elements in-place. The k pointer keeps track of the index where the next element that is not equal to val should be placed. The i pointer iterates through the array. If nums[i] is different from val, it's copied to the k-th position, effectively shifting non-val elements to the beginning. Elements beyond k are not relevant and their values don't matter.

Code:

public class Solution {
    public int RemoveElement(int[] nums, int val) {
        int k = 0; // Index for elements to keep
        for (int i = 0; i < nums.Length; i++) {
            if (nums[i] != val) {
                nums[k] = nums[i];
                k++;
            }
        }
        return k;
    }
}

Complexity:

  • Time Complexity: O(n), where n is the length of the input array. We iterate through the array once.
  • Space Complexity: O(1). We use only a constant amount of extra space for the pointers k and i.