Rotated Arrays & Binary Search on Answer Space
Inflection point pivot discovery in rotated sorted arrays, handling duplicates, and optimizing on monotonic feasibility predicates.
Topics Covered:
54. Search in Rotated Sorted Array & Pivot Identification • 55. Binary Search on Monotonic Answer Space (Optimization Problems)
When data deviates from simple linear contiguous ordering—through circular rotation or continuous monotonic function landscapes—binary search retains its logarithmic power through invariant preservation. In circularly shifted arrays, ordering is not destroyed but partitioned into piecewise monotonic segments where at least one half is always strictly sorted. Beyond physical arrays, binary search generalizes into an optimization engine capable of determining optimal capacities, thresholds, and allocations by querying monotonic feasibility predicates . This chapter formalizes circular rotation mechanics, pivot identification, duplicate key degradation, and the transformation of complex minimax optimization problems into binary search on answer spaces.
Learning Objectives
#- Formulate the half-sorted structural invariant of circularly rotated sorted arrays.
- Implement target search across rotated sequences by identifying sorted partitions and testing target inclusion boundaries.
- Develop pivot identification algorithms to locate the minimum element and compute the circular rotation factor .
- Analyze the worst-case degradation to when handling duplicate elements in rotated arrays and apply duplicate elimination rules.
- Generalize binary search to discrete and continuous monotonic answer spaces via feasibility predicate testing ().
- Apply binary search on answer space to solve canonical optimization problems including ship packaging capacity, allocation of pages, and aggressive cows.
Topic 54: Search in Rotated Sorted Array & Pivot Identification
#1. Mathematical Foundations & Circular Rotation
#Let be an array of distinct elements sorted in strictly ascending order such that . A circular right rotation by positions () maps each element at index to index . The resulting rotated array consists of two strictly increasing contiguous subarrays separated by a single point of discontinuity: the pivot element (the minimum element of the array).
The table below illustrates a circular rotation of by positions:
| Array Index () | Original Value | Rotated Value () | Subarray Partition | Monotonic Property | Structural Role |
|---|---|---|---|---|---|
0 | 0 | 4 | Left Segment () | Left Segment Start | |
1 | 1 | 5 | Left Segment () | Interior Element | |
2 | 2 | 6 | Left Segment () | Interior Element | |
3 | 4 | 7 | Left Segment () | Local Maximum (Pre-Pivot) | |
4 | 5 | 0 | Right Segment () | Global Minimum (Pivot Index ) | |
5 | 6 | 1 | Right Segment () | Interior Element | |
6 | 7 | 2 | Right Segment () | Right Segment End |
In this rotated state, every element in the left partition is strictly greater than every element in the right partition . The global minimum element resides at index , which marks the rotation offset.
2. The Half-Sorted Invariant
#Standard binary search assumes global monotonicity across . While a rotated array lacks global monotonicity, it satisfies a pivotal structural invariant:
The Half-Sorted Invariant:
For any arbitrary index within a rotated sorted array , at least one of the two halves—either or —is guaranteed to be strictly sorted.
Formal Proof:
- The entire array contains at most one point of descent (the pivot where ).
- The midpoint divides the interval into two disjoint sub-intervals: and .
- The single point of descent can belong to at most one of these two sub-intervals.
- Therefore, the sub-interval that does not contain the point of descent contains no inversions and must be strictly sorted.
By comparing the boundary values and , we deterministically classify which half is sorted:
- If : The left partition is monotonically sorted.
- If : The point of descent lies in the left half; therefore, the right partition is monotonically sorted.
Once the sorted half is identified, determining whether the target resides within its bounds requires a single range check. If the target falls inside the sorted half, we contract the search window to that half; otherwise, the target must lie in the opposite half.
| Evaluated Midpoint Condition | Sorted Sub-Interval | Target Inclusion Condition | Window Contraction Action | Discarded Search Half |
|---|---|---|---|---|
| Left half is sorted | Right half | |||
| Left half is sorted | Left half | |||
| Right half is sorted | Left half | |||
| Right half is sorted | Right half |
3. Step-by-Step State Trace
#Consider searching for in the rotated array of size :
| Step | Search Interval | () | () | () | Half Classification | Target In Range? | Pointer Update | Remaining Candidates |
|---|---|---|---|---|---|---|---|---|
| 1 | (4) | (2) | (7) | Left sorted () | is False | |||
| 2 | (0) | (2) | (1) | Left sorted () | is True | |||
| 3 | (0) | (0) | (0) | Match found () | Target Found | Return index 4 | Completed |
Total comparisons performed: 3 iterations, achieving logarithmic performance .
4. Canonical Algorithm: Search in Rotated Sorted Array
#FUNCTION SearchRotatedArray(A: Array of Integer, n: Integer, target: Integer) -> Integer:
low <- 0
high <- n - 1
WHILE low <= high DO
mid <- low + FLOOR((high - low) / 2)
IF A[mid] = target THEN
RETURN mid
END IF
// Check if the left partition [low..mid] is sorted
IF A[low] <= A[mid] THEN
// Left half is sorted; check if target lies within [A[low], A[mid])
IF A[low] <= target AND target < A[mid] THEN
high <- mid - 1
ELSE
low <- mid + 1
END IF
// Otherwise, the right partition [mid..high] must be sorted
ELSE
// Right half is sorted; check if target lies within (A[mid], A[high]]
IF A[mid] < target AND target <= A[high] THEN
low <- mid + 1
ELSE
high <- mid - 1
END IF
END IF
END WHILE
RETURN -1 // Target not present in arrayComplexity Analysis:
- Time Complexity: . At each iteration, exactly half of the remaining elements are eliminated from consideration, giving .
- Space Complexity: auxiliary memory; operates strictly in place with constant pointer variables.
5. Pivot Identification: Locating the Minimum Element
#In many applications, we need to locate the pivot index directly (e.g., to determine how many times an array has been rotated, or to find the minimum value in time).
When searching for the minimum element, we compare directly against the right boundary :
- If : The minimum element cannot be in ; it must reside strictly in . Thus, .
- If : The element at could itself be the minimum, or the minimum lies to the left in . Thus, .
- The loop terminates when , pointing directly to the minimum element.
Trace: Finding Minimum in
| Step | Comparison () | Inferred Pivot Location | Pointer Update | ||||
|---|---|---|---|---|---|---|---|
| 1 | 7 | 2 | Minimum is strictly right of | ||||
| 2 | 1 | 2 | Minimum is at or left of | ||||
| 3 | 0 | 1 | Minimum is at or left of | ||||
| Termination | — | — | — | Minimum located at index 4 () | — |
The rotation count of the original sorted array is given directly by the pivot index: .
6. Edge Case: Duplicate Elements & Worst-Case Degradation
When an array contains non-distinct duplicate values (e.g., or ), the half-sorted test can fail:
In this scenario, it is impossible to deduce whether the discontinuity lies in the left half or the right half based solely on boundary comparisons:
- In : . The pivot is in the left half.
- In : . The pivot is in the right half.
Mitigation Strategy:
When , we cannot safely discard half of the array. Instead, we shrink both boundaries inward:
| Scenario | Input Array Example | Boundary Status | Structural Consequence | Worst-Case Complexity |
|---|---|---|---|---|
| Distinct Elements | [4, 5, 6, 7, 0, 1, 2] | or | Exactly one half is unambiguously sorted | |
| Duplicates (Boundary Distinct) | [2, 2, 2, 3, 4, 2] | Sorted partition clearly identified | ||
| Degenerate Duplicates | [1, 1, 1, 0, 1, 1, 1] | Boundary trimming () required |
If all elements in the array are identical except for one (e.g., ), the algorithm trims one element at each step, degrading time complexity to .
Topic 55: Binary Search on Monotonic Answer Space
#1. The Optimization-to-Decision Transformation
#Many advanced algorithmic problems ask for an optimal numerical value rather than searching within a provided array:
- "Find the minimum capacity of a conveyor belt to ship packages within days."
- "Find the maximum minimum distance between cows placed in stalls."
- "Find the minimum reading speed to finish piles of books within hours."
These problems belong to the Minimax / Maximin optimization family. Direct constructive solutions are often NP-hard or require complex dynamic programming. However, if the underlying physical problem satisfies Monotonicity, we can invert the question:
The Monotonicity Condition:
Let be a validation predicate that checks whether candidate answer satisfies the problem constraints. A problem exhibits monotonicity over answer space if the predicate forms a single step-function transition:
- Minimization Problems (First True): If capacity is sufficient, any capacity is also sufficient:
- Maximization Problems (Last True): If distance is achievable, any smaller distance is also achievable:
The table below visualizes the predicate evaluation landscape across a discrete candidate answer space for a minimization problem:
| Candidate Answer () | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| Predicate | False | False | False | False | True | True | True | True | True | True |
| Physical Meaning | Infeasible | Infeasible | Infeasible | Infeasible | Min Valid | Valid | Valid | Valid | Valid | Valid |
| Search Action | Discard | Discard | Discard | Discard | Discard |
Because the boolean array is monotonically sorted, binary search locates the boundary value in time.
2. Algorithmic Templates
#Template A: Minimization (First True Pattern)
FUNCTION BinarySearchMinimization(minBound: Integer, maxBound: Integer) -> Integer:
low <- minBound
high <- maxBound
ans <- maxBound // Fallback upper bound
WHILE low <= high DO
mid <- low + FLOOR((high - low) / 2)
IF IsFeasible(mid) THEN
ans <- mid // Candidate answer found; try smaller values
high <- mid - 1
ELSE
low <- mid + 1 // mid is insufficient; increase candidate
END IF
END WHILE
RETURN ansTemplate B: Maximization (Last True Pattern)
FUNCTION BinarySearchMaximization(minBound: Integer, maxBound: Integer) -> Integer:
low <- minBound
high <- maxBound
ans <- minBound // Fallback lower bound
WHILE low <= high DO
mid <- low + FLOOR((high - low) / 2)
IF IsFeasible(mid) THEN
ans <- mid // Feasible; try larger values
low <- mid + 1
ELSE
high <- mid - 1 // Infeasible; decrease candidate
END IF
END WHILE
RETURN ans3. Case Study: Capacity to Ship Packages Within Days
#Problem Statement:
A conveyor belt carries packages with weights that must be shipped sequentially within days. Each day, packages are loaded onto a ship in the given order until loading another package would exceed the ship's weight capacity. Determine the minimum ship capacity required to ship all packages within days.
Numerical Instance:
- Packages: (, total weight , max single weight ).
- Deadline: days.
Derivation of Search Space Bounds:
- Lower Bound (): A ship must at least be able to carry the heaviest individual package:If , package can never be loaded.
- Upper Bound (): A single ship carrying all packages in day requires:
Feasibility Predicate ( Greedy Check):
Given a candidate capacity cap, sequentially accumulate weights into the current day. When adding package would exceed cap, dispatch the ship, increment days used by , and start the next day with package . If , return True; otherwise False.
FUNCTION CanShip(W: Array of Integer, n: Integer, D: Integer, cap: Integer) -> Boolean:
daysUsed <- 1
currentDayLoad <- 0
FOR i <- 0 TO n - 1 DO
IF currentDayLoad + W[i] > cap THEN
daysUsed <- daysUsed + 1
currentDayLoad <- W[i]
ELSE
currentDayLoad <- currentDayLoad + W[i]
END IF
END FOR
RETURN daysUsed <= D4. Step-by-Step Optimization Trace
#Executing binary search over the range with target days :
| Iteration | Active Interval | Candidate Capacity | Day-by-Day Load Partitions | Days Required | Feasible? () | Recorded Answer (ans) | Next Search Interval |
|---|---|---|---|---|---|---|---|
| 1 | 32 | ; ; | 3 | True () | 32 | ||
| 2 | 20 | ; ; ; | 4 | True () | 20 | ||
| 3 | 14 | ; ; ; ; ; | 6 | False () | 20 (unchanged) | ||
| 4 | 17 | ; ; ; | 4 | True () | 17 | ||
| 5 | 15 | ; ; ; ; | 5 | True () | 15 | ||
| End | — | ; Loop terminates | — | — | 15 | Result: |
The optimal minimum ship weight capacity is 15, found in exactly 5 predicate evaluations.
5. Canonical Problem Archetypes on Answer Space
#The table below summarizes classic algorithmic problems solvable via binary search on monotonic answer space:
| Problem Archetype | Search Variable () | Search Bounds | Predicate Invariant | Predicate Complexity | Total Time Complexity |
|---|---|---|---|---|---|
| Capacity to Ship Packages | Minimum weight capacity | Greedy daily packing: | |||
| Koko Eating Bananas | Minimum eating speed | Total hours spent: | |||
| Allocate Minimum Pages | Minimum maximum pages | Student partition count: | |||
| Aggressive Cows (Stalls) | Maximum minimum distance | Greedy cow placement: | |||
| Split Array Largest Sum | Minimum largest subarray sum | Subarray splits count: |
Module 03 Summary & Key Takeaways
#- The Half-Sorted Invariant: In any circularly rotated sorted array, dividing the interval at guarantees that at least one half is strictly sorted. Testing identifies the sorted partition in time.
- Boundary Testing for Discard: Once the sorted partition is identified, a single range check ( or ) determines whether the target lies inside the sorted half, enabling search.
- Pivot & Minimum Element: Comparing with locates the array's minimum element and rotation factor . If , the pivot is strictly right; if , the pivot is at or left of .
- Duplicate Penalty: When , the sorted half cannot be deduced. Trimming both boundaries () preserves correctness but degrades worst-case performance to .
- Answer Space Monotonicity: When optimization problems ask for "Minimum Capacity" or "Maximum Distance", formulate a verification predicate . If is monotonic, binary search computes the optimal answer in time.
References & Academic Attribution
#- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.), Chapter 2 (Getting Started) & Section 12.3. MIT Press.
- Bentley, J. (2000). Programming Pearls (2nd ed.), Column 4: Writing Correct Programs & Column 9: Code Tuning. Addison-Wesley.
- Knuth, D. E. (1998). The Art of Computer Programming, Volume 3: Sorting and Searching (2nd ed.), Section 6.2.1: Searching an Ordered Table. Addison-Wesley.
- Sedgewick, R., & Wayne, K. (2011). Algorithms (4th ed.), Chapter 1.4: Analysis of Algorithms (Binary Search on Functions). Addison-Wesley.