Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created April 29, 2021 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/3067865c3ac5fb81e04457660927850c to your computer and use it in GitHub Desktop.
Save vrat28/3067865c3ac5fb81e04457660927850c to your computer and use it in GitHub Desktop.
Find first and Last position using binary Search
class Solution {
public int[] searchRange(int[] N, int T) {
int Tleft = find(T, N, 0);
if (Tleft == N.length || N[Tleft] != T) return new int[] {-1, -1};
return new int[] {Tleft, find(T+1, N, Tleft) - 1};
}
public int find(int target, int[] arr, int left) {
int right = arr.length - 1;
while (left <= right) {
int mid = left + right >> 1;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return left;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment