Solving the “Remove Element” Problem in Java

Solving the “Remove Element” Problem in Java

Introduction

When it comes to solving array manipulation problems, the Two Pointers technique is a handy approach. In this blog post, we’ll explore how to apply this technique to solve the “Remove Element” problem in Java. This problem asks us to remove all occurrences of a specific value from an array in-place and return the number of remaining elements.

The Problem

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

The Two Pointers Approach

The Two Pointers technique involves maintaining two pointers to traverse the array. One pointer is used to iterate through the array, while the other pointer keeps track of the current position where elements not equal to the specified value should be placed.

Java Implementation

Let’s take a look at the Java code to solve this problem:

public class RemoveElement {
    public static int removeElement(int[] nums, int val) {
        int k = 0; // Initialize the variable to count elements not equal to val
// Iterate through the array
        for (int i = 0; i < nums.length; i++) {
            // If the current element is not equal to val
            if (nums[i] != val) {
                // Move the element to the front of the array
                nums[k] = nums[i];
                // Increment the count of elements not equal to val
                k++;
            }
        }
        return k; // Return the count of elements not equal to val
    }
    public static void main(String[] args) {
        // Test cases
        int[] nums = {3, 2, 2, 3};
        int val = 3;
        int k = removeElement(nums, val);
        System.out.println("Number of elements not equal to " + val + ": " + k);
        // Additional steps for custom judge
        Arrays.sort(nums, 0, k);
        System.out.println("Modified array: " + Arrays.toString(nums));
    }
}

Explanation

  • We initialize a variable k to count the number of elements not equal to val.

  • We iterate through the array, and for each element that is not equal to val, we move it to the front of the array at position k and increment k.

  • The function returns the value of k, representing the count of elements not equal to val.

Conclusion

The Two Pointers technique is a powerful tool for solving array manipulation problems efficiently. By maintaining two pointers to traverse the array, we can achieve a time complexity of O(n) for this “Remove Element” problem. This approach also allows us to perform the removal in-place, without requiring additional space.