Teaching Kids Programming – Group Integers


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given a list of integers nums, return whether you can split the list into 1 or more groups where:

The size of each group is larger than or equal to 2.
The sizes of all groups are equal.
All the integers in each group are the same.

Constraints
n ≤ 100,000 where n is the length of nums
Example 1
Input
nums = [2, 3, 5, 8, 3, 2, 5, 8]
Output
True
Explanation
We can group the numbers like so:
[2, 2]
[3, 3]
[5, 5]
[8, 8]

Example 2
Input
nums = [3, 0, 0, 3, 3, 3]
Output
True
Explanation
We can group the numbers like so:
[0, 0]
[3, 3]
[3, 3]

Group Integers

The values do not actually matter. The frequencies of each unique numbers matter. We can use Counter to count the numbers. And compute the Greatest Common Divisor of it. If the result is 1 meaning that we cannot group integers in such way that meet those 3 requirements.

1
2
3
4
5
6
7
class Solution:
    def solve(self, nums):
        m = list(Counter(nums).values())
        a = m[0]
        for i in m: # or m[1:]
            a = gcd(a, i)
        return a > 1
class Solution:
    def solve(self, nums):
        m = list(Counter(nums).values())
        a = m[0]
        for i in m: # or m[1:]
            a = gcd(a, i)
        return a > 1

One liner using the reduce function:

1
2
3
class Solution:
    def solve(self, nums):
        return reduce(gcd, Counter(nums).values()) > 1
class Solution:
    def solve(self, nums):
        return reduce(gcd, Counter(nums).values()) > 1

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
354 words
Last Post: Auto Close Resources: A Lock Wrapper in Java that Allows AutoCloseable (Try-With-Resources)
Next Post: GoLang: Reverse the Bits

The Permanent URL is: Teaching Kids Programming – Group Integers

Leave a Reply