Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Last active September 21, 2024 08:27
Show Gist options
  • Save KeshariPiyush24/fb84b517c2c4eceeda061db7b63b33f0 to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/fb84b517c2c4eceeda061db7b63b33f0 to your computer and use it in GitHub Desktop.
Implement Upper Bound

Question: Implement Upper Bound

Intution:

Time Complexity: $$O(log(n))$$

Space Complexity: $$O(1)$$

Solution:

public class Solution {
    public static int upperBound(int[] arr, int x, int n){
        int low = 0;
        int high = n - 1;
        int ans = n;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] <= x) low = mid + 1;
            else {
                ans = mid;
                high = mid - 1;
            }
        }
        return ans;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment