KatInterview

Count Animals from Legs and Population Ratios

Math & Bit ManipulationAuto-graded · 17 test cases
EasyAuto-gradedMath & Bit Manipulationalgebralinear-equationsconstraint-satisfaction

Last updated

Tests setting up and solving a system of linear equations with fixed ratios between variables.

You're observing three species in an enclosure: ants, chickens, and cows. Each species has a fixed number of legs, and their populations follow strict proportional relationships.

Given information:

  • Ants have 6 legs each
  • Chickens have 2 legs each
  • Cows have 4 legs each
  • The number of ants is exactly twice the number of chickens
  • The number of cows is exactly twice the number of ants

Your task: given the total count of legs observed, determine how many ants are present.

If the given leg count cannot be produced by any valid population (where all animal counts are positive integers satisfying the ratio constraints), return 0.

Constraints

  • 0 ≤ total_legs ≤ 10^6
  • All animal populations must be positive integers
  • The ratio constraints must be exactly satisfied

Examples

Example 1

Input: count_ants_from_legs(570)

Output: 38

Example 2

Input: count_ants_from_legs(30)

Output: 2

Example 3

Input: count_ants_from_legs(150)

Output: 10

Hints

Hint 1

Express all populations in terms of a single variable, then set up an equation for the total leg count.

Hint 2

The ratios form a chain: chickens determine ants, and ants determine cows. Choose the base of this chain as your variable.

Hint 3

Once you solve for the base variable, check whether it produces a positive integer for all three populations.