FastPrepRemove Duplicates From Sorted Array In Place
Problem · Array

Remove Duplicates From Sorted Array In Place

Learn this problem
EasyGet My Parking logoGet My ParkingFULLTIMEPHONE SCREEN

Problem statement

You are given an integer array nums sorted in nondecreasing order. Modify it in place so that each distinct value appears exactly once and the retained values stay in sorted order.

Return an array containing exactly the compacted prefix. Extra capacity after that prefix may be left unchanged.

What the interview report shared

The interviewer asked an easy coding question: remove duplicate elements in a sorted array in place. The candidate solved it in a shared Google Doc.

Function

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

Examples

Example 1

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

The sorted values are 1, 1, and 2. After in-place compaction the unique prefix is [1,2].

Example 2

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

Adjacent duplicates are overwritten so each retained value appears once. The compacted prefix is [0,1,2,3,4].

Example 3

nums = []return = []

An empty array has no values to retain, so the compacted prefix is empty.

Constraints

  • 0 <= nums.length <= 10^5.
  • -10^9 <= nums[i] <= 10^9.
  • nums is sorted in nondecreasing order.
drafts saved locally
public int[] removeDuplicates(int[] nums) {
  // Write your code here.
}
nums[1,1,2]
expected[1,2]
checking account