Skip to content

Commit 733d463

Browse files
committed
Added : Find First and Last Position of Element in Sorted Array
1 parent 556f5a2 commit 733d463

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
2+
3+
Your algorithm's runtime complexity must be in the order of O(log n).
4+
5+
If the target is not found in the array, return [-1, -1].
6+
7+
Example 1:
8+
9+
Input: nums = [5,7,7,8,8,10], target = 8
10+
Output: [3,4]
11+
Example 2:
12+
13+
Input: nums = [5,7,7,8,8,10], target = 6
14+
Output: [-1,-1]
15+
16+
17+
Constraints:
18+
19+
0 <= nums.length <= 10^5
20+
-10^9 <= nums[i] <= 10^9
21+
nums is a non decreasing array.
22+
-10^9 <= target <= 10^9
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
@lc id : 34
3+
@problem : Find First and Last Position of Element in Sorted Array
4+
@author : rohit
5+
@url : https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
6+
@difficulty : medium
7+
*/
8+
9+
class Solution {
10+
11+
public int findEndingIndex(int[] nums, int target){
12+
int index = -1;
13+
int start = 0;
14+
int end = nums.length - 1;
15+
16+
while(start <= end){
17+
int mid = start + (end - start) / 2;
18+
19+
if(nums[mid] == target)
20+
index = mid;
21+
22+
if(nums[mid] <= target)
23+
start = mid + 1;
24+
else end = mid - 1;
25+
}
26+
27+
28+
29+
30+
return index;
31+
}
32+
33+
public int findStartingIndex(int[] nums, int target){
34+
int index = -1;
35+
36+
int start = 0;
37+
int end = nums.length - 1;
38+
39+
while(start <= end){
40+
int mid = start + (end - start) / 2;
41+
if(nums[mid] == target)
42+
index = mid;
43+
44+
//If we have found target, still we want to go on left side
45+
//If we haven't found, and target is smaller than mid, go left
46+
if(nums[mid] >= target)
47+
end = mid - 1;
48+
49+
else start = mid + 1;
50+
}
51+
52+
return index;
53+
}
54+
55+
public int[] searchRange(int[] nums, int target) {
56+
57+
int[] result = new int[2];
58+
result[0] = findStartingIndex(nums, target);
59+
result[1] = findEndingIndex(nums, target);
60+
return result;
61+
}
62+
}

0 commit comments

Comments
 (0)