As reported: KLA, 1st round (2025), three coding questions on HackerRank while talking with the interviewer; this was the third:
njars (2 ≤ n ≤ 4) with capacitiesc1 … cnand initial wateri1 … in; find the minimum number of transfers to measureXliters; the answer is at most 6.
There are n jars. Jar j can hold capacities[j] liters and starts with initial[j] liters. In one transfer you pour water from one jar into another until either the source jar is empty or the target jar is full, whichever comes first. Water is never added or thrown away.
Return the minimum number of transfers after which some jar holds exactly target liters (0 if a jar already does).
Example 1
capacities = [8,5,3], initial = [8,0,0], target = 4 -> 6
One shortest sequence (amounts per jar): [8,0,0] → [3,5,0] → [3,2,3] → [6,2,0] → [6,0,2] → [1,5,2] → [1,4,3].
Example 2
capacities = [3,5], initial = [3,2], target = 5 -> 1 pour jar 0 into jar 1: [0,5]
Clarifications
- A transfer moves
min(water in source, free space in target)liters. - The inputs guarantee that
targetcan be reached in at most 6 transfers.
Constraints: 2 ≤ n ≤ 4; 1 ≤ capacities[j] ≤ 1000; 0 ≤ initial[j] ≤ capacities[j]; 0 ≤ target ≤ 1000.
Code runner format: three lines: capacities and initial as JSON arrays, then target. Implement minTransfers(capacities, initial, target); the harness prints the number of transfers.