Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in Swift: O(n) Bucket Sort

Practice O(n) Read the full explanation

You get an array of integers nums and an integer k.

Return the k values that show up most often in nums, in any order.

How often a value shows up is its frequency. The tests always have one clear answer. Every value you return shows up more often than every value you leave out.

 

Example 1:

Input: nums = [5,3,5,8,3,5,2], k = 2
Output: [3,5]
Explanation: 5 shows up 3 times.
3 shows up twice.
8 and 2 show up once each.
The top 2 are 5 and 3. [5,3] is just as correct.

Example 2:

Input: nums = [9,9,9,9], k = 1
Output: [9]
Explanation: 9 is the only value.

Example 3:

Input: nums = [-2,6,-2,0,6,-2,6,1], k = 2
Output: [-2,6]
Explanation: -2 and 6 both show up 3 times.
0 and 1 show up once each.
A tie inside the answer is fine.
Only the values left out must show up less often.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is from -10,000 to 10,000.
  • k is at least 1 and at most the number of different values in nums.
  • There is only one correct set of k values.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 12
    Ctrl + Enter to check

    SWIFT · HASH TABLE

    Top K Frequent Elements in Swift, explained

    Problem overview

    The method topKFrequent receives an array of integers, nums, and a number k. It returns the k values that appear most often in nums, in any order. A value's frequency is the number of times it appears. The answer is guaranteed to be unique: every value in it appears more often than every value left out, so there is no tie at the cut.

    For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears 3 times, 2 appears twice and 3 once, so the answer is [1, 2]. The statement asks for O(n) time and O(n) extra space, and notes that sorting the values by frequency would already cost O(n log n).

    Approach: count, then bucket by count

    Counting is the first half. One pass over nums with a dictionary from value to count takes O(n) time, because a dictionary finds a key in constant time on average.

    The second half is choosing the k largest counts. Sorting the distinct values by count would take O(n log n) in the worst case. The way around it is that a count can't be larger than nums.count. So instead of comparing counts, the lesson uses each count as an index into an array of buckets: buckets[f] holds the values that appear exactly f times. This is a bucket sort, and it needs no comparisons.

    For [1, 1, 1, 2, 2, 3] the counts are 1 appears 3 times, 2 appears 2 times and 3 appears once, and the buckets (indices 0 to 6) are:

    [[], [3], [2], [1], [], [], []]
    

    Bucket 3 holds the value 1, bucket 2 holds 2, and bucket 1 holds 3. Reading from the highest index down, 1 comes first, then 2. After two values, the answer is complete.

    Step by step

    1. Create count as a var of type [Int: Int], starting empty with [:]. It maps each value to the number of times it appears.
    2. Loop over every num in nums.
    3. Add 1 to its count with count[num, default: 0] += 1. The default is used when the key is missing, so a value seen for the first time starts from 0.
    4. Create the buckets. [[Int]](repeating: [], count: nums.count + 1) makes that many empty arrays. Counts range from 1 to nums.count, so index nums.count must exist, which is why there is a + 1.
    5. Loop over the dictionary taking each entry as (num, freq).
    6. Put each value in its bucket with buckets[freq].append(num).
    7. Create result, an empty [Int].
    8. Start freq at nums.count, the highest count a value could have, and read the buckets downward from there. Empty buckets add nothing.
    9. Loop while result.count < k.
    10. Take a whole bucket with append(contentsOf:), which adds every item of an array. The answer is unique, so a bucket never brings the result past k values.
    11. Move down with freq -= 1.
    12. Return result.

    The solution in Swift

    class Solution {
        func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
            var count: [Int: Int] = [:]
            for num in nums {
                count[num, default: 0] += 1
            }
            var buckets = [[Int]](repeating: [], count: nums.count + 1)
            for (num, freq) in count {
                buckets[freq].append(num)
            }
            var result: [Int] = []
            var freq = nums.count
            while result.count < k {
                result.append(contentsOf: buckets[freq])
                freq -= 1
            }
            return result
        }
    }
    

    Swift details worth knowing:

    • Dictionary subscripts return optionals. A plain count[num] has type Int?, and it is nil for a missing key. The form count[num, default: 0] returns a plain Int, and it can be used with += to update the entry in place.
    • Dictionary order is not fixed. Iterating for (num, freq) in count visits the entries in an order that Swift doesn't promise and that can change from one run of the program to the next. That only affects the order of values inside one bucket, and the problem allows any order.
    • Buckets are independent. [[Int]](repeating: [], count: n) copies the same empty array n times, but arrays are value types, so appending to one bucket doesn't touch the others.
    • Shadowing the name freq. The freq in for (num, freq) in count only exists inside that loop. The later var freq is a separate variable declared after it.
    • append against append(contentsOf:). append(x) adds one element. append(contentsOf: xs) adds each element of xs.

    Complexity

    Let n be the length of nums.

    Time: O(n). Counting is one pass. Building the buckets creates n + 1 arrays and places each distinct value once. The final loop visits at most n buckets and appends each value at most once.

    Space: O(n). The dictionary holds at most n entries and the buckets array has n + 1 slots, with every distinct value in exactly one of them.

    Edge cases and common mistakes

    • One value. [1] with k = 1 returns [1]. The only bucket used is bucket 1.
    • A value that fills the array. [5, 5, 5, 5] with k = 1 returns [5]. Its count is 4 = nums.count, which is why the buckets need the extra slot.
    • Negative values. They are fine as dictionary keys. [4, -1, 4, -1, 7, 4, -1, 9] with k = 2 returns 4 and -1, in either order.
    • Taking everything. With [1, 1, 2, 2, 3, 3, 3] and k = 3, all three distinct values come back. The one with the highest count comes first, and the other two follow in whatever order their shared bucket holds them.
    • Ties at the cut. The method relies on the guarantee that there are none. For [1, 2] and k = 1, both values have count 1 and share a bucket, so the method returns both, [2, 1] in one run, which is more than k.
    • A k that is too large. Asking for more values than there are distinct ones would make freq go below 0, and the bucket lookup would stop the program. The constraints rule it out.
    • Forgetting the + 1. Without it, a value that appears nums.count times has no bucket, and appending to it is an index error.

    Testing

    • [1, 1, 1, 2, 2, 3] with k = 2 gives [1, 2].
    • [1] with k = 1 gives [1].
    • [5, 5, 5, 5] with k = 1 gives [5].
    • [1, 2, 3, 3] with k = 1 gives [3].
    • [4, -1, 4, -1, 7, 4, -1, 9] with k = 2 gives [4, -1] in one run, and the order may differ.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free