Aggressive Cows

Pattern: Binary search on the answer

medium

Maximise the smallest gap. Guess a gap d, place cows greedily from the left with at least d between them, and see whether all k fit. Smaller gaps are easier, so binary search the largest d that works.

The problem

There are n stalls on a line at given positions and k cows, with 2 ≤ k ≤ n. Put each cow in a different stall so that the smallest distance between any two cows is as large as possible. Return that largest possible smallest distance. For example, stalls [1, 2, 4, 8, 9] with k = 3 give 3, using stalls 1, 4 and 8.

The link above is the SPOJ problem AGGRCOW, which reads several test cases from input. This guide's function aggressiveCows solves one case, and its name is this guide's own.

Think first

  • Fix a gap d. How can you check quickly whether k cows fit with at least d between neighbours?
  • If gap d works, does every smaller gap work?
  • What is the largest gap that could possibly work?

Hints

    Brute force, and why it fails

    Try every set of k stalls and take the best smallest gap: exponential. Trying every gap d with the greedy check is O(n × range). Binary search on d is O(n log range) after sorting.

    The key insight

    "Maximise the minimum" turns into a yes/no question: can every gap be at least d? That question is easy to answer greedily and only gets harder as d grows, so binary search finds the best d.

    Dry run

    10 
    21lo
    42 
    83 
    94 

    stalls = [1, 2, 4, 8, 9] and k = 3 cows. Sorted already. Gaps from 1 to 9 - 1 = 8 are possible.

    Step 1 of 4

    The plan

    sort stalls
    lo = 1, hi = stalls[n - 1] - stalls[0]
    while lo < hi:
        mid = lo + (hi - lo + 1) / 2
        if fits(mid): lo = mid
        else: hi = mid - 1
    return lo
    
    fits(d): placed = 1, last = stalls[0]
        for each s after the first: if s - last >= d: placed = placed + 1; last = s
        return placed >= k
    

    Complexity

    Time
    O(n log n + n log range)
    Space
    O(n)

    Sorting, then about log₂ range checks of O(n) each. The copy of the stalls takes O(n).

    Edge cases

    • k = 2: the answer is the full span, last - first.
    • k = n: every stall is used, so the answer is the smallest gap between neighbours.
    • Unsorted input: sort first.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int aggressiveCows(int[] stalls, int k) {
            int[] s = stalls.clone();
            Arrays.sort(s);
            int lo = 1, hi = s[s.length - 1] - s[0];    // the answer is the largest distance that still fits k cows
            while (lo < hi) {
                int mid = lo + (hi - lo + 1) / 2;       // round up, because lo = mid below
                if (fits(s, mid, k)) lo = mid;          // mid works: try bigger
                else hi = mid - 1;
            }
            return lo;
        }
    
        private boolean fits(int[] s, int d, int k) {
            int placed = 1, last = s[0];                // greedy: put a cow in the first stall
            for (int i = 1; i < s.length; i++) {
                if (s[i] - last >= d) { placed++; last = s[i]; }   // next stall far enough away
            }
            return placed >= k;
        }
    }

    C++

    class Solution {
    public:
        int aggressiveCows(vector<int>& stalls, int k) {
            vector<int> s = stalls;
            sort(s.begin(), s.end());
            int lo = 1, hi = s.back() - s[0];          // the answer is the largest distance that still fits k cows
            while (lo < hi) {
                int mid = lo + (hi - lo + 1) / 2;      // round up, because lo = mid below
                if (fits(s, mid, k)) lo = mid;         // mid works: try bigger
                else hi = mid - 1;
            }
            return lo;
        }
    
        bool fits(vector<int>& s, int d, int k) {
            int placed = 1, last = s[0];               // greedy: put a cow in the first stall
            for (size_t i = 1; i < s.size(); i++) {
                if (s[i] - last >= d) { placed++; last = s[i]; }   // next stall far enough away
            }
            return placed >= k;
        }
    };

    Python

    class Solution:
        def aggressiveCows(self, stalls: list[int], k: int) -> int:
            s = sorted(stalls)
            lo, hi = 1, s[-1] - s[0]                # the answer is the largest distance that still fits k cows
            while lo < hi:
                mid = (lo + hi + 1) // 2            # round up, because lo = mid below
                if self.fits(s, mid, k):
                    lo = mid                        # mid works: try bigger
                else:
                    hi = mid - 1
            return lo
    
        def fits(self, s: list[int], d: int, k: int) -> bool:
            placed, last = 1, s[0]                  # greedy: put a cow in the first stall
            for v in s[1:]:
                if v - last >= d:                   # next stall far enough away
                    placed += 1
                    last = v
            return placed >= k

    Common mistakes

    • Forgetting to sort the stalls.
    • Rounding mid down with lo = mid, which loops forever.
    • Checking whether exactly k cows fit instead of at least k. Extra room is fine.

    Similar problems