Cover image for Top 150 Interview Questions P26 Remove Duplicates from Sorted Array

Top 150 Interview Questions P26 Remove Duplicates from Sorted Array


Timeline

Timeline

2025-09-28

init

std::unique

Problem:

std::unique is a C++ function in it. It does not actually delete elements in the container, but moves adjacent duplicate elements to the back, and returns an iterator pointing to the new logical end. Combined with erase, it can remove duplicate elements.

1234567891011
#include <algorithm>#include <vector>using std::vector;class Solution {public:    int removeDuplicates(vector<int>& nums) {        nums.erase(std::unique(nums.begin(),nums.end()),nums.end());        return nums.size();    }};

Classic fast-slow pointer solution: the fast pointer represents the index position reached while traversing the array, and the slow pointer represents the index position where the next different element should be filled. Initially, both pointers point to index 1.

123456789101112131415161718
class Solution {public:    int removeDuplicates(vector<int>& nums) {        int n = nums.size();        if (n == 0) {            return 0;        }        int fast = 1, slow = 1;        while (fast < n) {            if (nums[fast] != nums[fast - 1]) {                nums[slow] = nums[fast];                ++slow;            }            ++fast;        }        return slow;    }};
Loading comments…