Search comparison counter

You are required to simulate and compare the performance of Sequential Search and Binary Search on a strictly increasing array of integers.

You must implement a class SearchComparator with a single method:

  • compareSearches(arr, queries): Takes a vector<int> representing the sorted array and a vector<int> of target values to search for. For each target, the method executes both search algorithms as follows:
  • Sequential Search: Iterates through the array starting from index 0 upward. It increments a comparison counter each time an element is examined. It stops only on a match or when it reaches the end of the array (it does not stop early if an element exceeds the target).
  • Binary Search: Initializes low = 0 and high = N - 1. While low <= high, it increments a comparison counter and calculates mid = low + floor((high - low) / 2). It stops immediately if arr[mid] == target. Otherwise, it adjusts low or high standardly (low = mid + 1 or high = mid - 1).

Note: Treat the examination of an element against the target as exactly 1 comparison, regardless of whether your code evaluates one or multiple relational operators (<, >, ==) under the hood.

The method should return a vector<vector<int>>, where each inner vector corresponds to a query and contains exactly three integers: [matching_index_or_minus_1, sequential_comparison_count, binary_comparison_count].

If the array is empty, both comparison counts are 0, and the matching index is -1.

Example 1:

Input: arr = [2, 5, 9]

queries = [9]

Output: [[2, 3, 2]]

Explanation:

N = 3, Q = 1. Array is [2, 5, 9]. Target is 9.

  • Sequential search checks 2, 5, and 9 (3 comparisons) and finds it at index 2.
  • Binary search checks mid=1 (5), goes right. Checks mid=2 (9), finds it (2 comparisons).

Example 2:

Input: arr = []

queries = [5]

Output: [[-1, 0, 0]]

Explanation:

N = 0, Q = 1. Array is empty. Target is 5.

  • With an empty array, no comparisons can be made, and the item cannot be found.

Now Your Turn!

Pick the correct output for the given input

Input: arr = [1, 3, 5, 7, 9]

queries = [4, 7]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= N <= 105
  • 1 <= number of queries <= 105
  • sum of N over all queries <= 5e6
  • Array values and target values lie in the range [-109, 109].
  • The array arr is guaranteed to be strictly increasing.
0
class SearchComparator {
public:
vector<vector<int>> compareSearches(vector<int>& arr, vector<int>& queries) {
// Your code goes here
return {};
}
};
Test Case

Input:

Arr
Queries