DSA Tracker

Medium

Aggressive Cows

A medium Binary Search problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Binary Search
Sheets
1
Core for
7 roles
Platform
LeetCode

The problem

You are herding cows into stalls along a line. Given the positions of all stalls and the number of cows to place, assign cows to stalls so that the minimum distance between any two cows is as large as possible. Return that maximum minimum distance.

Example 1

Input
stalls = [1,2,4,8,9], cows = 3
Output
3
Why
Place cows at positions 1, 4, and 8 (or 1, 4, 9). The minimum distance between any pair is 3.

Example 2

Input
stalls = [1,2,3,4,7], cows = 3
Output
3
Why
Place cows at positions 1, 4, and 7. The minimum distance is 3.

Constraints

  • 2 <= stalls.length <= 10^5
  • 2 <= cows <= stalls.length
  • 0 <= stalls[i] <= 10^9
  • stalls are sorted in non-decreasing order

How to think about it

Updated 2026-09-09

Testing whether all cows can be spaced apart by at least distance D is a linear scan: place the first cow at the earliest stall and greedily drop each subsequent cow at the first stall that maintains the separation. Because being able to space by D implies spacing by anything less than D is also achievable, the search space is monotonic.

Approaches, worst first

  1. Sequential distance probe

    time O((max - min) * n) · space O(1)

    Iterate distance candidate D from 1 upwards, verifying whether cows can be placed with greedy placement until the placement test fails. Inefficient when stall coordinates span up to 10^9.

  2. Binary search on answerWrite this one

    time O(n log(max - min)) · space O(1)

    Binary search over possible distances between 1 and stalls[n-1] - stalls[0]. For each mid, greedily assign cows to stalls meeting the distance gap; expand to the right half if cows placed reaches the target.

Where people lose marks · 3
  • Assuming the input stalls array is already sorted without checking the constraints; while this instance notes sorted order, greedy placement collapses if positions are unsorted.
  • Placing the first cow anywhere other than stalls[0] wastes available linear span, artificially constraining future cow placements.
  • Allowing the lower bound of distance to be 0 can cause divisions or infinite loops in implementations using distance ratios; minimum stall separation is at least 1.

The theory behind it

Binary Search — the ground this problem stands on. All Binary Search problems

What Binary Search is

Binary search is the guessing strategy used when searching a thick telephone directory or guessing a secret number between one and a hundred. Rather than inspecting names one by one from the first page, the search opens straight to the middle page. If the target precedes that middle entry, the entire back half is discarded; if it follows, the front half is eliminated. Repeating this halved split finds the item with remarkable speed.

When to reach for it

Reach for binary search when queries target sorted collections, rotated sorted arrays, or monotonic answer spaces. Strong hints include logarithmic time constraints like O(log n) or search ranges exceeding one billion where stepping one value at a time times out. It also applies when validating whether a guessed solution is possible via a monotonic boolean check, known as binary search on answer.

How the pattern works

Define the search territory with two inclusive pointers, low and high. Compute the midpoint using low plus half the difference to high, avoiding integer overflow. Formulate an exact boolean condition that divides the range into true and false halves. Decide whether the boundary condition includes the midpoint or shifts strictly past it. The loop invariant states that the sought target, if it exists, remains trapped inside the interval throughout every iteration.

What each operation costs

OperationTime
find target in sorted arrayO(log n)
find boundary in monotonic rangeO(log n)
What usually goes wrong with Binary Search
  • Triggering integer overflow by computing middle using low plus high divided by two instead of low plus half of high minus low in fixed-width numeric types.
  • Creating an infinite loop when the interval shrinks to two elements by setting low equal to mid when mid was rounded down.
  • Mismatched loop condition and bounds updates, such as pairing low less than or equal to high with non-advancing pointer assignments that never terminate.

Which roles need this problem

Binary Search is a core topic for these 7 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 17 more roles, including Full-Stack Developer, Data Engineer, Android Developer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Binary Search problems

Problem set and role mapping as of .