Count Distinct Values in a Huge Sorted Array
Updated
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[]) → intExamples
Example 1
nums = [1,1,1,2,2,4,4,4]return = 3The distinct values are 1, 2, and 4.
Example 2
nums = [-2,-2,-1,0,0,7]return = 4The array contains four distinct values: -2, -1, 0, and 7.
Constraints
numsis non-empty and sorted in nondecreasing order.- Every value is a signed integer.
More LinkedIn Onsite Interview questions
- Allocate Mailboxes with Squared DistanceONSITE INTERVIEW · Seen Nov 2026
- Find Leaves of a Binary TreeONSITE INTERVIEW · Seen Nov 2026
- Max Points on a LineONSITE INTERVIEW · Seen Nov 2026
- Explore an Unknown Grid and Find a PathONSITE INTERVIEW · Seen Nov 2026
- Fire Station Response BillONSITE INTERVIEW · Seen Nov 2026
- Roll a Weighted DieONSITE INTERVIEW · Seen Oct 2026
- Longest Binary Subarray With at Most K OnesONSITE INTERVIEW · Seen Oct 2026
- Kth Closest Element in a BSTONSITE INTERVIEW · Seen Oct 2026
- Longest Binary Window with at Most K OnesONSITE INTERVIEW · Seen Oct 2026
- LRU Cache OperationsONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Minimum Number of Days to Make m BouquetsPhonePe · ONSITE INTERVIEWPhonePe interview questions
- Count Winning Dice Face PairsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Search in a Rotated Sorted ArrayAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- 3Sum SmallerSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Smallest Batch Size Within a Step LimitMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Peak of an Increasing-Then-Decreasing ArraySnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- Online Meeting Scheduler with Fixed RoomsUber · ONSITE INTERVIEWUber interview questions
- Search a 2D MatrixWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Search in Rotated Sorted ArrayKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions