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 First 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 first occurrence (leftmost index) of key in the array.

If the element is not found, return -1.

Examples

Input ArrayKeyFirst Occurrence IndexDescription
[5, 10, 10, 10, 20, 20]10110 appears at indices 1, 2, 3. First occurrence is at index 1
[2, 4, 4, 4, 6, 6, 8]41First occurrence of 4 is at index 1
[1, 2, 3, 4, 5]6-16 does not exist in the array
[1, 1, 1, 1]10All elements are 1. First index is 0
[1, 2, 3, 4, 5]32Only one occurrence at index 2

Solution

To find the first occurrence of a number in a sorted array, we use a modified binary search. Even if we find the target, we keep searching on the left side to check if it appears earlier.

This is more efficient than checking every element and works in O(log n) time due to binary search.

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 end = mid - 1 to search left.
  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 first occurrence index or -1 if not found.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class FirstOccurrenceFinder {
  public static int solve(int n, int key, int[] v) {
    int start = 0;
    int end = n - 1;
    int res = -1;

    while (start <= end) {
      int mid = start + (end - start) / 2;
      if (v[mid] == key) {
        res = mid;       // Record the index
        end = mid - 1;   // Move left to check if it occurs earlier
      } else if (key < v[mid]) {
        end = mid - 1;
      } else {
        start = mid + 1;
      }
    }
    return res;
  }

  public static void main(String[] args) {
    int[] arr = {5, 10, 10, 10, 20, 20};
    int key = 10;
    int result = solve(arr.length, key, arr);
    System.out.println("First Occurrence Index: " + result);
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)The key is found at the mid index in the first iteration.
Average CaseO(log n)Binary search reduces the search space by half each time.
Average CaseO(log n)All elements must be checked in the narrowed space to find the first occurrence.

Space Complexity

O(1)

Explanation: The algorithm uses only a fixed number of variables regardless of input size.



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