↓Skip to main content
  1. LeetCode/

LeetCode 575: Distribute Candies

·1 min· ·
LeetCode Easy Array Hash-Table
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-27

  • Submissions: Runtime Error ×2 → Wrong Answer ×2 → Accepted ×3

Approach
#

Two limits: only n / 2 candies may be eaten, so at most n / 2 kinds; and only len(set(candyType)) kinds exist. Both are achievable, so the answer is their min (Hash Table).

My Attempts
#

The first two had syntax errors, and the next two used max, keeping only the looser limit: [4, 0] returned 2, although only one candy may be eaten. min passed.

Solution
#

class Solution:
    def distributeCandies(self, candyType: List[int]) -> int:
        return min(len(candyType) // 2, len(set(candyType)))

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Both limits apply, so take the min.

Interview Explanation
#

The number of kinds is limited both by eating only half and by how many kinds exist, so the answer is the smaller. Time O(n).

Related

LeetCode 448: Find All Numbers Disappeared in an Array
·1 min
LeetCode Easy Array Hash-Table
LeetCode 448 note: use the array itself as the hash table, marking nums[x - 1] negative for each x; positions still positive are the missing numbers
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 219: Contains Duplicate II
·2 mins
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 note: a hash map stores each value’s last index; only the most recent occurrence needs a distance check
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 1: Two Sum
·2 mins
LeetCode Easy Array Hash-Table
LeetCode 1 note: store seen numbers in a hash map while scanning and look up target - x; checking before storing prevents using one element twice