![]() |
VOOZH | about |
Given a sorted array of rational numbers, where each rational number is represented in the form p/q (where p is the numerator and q is the denominator), the task is to find the index of a given rational number x in the array. If the number does not exist in the array, return -1.
Examples:
Input: arr[] = [1/5, 2/3, 3/2, 13/2], x = 3/2
Output: 2
Explanation: The given rational element is present at index 2.Input: arr[] = [1/5, 2/3, 3/2, 13/2], x = 5/1
Output: -1
Explanation: The given rational number5/1does not exist in the array.Input: arr[] = [1/2, 2/3, 3/4, 4/5], x = 1/2
Output: 0
Explanation: The given rational number 1/2 is present at index 0 in the array.
Approach:
The idea is to use binary search to efficiently find the index of the given rational number
xin the sorted array of rational numbers. Since the array is sorted, we can compare rational numbers without using floating-point arithmetic by cross-multiplying the numerators and denominators, allowing us to determine whether to search in the left or right half of the array.
Step by step approach:
left and right, to represent the start and end of the search range in the array.mid = left + (right - left) / 2.x using cross-multiplication:arr[mid] == x, return mid (index found).arr[mid] > x, update right = mid - 1 to search in the left half.arr[mid] < x, update left = mid + 1 to search in the right half.left exceeds right.x, return -1 (element not found).2
Time Complexity: O(log n)
Auxiliary Space: O(1), since no extra space has been taken.