Competitive Programming
3.81K subscribers
1 photo
38 links
Experince a new world of algorithmic problems using C++
Channel link:
https://t.me/Competitive_Programming_Cpp

For any query contact me:
@saranyanaharoy
You can also share your experiences and ideas with us. We will share it in our channel.
Download Telegram
Channel photo updated
Well, many times you have uploaded a code and got different errors. Well it's ok.... it's a part of the learning process. Today I am going to discuss different types of errors we generally face with online judges.
1. Runtime Error- This mainly occurs if you try to access a memory location which is not allocated. For example if you initialize an array arr[5] and try to access arr[10] then you will get RE. You should always check whether the array location you are going to access is valid or not.
Even accessing a memory location suh as: arr[-1] will also give a RE. So also check the lower bound while accessing the array elements in reverse order.
2. Wrong Answer- The output of your code doesnot match with the correct answer. Well mostly it is the corner cases in which the code fails, so try to make some corner test cases by yourself and see whether your code passes it. There may be a possible buffer overflow so use long long int instead of int and watch carefully the given constraints.
3. Time Limit Exceeded (TLE)- Well nothing much to do in this one except brainstorming . You need to think of another algorithm to make it work.
4. Memory Limit Exceeded- This happens when you try to use more memory than the allotted memory. Probably you are declaring too big 2D array!!! Try to use different containers or data structure but it would be far better if you think of some different Algo.

You can get some silly errors which coders ofte make and how to handle it wisely in this article -
https://codeforces.com/blog/entry/67417

Happy Coding!!!
Every C/C++ program is said to have a main() function, but have you ever wondered is it possible to write a C/C++ program without main() function??
It is possible to write a C/C++ program without a main() function. Check out how -https://qr.ae/TWGwGa
Hello Everyone!!!
It is time to face some interesting problems.
Are you excited😄😄😄😄

Our 1st problem is from codechef


PROBLEM LINK:
ONE KING

DIFFICULTY:
EASY-MEDIUM

PROBLEM:
Given N (≤100000) intervals [Ai , Bi], one such interval can be deleted by placing a bomb at x if Ai ≤ x ≤ Bi. Find minimum number of bombs required to delete all intervals.




SOLUTION:
EXPLANATION
CODE:
code

NOTE: Above idea is implemented using C++. Some C++ template classes from STL(Standard Template Library) are used. (STL). Specifically vector and pair are used in the solution code.

vector
pair
sorting vector of pairs


#oneking #codechef
Hey there!!! Whenever we want to get the maximum value between two variables (suppose we want to store the largest value among variable1 and variable2 into variable3) we use the if else statement. But we can do it in another simple way without much effort by using max() function. The prototype is:
variable3=max(variable1,variable2);
Similarly, we can use the min() function to get the minimum among two variables.The prototype of the function is:
variable3=min(variable1,variable2);

Again, if we want to get the maximum value within an array we could do it very easily, we just need to call the *max_element() function. The prototype is:
variable_name=*max_element(arr,arr+n);
where arr[n] is an array of size n.
In the same way we could easily get the minium element from an array by using *min_element() function. The protype is:
variable_name=*min(arr,arr+n);
Here arr[n] is the array of size n.

Note: Don't forget to write #include<bits/stdc++.h> in the begining of the code, because every functions is defined in this header file!!!!

Happy Coding!!!
Hello Everyone!!


Question: How many zeros are there in 100! (100 factorial)?

Ok, let’s look at how trailing zeros are formed . When a 5 and a 2 is contained in factors of a number a trailing 0 is formed.Now all we have to do is count number of 5's and 2's in the factors.

Let’s count the 5’s first. 5, 10, 15, 20, 25 and so on making a total of (100/5)=20. However there is more to this. Since 25, 50, 75 and 100 have two 5’s in each of them (25 = 5 * 5, 50 = 2 * 5 * 5, …), you have to count them twice.
So this makes the total (20+100/25)=24.

In formula point of view:
Number of 5's in 100!
= 100/5 + 100/25 + 100/125 + ... = 24 (Integer values only)

Moving on to count the number of 2’s. 2, 4, 6, 8, 10 and so on.
Total of

50 multiples of 2’s,

25 multiples of 4’s (count these once more),

12 multiples of 8’s (count these once more)

and so on…
The grand total comes out to

