Hint: Modify Binary Search.
Solution:
You should use binary search twice first to find the first occurrence of $b$. Then apply it again to find the last occurrence.
The following code does this.
BinarySearchForFirst
int binarySearchForFirst(int l, int r){
int mid;
while(l <= r){
mid = l+(r-l)/2;
if(array[mid]=='b' && array[mid-1]=='a' ){//the desired case
return mid;
}
if(array[mid-1]=='b'){//we're to the right of required index
r = mid;
continue;
}
if(array[mid]=='a'){//we're to the left or required index
l = mid;
continue;
}
}
}
This returns the first index say $i$
Similarly find the second index $j$.
Then the answer is $j-i+1$