Remove Element - LeetCode Solution in C++, Java, Python

1. Introduction

In this blog post, we will provide a LeetCode solution for the "Merge Sorted Array" problem in C++, Java, and Python languages.

The "Remove Element" problem involves removing all instances of a specific value from an array in place and returning the new length of the array. This problem tests the ability to manipulate arrays efficiently.

2. Problem

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed, and then return the number of elements in nums which are not equal to val.

3. Solution in C++

int removeElement(vector<int>& nums, int val) {
    int k = 0; // Pointer for the next position
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] != val) {
            nums[k++] = nums[i];
        }
    }
    return k; // The new length of the array
}

Explanation:

1. Iterate through nums.

2. If the current element is not val, move it to the kth position.

3. Increment k for each element kept in the array.

4. k represents the new length of the array with val removed.

4. Solution in Java

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];
        }
    }
    return k;
}

Explanation:

1. Traverse the nums array.

2. When an element not equal to val is found, copy it to the index k.

3. Increment k each time a non-val element is encountered.

4. The final value of k is the count of elements not equal to val.

5. Solution in Python

def removeElement(nums, val):
    k = 0
    for i in range(len(nums)):
        if nums[i] != val:
            nums[k] = nums[i]
            k += 1
    return k

Explanation:

1. Loop through each element in nums.

2. If the element is not equal to val, place it at the index k.

3. Increase k each time a valid element is moved.

4. The final value of k gives the number of elements not equal to val.


Comments