Number of 2’s = 100/2 + 100/4 + 100/8 + 100/16 + 100/32 + 100/64 + 100/128 + … = 97 (Integer values only)

Each pair of 2 and 5 will cause a trailing zero. Since we have only 24 5’s, we can only make 24 pairs of 2’s and 5’s thus the number of trailing zeros in 100 factorial is 24.






Now we can use the concept to find number of trailing 0's in N!(Where N is an positive integer). We only have to calculate number of 5's in the factors of N! as number of 2's are always greater than the number of 5's.

Pseudocode:

N=input
div=5
count=0
while(N/div!=0)
count+=N/div;
div=div*5
print count

CODE:
code



For any question feel free to contact me:
@saranyanaharoy

Happy Learning!!
Question: Given an Array of objects, you have to determine whether it has a majority element or not. A majority element is any element in the array which is present more than n/2 times in the array. Here equality expression holds but inequility expression doesnot holds, means A[i]==A[j] or A[i] != A[j] can be evaluated but A[i]<A[j] or A[i]>A[j] are meaningless and cannot be evaluated. Device an O(n) algorithm that returns the majority element or say no majority element exists.




Solution: Idea is to pair up the elements arbitrarily to get ceil(n/2) pairs. In each pair if the two elements are different we discard both of them. If they are same only one of them is kept. After the proposed procedure, there are atmost ceil(n/2) elements left and if A has a majority element, then this new array of remaining elements will have the same majority element. We then recursively call the same procedure on this new array.
Lets say m be the majority element we get once we apply the algorithm, now it is mandatory to check if m is indeed a majority element of the array. This can be done by a GetFrequency() call followed by a check whether the frequency of m in A[1...n] is greater than n/2 .


Below is the pseudo code:

procedure Check(A[1...n])
Input: Array A of objects
Output: Majority element of A
m = GetMajorityElementLinear(A[1...n])
freq = GetFrequency(A[1...n],m)
if freq >floor(n/2) + 1:
return m
else
return NO-MAJORITY-ELEMENT



procedure GetMajorityElementLinear(A[1...n])
Input: Array A of objects
Output: Majority element of A
if n==1:
return A[1]
if n == 2:
if A[1] == A[2]:
return A[1]
else
return NO-MAJORITY-ELEMENT
Create a temporary array temp
for i = 1 to n:
if A[i] == A[i+1]:
Insert A[i] into temp
i = i+1
return GetMajorityElementLinear(temp)



Procedure GetFrequency(A[1,2.....n],m)
Input: Array A of object and an object m whose frequency is to be counted.
Output: Frequency of m.
c=0
for i=1 to n:
if A[i]==m:
c=c+1
return c

Recurrence relation for the algorithm is given as follows:
T(n) = T(n/2) + O(n).
As we can see the processing of array in the recursive function GetMajorityElementLinear() is done in O(n) time. Complexity of the function GetMajorityElementLinear() is O(n). Check() is also O(n). Therefore the whole algorithm is linear in terms of n.



Happy Coding!!!
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example Input:
[-2,1,-3,4,-1,2,1,-5,4],
Example Output: 6
Explanation:
[4,-1,2,1] has the largest sum = 6.

Hint : can be solved in O(N)
*Read Solution* : http://codingclub.tech/event/solution-max-subarray-sum
Hello Everyone!!

Yet Another Number Game Problem Code: NUMGAME
Alice and Bob play the following game. They choose a number N to play with. The rules are as follows :
1) Alice plays first, and the two players alternate.
2) In his/her turn, a player can subtract from N any proper divisor (not equal to N) of N. The number thus obtained is the new N.
3) The person who cannot make a move in his/her turn loses the game.

Assuming both play optimally, who wins the game ?

Input : The first line contains the number of test cases T. Each of the next T lines contains an integer N.
Output : Output T lines, one for each test case, containing "ALICE" if Alice wins the game, or "BOB" otherwise.

Sample Input :
2
1
2

Sample Output :
BOB
ALICE

Constraints :
1 <= T <= 10000
1 <= N <= 1000000000

Note : For the first test case, Alice cannot make any move and hence Bob wins the game. For the second test case, Alice subtracts 1 from N. Now, Bob cannot make a move and loses the game.

Can you solve ?
PROBLEM

Editorial for Solution:
EDITORIAL


Happy Learning
Fast IO Optimization in C++

In competitive programming, it is important to optimize I/O methods as time limit of some problems is very strict.

