FastPrepCount Distinct Values in a Sorted Array
Problem · Array

Count Distinct Values in a Sorted Array

Learn this problem
MediumGoogle logoGoogleINTERNONSITE INTERVIEW
See Google hiring insights

Problem statement

Given a nondecreasing integer array nums, return the number of distinct values in the array.

As a follow-up, let k be the number of distinct values. Design an approach that can skip long runs of duplicates and runs in O(k log n) time.

Function

countDistinct(nums: int[]) → int

Examples

Example 1

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

The distinct values are -3, -1, 2, and 8.

Example 2

nums = []return = 0

An empty array contains no distinct values.

Constraints

  • 0 <= nums.length <= 200000
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in nondecreasing order.

More Google problems

drafts saved locally
public int countDistinct(int[] nums) {
    // write your code here
}
nums[-3,-3,-1,2,2,2,8]
expected4
checking account