Given a book of N pages, the task is to calculate the minimum number of page turns to get to a give desired page K. We can either start turning pages from the front side of the book (i.e from page 1) or from the back side of the book (i.e page number N). Each page has two sides, front and back, except the first page, which has only back side and the last page which may only have back side depending on the number of pages of the book.
Input : N = 6 and K = 2. Output : 1. From front, (1) -> (2, 3), page turned = 1. From back, (6) -> (4, 5) -> (2,3), page turned = 2. So, Minimum number of page turned = 1. Input : N = 5 and K = 4. Output : 1. From front, (1) -> (2, 3) -> (4,5), page turned = 2. From back, (4, 5) page turned = 1. From back, it is 2nd page, since 4 is on other side of page 5 and page 5 is the first one from back So, Minimum number of page turned = 1.
The idea is to calculate distance of the desired page from the front and from the back of the book, minimum of this is the required answer.
Now, Consider there is page 0, which is front of the first page. And if N is even, consider there is page N+1, which is back of the last page, so total number of pages are N+1.
To calculate the distance,
1. If K is even, front distance = (K – 0)/2 and back distance = (N – 1 – K)/2.
2. If K is odd, front distance = (K – 1)/2 and back distance = (N – K)/2.
Time Complexity : O(1)
This article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count number of ways to divide a number in 4 parts
- Fifth root of a number
- Number of ways to calculate a target number using only array elements
- Happy Number
- Number of flips to make binary string alternate | Set 1
- Convert a number into negative base representation
- Minimum number of equal amount bags to collect at least M money
- Maximum number of groups of size 3 containing two type of items
- Make n using 1s and 2s with minimum number of terms multiple of k
- Count of Numbers in Range where the number does not contain more than K non zero digits
- Maths behind number of paths in matrix problem
- Sum of minimum difference between consecutive elements of an array
- Minimum steps to reach target by a Knight | Set 2
- Number of subsequences with negative product
- Find the node whose sum with X has minimum set bits