Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Aggressive Cows Problem
Optimal Binary Search Solution



Problem Statement

Given N stalls represented by their positions on a number line (sorted or unsorted), and K cows to place in these stalls, the goal is to place the cows such that the minimum distance between any two cows is as large as possible.

If the number of cows exceeds the number of stalls, it’s not possible to place all cows.

Examples

Stall PositionsNo. of Cows (K)OutputDescription
[1, 2, 4, 8, 9]33We can place cows at positions 1, 4, and 8 — min distance = 3
[1, 2, 4, 8, 9]28Place cows at positions 1 and 9 — max possible distance
[5, 17, 100, 111]2106Place cows at 5 and 111 — max min distance is 106
[5, 17, 100, 111]46All cows must be placed, closest pair ends up at 6 units apart
[10]10Only one cow, no distance to maximize
[10]2-1Not enough stalls to place 2 cows
[]2-1Empty array, no stalls available
[2, 4, 6]00Zero cows, so minimum distance is trivially zero

Solution

The Aggressive Cows problem is a classic example where we want to use binary search on the answer. Instead of searching through positions, we ask: what is the largest possible minimum distance we can achieve between cows placed in stalls?

Understanding the Problem

We are given stall positions — say [1, 2, 4, 8, 9] — and asked to place K cows in them. The twist is: we want to maximize the minimum distance between any two cows. That means, the cows should be as far apart as possible, but we still need to fit all of them into the stalls.

Different Scenarios to Consider

  • Exact fit: If the number of cows equals the number of stalls, the only option is one cow per stall, and the smallest distance between any two is what we return.
  • Single cow: If there’s only one cow to place, we can put it anywhere. There’s no pair to measure distance, so the answer is 0.
  • Too many cows: If K > N, we cannot place all cows — so we return -1 or some invalid flag.
  • Empty stalls: If the stall list is empty, there’s no way to place any cows — again, return -1.

How the Strategy Works

First, we sort the stall positions to ensure they're in order. Then, we try to guess the minimum distance between cows (starting from 1 up to the max difference between stalls) using binary search.

At each step, we check: "Can we place all K cows such that the gap between any two is at least mid?"

  • If yes → maybe we can do even better, so try a bigger distance.
  • If no → that distance is too much, reduce the range.

We keep narrowing the range until we find the largest distance that works — that’s our answer.

Efficiency

This method is very efficient: we’re doing a binary search on distance (which ranges from 1 to max stall gap), and for each guess, we do a linear pass to see if placement is possible. This gives us an overall time complexity of O(N log(MaxDistance)).

It’s an excellent real-world inspired problem that blends greedy thinking with binary search — ideal for learning how to "search on the answer".

Visualization

Algorithm Steps

  1. Sort the arr in increasing order.
  2. Set low = 1 (smallest possible min distance) and high = arr[n - 1] - arr[0] (largest possible).
  3. Use binary search: while low ≤ high:
  4. → Compute mid = (low + high) / 2.
  5. → Check if it's possible to place k cows with at least mid distance between them.
  6. → If yes, store mid as a candidate and try for a larger value (low = mid + 1).
  7. → If not, reduce the distance (high = mid - 1).
  8. Return the largest valid mid found.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
import java.util.Arrays;

public class AggressiveCows {
    public static boolean canPlace(int[] stalls, int cows, int minDist) {
        int count = 1; // Place first cow at the first stall
        int lastPlaced = stalls[0];
        for (int i = 1; i < stalls.length; i++) {
            if (stalls[i] - lastPlaced >= minDist) {
                count++;
                lastPlaced = stalls[i];
                if (count == cows) return true;
            }
        }
        return false;
    }

    public static int solve(int n, int k, int[] arr) {
        Arrays.sort(arr);
        int low = 1, high = arr[n - 1] - arr[0];
        int result = 0;

        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (canPlace(arr, k, mid)) {
                result = mid; // Try for a bigger answer
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] stalls = {1, 2, 4, 8, 9};
        int k = 3;
        System.out.println("Max Min Distance: " + solve(stalls.length, k, stalls));
    }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n log(maxDist))Binary search on the distance (log(max position)) and each check takes O(n).
Average CaseO(n log(maxDist))Each iteration of binary search checks placement for given mid using O(n).
Average CaseO(n log(maxDist))In the worst case, binary search runs log(max distance) steps and each step scans the stalls.

Space Complexity

O(1)

Explanation: No extra space apart from a few variables; we sort in-place and use constant memory.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M