Open In App

Understanding Opposite Polarity Concept in Binary Search

Opposite Polarity is a concept in Binary Search which works on the search space with the condition that the before and after regions of the search space will be reversed when the Binary Search Algorithm is applied to it. In this post, we will understand how the Opposite polarity concept in Binary Search works with the help of a problem.

What is the Opposite polarity concept in Binary Search?

While using the Binary Search algorithm to solve any problem, we initially take two pointers- low and high, which denote the starting and end of the search space respectively. So, the Opposite polarity concept of Binary search states that, if low is initially pointing to the non-solution region and high is pointing to the solution region, then after ending of Binary Search algorithm, low will point to the solution region, and high will point to the non-solution region, or vice-versa.



Opposite polarity concept in Binary Search

Understanding Opposite polarity concept in Binary Search with the help of a Problem

Let’s recall the problem Koko Eating Bananas to understand it in a better way:

In this problem, we have to find the number of Bananas from the entire answer space such that, all the given bananas got eaten within H hours.



Considered an example of the above problem:

n = 4, piles = [3, 6, 7, 11], H = 8

Initial Configuration before applying Binary Search Algorithm

Solution and Non-Solution Region before applying Binary Search

So these two points divides the entire search space into two regions:

Using Binary Search Algorithm

1. First Iteration:

2. Second Iteration:

3. Third Iteration:

4. Fourth Iteration (Last Iteration):

Solution and Non-Solution Region after applying Binary Search

We can see that initially low was in non solution region and high was in solution region. But after ending of Binary Search, high is in non solution region and low is in solution region.

Solution and Non-Solution Region after applying Binary Search

This is the opposite polarity concept in Binary Search.

        


Article Tags :