- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Duplicates from Sorted Array II in C++
Suppose we have a sorted array nums, we have to remove the duplicates in-place such that duplicates elements will appear at most twice and return the new length. To do this task we cannot take extra space. We have to solve this with O(1) amount of space. For example, if the array is like [0,0,0,1,1,1,1,2,3,3], then the output will be [0,0,1,1,2,3,3], its length is 7
Let us see the steps −
- len := 2 and n := size of array
- if n <= 2, then return n
- for i := 2 to n
- if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]
- nums[len] := nums[i], and increase len by 1
- if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]
- return len
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { int len = 2; int n = nums.size(); if(n <= 2)return n; for(int i = 2; i < n; i++){ if( nums[i] != nums[len - 2] || nums[i] != nums[len - 1]){ nums[len] = nums[i]; len++; } } return len; } }; main(){ Solution ob; vector<int> v = {0,0,0,1,1,1,1,2,3,3}; cout << ob.removeDuplicates(v); }
Input
[0,0,0,1,1,1,1,2,3,3]
Output
7
- Related Articles
- Remove Duplicates from Sorted List II in C++
- Remove Duplicates from Sorted Array in Python
- Remove Duplicates from Sorted List in C++
- How to remove duplicates from the sorted array and return the length using C#?
- How to remove duplicates from the sorted array and return the non-duplicated array using C#?
- Remove Duplicates from a Sorted Linked List Using Recursion
- How to remove duplicates from a sorted linked list in android?
- Removing duplicates from a sorted array of literals in JavaScript
- Remove All Adjacent Duplicates in String II in C++
- Remove duplicates from array with URL values in JavaScript
- Remove duplicates from a List in C#
- Remove duplicates from a array of objects JavaScript
- Java Program to Remove Duplicates from an Array List
- Remove duplicates from an array keeping its length same in JavaScript
- Remove all duplicates from a given string in C#

Advertisements