FastPrepKeep At Most Two Copies in a Sorted Array

Keep At Most Two Copies in a Sorted Array

Amazon logoAmazon● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a nondecreasing integer array, compact it so that each distinct value appears at most twice.

Return the compacted prefix as a new array. Preserve sorted order.

Function

keepAtMostTwo(nums: int[]) → int[]

Examples

Example 1

nums = [1,1,1,2,2,3]return = [1,1,2,2,3]

The third one is removed.

Example 2

nums = [0,0,1,1,1,1,2,3,3]return = [0,0,1,1,2,3,3]

At most two copies of every value remain.

Example 3

nums = []return = []

Empty input stays empty.

Constraints

  • 0 <= nums.length <= 100000.
  • Values fit in a signed 32-bit integer.

More Amazon problems

See Amazon hiring insights
public int[] keepAtMostTwo(int[] nums) {
    // write your code here
}
nums[1,1,1,2,2,3]
expected[1,1,2,2,3]
Checking account…