Straightforward C# Solution with Explanation

  • 0

    This is my solution using two indexes and a counter. Loop through the array and copy from loop index to another index that maintains the last element in the "new" array. The counter maintains how many of current value we've copied. It is reset when we encounter a new value. Can be generalized to allow any number of duplicates. Runs in O(n) time. Pretty straightforward I think.

    public class Solution {
        public int RemoveDuplicates(int[] nums) {
            if(nums.Length==0) return 0;
            int currIndex = 0, count = 1;
            for(int i=1; i < nums.Length; i++) {
                if(nums[i] != nums[currIndex]) {
                    nums[++currIndex] = nums[i];
                    count = 0; //reset counter
                } else if(count < 2) {  //allow 2 duplicates or change this to allow any number
                    nums[++currIndex] = nums[i];
            return currIndex + 1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.