Find >n/3 elements in sorted array
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This TikTok software-engineer screen asks you to return every value occurring strictly more than n/3 times in a sorted array, in O(log n) time and O(1) space. The solution proves at most two such values can exist, samples the fixed positions n/3 and 2n/3, and confirms each candidate's count with lower_bound/upper_bound binary searches. It tests frequency reasoning on sorted data, combinatorial bounds, and rigorous complexity and edge-case analysis.
Constraints
- 0 <= n <= 10^6
- A is sorted in non-decreasing order
- -10^9 <= A[i] <= 10^9
- At most two distinct values can satisfy the condition
- Target O(log n) time and O(1) extra space (output excluded)
Examples
Input: ([1, 2, 2, 2, 3],)
Expected Output: [2]
Explanation: n=5, threshold count>5/3. 2 appears 3 times (3>5/3), so [2].
Input: ([1, 1, 1, 2, 2, 2, 3],)
Expected Output: [1, 2]
Explanation: n=7. 1 and 2 each appear 3 times (3>7/3); 3 appears once. Both qualify.
Hints
- In a sorted array, all copies of a value are contiguous, so each value's count is upper_bound(v) - lower_bound(v).
- If three distinct values each exceeded n/3, their disjoint counts would sum to more than n elements -- impossible. So at most two qualify.
- Any contiguous block longer than n/3 cannot fit strictly between consecutive thirds, so it must cover A[n/3] or A[2n/3]. Only those two positions can host a qualifier.
- Use the integer test 3 * count > n instead of count > n/3 to avoid floating point, and deduplicate the two sampled values for all-equal arrays.