Determine Animal Quantities in a Barn
Math & Bit ManipulationAuto-graded · 17 test casesLast updated
Find the integer count of each animal species given the total legs and proportional species constraints.
You are tasked with evaluating the exact population breakdown in a barn containing chickens, ants, and cows.
The populations follow fixed proportional relations:
- The count of ants is twice the count of chickens.
- The count of cows is twice the count of ants.
Standard leg counts per individual of each species are:
- Chickens: 2 legs
- Ants: 6 legs
- Cows: 4 legs
Given an integer total_legs, determine if a non-negative integer count exists for each species that satisfies both the proportional rules and the exact leg count.
If a valid configuration exists, return a dictionary containing keys "chickens", "ants", and "cows" mapped to their respective integer counts. If no valid non-negative integer solution exists, return None.
Constraints
- $0 \le \text{total_legs} \le 10^9$
Examples
Example 1
Input: solve_barn_counts(570)
Output: {'chickens': 19, 'ants': 38, 'cows': 76}
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We represent all animal counts in terms of a single variable $C$, denoting the count of chickens.
From the problem rules:
- Ants: $A = 2C$
- Cows: $W = 2A = 4C$
Using the standard leg numbers for each animal (2 per chicken, 6 per ant, 4 per cow), the total leg sum is: $$\text{Total Legs} = 2C + 6A + 4W$$
Substituting $A$ and $W$ in terms of $C$: $$\text{Total Legs} = 2C + 6(2C) + 4(4C) = 2C + 12C + 16C = 30C$$
This shows that any valid barn configuration must have a total leg count that is a multiple of 30. A single base group (1 chicken, 2 ants, and 4 cows) contributes exactly 30 legs.
Algorithm
- If
total_legs % 30 != 0, no non-negative integer solution exists, so returnNone. - Compute $C = \text{total_legs} // 30$.
- Compute $A = 2C$ and $W = 4C$.
- Return the result dictionary with keys
"chickens","ants", and"cows".
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$ as it involves constant-time arithmetic operations.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space.
from typing import Optional, Dict
def solve_barn_counts(total_legs: int) -> Optional[Dict[str, int]]:
if total_legs % 30 != 0:
return None
chickens = total_legs // 30
ants = 2 * chickens
cows = 4 * chickens
return {
"chickens": chickens,
"ants": ants,
"cows": cows
}