You must have seen various problem statements saying: “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”. Key for such problems is to use Faster I/O techniques.

Lets say you have taken an input of 10^5 numbers, there are many methods for input/output

1. std::cin>>x;
std::cout<<x;

you can use std::cin and std::cout. How ever there are better methods

2.scanf("%d",&x);
printf ("%d",x);

scanf / printf are roughly thrice as fast as the cin/cout.

However, you can still use cin/cout and achieve the same speed as scanf/printf by including the following lines in your main function.

#include <bits/stdc++.h>
using namespace std;

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}

To know more about this read here.

3. FAST IO

void fastscan(int &x)
{
bool neg = false;
register int c;
x = 0;
c = getchar();
if(c == '-')
{
neg = true;
c = getchar();
}
for(;(c>47 && c<58);c=getchar()) x=(x<<1)+(x<<3)+c-48;
if(neg) x *=-1;
}

fastscan(x);

this is one of the fastest way to take an integer input from STDIN this is around 10 times faster than scanf() This is very useful in competetive programming.

Similiarly to print an integer, the following fastprint() function can be used.

void fastprint(int n)
{
if (n == 0)
{
putchar('0');
putchar('\n');
}
else if (n == -1)
{
putchar('-');
putchar('1');
putchar('\n');
}
else
{
int neg=0;
char buf[20];
if(n<0){
neg=1;
n=-n;
}
buf[10] = '\n';
int i = 9;
while (n)
{
buf[i--] = n % 10 + '0';
n /= 10;
}
if(neg)buf[i--]='-';
while (buf[i] != '\n')
putchar(buf[++i]);
}
}

fastprint(n);



We can test our input and output methods on the problem : PROBLEM

Solution:
CODE

For any doubt or correction feel free to contact me:
@saranyanaharoy

Happy Learning
Hello Everyone!!

Find the middle element of a linked list

Naive solution:
1. A simple way to determine the middle node would be
to fully pass through all nodes in the linked list
and count how many elements there are in total.
2. Then traverse the linked list again this time
stopping at the total/2 node.

For example,
the first time you traverse the linked list your program determines there are 10 nodes,
then the second pass through the linked list you stop at the 5th node,
which is the middle node.


This is a possible solution,
but there is a faster way.
Can you find it out ?

Read Optimal and Full Solution
SOLUTION


Happy Learning
Problem 1: You have n lists, each consisting of m integers sorted in ascending order. Merging these lists into a single sorted list will take time:

(a) O(nm log m) (b) O(mn log n)
(c) O(m + n) (d) O(mn)


Problem 2: A simple graph is one in which there are no self loops and each pair of distinct vertices is connected by at most one edge. Let G be a simple graph on 8 vertices such that there is a vertex of degree 1, a vertex of degree 2, a vertex of degree 3, a vertex of degree 4, a vertex of degree 5, a vertex of degree 6 and a vertex of degree 7. Which of the following can be the degree of the last vertex?

(a) 3 (b) 0
(c) 5 (d) 4


Problem 3: When a user submits a query, a search engine does the following. For every webpage that has been visited by the search engine, it computes a score indicating how relevant that page is to the query. Finally, it reports the pages with the top k scores on the screen, for a number k specified by the user. A good data structure for accumulating the scores and ranking them is:

(a) a queue (b) a heap
(c) a stack (d) a binary search tree


Problem 4: A complete graph on n vertices is an undirected graph in which every pair of distinct vertices is connected by an edge. A simple path in a graph is one in which no vertex is repeated. Let G be a complete graph on 10 vertices. Let u, v, w be three distinct vertices in G. How many simple paths are there from u to v going through w?


Solutions:
Answer 1: b) O(mn log n)

We can merge two sorted lists of size k and l in time
O(k +l). We begin by merging the lists in pairs to generate n/2 lists of size 2m each. To generate a list of size 2m we require O(m+m) time. Therefore to generate n/2 list the time required will be O(mn). If we repeat this, we get n/4 lists of size 4m each, again in total time O(mn). Thus, in O(log n) rounds, we converge to a single sorted list. Each round takes time O(mn), so the total time is O(mn log n).
Another strategy to achieve complexity O(mn log n) is to build a min-heap of size n, consisting the first element in each of the n lists. We then extract the minimum element from the heap to the output and replace it in the heap with the next element from the list from which the minimum came. Thus, it takes time O(log n) to generate each element in the output and there are O(mn) output elements in all, so the overall time
is O(mn log n).


