Problem · Array

Count Distinct Values in a Huge Sorted Array

Learn this problem
MediumLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem statement

Given a non-empty integer array nums sorted in nondecreasing order, return the number of distinct values.

The array may be much larger than the number of distinct values. Use binary search to jump from the first occurrence of one value to the first greater value instead of inspecting every duplicate.

Function

countDistinct(nums: int[]) → int

Examples

Example 1

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

The distinct values are 1, 2, and 4.

Example 2

nums = [-2,-2,-1,0,0,7]return = 4

The array contains four distinct values: -2, -1, 0, and 7.

Constraints

  • nums is non-empty and sorted in nondecreasing order.
  • Every value is a signed integer.

More LinkedIn problems

drafts saved locally
public int countDistinct(int[] nums) {
    // TODO: jump across equal-value runs.
}
nums[1,1,1,2,2,4,4,4]
expected3
checking account