'Code is working good in my ide but not getting output after submitting on GeeksforGeeks
First and last occurrences of X.
a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
Note: If the number x is not found in the array just print '-1'.
Input: The first line consists of an integer T i.e number of test cases. The first line of each test case contains two integers n and x. The second line contains n spaced integers.
Output: Print index of the first and last occurrences of the number x with a space in between.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String [] args){
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int x = scn.nextInt();
int [] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i]= scn.nextInt();
}
int low = 0;
int high = arr.length -1;
int fi;
while(low <= high){
int mid = (low + high)/ 2;
fi = -1;
if(x > arr[mid]){
low = mid + 1;
}else if(x < arr[mid]){
high = mid - 1;
}else{
fi = mid;
high = mid - 1;
}
}
low = 0;
high = arr.length -1;
int li;
while(low <= high){
int mid = (low + high)/ 2;
li = -1;
if(x > arr[mid]){
low = mid + 1;
}else if(x < arr[mid]){
high = mid - 1;
}else{
li = mid;
low = mid + 1;
}
}
System.out.println(fi);
System.out.println(li);
}
}
OUTPUT AFTER Running code -1; -1;
Solution 1:[1]
There are some logical mistakes in your code.
You are reinitialising the values of variables fi and li in the while loops.
They should be only initialised once, and that is outside the loop.
I have corrected your code and submitted it on the Geeks For Geeks Practice Question, First and last occurrences of X.
Have a look at the following implementation which has Accepted status on GFG:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String [] args){
Scanner scn = new Scanner(System.in);
int testcase = scn.nextInt();
while(testcase-- > 0){
int n = scn.nextInt();
int x = scn.nextInt();
int [] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i]= scn.nextInt();
}
int low = 0;
int high = arr.length -1;
int fi = -1;
while(low <= high){
int mid = (low + high)/ 2;
if(x > arr[mid]){
low = mid + 1;
}else if(x < arr[mid]){
high = mid - 1;
}else{
fi = mid;
high = mid - 1;
}
}
low = 0;
high = arr.length -1;
int li = -1;
while(low <= high){
int mid = (low + high)/ 2;
if(x > arr[mid]){
low = mid + 1;
}else if(x < arr[mid]){
high = mid - 1;
}else{
li = mid;
low = mid + 1;
}
}
if(fi==-1 || li==-1){
System.out.println(fi);
}else{
System.out.println(fi + " " + li);
}
}
}
}
PS: Accepted Verdict on GFG Practice:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepak Tatyaji Ahire |