Answer 2: d) 4

The number of odd degree vertices in any graph is even. Since we already have four
vertices of odd degree, the degree of the last vertex cannot be 3 or 5. It cannot be 0 either, since there is one vertex with degree 7, which means that it is a neighbour to all the other vertices, which implies that there is no isolated vertex in the graph. Thus the only possible degree of the last vertex is 4.


Answer 3: b) a heap

Let n be the number of pages visited by the search engine at the time a query is submitted. Assume that it takes constant time to compute the relevance score for each page w.r.t. a query. Then it takes O(n) time to compute the relevance scores, a further O(n) time to build a heap of n relevance scores, and O(k·log n) time for k delete-max operations to return the top k scores.

Answer 4: For every path from u to v, w is always present. Now, the no of nodes from the remaining 7 nodes (10 nodes -{u,v,w}) can be choosen in 7Ci ways and for each of the choosen i vertices, these nodes can be travelled in (i+1)! ways ( i+1 because we are including the w vertex also, along with the i vertices). Thus the total no of ways are:

=(7C0).(1!) + (7C1).(2!) + (7C2).(3!) + (7C3).(4!) + (7C4).(5!) + (7C5).(6!) + (7C6).(7!) + (7C7).(8!)

=95901.



Happy Coding!!!!
Hello Everyone!!

Problem Link: PROBLEM

Question
An archeologist seeking proof of the presence of extraterrestrials in the Earth’s past, stumbles upon a partially destroyed wall containing strange chains of numbers. The left-hand part of these lines of digits is always intact, but unfortunately the right-hand one is often lost by erosion of the stone. However, she notices that all the numbers with all its digits intact are powers of 2, so that the hypothesis that all of them are powers of 2 is obvious. To reinforce her belief, she selects a list of numbers on which it is apparent that the number of legible digits is strictly smaller than the number of lost ones, and asks you to find the smallest power of 2 (if any) whose first digits coincide with those of the list.
Thus you must write a program such that given an integer, it determines (if it exists) the smallest exponent E such that the first digits of 2^E coincide with the integer (remember that more than half of the digits are missing).

Input
It is a set of lines with a positive integer N not bigger than 2147483648 in each of them.

Output
For every one of these integers a line containing the smallest positive integer E such that the first digits
of 2^E are precisely the digits of N, or, if there is no one, the sentence ‘no power of 2’.

Sample Input
1
2
10


Sample Output
7
8
20

Explanation
Input 1
2^7 = 128
input 2
2^8=256
input 3
2^20=1048576





Solution:
EDITORIAL

Pseudocode:
N=input 
T=floorl(log10(N)+2)
A=log2(N)+T*log2(10)
B=log2(N+1)+T*log2(10)
while(ceill(A)>=B)
T=T+1
A=log2(N)+T*log2(10)
B=log2(N+1)+T*log2(10)
print ceill(A)

Code:
CODE

For any doubt or correction feel free to contact me:
@saranyanaharoy

Happy Learning
For enhancing the book reading, school distributed story books to students as part of the Children’s day celebrations.

To increase the reading habit, the class teacher decided to exchange the books every weeks so that everyone will have a different book to read. She wants to know how many possible exchanges are possible.

If they have 4 books and students, the possible exchanges are 9. Bi is the book of i-th student and after the exchange he should get a different book, other than Bi.

B1 B2 B3 B4 - first state, before exchange of the books

B2 B1 B4 B3

B2 B3 B4 B1

B2 B4 B1 B3

B3 B1 B4 B2

B3 B4 B1 B2

B3 B4 B2 B1

B4 B1 B2 B3

B4 B3 B1 B2

B4 B3 B2 B1

Find the number of possible exchanges, if the books are exchanged so that every student will receive a different book.


Solution
We have to apply derangement formula here.
DERANGEMENTS
Count Derangements :
SOLUTION

Happy Learning
Problem:
You are going abroad and you have to complete a number of formalities before you leave. Each task takes a full day to complete. Fortunately, you have an army of friends to help you and each task can be done by either you or any of your friends, so you can complete as many tasks as possible in parallel, on the same day.
Some tasks depend on others: for instance, you cannot purchase foreign exchange till you have bought your ticket. If task B depends on task A, you can start B only after you complete A. A set of tasks with no pending dependencies can be completed in parallel.
You are given a list of n such tasks to be completed, where each task comes with a set of other tasks that it depends on. The set of tasks is feasible: there are no circular dependencies. You want to compute the minimum number of days needed to complete all the tasks, given the constraints.



