FastPrepRemove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Nykaa logoNykaa● EasyFULLTIMEPHONE SCREEN

Problem statement

You are given an integer array nums sorted in non-decreasing order. Remove the repeated values in place, so that each distinct value appears only once and the values stay in the same order.

Let k be the number of distinct values in nums. After your changes, the first k elements of nums should hold those distinct values in order. What is left after the first k elements does not matter.

Return the first k elements of nums as an array. Its length, k, is the number of unique elements.

Function

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

Examples

Example 1

nums = [-3,-3,0,2,2,2,7]return = [-3,0,2,7]

The value -3 appears twice and 2 appears three times. Keeping one copy of each value, in order, gives [-3,0,2,7]. There are 4 unique elements.

Example 2

nums = [4,4,4,4]return = [4]

Every element is 4, so only one copy is kept. The answer is [4] and there is 1 unique element.

Example 3

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

No value repeats, so all three elements stay in the same order.

Constraints

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

More Nykaa problems

See Nykaa hiring insights
Saved
public int[] removeDuplicates(int[] nums) {
    // Write your code here.
}
Checking account…