BackmediumArraysarraysmedium

Book Availability Checker Solution

Problem Statement

You are tasked with implementing a utility function for a digital library management system. The system maintains a collection of book records, represented as an array of objects. Each object contains two properties: bookId (a unique integer identifier) and isAvailable (a boolean flag indicating if the book is currently in stock).

Given this array of book records and a target bookId, your function must determine two specific conditions: whether the book with the target ID exists in the collection, and if it does, whether it is available. The function should return a boolean array of length 2. The first element should be true if the book ID is found in the array, otherwise false. The second element should be true if the book exists AND is available, otherwise false (including cases where the book does not exist).

Note: The bookId values in the input array are guaranteed to be unique. You must handle the case where the target book ID is not present in the array efficiently.

Example 1
Input
books = [{"bookId": 101, "isAvailable": true}, {"bookId": 202, "isAvailable": false}, {"bookId": 303, "isAvailable": true}], targetId = 202
Output
[true, false]

Explanation: Step 1: Search for bookId 202 in the array. It is found at index 1. Step 2: Since the book exists, the first element of the result is true. Step 3: Check the isAvailable property for bookId 202. It is false. Step 4: Since the book exists but is not available, the second element is false. Final output: [true, false].

Example 2
Input
books = [{"bookId": 50, "isAvailable": false}, {"bookId": 60, "isAvailable": true}], targetId = 60
Output
[true, true]

Explanation: Step 1: Search for bookId 60 in the array. It is found at index 1. Step 2: Since the book exists, the first element of the result is true. Step 3: Check the isAvailable property for bookId 60. It is true. Step 4: Since the book exists and is available, the second element is true. Final output: [true, true].

Example 3
Input
books = [{"bookId": 1, "isAvailable": true}, {"bookId": 2, "isAvailable": true}], targetId = 99
Output
[false, false]

Explanation: Step 1: Search for bookId 99 in the array. It is not found in any object. Step 2: Since the book does not exist, the first element of the result is false. Step 3: Since the book does not exist, it cannot be available. The second element is false. Final output: [false, false].

Example 4
Input
books = [{"bookId": 10, "isAvailable": false}, {"bookId": 20, "isAvailable": false}, {"bookId": 30, "isAvailable": false}], targetId = 20
Output
[true, false]

Explanation: Step 1: Search for bookId 20 in the array. It is found at index 1. Step 2: Since the book exists, the first element of the result is true. Step 3: Check the isAvailable property for bookId 20. It is false. Step 4: Since the book exists but is not available, the second element is false. Final output: [true, false].

Constraints

  • 1 <= books.length <= 10^5
  • 1 <= bookId <= 10^9
  • All bookId values in the books array are unique.
  • targetId is an integer between 1 and 10^9.
  • isAvailable is a boolean value (true or false).
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Book Availability Checker — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(1) average for hash‑map lookup (O(n) preprocessing), O(log n) for binary search after O(n log n) sort
|
SpaceO(n) for the hash map or sorted array

Problem Description

You are tasked with implementing a utility function for a digital library management system. The system maintains a collection of book records, represented as an array of objects. Each object contains two properties: bookId (a unique integer identifier) and isAvailable (a boolean flag indicating if the book is currently in stock).

Given this array of book records and a target bookId, your function must determine two specific conditions: whether the book with the target ID exists in the collection, and if it does, whether it is available. The function should return a boolean array of length 2. The first element should be true if the book ID is found in the array, otherwise false. The second element should be true if the book exists AND is available, otherwise false (including cases where the book does not exist).

Note: The bookId values in the input array are guaranteed to be unique. You must handle the case where the target book ID is not present in the array efficiently.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Book Availability Checker"

medium

WHY DOES IT MATTER?

Fast lookup patterns are fundamental in any system that must answer membership or status queries at scale—think caching layers, authentication token validation, or inventory checks. Mastering hash‑based retrieval prevents bottlenecks that would otherwise degrade user experience.

OPTIMIZATION CHALLENGE

The key insight is to pre‑process the data into a structure that offers constant‑time direct access, eliminating the need to scan the entire collection for each query. This shift from O(n) to O(1) dramatically reduces latency for high‑frequency queries.

REAL-WORLD CONNECTION

Consider a distributed CDN edge server that must instantly verify whether a content ID is cached locally. It uses a hash table to map content IDs to cache entries, mirroring the book‑availability lookup in a library system.

During an interview, first clarify whether the dataset is static or mutable. If mutable, propose a hash map; if static with many queries, suggest sorting once and using binary search. Mention trade‑offs in space and preprocessing time to demonstrate depth.

COMPLEXITY AT A GLANCE