Solutions:
Construct a graph in which the tasks are the vertices and there is an edge (i, j) if task i must be completed before starting task j. This is a directed graph without cycles, so it is a directed acyclic graph (dag). Any path (suppose v1->v2->v3->.....->vk of length k) of tasks would take a minimum of k days to complete because each edge in the path describes a dependency. Hence, the problem is one of finding the longest path in a dag.

In any dag, there must be some vertex with no incoming edge (indegree 0). Any vertex of indegree 0 represents a task that has no pending dependencies and can hence be immediately completed. Once it is completed, we can remove it from the graph and operate on the tasks that remain.
The algorithm is thus the following.
• Initialize a counter c to 0.
• While the dag is not empty
– Remove all vertices of indegree 0
– Recompute indegrees of remaining vertices
– Increment c

The final value of c is the answer we seek.
The complexity of this algorithm depends on how we represent the graph. For G = (V, E) let |V | = n and |E| = m. If we use an adjacency matrix, for each vertex we remove, we have to scan a row of the matrix to determine which indegrees to decrement, so it will take time O(n^2). If we use adjacency lists, for each vertex we delete, we can scan its list of outgoing edges and directly decrement indegrees for its outgoing neighbours. Across the n vertices we delete, we scan each of the m edges once, so the overall time is O(n + m).


Happy Coding!!!
Problem: Your final exams are over and you are catching up on watching sports on TV. You have a schedule of interesting matches coming up all over the world during the next week. You hate to start or stop watching a match midway, so your aim is to watch as many complete matches as possible during the week. Suppose there are n such matches scheduled during the coming week and you know the starting and finishing time for each match.
Describe an efficient algorithm to compute the following: for each match, what is the next match whose starting time is strictly later than the finishing time of the current match?




Solution: We can accumulate information about the matches in the order in which they appear in the TV schedule. Hence, we can assume that the starting times and ending times of the matches are recorded in two arrays B[1..n] and E[1..n], where B[i] and E[i] are the beginning and ending time, respectively, of match i and B is sorted in ascending order. For each match i, we use binary search in B to find the earliest match j such that E[i] ≤ B[j] and set Next[i] = j. We do n binary searches, so this takes time O(n log n).



Happy Coding!!!!
Forwarded from Strange
Problem 1: Let A be an array of n integers, sorted so that A[1] ≤ A[2] ≤ · · · ≤ A[n]. You are given a number x. The aim is to find out if there are indices k and l such that A[k] + A[l] = x. Design an algorithm for this problem that works in time O(n).

Problem 2: Let A be array of n integers that is assumed to be sorted. You are given a number x. The aim is to find out if there are indices k, l and m such that
A[k] + A[l] + A[m] = x. Design an algorithm for this problem that works in time O(n^2).





Solution 1: Consider the two endpoints A[1] and A[n].
• If A[1] + A[n] > x, A[n] is useless since it cannot be paired with any number to achieve the sum—any sum A[i] + A[n], i > 1, will be greater than or equal to A[1] + A[n] since A[i] ≥ A[1].
• Likewise, if A[1] + A[n] < x, A[1] is useless since it cannot be paired with any number to achieve the sum.
Hence, we start with two pointers left and right, with left = 1 and right = n initially. At each stage, we check the sum A[left] + A[right]. If this sum exceeds x, we decrement right and if this sum is less than x we increment left. Eventually, either left and right meet and there is no solution, or we find the indices k and that we are looking for.
This takes a single scan of A, so the overall time is O(n).


Solution 2: Suppose we fix the first index k = 1. Then the problem reduces to finding l and m in 2, 3, . . . , n such that A[l] +A[m] = x−A[1]. This can be solved in time O(n)
by the solution 1 discuss earlier in this post. . We vary k from 1, 2, . . . , n−3, and check for l and m in k+1, k+2, . . . , n such that A[l] + A[m] = x − A[k]. This takes time (n−1) +(n−2) + (n−3) + · · · · · · · + 1 = O(n^2).


Happy Coding!!!!
Hello Everyone!!

Problem Link: TOWER

