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.
Input: ([1, 2, 3, 4, 5, 6],)
Expected Output: []
Explanation: n=6, every value appears once (1 is not > 2), so no qualifier.
Input: ([],)
Expected Output: []
Explanation: Empty array returns empty list.
Input: ([7],)
Expected Output: [7]
Explanation: n=1, single element has count 1 and 3*1>1, so it qualifies.
Input: ([5, 5, 5, 5, 5, 5],)
Expected Output: [5]
Explanation: All-equal: both sampled positions hold 5; dedup reports it once.
Input: ([-3, -3, -3, -1, 0, 4, 4],)
Expected Output: [-3]
Explanation: n=7. -3 appears 3 times (3*3=9>7); positions n/3=2 (-3) and 2n/3=4 (0). Only -3 qualifies.
Input: ([1, 1, 2, 2, 3, 3],)
Expected Output: []
Explanation: n=6, each value appears twice (2 is not > 2). No qualifier.
Input: ([2, 2],)
Expected Output: [2]
Explanation: n=2, 2 appears twice and 3*2=6>2, so it qualifies.
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.