C++ code to count number of unread chapters


Suppose we have an array of pairs P. Where P[i] is in the form (l, r), and have another number k. Consider we are going to read a book with n chapters. so that one page of the book belongs to exactly one chapter and each chapter contains at least one page. We have read some pages and marked the page with number k as the first page which was not read. We have to find the number of chapters we have not completely read yet. P[i] represents the chapter page numbers range.

So, if the input is like P = [[1, 3], [4, 7], [8, 11]]; k = 4, then the output will be 2, because we have read the first chapter, another two chapters are there to read.

Steps

To solve this, we will follow these steps −

n := size of P
for initialize i := 1, when i <= n, update (increase i by 1), do:
   if k >= P[i - 1, 0] and k <= P[i - 1, 1], then:
      return n - i + 1
return 0

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<vector<int>> P, int k){
   int n = P.size();
   for (int i = 1; i <= n; i++){
      if (k >= P[i - 1][0] && k <= P[i - 1][1])
         return n - i + 1;
   }
   return 0;
}
int main(){
   vector<vector<int>> P = { { 1, 3 }, { 4, 7 }, { 8, 11 } };
   int k = 4;
   cout << solve(P, k) << endl;
}

Input

{ { 1, 3 }, { 4, 7 }, { 8, 11 } }, 4

Output

2

Updated on: 15-Mar-2022

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements