Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Upper Bound in Sorted Array
Binary Search Approach



Problem Statement

Given a sorted array of integers and a target number x, your task is to find the upper bound of x in the array.

Examples

Input ArrayKey (x)Upper Bound IndexValue at Upper BoundDescription
[10, 20, 30, 40, 50]30340First element greater than 30 is at index 3
[10, 20, 30, 40, 50]4545050 is the first element greater than 45
[10, 20, 30, 40, 50]505-No element greater than 50, so return array length 5
[5, 10, 15]105All elements are greater, first is at index 0
[10]5010Single element greater than key
[10]101-No element greater than 10
[10]151-All elements less than or equal to 15

Solution

To find the upper bound of a number x in a sorted array, we use a technique called Binary Search. This approach is much faster than checking each element because it divides the search range in half each time.

What is the Upper Bound?

The upper bound is the position (index) of the first element that is strictly greater than the given number x. If no such element exists, it means all elements are less than or equal to x, and we return the size of the array.

How It Works (Beginner Friendly)

We begin the search with two pointers:

  • low pointing to the start of the array
  • high pointing to the end

We also initialize a variable ans to the length of the array. This will store the index of the potential upper bound if found.

We run a loop while low ≤ high. At each step:

  • We calculate the middle index mid
  • If the element at mid is greater than x, this is a valid candidate for upper bound, so we:
    • Update ans = mid
    • Move the high pointer to the left (mid - 1) to see if there's an even smaller valid index
  • If the element is less than or equal to x, then we move low to the right (mid + 1) because we’re looking for a greater number

After the loop, ans will hold the index of the smallest number greater than x. If no such element exists, it stays as arr.length.

Why This Works

Since the array is sorted, binary search ensures we skip unnecessary elements and reduce the time complexity to O(log n). This makes the solution efficient even for very large arrays.

Visualization

Algorithm Steps

  1. Given a sorted array arr of N integers and an integer x.
  2. Initialize two pointers: low = 0 and high = arr.length - 1.
  3. Initialize ans = arr.length to track the possible answer.
  4. While low ≤ high:
  5. → Compute mid = Math.floor((low + high) / 2).
  6. → If arr[mid] > x, update ans = mid and set high = mid - 1.
  7. → Else, set low = mid + 1.
  8. After the loop, ans will hold the index of the upper bound.

Code

Python
JavaScript
Java
C++
C
def upper_bound(arr, x):
    low, high = 0, len(arr) - 1
    ans = len(arr)
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] > x:
            ans = mid
            high = mid - 1
        else:
            low = mid + 1
    return ans

# Sample Input
arr = [1, 2, 4, 4, 5, 7]
x = 4
print("Upper Bound Index:", upper_bound(arr, x))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)The target is immediately found at the mid index in the first comparison.
Average CaseO(log n)With each iteration, the search space is halved until the upper bound index is found.
Average CaseO(log n)The binary search may continue until the search space is reduced to one element before finding the correct index or determining it does not exist.

Space Complexity

O(1)

Explanation: The algorithm uses a constant amount of extra space regardless of the input size. All operations are done in-place using variables like low, high, mid, and ans.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M