Remove Element Problem and Solution

1. Introduction

The "Remove Element" problem involves modifying an array in place to remove all instances of a given value, and returning the new length of the array.

2. Problem

Given an array nums and a value val, remove all instances of that value in place and return the new length. The order of elements can be changed, and the elements beyond the new length do not matter.

3. Solution in C++

#include <iostream>
#include <vector>
using namespace std;

int removeElement(vector<int>& nums, int val) {
    int i = 0;
    for (int j = 0; j < nums.size(); j++) {
        if (nums[j] != val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}

// Example usage
int main() {
    vector<int> nums = {3, 2, 2, 3};
    int val = 3;
    int newLength = removeElement(nums, val);
    for (int i = 0; i < newLength; i++) {
        cout << nums[i] << " ";
    }
    cout << endl;
    return 0;
}

Output:

2 2

Explanation:

1. removeElement in C++ uses a two-pointer approach.

2. It iterates through the array with pointer j.

3. When an element not equal to val is found, it's moved to the front of the array at position i.

4. Returns the new length of the array after removals.

4. Solution in Java

public class RemoveElement {
    public static int removeElement(int[] nums, int val) {
        int i = 0;
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != val) {
                nums[i] = nums[j];
                i++;
            }
        }
        return i;
    }

    // Example usage
    public static void main(String[] args) {
        int[] nums = {3, 2, 2, 3};
        int val = 3;
        int newLength = removeElement(nums, val);
        for (int i = 0; i < newLength; i++) {
            System.out.print(nums[i] + " ");
        }
        System.out.println();
    }
}

Output:

2 2

Explanation:

1. Java's removeElement method uses a similar two-pointer approach as in C++.

2. Iterates through the array, shifting non-val elements to the front.

3. Returns the count of the new array length after removals.


Comments