Find Upper and Lower bound [codingblocks]
Find position of the last and first occurrence of a given number in a sorted array. If number does not exist then print lower and upper bound as -1.
Input Format
First line contains an integer n denoting the size of the array.
Second line contains n space separated integers denoting array elements.
Third line contains a single integer Q denoting the no of queries.
Q lines follow, each containing a single integer x that is to be searched in the array.
Constraints
1 <= N <= 10^5
1 <= Q <= 100
Output Format
For each query , print the lowerbound and the upperbound for the number x in a new line each.
Sample Input
5
1 2 3 3 4
3
2
3
10
Sample Output
1 1
2 3
-1 -1
Explanation
The first and the last occurrence of 2 in the given array are both 1.
The first occurrence of 3 is at index=2 and last at index=3.
10 is not present in the array so we print -1 for it.
/* Amit Kumar 06-12-2020 IDE Code: https://ide.geeksforgeeks.org/LrwS4j58tR */ package array; import java.util.Scanner; public class Array_FindUpperAndLowerBound { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int size = scanner.nextInt(); int[] array = new int[size]; for (int i=0; i<size; i++) { array[i] = scanner.nextInt(); } int queries = scanner.nextInt(); while (queries-- > 0) { int element = scanner.nextInt(); System.out.print(getUpperBound(array, element) + " "); System.out.print(getLowerBound(array, element)); System.out.println(""); } } private static int getUpperBound(int[] array, int element) { int start, end, mid, upperBound; start = 0; end = array.length-1; upperBound = -1; while (start <= end) { mid = (start + end)/2; if (array[mid] == element) { upperBound = mid; end = mid - 1; } else if (array[mid] > element) { end = mid - 1; } else { start = mid + 1; } } return upperBound; } private static int getLowerBound(int[] array, int element) { int start, end, mid, lowerBound; start = 0; end = array.length-1; lowerBound = -1; while (start <= end) { mid = (start + end)/2; if (array[mid] == element) { lowerBound = mid; start = mid + 1; } else if (array[mid] > element) { end = mid - 1; } else { start = mid + 1; } } return lowerBound; } }
Comments
Post a Comment