Leetcode Remove Duplicates from Sorted Array II problem solution YASH PAL, 31 July 2024 In this Remove Duplicates from Sorted Array II problem solution we have Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in place with O(1) extra memory. Problem solution in Python. class Solution: def removeDuplicates(self, nums: List[int]) -> int: for num in nums: while nums.count(num) > 2: nums.remove(num) return len(nums) Problem solution in Java. public class Solution { public int removeDuplicates(int[] nums) { if(nums.length==0){ return 0; } int x=1,index=0; for(int i=0;i<nums.length-1;i++){ if(nums[i]==nums[i+1] && x==1){ x++; nums[index++]=nums[i]; } else if(nums[i]!=nums[i+1]){ x=1; nums[index++]=nums[i]; } } nums[index++]=nums[nums.length-1]; return index; } } Problem solution in C++. class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<3) return nums.size(); int i =1; while (i<nums.size()){ if(nums[i-1] == nums[i]){ if(i == nums.size()-1) return nums.size(); if(nums[i+1] == nums[i]) {nums.erase(nums.begin()+i);continue;} } i++; } return nums.size(); } }; Problem solution in C. int removeDuplicates(int* nums, int numsSize){ if(!numsSize) return 0; int len = 0, count = 1; for (int i = 1; i < numsSize; i++) { if (nums[i] != nums[len]) { len++; nums[len] = nums[i]; count = 1; } else { count++; if (count <= 2) { len++; nums[len] = nums[i]; } } } return len+1; } coding problems