Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

first and last position of a sorted array

class Solution {
   public int[] searchRange(int[] nums, int target) {
    int si=0;
    int ei=nums.length-1;
    int[] ans=new int[]{-1,-1};
while(si<=ei){
    int mid=si+(ei-si)/2;
    if(nums[mid]==target){
        si=mid-1;ei=mid+1;
		// search for first index with while loop in -ve  direction
        while(si>=0&&nums[si]==target){si--;}
        ans[0]=si+1;
		// search for ending index in +ve direction
        while(ei<nums.length&&nums[ei]==target){ei++;}
        ans[1]=ei-1;
        return ans;
    }
    else if(target>nums[mid]){
        si=mid+1;
    }
   
    else ei=mid-1;
}
    return ans;
    
}
}
 
PREVIOUS NEXT
Tagged: #position #sorted #array
ADD COMMENT
Topic
Name
4+1 =