⏱ Time:O(1) average for hash‑map lookup (O(n) preprocessing), O(log n) for binary search after O(n log n) sort
💾 Space:O(n) for the hash map or sorted array

Core Theory — Why This Approach?

The core of this problem lies in efficient search within an unsorted collection of objects. A naive linear scan examines each element until the target bookId is found, leading to O(n) time which becomes prohibitive when the library catalog contains millions of entries. By leveraging a hash‑based lookup (e.g., JavaScript's Map or Python's dict), we can transform the search into an average‑case O(1) operation, because the hash function distributes keys uniformly across buckets, allowing direct access. Alternatively, sorting the array by bookId and applying binary search yields O(log n) query time after an O(n log n) preprocessing step, which is advantageous when many queries are performed on a static dataset. The optimal paradigm therefore depends on the query‑to‑update ratio: use a hash map for frequent lookups with occasional inserts, or sort‑once‑binary‑search for read‑only workloads.

Interview Questions on This Problem

Q1How would you design a data structure to support O(1) average‑case look‑ups for book availability while also allowing O(1) insertions and deletions?

Use a hash map where the key is bookId and the value is the isAvailable flag (or a reference to the full record). Insertion, deletion, and lookup are all O(1) on average because they rely on constant‑time hash computations and bucket access.

Q2If the library system must support range queries (e.g., find all available books with IDs between 1000 and 2000), which data structure would you choose and why?

A balanced binary search tree (e.g., AVL or Red‑Black tree) keyed by bookId allows ordered traversal and range queries in O(log n + k) time, where k is the number of books in the range. This is more suitable than a hash map, which lacks ordering.

Q3Explain how you would handle concurrent read/write access to the book availability map in a high‑traffic microservice.

Employ a read‑write lock or lock‑free concurrent hash map (e.g., Java's ConcurrentHashMap). Reads acquire a shared lock or proceed lock‑free, while writes acquire an exclusive lock or use atomic compare‑and‑swap to ensure consistency without blocking readers.

Examples

Example 1

Input

books = [{"bookId": 101, "isAvailable": true}, {"bookId": 202, "isAvailable": false}, {"bookId": 303, "isAvailable": true}], targetId = 202

Output

[true, false]

Explanation: Step 1: Search for bookId 202 in the array. It is found at index 1. Step 2: Since the book exists, the first element of the result is true. Step 3: Check the isAvailable property for bookId 202. It is false. Step 4: Since the book exists but is not available, the second element is false. Final output: [true, false].

Example 2

Input

books = [{"bookId": 50, "isAvailable": false}, {"bookId": 60, "isAvailable": true}], targetId = 60

Output

[true, true]

Explanation: Step 1: Search for bookId 60 in the array. It is found at index 1. Step 2: Since the book exists, the first element of the result is true. Step 3: Check the isAvailable property for bookId 60. It is true. Step 4: Since the book exists and is available, the second element is true. Final output: [true, true].

Example 3

Input

books = [{"bookId": 1, "isAvailable": true}, {"bookId": 2, "isAvailable": true}], targetId = 99

Output

[false, false]

Explanation: Step 1: Search for bookId 99 in the array. It is not found in any object. Step 2: Since the book does not exist, the first element of the result is false. Step 3: Since the book does not exist, it cannot be available. The second element is false. Final output: [false, false].

Example 4

Input

books = [{"bookId": 10, "isAvailable": false}, {"bookId": 20, "isAvailable": false}, {"bookId": 30, "isAvailable": false}], targetId = 20

Output

[true, false]

Explanation: Step 1: Search for bookId 20 in the array. It is found at index 1. Step 2: Since the book exists, the first element of the result is true. Step 3: Check the isAvailable property for bookId 20. It is false. Step 4: Since the book exists but is not available, the second element is false. Final output: [true, false].

Constraints

  • 1 <= books.length <= 10^5
  • 1 <= bookId <= 10^9
  • All bookId values in the books array are unique.
  • targetId is an integer between 1 and 10^9.
  • isAvailable is a boolean value (true or false).

Optimal Approach & Strategy

Create a hash map keyed by bookId for constant‑time look‑ups, or sort the array and apply binary search for logarithmic query time if the dataset is immutable.

Brute Force Approach

Iterate through the array and compare each record's bookId with the target until a match is found; return its isAvailable flag.

Verified Code Solutions

JavaScript Solution
Time: O(1) average for hash‑map lookup (O(n) preprocessing), O(log n) for binary search after O(n log n) sort
function checkBookAvailability(books, bookId) {
       for (let book of books) {
           if (book.bookId === bookId) {
               return [true, book.isAvailable];
           }
       }
       return [false, false];
   }

Asked in Top Tech Interviews

arraysmediumlinear-scan

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.