From 43d0f843d6fd1fbf1c40686b30961580e6ff3170 Mon Sep 17 00:00:00 2001 From: Jishnudeep Borah <85721902+Jishnu2608@users.noreply.github.com> Date: Mon, 9 Oct 2023 22:16:36 +0530 Subject: [PATCH] Create firstAndLastPositionElementSortedArray.java --- firstAndLastPositionElementSortedArray.java | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 firstAndLastPositionElementSortedArray.java diff --git a/firstAndLastPositionElementSortedArray.java b/firstAndLastPositionElementSortedArray.java new file mode 100644 index 0000000..15630ab --- /dev/null +++ b/firstAndLastPositionElementSortedArray.java @@ -0,0 +1,59 @@ +class Solution { + public int[] searchRange(int[] arr, int target) { + int[] result = {-1,-1}; + + if (arr == null || arr.length == 0) { + return result; + } + + int left = binarySearchLeft(arr,target); + int right = binarySearchRight(arr,target); + + result[0]= left; + result[1] = right; + + return result; + } + + public int binarySearchLeft(int[] arr, int target){ + int left=0; + int right = arr.length-1; + int result = -1; + + while(left<=right){ + int mid = (left+right)/2; + + if(arr[mid] == target){ + result=mid; + right = mid-1; + } + else if (arr[mid] < target){ + left=mid+1; + }else{ + right=mid-1; + } + } + return result; + } + + public int binarySearchRight(int[] arr, int target){ + int left=0; + int right = arr.length-1; + int result = -1; + + while(left<=right){ + int mid = (left+right)/2; + + if(arr[mid] == target){ + result=mid; + left = mid+1; + } + else if (arr[mid] < target){ + left=mid+1; + }else{ + right=mid-1; + } + } + return result; + } +}