Skip to content

Bug Report for top-k-elements-in-list #4425

@denyszhak

Description

@denyszhak

Bug Report for https://neetcode.io/problems/top-k-elements-in-list

Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.

This solution is perfectly accepted:

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count = {}

        for n in nums:
            count[n] = count.get(n, 0) + 1

        arr = [[] for _ in range(len(nums) + 1)]
        for n, c in count.items():
            arr[c].append(n)

        result = []
        for subarr in arr[::-1]:
            if len(result) == k:
                break

            for n in subarr:
                result.append(n)

        return result

although it has a bug for input like
[1,1,2,2,3,3]
2

This is how the last iteration should look

for subarr in arr[::-1]:
    for n in subarr:
        if len(result) == k:
            break

        result.append(n)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions