0% found this document useful (0 votes)
11 views

Lecture-2-Binary SearchTwo Pointers (1) (1)

The document discusses searching algorithms, specifically linear and binary search, detailing their methods and complexities. It also introduces the two-pointer technique for solving problems involving contiguous subarrays and sorted arrays. Additionally, it covers bit manipulation concepts, including bitwise operations and shifts, providing examples and useful techniques for implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lecture-2-Binary SearchTwo Pointers (1) (1)

The document discusses searching algorithms, specifically linear and binary search, detailing their methods and complexities. It also introduces the two-pointer technique for solving problems involving contiguous subarrays and sorted arrays. Additionally, it covers bit manipulation concepts, including bitwise operations and shifts, providing examples and useful techniques for implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

HEADSTART ​

By Programming and
Algorithms Group​
Search
&
TWO
POINT
Searching

We are trying to find something. It can be anything, an


index, an element, a value, a node or even the answer
itself!

So,

Let’s do some searching !!


Linear Search:
• Imagine you have an array: [3,5,7,9,11] (can be
unsorted too).
• To find the number 9, you start at the beginning and
check each element: 3 (nope), 5 (nope), 7 (nope), 9
(yes!).
• Worst-case: you might need to check all elements.
With n elements, that’s n checks.
Binary Search:
•Now, the array is sorted: [3,5,7,9,11].
•To find the number 9:
1. Check the middle element (7). Since 9 is
greater than 7, you ignore the left half.
2. Now you check the middle of the right half (9).
Bingo!
• Worst-case: You halve the search area each time. With
n elements, that’s significantly faster for large arrays (will
Intuition for Binary Search

Binary search is an algorithm to quickly search


something in a monotonous collection.

It is based on the observation that once


we compare a value to the required
value, we can determine on which
side of this value does our required
value lie. So, we can skip checking
that
So, how do weside for
actually ourthis
apply value.
observation ?
Active Region is

Implementation generally
marked by two
variables, start
and end.
Consider a sorted array containing 54.
You wanna find its position.

We’ll maintain an active region where it can


be.
Initially, that’s the whole array.
Compare the middle element ( ) of active region
with 54.
If it’s more than 54 , change end to
If it’s less than or equal to 54, change start to .

Repeat till your active region has only one element


(),
Congratulations! You have found 54 or not.
Pseudocode
low = 0, high = n - 1;
ans = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (a[mid] <= 54) Can you guess the
{
ans = mid; complexity?
low = mid + 1;
}
else{
high = mid - 1;
}
}
return (a[ans] == 54);
Complexity Calculation
So, first of all let’s imagine an active region in
our array (At the beginning the entire array
would be the active region ).
Then, we check the middle element of this
region. Upon seeing it, either we would have
found what we were searching for or we can
determine on which side of this region does it
lie ? Hence in one step we effectively half the
size of our active region.

So, the number of steps to obtain an active


region of size 1 is about log(n).
How Fast Is It?
Find 37!

For , the time complexity of linear is


While for binary search is around 34.
Problem I
Floor(sqrt)

Find the square root of a number using binary search.


(The absolute error shouldn’t be greater than )
Solutio
n
Problem II
https://codeforces.com/contest/1999/problem/G1
Solutio
n
Binary Search available
in STL?
Direct Functions available in STL library of C++
so you don’t have to write the implementation.

Lower Bound:
Lower Bound of x returns the index of element
greater than or equal to x in a sorted array or
vector.

Upper Bound:
Upper Bound of x returns the index of element
Example
Consider the array A = [1,2,3,3,4,5,6,8]

Lower Bound of 3 = 2
Upper Bound of 3 = 5

Lower Bound of 9 = 8
Upper Bound of 8 = 8

Lower Bound of 0 = 0
Upper Bound of 0 = 0
Predicate Functions
1. Predicate Function:
• This function helps determine whether a given value is
a valid answer.
• It maps the problem's constraints to a boolean value
(true/false).
• For example, given a value , the predicate function will
return true if meets the required condition, otherwise
false.

2. Concept of 0000111 or 1110000:


• The key insight is that, for many problems, the
sequence of possible answers evaluated through the
predicate function forms a pattern of consecutive 0s
followed by consecutive 1s or vice versa.
• Think of it like this: if the predicate function returns
false up to a certain point and then true for all
Problem III
https://codeforces.com/contest/1201/problem/C
Solutio
n
Some more Questions
(Homework)

Problem - 492B
Problem - 1985F
https://codeforces.com/problemset/problem/20
32/C
https://codeforces.com/contest/1480/
problem/C
Two
pointe
r
metho
Introduction
The Two Pointers Method is an important technique that is often used
in competitive programming. It is a broad concept which helps us
deal with a multitude of problems.

As the name suggests, we will be using two pointers to approach the


question in hand. This may be applied whenever:

● Dealing with properties of contiguous subarrays


● Dealing with sorted arrays and searching
● Dealing with specifically two values in a given set
Problem IV
Given an array of integers , determine if there exists a pair of
indices such that where .

Example

a =  Output: YES
a =  Output: NO
Solution
Problem V
https://codeforces.com/problemset/problem/1995/B1
Soluti
on
Problem VI
https://codeforces.com/problemset/problem/1941/F
Hints

1. 1. Which difference should be minimised to reduce


imbalance (Think GREEDY!)

2. 2. What’s the most optimal value of to be inserted in


the array to minimise the imbalance. (Think GREEDY
again! )

3. 3. Can we achieve it using the two arrays. If not, can


Hints we find the closest value in O(n) / O(n log n)
Solution

1. Finding differences
a. As we can only minimise one difference, we greedily take
the maximum difference
b. If the frequency of is more than 1, we can’t make any
optimisations and the answer is . Let the index where max diff occurs
is ()
c. We also store the second maximum difference (call it )

2. Inserting the new value


a. Most optimally, we insert value equal to
Hints b. We sort the array , and we iterate through the array .
c. For each , we find such that is closest to .
Solution
3. How to find closest?
a. We use binary search and find max value of such that .
b. That may be the optimal value, else may too be the
optimal value i.e., .
c. We update the minimal difference now.

4. The answer
a. Let’s consider the minimum of these maximum
imbalances, which is .
b. So the answer is .

Hints
Solution
https://codeforces.com/contest/1941/submission/290184294

Hints
Bit
Manipul
ation
Binary Number
System
Binary number system is the system of writing numbers in
base 2 instead of the usual base 10. Here, every digit can
either be 0 or 1. This binary digit is called a bit.

Decimal Representation Binary Representation

0 = ( 22 * 0 ) + ( 21 * 0 ) + 000

( 20 * )
1 = (22 * 0) + (21 * 0) +(20 * 1) 00

2 = (22 * 0) + (21 * 1) 1
+(20 * 0)
3 = (22 * 0) + (21 * 1) 01
+(20 * 1)
3 = (22 * 1) + (21 * 0) 0
Bitwise Operations
There are 4 bitwise operators. As the name suggests,
they work bitwise, ie independently on each bit.

Not ~
Or |
And &
Xor
Bitwise Not
It changes the bits from 0 to 1 and vice
versa.

A ~A

1 0

0 1
Bitwise Or
It results in 1 if either of the bits is
1.

A B A|B

0 0 0

1 0 1

0 1 1

1 1 1
Bitwise And
It results in 1 if both the bits are 1.

A B A&B

0 0 0

1 0 0

0 1 0

1 1 1
Bitwise Xor
It results in 1 if one of the bit is 0 and the other is
1.

A B A&B

0 0 0

1 0 1

0 1 1

1 1 0
Properties of XOR
• 0 is the identity element.
X^0=X
Any element is its own inverse element
X^X=0
• XOR operation is invertible
Example
57 = 111001
19 = 010011

57 = 111001
57 & 19 = 17 19 = 010011
17 = 010001

57 = 111001
57 | 19 = 59 19 = 010011
59 = 111011

57 = 111001
19 = 010011
57 ^ 19 = 17 42 = 101010
Bitwise Shift
We can shift all bits in a number to the left or right with
<<
and >> ( unrelated to cin and cout !! )

<< shifts bits to the left.


Ex. 26 << 2 = 104
As 26 = 11010, shifting it left twice gives 1101000
= 104.

>> shifts bits to the right.


Ex. 26 >> 2 = 6
As 26 = 11010, shifting it right twice gives
110 = 6.
Left vs Right
Left Shift ( n << k ) Right Shift ( n >> k )
k
Equivalent to multiplying n by 2k Equivalent to dividing n by2
. .

n << k = n * 2k n >> k = ⌊ n / 2k ⌋

We are appending k new zeroes at We are cutting


theaway
end.k digits from
the end.
Useful Techniques

string to_binary(int n){


string ans = "";
for (int bit = 30; bit > -1;
bit--) {
if((1<<bit)&n) ans+='1';
else ans+='0';
}
return ans;
}
Useful Techniques

string to_binary(long long n){


string ans = "";
for (int bit = 60; bit > -1;
bit--) {
if((1<<bit)&n) ans+='1';
else ans+='0';
}
return ans;
}
Useful Techniques

string to_binary(long long n){


string ans = "";
for (int bit = 60; bit > -1;
bit--) {
if((1LL<<bit)&n) ans+='1';
else ans+='0';
}
return ans;
}
Problem
C(579A)
Solution
• Write down x into its binary form. If the ith least significant
bit is 1 and x contains n bits, we put one bacteria into this
box in the morning of (n + 1 - i)th day.

• Then at the noon of the nth day, the box will


contain x bacteria. So the answer is the number of ones in
the binary form of x.
@pag_iitr discord.gg/dlulsll5Du

You might also like