Find first and last positions of an element in a sorted array

You are given a sorted array ARR consisting of N integers and an integer X. You need to find the first and last position of occurrence of X in the array.

Note:

1. The array follows 0-based indexing, so you need to return 0-based indices.
2. If X is not present in the array, return “-1 -1”.
3. If X is only present once in the array, the first and last position of its occurrence will be the same.

Follow Up:

Try to solve the problem in O(log(N)) time complexity.
Input Format:
The first line of the input contains an integer T denoting the number of test cases.

The first line of each test case contains the integer N, denoting the size of the sorted array.

The second line of each test case contains N space-separated integers denoting the array elements.

The third and last line of each test case contains the value X, whose first and last position of occurrence you need to find.
Output Format:
The only line of output of each test case should contain two space-separated integers, where the first and second integer will be the first and the last position of occurrence of X respectively in the array.
Note:
Just implement the given function. You do not need to print anything, it has already been taken care of.
Constraints:
1 <= T <= 50
1 <= N <= 10^4
-10^9 <= ARR[i] <= 10^9
-10^9 <= X <= 10^9

Time Limit: 1sec
CodingNinjas
author
2y

Firstly, I used binary search to find the element and the used linear search from that index to find the range
Interviewer asked me to optimise the solution.
Then, I used binary search 2 times to find l...read more

CodingNinjas
author
2y
Naively find first and the last occurrence
  • Create two storage variables IDX1 and idx2 to store the first and last position of occurrence and initialise them to -1.
  • Iterate through the array, if you enco...read more
CodingNinjas
author
2y
Binary Search
  • The given input array is sorted, thus we can apply binary search to the array. Binary search finds any element in O(log(N)), where N is the size of the input array.
  • Binary search prunes th...read more
Add answer anonymously...
Amazon Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter