#K64767. Binary Search and Occurrence Finder

    ID: 32049 Type: Default 1000ms 256MiB

Binary Search and Occurrence Finder

Binary Search and Occurrence Finder

You are given a sorted array of integers and a target integer x. Your task is to implement three functions:

  • binarySearch: Find any occurrence of x in the array using binary search. If found, return its index; otherwise, return -1.
  • findFirstOccurrence: Find the index of the first occurrence of x in the array. If x does not exist, return -1.
  • findLastOccurrence: Find the index of the last occurrence of x in the array. If x does not exist, return -1.

The functions should work in O(log n) time complexity using a variant of binary search. In mathematical terms, if the array is A and its indices go from 0 to n-1, then for a given target x, you need to compute:

  • \( \text{binarySearch}(A, x) = i \) for some index i such that \( A[i] = x \), if such an index exists; otherwise, -1.
  • \( \text{findFirstOccurrence}(A, x) = \min\{ i \mid A[i] = x \} \) if \( x \) appears in A, otherwise -1.
  • \( \text{findLastOccurrence}(A, x) = \max\{ i \mid A[i] = x \} \) if \( x \) appears in A, otherwise -1.

inputFormat

The input begins with an integer T representing the number of test cases. For each test case:

  1. An integer n denoting the number of elements in the sorted array.
  2. A line with n space-separated integers representing the sorted array.
  3. An integer x, the target value.

outputFormat

For each test case, output a single line with three space-separated integers in the following order:

  1. The result from binarySearch.
  2. The result from findFirstOccurrence.
  3. The result from findLastOccurrence.

If the target x is not present in the array, all three outputs should be -1.

## sample
4
7
1 2 2 2 3 4 5
2
7
1 2 2 2 3 4 5
6
1
5
5
5
2 2 2 2 2
2
3 1 3

-1 -1 -1 0 0 0 2 0 4

</p>