{"id":601,"date":"2025-07-10T12:44:09","date_gmt":"2025-07-10T07:14:09","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=601"},"modified":"2025-07-10T12:44:10","modified_gmt":"2025-07-10T07:14:10","slug":"aggresive-cows","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/","title":{"rendered":"Aggressive Cows | GeeksforGeeks Solution Explained | Binary Search"},"content":{"rendered":"\n<p>The &#8220;Aggressive Cows&#8221; problem is a classic binary search question that is often asked in coding interviews. <\/p>\n\n\n\n<p>It teaches you how to optimize placement problems using binary search. In this blog, we\u2019ll 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.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/aggressive-cows\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-problem-statement-\"><strong>Problem Statement<\/strong><\/h2>\n\n\n\n<p>You are given an array with unique elements of stalls[],<strong>&nbsp;<\/strong>which denote the position of a&nbsp;<strong>stall<\/strong>. You are also given an integer&nbsp;<strong>k<\/strong>&nbsp;which denotes the number of aggressive cows. Your task is to assign&nbsp;<strong>stalls&nbsp;<\/strong>to<strong>&nbsp;k&nbsp;<\/strong>cows such that the&nbsp;<strong>minimum distance&nbsp;<\/strong>between any two of them is the<strong>&nbsp;maximum&nbsp;<\/strong>possible.<\/p>\n\n\n\n<p><strong>Examples :<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>stalls[] = [1, 2, 4, 8, 9], k = 3<br><strong>Output: <\/strong>3<br><strong>Explanation: <\/strong>The first cow can be placed at stalls[0], <br>the second cow can be placed at stalls[2] and <br>the third cow can be placed at stalls[3]. <br>The minimum distance between cows, in this case, is 3, which also is the largest among all possible ways.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>stalls[] = [10, 1, 2, 7, 5], k = 3\n<strong>Output: <\/strong>4\n<strong>Explanation: <\/strong>The first cow can be placed at stalls[0],\nthe second cow can be placed at stalls[1] and\nthe third cow can be placed at stalls[4].\nThe minimum distance between cows, in this case, is 4, which also is the largest among all possible ways.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>stalls[] = [2, 12, 11, 3, 26, 7], k = 5\n<strong>Output: <\/strong>1\n<strong>Explanation: <\/strong>Each cow can be placed in any of the stalls, as the no. of stalls are exactly equal to the number of cows.\nThe minimum distance between cows, in this case, is 1, which also is the largest among all possible ways.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><br>2 &lt;= stalls.size() &lt;= 10<sup>6<\/sup><br>0 &lt;= stalls[i] &lt;= 10<sup>8<\/sup><br>2 &lt;= k &lt;=&nbsp;stalls.size()<\/p>\n\n\n<div class=\"wp-block-ub-table-of-contents-block ub_table-of-contents\" id=\"ub_table-of-contents-fe33c7c1-c0ab-407c-a911-37bad1fa7a4a\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"false\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"true\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column \">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#0-problem-statement-\" style=\"\">Problem Statement<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#1-brute-force-solution-try-every-possible-distance\" style=\"\">Brute Force Solution (Try Every Possible Distance)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#2-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#3-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#4-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#5-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#6-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#7-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#8-optimal-solution-binary-search\" style=\"\">Optimal Solution (Binary Search)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#9-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#10-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#11-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#12-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#13-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#14-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/aggresive-cows\/#15-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-brute-force-solution-try-every-possible-distance\">Brute Force Solution (Try Every Possible Distance)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Let\u2019s solve the problem in the most straightforward way:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Try Every Distance:<\/strong><br>Try every possible minimum distance from 1 up to the maximum possible (difference between the farthest and closest stall).<\/li>\n\n\n\n<li><strong>Check If Placement Is Possible:<\/strong><br>For each distance, check if it is possible to place all cows with at least that much distance between them.<\/li>\n\n\n\n<li><strong>Return the Largest Valid Distance:<\/strong><br>The largest distance for which placement is possible is our answer.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>We check every possible distance, so we\u2019re sure to find the largest one that works.<\/li>\n<\/ol>\n\n\n\n<p>This approach is easy to understand but not efficient for large inputs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#e1e4e8;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#24292e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n\n    def canWePlace(self, stalls, dist, cows):\n        # Size of array\n        n = len(stalls)\n\n        # Number of cows placed\n        cntCows = 1\n\n        # Position of last placed cow\n        last = stalls[0]\n        for i in range(1, n):\n            if stalls[i] - last &gt;= dist:\n                # Place next cow\n                cntCows += 1\n\n                # Update the last location\n                last = stalls[i]\n            if cntCows &gt;= cows:\n                return True\n\n        return False\n\n    def aggressiveCows(self, stalls, k):\n        # Size of list\n        n = len(stalls)\n\n        # Sort the nums\n        stalls.sort()\n\n        limit = stalls[-1] - stalls[0]\n        for i in range(1, limit + 1):\n            if not self.canWePlace(stalls, i, k):\n                return i - 1\n\n        # Return the answer\n        return limit\" style=\"color:#e1e4e8;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark\" style=\"background-color: #24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F97583\">class<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #B392F0\">Solution<\/span><span style=\"color: #E1E4E8\">:<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">    <\/span><span style=\"color: #F97583\">def<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #B392F0\">canWePlace<\/span><span style=\"color: #E1E4E8\">(self, stalls, dist, cows):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Size of array<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        n <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">len<\/span><span style=\"color: #E1E4E8\">(stalls)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Number of cows placed<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        cntCows <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Position of last placed cow<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        last <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> stalls[<\/span><span style=\"color: #79B8FF\">0<\/span><span style=\"color: #E1E4E8\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">for<\/span><span style=\"color: #E1E4E8\"> i <\/span><span style=\"color: #F97583\">in<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">range<\/span><span style=\"color: #E1E4E8\">(<\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">if<\/span><span style=\"color: #E1E4E8\"> stalls[i] <\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #E1E4E8\"> last <\/span><span style=\"color: #F97583\">&gt;=<\/span><span style=\"color: #E1E4E8\"> dist:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #6A737D\"># Place next cow<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                cntCows <\/span><span style=\"color: #F97583\">+=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #6A737D\"># Update the last location<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                last <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> stalls[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">if<\/span><span style=\"color: #E1E4E8\"> cntCows <\/span><span style=\"color: #F97583\">&gt;=<\/span><span style=\"color: #E1E4E8\"> cows:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">True<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">False<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">    <\/span><span style=\"color: #F97583\">def<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #B392F0\">aggressiveCows<\/span><span style=\"color: #E1E4E8\">(self, stalls, k):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Size of list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        n <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">len<\/span><span style=\"color: #E1E4E8\">(stalls)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Sort the nums<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        stalls.sort()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        limit <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> stalls[<\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">] <\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #E1E4E8\"> stalls[<\/span><span style=\"color: #79B8FF\">0<\/span><span style=\"color: #E1E4E8\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">for<\/span><span style=\"color: #E1E4E8\"> i <\/span><span style=\"color: #F97583\">in<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">range<\/span><span style=\"color: #E1E4E8\">(<\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">, limit <\/span><span style=\"color: #F97583\">+<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">if<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #F97583\">not<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">self<\/span><span style=\"color: #E1E4E8\">.canWePlace(stalls, i, k):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> i <\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Return the answer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> limit<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#24292e;color:#d3d7dd;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For each possible distance from 1 to the maximum possible, check if you can place all cows.<\/li>\n\n\n\n<li>The helper function\u00a0<code>canWePlace<\/code>\u00a0tries to place cows with at least\u00a0<code>dist<\/code>\u00a0distance apart.<\/li>\n\n\n\n<li>Return the largest distance for which placement is possible.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>stalls = [1], k = 3<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Try distance = 1: possible<\/li>\n\n\n\n<li>Try distance = 2: possible<\/li>\n\n\n\n<li>Try distance = 3: possible<\/li>\n\n\n\n<li>Try distance = 4: not possible (can&#8217;t place all cows)<\/li>\n\n\n\n<li>Return 3<\/li>\n<\/ul>\n\n\n\n<p><strong>Final Output:<\/strong><br><code>3<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O((max(stalls) &#8211; min(stalls)) * n)<br>For each distance, we check all stalls.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(1)<br>Only variables for counting.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The brute force approach is simple and works for small inputs, but it\u2019s too slow for large values.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-optimal-solution-binary-search\">Optimal Solution (Binary Search)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>We can do much better using binary search:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Binary Search on Distance:<\/strong><br>The answer lies between 1 and the difference between the farthest and closest stall. Use binary search to find the largest minimum distance.<\/li>\n\n\n\n<li><strong>Check If Placement Is Possible:<\/strong><br>For each mid value (distance), check if it\u2019s possible to place all cows.<\/li>\n\n\n\n<li><strong>Adjust Search Window:<\/strong>\n<ul class=\"wp-block-list\">\n<li>If placement is possible, try a larger distance.<\/li>\n\n\n\n<li>If not, try a smaller distance.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>The placement function is monotonic: as the distance increases, it becomes harder to place all cows. Binary search is perfect for this.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#e1e4e8;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#24292e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n\n    def canWePlace(self, stalls, dist, cows):\n        # Size of array\n        n = len(stalls)\n\n        # Number of cows placed\n        cntCows = 1\n\n        # Position of last placed cow\n        last = stalls[0]\n        for i in range(1, n):\n            if stalls[i] - last &gt;= dist:\n                # Place next cow\n                cntCows += 1\n\n                # Update the last location\n                last = stalls[i]\n            if cntCows &gt;= cows:\n                return True\n\n        return False\n\n    def aggressiveCows(self, stalls, k):\n        # Sort the stalls to place cows in sorted positions\n        stalls.sort()\n\n        # Binary search for the maximum minimum distance\n        low = 1  # Minimum possible distance\n        high = stalls[-1] - stalls[0]  # Maximum possible distance\n\n        result = 0\n\n        while low &lt;= high:\n            mid = (low + high) \/\/ 2  # Try this distance\n\n            if self.canWePlace(stalls, mid, k):\n                # If we can place cows with at least `mid` distance, try for a larger distance\n                result = mid\n                low = mid + 1\n            else:\n                # If we can't place cows with at least `mid` distance, try for a smaller distance\n                high = mid - 1\n\n        return result\" style=\"color:#e1e4e8;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark\" style=\"background-color: #24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F97583\">class<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #B392F0\">Solution<\/span><span style=\"color: #E1E4E8\">:<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">    <\/span><span style=\"color: #F97583\">def<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #B392F0\">canWePlace<\/span><span style=\"color: #E1E4E8\">(self, stalls, dist, cows):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Size of array<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        n <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">len<\/span><span style=\"color: #E1E4E8\">(stalls)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Number of cows placed<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        cntCows <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Position of last placed cow<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        last <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> stalls[<\/span><span style=\"color: #79B8FF\">0<\/span><span style=\"color: #E1E4E8\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">for<\/span><span style=\"color: #E1E4E8\"> i <\/span><span style=\"color: #F97583\">in<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">range<\/span><span style=\"color: #E1E4E8\">(<\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">if<\/span><span style=\"color: #E1E4E8\"> stalls[i] <\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #E1E4E8\"> last <\/span><span style=\"color: #F97583\">&gt;=<\/span><span style=\"color: #E1E4E8\"> dist:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #6A737D\"># Place next cow<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                cntCows <\/span><span style=\"color: #F97583\">+=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #6A737D\"># Update the last location<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                last <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> stalls[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">if<\/span><span style=\"color: #E1E4E8\"> cntCows <\/span><span style=\"color: #F97583\">&gt;=<\/span><span style=\"color: #E1E4E8\"> cows:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">True<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">False<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">    <\/span><span style=\"color: #F97583\">def<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #B392F0\">aggressiveCows<\/span><span style=\"color: #E1E4E8\">(self, stalls, k):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Sort the stalls to place cows in sorted positions<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        stalls.sort()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #6A737D\"># Binary search for the maximum minimum distance<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        low <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">  <\/span><span style=\"color: #6A737D\"># Minimum possible distance<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        high <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> stalls[<\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #79B8FF\">1<\/span><span style=\"color: #E1E4E8\">] <\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #E1E4E8\"> stalls[<\/span><span style=\"color: #79B8FF\">0<\/span><span style=\"color: #E1E4E8\">]  <\/span><span style=\"color: #6A737D\"># Maximum possible distance<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        result <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">while<\/span><span style=\"color: #E1E4E8\"> low <\/span><span style=\"color: #F97583\">&lt;=<\/span><span style=\"color: #E1E4E8\"> high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            mid <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> (low <\/span><span style=\"color: #F97583\">+<\/span><span style=\"color: #E1E4E8\"> high) <\/span><span style=\"color: #F97583\">\/\/<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">2<\/span><span style=\"color: #E1E4E8\">  <\/span><span style=\"color: #6A737D\"># Try this distance<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">if<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">self<\/span><span style=\"color: #E1E4E8\">.canWePlace(stalls, mid, k):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #6A737D\"># If we can place cows with at least `mid` distance, try for a larger distance<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                result <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> mid<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                low <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> mid <\/span><span style=\"color: #F97583\">+<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">            <\/span><span style=\"color: #F97583\">else<\/span><span style=\"color: #E1E4E8\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                <\/span><span style=\"color: #6A737D\"># If we can&#39;t place cows with at least `mid` distance, try for a smaller distance<\/span><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">                high <\/span><span style=\"color: #F97583\">=<\/span><span style=\"color: #E1E4E8\"> mid <\/span><span style=\"color: #F97583\">-<\/span><span style=\"color: #E1E4E8\"> <\/span><span style=\"color: #79B8FF\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #E1E4E8\">        <\/span><span style=\"color: #F97583\">return<\/span><span style=\"color: #E1E4E8\"> result<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#24292e;color:#d3d7dd;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use binary search between 1 and the maximum possible distance.<\/li>\n\n\n\n<li>For each mid distance, check if you can place all cows.<\/li>\n\n\n\n<li>If you can, store the distance and try a larger one.<\/li>\n\n\n\n<li>If not, try a smaller distance.<\/li>\n\n\n\n<li>Return the largest valid distance found.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>stalls = [1], k = 3<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>low = 1, high = 8<\/li>\n\n\n\n<li>mid = 4: can&#8217;t place all cows \u2192 high = 3<\/li>\n\n\n\n<li>mid = 2: can place all cows \u2192 result = 2, low = 3<\/li>\n\n\n\n<li>mid = 3: can place all cows \u2192 result = 3, low = 4<\/li>\n<\/ul>\n\n\n\n<p>Loop ends, answer is 3.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(n * log(max(stalls) &#8211; min(stalls)))<br>Binary search on distance, checking all stalls for each guess.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(1)<br>Only variables for counting.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The optimal solution is efficient and works well for large arrays and high values. It\u2019s the best approach for interviews and practical use.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"15-final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<p>The &#8220;Aggressive Cows&#8221; 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.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The &#8220;Aggressive Cows&#8221; 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\u2019ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with code comments, dry runs,<\/p>\n","protected":false},"author":1,"featured_media":603,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[28,18],"class_list":{"0":"post-601","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-binary-search-on-answers","10":"tag-hard"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/aggresive-cows-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/601","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=601"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/601\/revisions"}],"predecessor-version":[{"id":604,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/601\/revisions\/604"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/603"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=601"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=601"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=601"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}