Suppose we have a list of numbers called nums, we have to check whether we can split the list into 1 or more groups such that: 1. Size of each group is greater than or equal to 2. 2. Sizes of all groups are same. 3. All the numbers present in each group are the same.
So, if the input is like [3, 4, 6, 9, 4, 3, 6, 9], then the output will be True.
To solve this, we will follow these steps −
- counts := a map where each key are distinct element and values are their frequencies
- temp := 0
- for each count in counts, do
- if temp is same as 0, then
- temp := counts[count]
- otherwise,
- temp := gcd of counts[count] and temp
- if temp is same as 1, then
- return False
- if temp is same as 0, then
- return True
Let us see the following implementation to get better understanding −
Example
from collections import Counter import math class Solution: def solve(self, nums): counts = Counter(nums) temp = 0 for count in counts: if temp == 0: temp = counts[count] else: temp = math.gcd(counts[count], temp) if temp == 1: return False return True ob = Solution() L = [3, 4, 6, 9, 4, 3, 6, 9] print(ob.solve(L))
Input
[3, 4, 6, 9, 4, 3, 6, 9]
Output
True