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

Count Total Occurrences of an Element in a Sorted Array
Using Binary Search



Problem Statement

Given a sorted array of integers and a target number x, your task is to count how many times the number x appears in the array.

Examples

Input ArrayKey (x)CountDescription
[1, 2, 2, 2, 3, 4]232 appears at indices 1, 2, 3
[1, 1, 1, 1, 1]15All elements are the key
[5, 10, 10, 10, 20]10310 appears three times in the middle
[1, 2, 3, 4, 5]606 is not present in the array
[1, 2, 3, 4, 5]000 is not present and is smaller than all elements
[2]21Single element match
[2]30Single element, but not a match
[]10Empty array, so count is 0

Solution

To count how many times a number x appears in a sorted array, we use a technique based on binary search. The idea is to find the first and last positions where x appears, and then compute the total count from those two indices.

Understanding the Different Cases

Case 1: The element exists multiple times
If the key appears several times (for example, at indices 3, 4, 5), the total count is just lastIndex - firstIndex + 1. Binary search helps us find both boundaries efficiently.

Case 2: The element appears only once
If the key is found at a single index (say, index 2), then both first and last index will be the same, so the count is 1.

Case 3: The element does not exist
If binary search doesn’t find the key at all, we simply return 0 because there are no occurrences in the array.

Case 4: Edge elements
Sometimes the element may be at the beginning or end of the array. For example, in [5, 6, 6, 6], key = 5 will be found only once at index 0. In [1, 2, 3, 4, 4], key = 4 appears at the end.

Case 5: Empty array
If the array has no elements, then the answer is obviously 0 because there's nothing to count.

Why Use Binary Search?

Since the array is sorted, binary search lets us quickly locate the first and last positions of the key. This reduces the time complexity from O(n) (checking every element) to O(log n), which is much faster, especially for large arrays.

In summary, we apply binary search twice — once to find the first occurrence and once for the last. If both searches return valid indices, we compute the total count. If not, we return 0. This makes the approach both efficient and elegant.

Visualization

Algorithm Steps

  1. Use binary search to find the first occurrence of the key.
  2. Use binary search again to find the last occurrence of the key.
  3. If key is not found, return 0.
  4. Otherwise, return lastIndex - firstIndex + 1.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
public class CountOccurrences {

  public static int countOccurrences(int[] arr, int key) {
    int first = findFirst(arr, key);
    int last = findLast(arr, key);

    if (first == -1 || last == -1) return 0;
    return last - first + 1;
  }

  private static int findFirst(int[] arr, int key) {
    int start = 0, end = arr.length - 1, res = -1;
    while (start <= end) {
      int mid = start + (end - start) / 2;
      if (arr[mid] == key) {
        res = mid;
        end = mid - 1; // go left to find earlier occurrence
      } else if (arr[mid] < key) {
        start = mid + 1;
      } else {
        end = mid - 1;
      }
    }
    return res;
  }

  private static int findLast(int[] arr, int key) {
    int start = 0, end = arr.length - 1, res = -1;
    while (start <= end) {
      int mid = start + (end - start) / 2;
      if (arr[mid] == key) {
        res = mid;
        start = mid + 1; // go right to find later occurrence
      } else if (arr[mid] < key) {
        start = mid + 1;
      } else {
        end = mid - 1;
      }
    }
    return res;
  }

  public static void main(String[] args) {
    int[] arr = {1, 2, 2, 2, 3, 4};
    int key = 2;
    System.out.println("Count of " + key + ": " + countOccurrences(arr, key));
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)If both first and last occurrences are found on the first try.
Average CaseO(log n)Binary search splits the array in half on each step, giving logarithmic performance.
Average CaseO(log n)Both first and last searches may take log n steps independently.

Space Complexity

O(1)

Explanation: Only a few variables are used; no extra space is needed.



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