Similar Problems
Similar Problems not available
Remove Element - Leetcode Solution
LeetCode: Remove Element Leetcode Solution
Difficulty: Easy
Topics: array two-pointers
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.
Example 1:
Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2] Explanation: Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,3,0,0], your answer will be accepted.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,3,0,4] Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
Solution:
The problem requires us to remove all instances of a given value in-place. We can do this by using two-pointers. We will initialize two-pointers i and j. Pointer i will traverse the array and pointer j will point to the position where we can swap the value present at i with the value present at j (value being val).
Step 1: Initialize two-pointers i=0 and j=0 Step 2: Traverse the array nums using pointer i and perform the following steps: If the value of nums[i] is not equal to val, then swap the values of nums[i] and nums[j], and increment j. Continue this process till we traverse the complete array. Step 3: Return the final value of j, as it will give us the length of the new array.
Let's implement the solution:
class Solution { public: int removeElement(vector<int>& nums, int val) { int j = 0; //pointer j will point to the position where the value can be swapped int n = nums.size(); for(int i=0;i<n;i++){ if(nums[i]!=val){ nums[j] = nums[i]; j++; } } return j; //return the value of j as it is pointing to the position where value can be swapped } };
Time Complexity: O(n), where n is the size of the given array nums. We traverse the complete array once.
Space Complexity: O(1), as we are not using any extra space and performing the operation in-place.
The above code got accepted on Leetcode.
Remove Element Solution Code
1