
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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