|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +public class Occurrence { // Question: Find the first and last occurrence of the target number in array in O(log n) time complexity. |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + |
| 7 | + int[] arr = {1, 1, 2, 3, 5, 6, 8, 8, 10, 11, 12, 13, 13}; // Initializing and declaring the sorted array |
| 8 | + |
| 9 | +// int[] arr = new int[20]; // Since array is initialized with zero it will print [0 19] |
| 10 | + |
| 11 | + System.out.println(Arrays.toString(occurrence(arr, 4))); // Calling the function and printing the return value |
| 12 | + } |
| 13 | + |
| 14 | + public static int[] occurrence(int[] arr, int target) { |
| 15 | + |
| 16 | + int[] pos = {-1, -1}; |
| 17 | + |
| 18 | + pos[0] = searchElement(arr, target, true); |
| 19 | + |
| 20 | + if(pos[0] != -1){ // If the target is not present in left side then no need to check the target in right side of the array |
| 21 | + // because if target present then the index value will not be -1 |
| 22 | + // This check makes the program much faster |
| 23 | + |
| 24 | + pos[1] = searchElement(arr, target, false); |
| 25 | + } |
| 26 | + |
| 27 | + return pos; |
| 28 | + } |
| 29 | + |
| 30 | + // Function to find the target element |
| 31 | + public static int searchElement(int[] arr, int target, boolean check) { |
| 32 | + |
| 33 | + int start = 0; |
| 34 | + int end = arr.length - 1; |
| 35 | + int occur = -1; |
| 36 | + |
| 37 | + while(start <= end) { |
| 38 | + |
| 39 | + int midElement = start + (end - start) / 2; // Finding the middle element |
| 40 | + |
| 41 | + if(target < arr[midElement]) { |
| 42 | + |
| 43 | + end = midElement - 1; |
| 44 | + }else if(target > arr[midElement]) { |
| 45 | + |
| 46 | + start = midElement + 1; |
| 47 | + }else { |
| 48 | + |
| 49 | + occur = midElement; |
| 50 | + |
| 51 | + if(check) { // if target is present in array it might be possible that the more target elements are at left side and right side of the |
| 52 | + // array so we check that, is target present in left side |
| 53 | + end = midElement - 1; |
| 54 | + }else { |
| 55 | + |
| 56 | + start = midElement + 1; // Here we check that, is target present at right side |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return occur; |
| 61 | + } |
| 62 | +} |
0 commit comments