Search for a Range InterviewBit Solution
- illuminati
- Sep 6, 2020
- 1 min read
Updated: Sep 12, 2020
Problem: Search for a Range
Problem Description:
Given a sorted array of integers A(0 based index) of size N, find the starting and ending position of a given integer B in array A.
Your algorithm’s runtime complexity must be in the order of O(log n).
Return an array of size 2, such that first element = starting position of B in A and second element = ending position of B in A, if B is not found in A return [-1, -1].
Input Format
The first argument given is the integer array A. The second argument given is the integer B.
Output Format
Return an array of size 2, such that first element = starting position of B in A and second element = ending position of B in A, if B is not found in A return [-1, -1].
Constraints
1 <= N <= 10^6
1 <= A[i], B <= 10^9
For Example
Input 1:
A = [5, 7, 7, 8, 8, 10]
B = 8
Output 1:
[3, 4]
Explanation 1:
First occurence of 8 in A is at index 3
Second occurence of 8 in A is at index 4
ans = [3, 4]
Input 2:
A = [5, 17, 100, 111]
B = 3
Output 2:
[-1, -1]
Approach
The solution is to about finding the lower bound and upper bound of the given element.
So we can use two binary search algorithm for each one to find out our desired result.
Time & Space Complexity
Time Complexity: O(LogN)
- Since we have used a binary search algorithm.
Space Complexity: O(1)
- Ignoring space taken by input array.
Solution
Code in C++
Recent Posts
See AllYou are given an array of N non-negative integers, A0, A1 ,…, AN-1.Considering each array element Ai as the edge length of some line segment
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
Comments