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

Find Last Occurrence of an Element in a Sorted Array
Using Binary Search



Problem Statement

Given a sorted array of integers and a target number key, your task is to find the last occurrence (last index) of the key in the array.

This problem is commonly solved using a modified version of binary search for better efficiency.

Examples

Input ArrayKeyLast Occurrence IndexDescription
[5, 10, 10, 10, 20, 20]103Key 10 appears at indices 1, 2, and 3. Last is at index 3.
[1, 2, 3, 4, 5]32Key 3 occurs only once at index 2.
[1, 1, 1, 1, 1]14All elements are the key. Last is at index 4.
[1, 2, 4, 5, 6]3-1Key 3 is not present in the array.
[1, 2, 3, 4, 5]54Key is the last element in the array.
[10, 20, 30, 40, 50]100Key is the first element, and occurs only once.
[]7-1Empty array. No elements to search.

Solution

To find the last occurrence of a given number in a sorted array, we use a variation of binary search that continues the search even after finding a match. This ensures we find the rightmost index where the element appears.

We begin by setting up two pointers—start at the beginning of the array and end at the end. We also keep a variable, say res, initialized to -1 which will store the result.

Now, we repeatedly calculate the mid index and compare the arr[mid] value with the key:

  • Case 1: If arr[mid] is equal to the key, it means we found a match. But we don't stop here—there might be more occurrences to the right. So we update res = mid and shift our search to the right side by setting start = mid + 1.
  • Case 2: If arr[mid] < key, it means we need to move right, so we update start = mid + 1.
  • Case 3: If arr[mid] > key, the key (if present) must be on the left side, so we update end = mid - 1.

We continue this loop until start exceeds end. At the end, if res is still -1, that means the key was not found in the array.

Handling Different Scenarios

  • If the key occurs once: The algorithm will detect and return the exact index on the first match.
  • If the key occurs multiple times: It will skip earlier matches and eventually return the rightmost index.
  • If the key does not exist: It will return -1 after exhausting the search range.
  • If the array is empty: The loop doesn't run, and -1 is returned immediately.

This binary search variation is optimal with a time complexity of O(log n), making it ideal for large sorted arrays.

Visualization

Algorithm Steps

  1. Initialize start = 0, end = n - 1, and res = -1 to store the result.
  2. While start ≤ end, calculate mid = start + (end - start) / 2.
  3. If arr[mid] == key: update res = mid and move start = mid + 1 to search towards the right.
  4. If arr[mid] < key: move start = mid + 1.
  5. If arr[mid] > key: move end = mid - 1.
  6. After the loop, res will contain the last occurrence index or -1 if not found.

Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def last_occurrence(arr, key):
    start, end = 0, len(arr) - 1
    result = -1

    while start <= end:
        mid = start + (end - start) // 2
        if arr[mid] == key:
            result = mid  # Record the index
            start = mid + 1  # Move right to find a later occurrence
        elif key < arr[mid]:
            end = mid - 1
        else:
            start = mid + 1

    return result

# Example usage
arr = [5, 10, 10, 10, 20, 20]
key = 10
print("Last Occurrence Index:", last_occurrence(arr, key))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)When the key is found at the first mid computation and no further checking is needed.
Average CaseO(log n)Each iteration halves the search space, leading to logarithmic performance.
Average CaseO(log n)In the worst case, the search checks each level of the binary search tree until no more right occurrences are found.

Space Complexity

O(1)

Explanation: Only a fixed number of variables are used, with no extra memory required.



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