Problem Link - List of Books
Problem Statement
This is another problem about Indraneel’s library. His library has one long shelf. His books are numbered and he identifies the books by their number. Each book has a distinct number.
He has lost many books, since many of his friends borrow his books and never bother to return them. He does not want to lose any more books and has decided to keep a record of all books that he lends to his friends. To make the task of borrowing a book a little difficult, he has given the following instructions to his friends: when they borrow a book, they must record in a register its position from the left among the books currently on the shelf.
Suppose there are 5 books in the library and they are arranged as follows:
26~~~~~1~~~~~42~~~~~15~~~~~3
If someone walks in and borrows the book 42, then he will record 3 in the register because this book is the third from the left on the shelf. Now the shelf looks like this:
26~~~~~1~~~~~15~~~~~3
If the next person borrow the book 3, he writes down 4 in the register since this is currently the fourth book from the left on the shelf, and so on.
Indraneel knows the initial arrangement of the books in his library at the time that he introduced the register system. After a while he examines his register and would like to know which books have been borrowed. Your task is to write a program to help Indraneel solve this problem.
Approach
We start with an array representing the books on the shelf in their initial order. Each book is identified by its position in the array. When a query is received, the given position represents the book being borrowed. The program retrieves the book at that position, displays its number, and removes it from the shelf by shifting all subsequent books one position to the left. This ensures that the array always reflects the current state of the shelf. The process repeats for each query, updating the shelf after each borrowing action.
Time Complexity
The worst-case time complexity for each query is O(n) due to the shifting of books after a removal. For q queries, the total complexity is O(n * q).
Space Complexity
The space complexity is O(n), where n is the number of books, as the array stores the current state of the shelf.