Similar Problems

Similar Problems not available

Counter - Leetcode Solution

Companies:

LeetCode:  Counter Leetcode Solution

Difficulty: Unknown

Topics: unknown  

The counter problem on LeetCode involves counting the number of occurrences of each element in an array and returning a new array with the counts. The input array can have both positive and negative integers. The output array should have the counts of each integer in ascending order.

Here is a detailed solution to solve this problem in Python:

  1. First, we create an empty dictionary to store the counts of each integer in the input array.

  2. We then loop through each element in the input array.

  3. If the element is not already in the dictionary, we add it to the dictionary and set its count to 1.

  4. If the element is already in the dictionary, we increment its count by 1.

  5. Finally, we create a new list and populate it with the counts of each integer in ascending order using the sorted() function.

Here is the Python code for the solution:

def counter(nums):
    counts = {}
    for num in nums:
        if num not in counts:
            counts[num] = 1
        else:
            counts[num] += 1
    result = []
    for num, count in sorted(counts.items()):
        result.extend([num] * count)
    return result

This code first creates an empty dictionary counts to store the counts of each integer. It then loops through each element in the input array nums. If the element num is not in the counts dictionary, we add it with a count of 1. If the element is already in the dictionary, we increment its count by 1.

Finally, we create a new list result and use the sorted() function to sort the dictionary by its keys (the integers in the input array). We then loop through the sorted dictionary and append the integers to the result list, multiplying each integer by its count. This gives us a list with the counts of each integer in ascending order.

We can test this function with the following input:

print(counter([1, 2, 3, 4, 4, 3, 2, 1, 5, -1, -2, -3]))

This input has both positive and negative integers, and contains repeated numbers. The expected output is:

[-3, -2, -1, 1, 2, 3, 4, 5]

This output correctly shows the counts of each integer in the input array, in ascending order.

Counter Solution Code

1