← Back to LeetCode Notes

26. Remove Duplicates from Sorted Array

easy · array · two-pointers · solved 2026.08.01 · 15 sec read

C++
class Solution {public:    int removeDuplicates(vector<int>& nums) {        int k = 0;        nums.push_back(-99);        for (int i = 0; i < nums.size(); i++) {            if (nums[k] != nums[i]) {                nums[++k] = nums[i];            }        }        return k;    }};

inspired by Remove Element was just keeping track of an internal sub array, k which I increase and add another element onto every time there is a value that is not the same as the last value that was added to my subarray k. just gotta keep it simple...