/80. Remove Duplicates from Sorted Array II

80. Remove Duplicates from Sorted Array II

Medium
Arrays64.4% acceptance

Given a sorted integer array arr in non-decreasing order, modify arr in-place so that each distinct value appears at most twice. The relative order of elements must be preserved. Return the integer count n of elements retained in the first n positions of arr. The values beyond the first n positions are irrelevant. You must use O(1) additional space.

Example 1

Input: [2,2,2,3,3,4,4,4,5]

Output: 7

Explanation: After removing extra duplicates, arr becomes [2,2,3,3,4,4,5]. The function returns 7.

Example 2

Input: [7,7,8,8,8,9,10,10,10,10]

Output: 7

Explanation: After removing extra duplicates, arr becomes [7,7,8,8,9,10,10]. The function returns 7.

Constraints

  • 1 <= len(arr) <= 30000
  • -10000 <= arr[i] <= 10000
  • arr is sorted in non-decreasing order
Python (current runtime)

Case 1

Input: [1,1,2,2,2,3,3,3,4]

Expected: 7

Case 2

Input: [0,1,1,1,2,2,2,3,4,4,4,5]

Expected: 8

Case 3

Input: [5,5,5,5,5]

Expected: 2

Case 4

Input: [-2,-2,-2,-1,-1,0,0,0,1,1,1]

Expected: 8

Case 5

Input: [10000]

Expected: 1