File: distribute-candies/solution.py

Date: 2026-06-06

Time: 16:25

distribute-candies/solution.py

Purpose

This file solves LeetCode 575 - Distribute Candies. It determines the maximum number of distinct candy types Alice can eat, given she's allowed exactly half the total candies.

Key Components

maxNumberOfCandies(candyType: list[int]) -> int — The sole function. Takes an array where each element represents a candy's type, returns the maximum number of *distinct* types Alice can eat when restricted to n/2 candies.

The implementation is a single expression: min(len(candyType) // 2, len(set(candyType))).

Patterns

Constraint-as-min pattern. The answer is bounded by two independent constraints — she can eat at most n/2 candies, and there are at most k distinct types. The answer is simply min(n/2, k). This is a common idiom in greedy problems where the answer is the tighter of two upper bounds.

Standalone function (no class). Unlike LeetCode's typical class Solution wrapper, this exports a bare function. Consistent with the rest of this repo's convention.

Dependencies

Imports: None. Uses only builtins (len, set, min, integer division).

Imported by: distribute-candies/test_solution.py directly. The "Imported By" list in the prompt is misleading — those are *all* test files across the repo, likely an artifact of the test harness importing a shared runner, not this specific module.

Flow

1. set(candyType) — deduplicate to get the count of distinct types, O(n).

2. len(candyType) // 2 — compute Alice's eating quota (integer division, always valid since the problem guarantees even-length input).

3. min(...) — return the tighter bound.

No branching, no iteration beyond what set() does internally. Single-pass through the data.

Invariants

Error Handling

None. The function trusts its caller to provide valid input per the problem constraints. An empty list would return 0 (not crash), but odd-length lists would silently floor-divide — acceptable given the problem contract.