All questions
Medium2026-07-30

Remove Duplicates from Sorted Array — Allow at Most K

Company
Oracle
Role

Senior SDE

Round

Onsite (Stage 3)

ArrayTwo PointersIn-Place

Problem Statement

Given a sorted integer array, remove duplicates in-place such that each unique element appears at most K times. Return the new length of the modified array.

You must do this with:

  • O(n) time complexity
  • O(1) extra space (modify the array in-place)

The relative order of elements should be maintained. Elements beyond the returned length don't matter.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order
  • 1 <= K <= nums.length

Example

Input: nums = [1, 1, 1, 2, 2, 2, 3, 3], K = 2

Output: 6, array becomes [1, 1, 2, 2, 3, 3, ...]

Explanation: Each element appears at most 2 times.

Input: nums = [0, 0, 0, 0, 1, 1, 1, 1, 2], K = 3

Output: 7, array becomes [0, 0, 0, 1, 1, 1, 2, ...]

Follow-ups

  1. What if K = 1? Can you simplify the logic?
  2. What if the array is NOT sorted? Does your approach still work?
  3. Can you generalize this to work with any arbitrary predicate (not just duplicate count)?
  4. What's the key insight that makes the two-pointer approach work here?
🧠

No solution provided

Think through it. That's how you build real interview muscle.

Share: