Search~20 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
A search engine sorts the relevance scores of its results with quick sort. The team wants to know how risky a random pivot is for a given list. A pivot is balanced when neither side of the split holds more than three quarters of the results.
For a pivot score p, the smaller side holds the scores less than p, and the larger side holds the scores greater than p. Scores equal to p stay with the pivot, so they are on neither side.
Write count_balanced_pivots(scores).
i, let smaller be the number of scores less than scores[i], and larger the number greater than it.4 × max(smaller, larger) ≤ 3 × n. Return the number of balanced choices.Input: scores = [4, 8, 15, 16, 23, 42]
Output: 4There are six results, so a side may hold at most 4 of them (4 × 4 = 16 ≤ 18, and 4 × 5 = 20 > 18).
| Pivot | Smaller | Larger | max | Balanced? |
|---|---|---|---|---|
| 4 | 0 | 5 | 5 | no |
| 8 | 1 | 4 | 4 | yes |
| 15 | 2 | 3 | 3 | yes |
| 16 | 3 | 2 | 3 | yes |
| 23 | 4 | 1 | 4 | yes |
| 42 | 5 | 0 | 5 | no |
Four choices are balanced.
Input: scores = [5, 5, 5, 5]
Output: 4For every pivot there are no smaller and no larger scores, so each of the four choices is balanced.
Input: scores = [3, 1, 3, 3, 9]
Output: 3The three scores equal to 3 each have 1 smaller and 1 larger. The 1 has 4 larger scores, and the 9 has 4 smaller scores, and 4 × 4 = 16 is more than 15.
0 ≤ scores.length ≤ 100,000 (results)0 ≤ scores[i] ≤ 1,000,000,000Counting the smaller and larger scores for every pivot costs about n × n steps, which is 10^10 at n = 100,000. Sorting once costs about n log n, roughly 1.7 million steps, and then every pivot's counts are read from its position.