Keep at Most Two Copies in a Sorted Array Prefix

Quick Overview

Retain at most two copies of each sorted value in the original array prefix using constant extra memory.

Keep at Most Two Copies in a Sorted Array Prefix

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem The integer array `nums` is sorted in nondecreasing order. Modify it in place to retain at most two occurrences of each value, preserving their relative order. Return the retained length `k`; the first `k` positions must contain the resulting sorted sequence. Positions beyond that prefix are ignored. Use constant extra memory and do not allocate a second array for the result. Preserve the original interface: ```cpp int removeDuplicates(vector<int>& nums); ``` Return only `k`; the prefix is an observable mutation of the argument, not an additional returned array. ### Examples ```text Input: nums = [-3,-3,-3,0,0,0,4] Returned k: 5 Required prefix: [-3,-3,0,0,4] ``` ```text Input: nums = [6,6,6,6] Returned k: 2 Required prefix: [6,6] ``` ### Constraints - `1 <= nums.length <= 30000`. - Each value is between -10000 and 10000, inclusive. - Input order is nondecreasing; retain the original relative order. - Mutate the prefix using `O(1)` extra memory. The ignored suffix needs no special marker.

Overview: Retain at most two copies of each sorted value in the original array prefix using constant extra memory.

Amazon logo
Amazon
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

The integer array nums is sorted in nondecreasing order. Modify it in place to retain at most two occurrences of each value, preserving their relative order. Return the retained length k; the first k positions must contain the resulting sorted sequence. Positions beyond that prefix are ignored.

Use constant extra memory and do not allocate a second array for the result. Preserve the original interface:

int removeDuplicates(vector<int>& nums);

Return only k; the prefix is an observable mutation of the argument, not an additional returned array.

Examples

Input: nums = [-3,-3,-3,0,0,0,4]
Returned k: 5
Required prefix: [-3,-3,0,0,4]
Input: nums = [6,6,6,6]
Returned k: 2
Required prefix: [6,6]

Constraints

  • 1 <= nums.length <= 30000 .
  • Each value is between -10000 and 10000, inclusive.
  • Input order is nondecreasing; retain the original relative order.
  • Mutate the prefix using O(1) extra memory. The ignored suffix needs no special marker.