80. Remove Duplicates from Sorted Array II

80. Remove Duplicates from Sorted Array II

Tags
Leetcode
Coding
Problem solving
C#
Published
April 3, 2024
Author
Delgersaikhan

Intuition

By maintaining two pointers - one to keep track of the position where the next non-duplicate element should be placed (k), and another to keep track of the count of occurrences of the current element (lcount) - we can efficiently iterate through the array and identify which elements need to be included in the modified array.

Approach

In this problem, we are tasked with removing duplicate elements from a sorted array while allowing at most two occurrences of each element to remain. To achieve this, we can utilize a two-pointer approach where one pointer (k) is used to keep track of the position where the next non-duplicate element should be placed. We also maintain a count of the occurrences of the current element (lcount) and update it accordingly as we iterate through the array.

Complexity

  • Time complexity:O(n)O(n)O(n)
  • Space complexity:O(1)O(1)O(1)

Code

public class Solution { public int RemoveDuplicates(int[] nums) { int lcount = 1; int last = nums[0]; int k = 1; for(int i = 1; i<nums.Length; i++) { lcount = last == nums[i]? lcount + 1 : 1; if(lcount <= 2) nums[k++] = nums[i]; last = nums[i]; } return k; } }
 
Blog Posts