-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProblem-1.java
91 lines (68 loc) · 2 KB
/
Problem-1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* @author AkashGoyal
*/
/**
--------------------- Problem----------->> Find first and last positions of an element in a sorted array
Problem Link :- https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x/0
*/
class Solution {
ArrayList<Long> find(long arr[], int n, int x)
{
// code here
ArrayList<Long>alist=new ArrayList<Long>();
//Searching the element through binary search
int mid= BinSearch(arr,0,n-1,x);
//edge cases(if x does not exist)
if(mid==-1)
{
alist.add((long)-1);
alist.add((long)-1);
return alist;
}
//if we found x at mid index;
int move_left=mid-1;
int move_right=mid+1;
//now traverse to the left till we find different element
while(move_left>=0)
{
if(x!=arr[move_left])
{
break;
}
move_left--;
}
alist.add((long)move_left+1);
//now traverse to the right till we find different element
while(move_right<=arr.length-1)
{
if(x!=arr[move_right])
{
break;
}
move_right++;
}
alist.add((long)move_right-1);
return alist;
}
public int BinSearch(long arr[], int left,int right, int x)
{
int mid=0;
while(left<=right)
{
mid=left+(right-left)/2;
if(x<arr[mid])
{
right=mid-1;
}
else if(x>arr[mid])
{
left=mid+1;
}
else
{
return mid;
}
}
return -1;
}
}