1st LeetCode- X of a Kind in a Deck of Cards

Shu-Yu Huang
2 min readApr 15, 2020

LeetCode is a platform for practicing coding skills especially skills in designing algorithms.
It’s my first try on LeetCode, so I picked up one Easy level problem:

In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

  • Each group has exactly X cards.
  • All the cards in each group have the same integer.

In the gist, to determine iff there exist N group of x same integer in the deck with K cards.

My solution 1:
1. If the length of deck <2, return false.
2. Put 1 card into group 1 and start comparing it with the following cards (card k) then follow procedures below:
a. Start from group 1, search if it is identical to the 1st of that group.
b-1. If there exists a group that card k is identical to, then store card k into that group.
b-2.Else, create a new group for card k
3. Repeat step 2 for each card k until all cards are sorted into groups
4. Find the minimal card amount among groups by comparing the card amount 1 by 1.
5. For each group n, check if {card amount of group n} mod {minimal card amount} is zero.

  • Each group has exactly X cards.
  • All the cards in each group have the same integer.
# Dev: Chumicat
# Date: 2019/12/1
# Submission: https://leetcode.com/submissions/detail/282916566/
# (Time, Space) Complexity : O(n), O(n)

from collections import Counter
from math import gcd
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
# Rule:
# We just need to check if nums count are interprime
# If they have same prime factor, X must exist
# Strategy:
# 1. Get all count of each number
# 2. Use gcd to check
# 3. Return result

# 1. Get all count of each number
# I take value from set arbitrarily rather than pop
# So that I didn't need to dealing one value case
cnt_set = set(Counter(deck).values())
gcd_val = next(iter(cnt_set))

# 2, 3. Use gcd to check, return result
for cnt in cnt_set:
gcd_val = gcd(gcd_val, cnt)
if gcd_val == 1: return False
return True

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shu-Yu Huang
Shu-Yu Huang

Written by Shu-Yu Huang

AI engineer in Taiwan AI Academy| Former process engineer in TSMC| Former Research Assistance in NYMU| Studying few-shot-learning and GAN

No responses yet

Write a response