Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Aggressive Cows | GeeksforGeeks Solution Explained | Binary Search
    Data Structures & Algorithms

    Aggressive Cows | GeeksforGeeks Solution Explained | Binary Search

    Anirudh KhuranaBy Anirudh Khurana10 July 2025Updated:16 November 2026No Comments11 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of a question to solve aggresive cows question
    Share
    Facebook Twitter LinkedIn Pinterest Email

    The “Aggressive Cows” problem is a classic binary search question that is often asked in coding interviews.

    It teaches you how to optimize placement problems using binary search. In this blog, we’ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with code comments, dry runs, and clear explanations.

    Here’s the [Problem Link] to begin with.


    Problem Statement

    You are given an array with unique elements of stalls[], which denote the position of a stall. You are also given an integer k which denotes the number of aggressive cows. Your task is to assign stalls to k cows such that the minimum distance between any two of them is the maximum possible.

    Examples :

    Input: stalls[] = [1, 2, 4, 8, 9], k = 3
    Output: 3
    Explanation: The first cow can be placed at stalls[0],
    the second cow can be placed at stalls[2] and
    the third cow can be placed at stalls[3].
    The minimum distance between cows, in this case, is 3, which also is the largest among all possible ways.
    Input: stalls[] = [10, 1, 2, 7, 5], k = 3
    Output: 4
    Explanation: The first cow can be placed at stalls[0],
    the second cow can be placed at stalls[1] and
    the third cow can be placed at stalls[4].
    The minimum distance between cows, in this case, is 4, which also is the largest among all possible ways.
    Input: stalls[] = [2, 12, 11, 3, 26, 7], k = 5
    Output: 1
    Explanation: Each cow can be placed in any of the stalls, as the no. of stalls are exactly equal to the number of cows.
    The minimum distance between cows, in this case, is 1, which also is the largest among all possible ways.

    Constraints:
    2 <= stalls.size() <= 106
    0 <= stalls[i] <= 108
    2 <= k <= stalls.size()

    Contents:
    • Problem Statement
    • Brute Force Solution (Try Every Possible Distance)
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Dry Run
      • Time and Space Complexity
      • Conclusion
    • Optimal Solution (Binary Search)
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Dry Run
      • Time and Space Complexity
      • Conclusion
    • Final Thoughts

    Interactive Visualizer: Binary Search on the Answer

    Choose an example or type stall positions, a | and the number of cows, then press Next. Each step tries one distance, places cows greedily from left to right, and moves low or high depending on whether all cows fit.



    Brute Force Solution (Try Every Possible Distance)

    Intuition and Approach

    Let’s solve the problem in the most straightforward way:

    1. Try Every Distance:
      Try every possible minimum distance from 1 up to the maximum possible (difference between the farthest and closest stall).
    2. Check If Placement Is Possible:
      For each distance, check if it is possible to place all cows with at least that much distance between them.
    3. Return the Largest Valid Distance:
      The largest distance for which placement is possible is our answer.
    4. Why does this work?
      We check every possible distance, so we’re sure to find the largest one that works.

    This approach is easy to understand but not efficient for large inputs.

    Code Implementation

    class Solution:
    
        def canWePlace(self, stalls, dist, cows):
            # Size of array
            n = len(stalls)
    
            # Number of cows placed
            cntCows = 1
    
            # Position of last placed cow
            last = stalls[0]
            for i in range(1, n):
                if stalls[i] - last >= dist:
                    # Place next cow
                    cntCows += 1
    
                    # Update the last location
                    last = stalls[i]
                if cntCows >= cows:
                    return True
    
            return False
    
        def aggressiveCows(self, stalls, k):
            # Size of list
            n = len(stalls)
    
            # Sort the nums
            stalls.sort()
    
            limit = stalls[-1] - stalls[0]
            for i in range(1, limit + 1):
                if not self.canWePlace(stalls, i, k):
                    return i - 1
    
            # Return the answer
            return limit
    Python
    class Solution {
        private boolean canWePlace(int[] stalls, int dist, int cows) {
            // Size of array
            int n = stalls.length;
    
            // Number of cows placed
            int cntCows = 1;
    
            // Position of last placed cow
            int last = stalls[0];
            for (int i = 1; i < n; i++) {
                if (stalls[i] - last >= dist) {
                    // Place next cow
                    cntCows++;
    
                    // Update the last location
                    last = stalls[i];
                }
                if (cntCows >= cows) return true;
            }
            return false;
        }
    
        public int aggressiveCows(int[] stalls, int k) {
            // Sort the stalls
            Arrays.sort(stalls);
    
            int limit = stalls[stalls.length - 1] - stalls[0];
            for (int i = 1; i <= limit; i++) {
                if (!canWePlace(stalls, i, k)) return i - 1;
            }
            // Return the answer
            return limit;
        }
    }
    class Solution {
        bool canWePlace(vector<int>& stalls, int dist, int cows) {
            // Size of array
            int n = stalls.size();
    
            // Number of cows placed
            int cntCows = 1;
    
            // Position of last placed cow
            int last = stalls[0];
            for (int i = 1; i < n; i++) {
                if (stalls[i] - last >= dist) {
                    // Place next cow
                    cntCows++;
    
                    // Update the last location
                    last = stalls[i];
                }
                if (cntCows >= cows) return true;
            }
            return false;
        }
    
    public:
        int aggressiveCows(vector<int>& stalls, int k) {
            // Sort the stalls
            sort(stalls.begin(), stalls.end());
    
            int limit = stalls.back() - stalls[0];
            for (int i = 1; i <= limit; i++) {
                if (!canWePlace(stalls, i, k)) return i - 1;
            }
            // Return the answer
            return limit;
        }
    };

    Code Explanation

    • For each possible distance from 1 to the maximum possible, check if you can place all cows.
    • The helper function canWePlace tries to place cows with at least dist distance apart.
    • Return the largest distance for which placement is possible.

    Dry Run

    Input:
    stalls = [1], k = 3

    • Try distance = 1: possible
    • Try distance = 2: possible
    • Try distance = 3: possible
    • Try distance = 4: not possible (can’t place all cows)
    • Return 3

    Final Output:
    3

    Time and Space Complexity

    • Time Complexity: O((max(stalls) – min(stalls)) * n)
      For each distance, we check all stalls.
    • Space Complexity: O(1)
      Only variables for counting.

    Conclusion

    The brute force approach is simple and works for small inputs, but it’s too slow for large values.


    Optimal Solution (Binary Search)

    Intuition and Approach

    We can do much better using binary search:

    1. Binary Search on Distance:
      The answer lies between 1 and the difference between the farthest and closest stall. Use binary search to find the largest minimum distance.
    2. Check If Placement Is Possible:
      For each mid value (distance), check if it’s possible to place all cows.
    3. Adjust Search Window:
      • If placement is possible, try a larger distance.
      • If not, try a smaller distance.
    4. Why does this work?
      The placement function is monotonic: as the distance increases, it becomes harder to place all cows. Binary search is perfect for this.

    Code Implementation

    class Solution:
    
        def canWePlace(self, stalls, dist, cows):
            # Size of array
            n = len(stalls)
    
            # Number of cows placed
            cntCows = 1
    
            # Position of last placed cow
            last = stalls[0]
            for i in range(1, n):
                if stalls[i] - last >= dist:
                    # Place next cow
                    cntCows += 1
    
                    # Update the last location
                    last = stalls[i]
                if cntCows >= cows:
                    return True
    
            return False
    
        def aggressiveCows(self, stalls, k):
            # Sort the stalls to place cows in sorted positions
            stalls.sort()
    
            # Binary search for the maximum minimum distance
            low = 1  # Minimum possible distance
            high = stalls[-1] - stalls[0]  # Maximum possible distance
    
            result = 0
    
            while low <= high:
                mid = (low + high) // 2  # Try this distance
    
                if self.canWePlace(stalls, mid, k):
                    # If we can place cows with at least `mid` distance, try for a larger distance
                    result = mid
                    low = mid + 1
                else:
                    # If we can't place cows with at least `mid` distance, try for a smaller distance
                    high = mid - 1
    
            return result
    Python
    class Solution {
        private boolean canWePlace(int[] stalls, int dist, int cows) {
            // Size of array
            int n = stalls.length;
    
            // Number of cows placed
            int cntCows = 1;
    
            // Position of last placed cow
            int last = stalls[0];
            for (int i = 1; i < n; i++) {
                if (stalls[i] - last >= dist) {
                    // Place next cow
                    cntCows++;
    
                    // Update the last location
                    last = stalls[i];
                }
                if (cntCows >= cows) return true;
            }
            return false;
        }
    
        public int aggressiveCows(int[] stalls, int k) {
            // Sort the stalls to place cows in sorted positions
            Arrays.sort(stalls);
    
            // Binary search for the maximum minimum distance
            int low = 1;                                      // Minimum possible distance
            int high = stalls[stalls.length - 1] - stalls[0]; // Maximum possible distance
            int result = 0;
    
            while (low <= high) {
                int mid = low + (high - low) / 2; // Try this distance
                if (canWePlace(stalls, mid, k)) {
                    // We can place cows with at least mid distance, try a larger distance
                    result = mid;
                    low = mid + 1;
                } else {
                    // We can't place cows with at least mid distance, try a smaller distance
                    high = mid - 1;
                }
            }
            return result;
        }
    }
    class Solution {
        bool canWePlace(vector<int>& stalls, int dist, int cows) {
            // Size of array
            int n = stalls.size();
    
            // Number of cows placed
            int cntCows = 1;
    
            // Position of last placed cow
            int last = stalls[0];
            for (int i = 1; i < n; i++) {
                if (stalls[i] - last >= dist) {
                    // Place next cow
                    cntCows++;
    
                    // Update the last location
                    last = stalls[i];
                }
                if (cntCows >= cows) return true;
            }
            return false;
        }
    
    public:
        int aggressiveCows(vector<int>& stalls, int k) {
            // Sort the stalls to place cows in sorted positions
            sort(stalls.begin(), stalls.end());
    
            // Binary search for the maximum minimum distance
            int low = 1;                         // Minimum possible distance
            int high = stalls.back() - stalls[0]; // Maximum possible distance
            int result = 0;
    
            while (low <= high) {
                int mid = low + (high - low) / 2; // Try this distance
                if (canWePlace(stalls, mid, k)) {
                    // We can place cows with at least mid distance, try a larger distance
                    result = mid;
                    low = mid + 1;
                } else {
                    // We can't place cows with at least mid distance, try a smaller distance
                    high = mid - 1;
                }
            }
            return result;
        }
    };

    Code Explanation

    • Use binary search between 1 and the maximum possible distance.
    • For each mid distance, check if you can place all cows.
    • If you can, store the distance and try a larger one.
    • If not, try a smaller distance.
    • Return the largest valid distance found.

    Dry Run

    Input:
    stalls = [1], k = 3

    • low = 1, high = 8
    • mid = 4: can’t place all cows → high = 3
    • mid = 2: can place all cows → result = 2, low = 3
    • mid = 3: can place all cows → result = 3, low = 4

    Loop ends, answer is 3.

    Time and Space Complexity

    • Time Complexity: O(n * log(max(stalls) – min(stalls)))
      Binary search on distance, checking all stalls for each guess.
    • Space Complexity: O(1)
      Only variables for counting.

    Conclusion

    The optimal solution is efficient and works well for large arrays and high values. It’s the best approach for interviews and practical use.

    Final Thoughts

    The “Aggressive Cows” problem is a great example of how to optimize from brute force to an efficient binary search solution. Start with brute force to understand the basics, then use binary search for best performance.

    Frequently Asked Questions

    What is the Aggressive Cows problem?

    You are given stall positions and k cows. Place the cows in stalls so that the minimum distance between any two cows is as large as possible, and return that distance. For stalls [1, 2, 4, 8, 9] and k = 3 the answer is 3.

    Why can we use binary search in Aggressive Cows?

    The answer is monotonic: if the cows can be placed with a minimum distance d, they can also be placed with any smaller distance. So the distances that work form a range starting at 1, and binary search finds the largest one.

    Why does greedy placement work for checking a distance?

    Placing the first cow in the first stall and every next cow in the earliest stall that is far enough leaves the most room for the remaining cows. If greedy cannot fit all k cows, no other placement can.

    What is the time complexity of Aggressive Cows?

    Sorting takes O(n log n). Binary search runs O(log(max − min)) checks, and each check is O(n), so the total is O(n log n + n log(max − min)). The brute force version tries every distance, which is O(n × (max − min)).

    Which problems use the same binary search on answer pattern?

    Book allocation, The Painter’s Partition Problem, Koko Eating Bananas and Capacity to Ship Packages all binary search over the answer with a greedy feasibility check.


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.

    Binary Search on Answers Hard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleCapacity To Ship Packages Within D Days | Leetcode 1011
    Next Article Allocate Minimum Pages | GFG | Binary Search
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (6)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (2)
    Recent Posts

    Normalization in DBMS: 1NF, 2NF and 3NF With SQL Examples

    25 November 2026

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.