DSA interview question
A farmer has n stalls along a straight barn at given positions and c cows that fight when placed close together. He wants to place all c cows in stalls so that the minimum distance between any two cows is as large as possible. Trying all placements is exponential. Flip the question: "Can I place c cows so that every pair is at least d apart?" That's a greedy check (put each cow in the first stall far enough from the previous one), and if distance d is achievable, every smaller distance is too. So binary search the largest achievable d.
Example: stalls [1, 2, 4, 8, 9], c = 3 → 3 (cows at 1, 4 and 8, or 1, 4 and 9).
int aggressiveCows(vector<int> stalls, int cows); // largest possible minimum distance; 2 <= cows <= n
Input (stalls, cows) | Output | Explanation |
|---|---|---|
([1, 2, 4, 8, 9], 3) | 3 | For example 1, 4, 8 |
([10, 1, 2, 7, 5], 3) | 4 | Sorted [1, 2, 5, 7, 10]: 1, 5, 10 |
([2, 12, 11, 3, 26, 7], 5) | 1 | Five cows force stalls 1 apart |
([0, 3, 4, 7, 10, 9], 4) | 3 | 0, 3, 7, 10 |
([1, 2], 2) | 1 |
(Confirm: stall positions are distinct and unsorted; 2 ≤ cows ≤ number of stalls.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in