Leetcode 27 Java Solution: Remove Element

Problem Statement:-

Given an array nums and a value val, remove all instances of that value

in place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

Solution:-

Summary:- We have given one Array of numbers and one integer as an input in a function. Now we have to remove that given value of integer number from that array , if that number present in that given Array. And then we have to return the new length of that Array.]

Logic :-

As we can’t use extra space so we have to define here only one array data structure only :-

So our approach for this problem is :-

  1. Define one variable which will act as a counter. Whose value will start from zero.
  2. Scan that given array from left to right. For that we will use the for loop.
  3. If the current element of the given Array is not equal to given integer number value, then only we will add that element of that array in place of counter.

Flow-Chart Diagram:-

Time Complexity:-

Here the time complexity will totally depend on the length of the array as we are scanning the whole Array and only we are scanning the array data structure only one time. So time complexity O(n)

Space complexity:-

Here only one Array data structure is used. So the space complexity is O(1).

Code in Java:-

public class RemoveElement {

	

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