logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›faqs

Aggressive Cows

# Question

Given an array stalls representing positions on a coordinate line and an integer k representing the number of aggressive cows. Assign stalls to the kkk cows such that the minimum distance between any two cows is as large as possible (i.e., maximize the minimum distance). Return this maximum possible minimum distance.

# Solution

# Pattern

Binary Search on Answer (Maximize the Minimum) Instead of calculating distances between combinations of stalls, we define a search space of all possible "minimum distances" (from 1 up to the total span of the stalls). We binary search this space. For a "guessed" minimum distance, we use a greedy algorithm to see if we can successfully place kkk cows that far apart. If we can, we try a larger distance. If we can't, we try a smaller distance.

# How to Identify

  • The problem asks to "maximize a minimum" or "minimize a maximum".
  • The search space is monotonic (if a distance DDD is valid, any distance < D is definitely valid. If DDD is invalid, any distance > D is definitely invalid).
  • Simulating a configuration for a fixed value takes O(N)O(N)O(N) greedy time.

# Description

Step-by-step explanation:

  1. Sort the Array: The stalls must be sorted so we can greedily place cows from left to right.

  2. Establish Bounds: - left = 1: The absolute smallest possible distance between two distinct integer stalls. - right = stalls[n-1] - stalls[0]: The absolute largest distance possible (placing only two cows at the extreme ends).

  3. Binary Search: Loop while left <= right. Calculate mid as the "guessed" minimum distance.

  4. Greedy Validation (canPlaceCows):

    • Always place the first cow in the very first stall (stalls[0]). This is mathematically optimal to maximize remaining space.
    • Iterate through the remaining stalls. If the distance between the current stall and the lastPlacedPosition is ≥mid\ge mid≥mid, place a cow here.
    • If we successfully place all kkk cows, return true. If the loop finishes and we placed <k< k<k cows, return false.
  5. Adjust Bounds:

    • If true: The distance mid is possible. But we want to maximize it, so we throw away the lower half: left = mid + 1.
    • If false: The distance mid is too large; we couldn't fit the cows. Throw away the upper half: right = mid - 1.
  6. Return: When the loop breaks, right will point to the largest valid distance.

# The Intuition

Think of this like setting a restraining order distance between kkk people in a room with fixed chairs. You guess they need to sit 10 feet apart. You put the first person in the first chair. You walk down the row. The next chair is 3 feet away. Too close. The next is 8 feet. Too close. The next is 11 feet away. Perfect! You put the second person there. If you manage to seat everyone, a 10-foot restraining order works. But maybe you can push them 12 feet apart? You try a larger number. If you run out of chairs before seating everyone, 10 feet was too strict. You have to settle for 8 feet. You binary search this exact threshold.

# Complexity

LabelWorstAverage
Time ComplexityO(Nlog⁡N+Nlog⁡M)O(N \log N + N \log M)O(NlogN+NlogM)O(Nlog⁡N+Nlog⁡M)O(N \log N + N \log M)O(NlogN+NlogM)
Space ComplexityO(log⁡N)O(\log N)O(logN)O(log⁡N)O(\log N)O(logN)

# Time Complexity

Let NNN be the number of stalls and MMM be the distance between the first and last stall.

  1. Sorting the stalls takes O(Nlog⁡N)O(N \log N)O(NlogN) time.
  2. The binary search takes O(log⁡M)O(\log M)O(logM) iterations.
  3. Inside the binary search, the greedy check takes O(N)O(N)O(N) time. Total Time: O(Nlog⁡N+Nlog⁡M)O(N \log N + N \log M)O(NlogN+NlogM).

# Space Complexity

The algorithm uses O(1)O(1)O(1) auxiliary variables. However, the in-place sorting algorithm (like Dual-Pivot Quicksort in Java) requires O(log⁡N)O(\log N)O(logN) space for the recursion stack.

# Code

import java.util.Arrays;
 
class Solution {
    public int aggressiveCows(int[] stalls, int cows) {
        if (stalls == null || stalls.length < cows) return -1;
        
        // 1. Sort is mandatory for greedy placement
        Arrays.sort(stalls);
        
        // 2. Define search space
        int left = 1; 
        int right = stalls[stalls.length - 1] - stalls[0];
        
        // 3. Binary Search
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (canPlaceCows(stalls, cows, mid)) {
                // Valid, try to find a larger distance
                left = mid + 1;
            } else {
                // Invalid, distance too large
                right = mid - 1;
            }
        }
        
        return right;
    }
    
    private boolean canPlaceCows(int[] stalls, int totalCows, int minDistance) {
        int cowsPlaced = 1; // Always place first cow at index 0
        int lastPlacedPosition = stalls[0];
        
        for (int i = 1; i < stalls.length; i++) {
            if (stalls[i] - lastPlacedPosition &gt;= minDistance) {
                cowsPlaced++;
                lastPlacedPosition = stalls[i];
                
                // Fast-fail to save linear scan time
                if (cowsPlaced == totalCows) return true;
            }
        }
        
        return false;
    }
}

# Caveats

  • Forgetting to Sort: The input array is often given unsorted in this problem. The greedy choice (placing the cow at the very next available stall ≥D\ge D≥D) only works if you are scanning a sorted number line.
  • Returning left vs right: Because the condition is left &lt;= right, when the loop terminates, left and right cross. left points to the first invalid distance, and right points to the last valid distance. Since we are maximizing the valid state, we return right.
  • Sorting Requirement: Many candidates forget that the greedy placement only works if the stalls are sorted. Without sorting, the check becomes a variation of the NP-Hard Clique problem.
  • Search Space Range: If coordinates are very large (e.g., 10910^9109), the log⁡D\log DlogD factor remains small (≈30\approx 30≈30), making this highly efficient.

# Concepts to Think About

  • The Master Template: This problem is the inverse twin of LeetCode 410 (Split Array Largest Sum / Painter's Partition / Book Allocation).

    • Those problems ask to Minimize a Maximum →\rightarrow→ Search for valid states, adjust right = mid - 1, return left.
    • Aggressive Cows asks to Maximize a Minimum →\rightarrow→ Search for valid states, adjust left = mid + 1, return right.
  • Maximize Minimum vs Minimize Maximum: Both are solved via Binary Search on Answer Space. For "Minimize Maximum," the greedy check logic and bound updates are simply mirrored.

  • Floating Point: If stall positions were doubles, the binary search would use a fixed number of iterations (e.g., 100) or a while (right - left &gt; precision).

  • Integer Overflow: (right + left) / 2 can overflow if right and left are large; always use left + (right - left) / 2.

# Logical Follow-up

Question: Why is it always optimal to place the first cow in the very first stall (stalls[0])?

Solution: Placing the first cow at stalls[0] maximizes the remaining distance available for all subsequent cows. If you were to place the first cow at stalls[1], you are strictly reducing the remaining coordinate space on the right side without gaining any benefit on the left side (since no cow is placed before it). Therefore, a configuration starting at index 1 can never yield a larger minimum distance than one starting at index 0.

Question: What if the stalls are arranged in a Circle?

Solution: This is significantly harder. If circular, the distance between the last cow and the first cow also counts. You would need to run the greedy check fixing the first cow at different positions or use a "broken circle" approach where you duplicate the array and use a sliding window logic within the binary search check.

Question: What if each cow has a different "Aggression Level" (needs a different minimum distance from others)?

Solution: Binary search on answer space no longer works directly because there isn't a single "min distance" to optimize. This would likely require a Dynamic Programming approach or a more complex Greedy strategy if the aggression levels are sorted.

PreviousSearch In A 2D MatrixNextAllocate Books
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up