Question
There are N cities in Magic land arranged as a one dimensional array. For simplicity we can assume an array of size N as N cities. The king of Magic land is now installing new 4G internet towers in various cities. Let us consider the array is A1 , A2 , A3 , A4 ,......, AN. Now, consider the following statement:

If Ai is equal to 0 then it means there is no tower in the city.
If Ai is equal to k (k is a positive integer), then there is a tower in ith city and the range of the tower is k. It means the city from A max ( 1 , i - k ) to A min ( N , i + k ) will get the internet connection.
Suppose, A5 = 1 , then A4 , A5 and A6 will get the internet connection even if there is no tower in A4 or A6.

The installation of towers is over now. The king wants to know how many cities are there without internet connection.

Input
•The first line contains an integer N denoting the number of cities
•The second line contains N spaced seperated integers denoting A1 , A2 , A3 , . . . . . . , AN

Output
•The one and only line contains an integer denoting the number of cities without any internet connections

Constraints
•1 ≤ N ≤ 106
•0 ≤ Ai ≤ 109

Sample Input 1
4
0 0 1 0
Sample output 1
1

Sample Input 2
7
0 2 0 0 0 0 1
Sample output 2
1

Explanation

For sample input 1 :
There is only one tower in city 3 whose range is 1. City 2 , 3 and 4 gets the internet connection from this tower but city 1 doesnot get it hence the output is 1.

For sample input 2:
There is a tower at city 2 whose range is 2. City 1 , 2 , 3 and 4 gets the internet connection from this tower. Similarly city 6 and 7 get internet connection from the tower at city 7. But city 5 doesnot get internet connection at all. Hence the output is 1.





Solution:
EDITORIAL

Pseudocode:

n=number of cities
A=array
n,A=input

for i = 0 to n-1
if Ai>0
Ai++

Leftc[n]
Rightc[n]
c=0

for i=0 to n-1
c=c-1
c=max(c,A[i])
Rightc[i]=c

c=0

for i=n-1 to 0
c=c-1
c=max(c,A[i])
Leftc[i]=c

count=0

for i=0 to n-1
if(Leftc[i]==0 && Rightc[i]==0)
count++

print count

Code:
CODE

For any doubt or correction feel free to contact me:
@saranyanaharoy

Happy Learning
Question:

Take an input array, say A and print the maximum value of x
where x = |(A[i] – A[j]) + (i – j)| .

Constraints:
Max array size: 20000
Time limit: 0.1s

Time limit is a major factor in this question.


Hint:
https://imgur.com/0jhFcBi

Solution Approach:
https://imgur.com/5xc5AO2

Complete Solution:
https://imgur.com/abadlKe

Happy Learning
Question
Given an array of strings with R, G & B as characters. Sort the array such that all R comes first, followed by Gs & followed by Bs.
Do it in O(n) time complexity.

For eg. array is:
I/P: G G R B R B B G R B R
O/P: R R R R G G G B B B B

Read Solution:
DNF algorithm

Happy Learning
problem: You are given an array A of size n. You are told that A comprises three consecutive runs – first a run of ’a’s, then a run of ’b’s and finally a run of ’c’s. Moreover, you are provided an index i such that A[i] = b. Design an O(log n) time algorithm to determine the number of ’b’s (i.e.,
length of the second run) in A.


Solution: We will use modified binary search to find the first occurrence of 'b'. In the similar manner we will find the last occurrence of 'b'. The final answer is (last occurrence - first occurrence +1).
Now, to find the first occurrence we have to check that if the current element is 'b' and the element before this current element is 'a'. If yes, then we got our first occurrence else we search on the right segment if the current element is 'a', else we search in the left segment.
Pseudo Code:
first_occurrence(A[],low,high)
mid=(low+high)/2
if(A[mid]=='b' && A[mid-1]=='a'):
return mid
else if(A[i]=='a'):
return first_occurrence(A,mid+1,high)
else:
return first_occurrence(A,low,mid-1)


In the similar manner we can find the last occurrence. If the current element is 'b' and the next element is 'c' then it is the last occurrence of 'b'. Else we search on the left segment if the current element is 'c'. Otherwise we search the right segment.
Pseudo Code:
last_occurrence(A[],low,high)
mid=(low+high)/2
if(A[mid]=='b' && A[mid+1]=='c'):
return mid
else if(A[i]=='b'):
return last_occurrence(A,mid+1,high)
else:
return last_occurrence(A,low,mid-1)



Happy Coding!!!