Binary Search on Monotonic Predicate Function
Difference between en1 and en2, changed 1385 character(s)
### Predicate Function↵
↵
fFunction that returns either **true** or **false**↵
↵
example↵
↵
↵
![ ](
/predownloaded/51/2b/512be882774f52b109e56cf9920441fe791e49c5.png\cc/99/cc99af6bba98fc5c99c54f7897440e3f0dbd9fba.jpeg)↵
↵
### Monotonic Predicate Function↵
↵
A monotonic predicate function is a function that returns true or false, where the result changes at most once as x increases.↵
![ ](/predownloaded/e9/c9/e9c9ba2d67328ee23567c04b4854461071c0965d.jpeg)↵
↵
### Binary Search Monotonic Predicate Function↵
↵
![ ](/predownloaded/cc/74/cc74f1a077b7ec245dcc70aa494f4800974c78d1.png)↵
↵
Define valid range of x ↵
minimum possible value of x => low ↵
maximum possible value of x => high↵
↵
in range [low,high] function f(x) is Monotonic Predicate Function ↵
↵
Define ans to store the possible answer.↵
↵
mid=low+(high-low)/2↵
↵
if f(mid)=false ↵
means mid<A ↵
so update low=mid+1↵
↵
![ ](/predownloaded/c5/ae/c5aeda4501db24b73e437a9da26ea7874eea233f.jpeg)↵
↵
if f(mid)=true↵
means mid>=A ↵
↵
here mid is also possible answer so update ↵
ans=mid and high=mid-1 ↵
↵
![ ](/predownloaded/f8/5b/f85bbf512aa79dec61789f93fac1fc82d7ddcf34.jpeg)↵
↵
↵
Final code templete↵
-------------------↵
↵
↵
~~~~~↵
int low = 1;↵
int high = 1e9+7; //suppose [1,1e9+7] is valid range↵
int ans = -1; //No answer found yet↵
↵
while(low <= high){↵
     int mid = low + (high - low) / 2;↵
     if(f(mid)){ //define f function also↵
          ans = mid;↵
          high = mid - 1;↵
     }↵
     else ↵
          low = mid + 1;↵
}↵
cout << ans << "\n";↵
~~~~~↵
↵
Happy Coding!!!↵
↵
↵

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English Nerix29E 2026-10-12 21:00:32 1385 Tiny change: 'nexample\n![ ](/pr' -> 'nexample\n\n\n![ ](/pr' (published)
en1 English Nerix29E 2026-10-12 20:01:50 194 Initial revision (saved to drafts)