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 Single Element in Sorted Array
Optimal Binary Search Approach



Problem Statement

You are given a sorted array where every element appears exactly twice, except one element that appears only once. Your task is to find and return the single non-repeating element.

Note: The array is sorted in non-decreasing order. There will always be exactly one such unique element in the array.

If the array is empty, return null or an appropriate message indicating that the array is invalid.

Examples

Input ArrayOutputDescription
[1, 1, 2, 2, 3, 4, 4]33 is the only number that appears once; others appear in pairs
[0, 1, 1, 2, 2, 3, 3]00 is the single element at the beginning
[1, 1, 2, 2, 3, 3, 4]44 is the single element at the end
[5]5Only one element in the array, it is the single element
[]nullArray is empty, no element to return
[7, 7, 9, 9, 11, 11, 13, 15, 15]1313 is the only number that doesn't repeat

Solution

The problem requires finding a unique element in a sorted array where every other element appears exactly twice. This specific structure helps us solve the problem efficiently using binary search.

Understanding the Structure

In a perfectly paired array (without the unique element), each pair starts at an even index: [a,a,b,b,...]. Once a single non-repeating element is inserted, it disrupts this pattern. All elements after the unique element shift by one index, and their pairing changes: one element of a pair will appear at an odd index instead of even.

Different Scenarios to Consider

  • Single element in the middle: If the single element is somewhere in the middle, you'll find that the pairing breaks right after it. Using this, we can decide whether to search left or right.
  • Single element at the beginning: The very first element is not equal to the one after it, so it's the answer.
  • Single element at the end: The last element doesn't match the one before it — again, it's the answer.
  • Single element is the only element: In case the array has only one number, it is the unique one by default.
  • Empty array: Since there is no data to search, we return null or a custom message to indicate invalid input.

How We Approach It

We use binary search to find the single element in O(log n) time. At each step, we check whether the middle index mid breaks the pairing pattern. Based on whether the index is even or odd, and how it compares to neighboring elements, we decide which half of the array to continue searching in.

Eventually, we narrow down the search to a single index where the unique element is located. This efficient approach is much better than a linear scan, especially for large arrays.

This method works only because the array is sorted and contains exactly one non-repeating element. If these conditions aren’t guaranteed, we’d need a different strategy.

Visualization

Algorithm Steps

  1. Initialize start = 0 and end = n - 2.
  2. While start ≤ end:
  3. → Compute mid = start + (end - start) / 2.
  4. → Check if mid is even:
  5. → If arr[mid] == arr[mid + 1], the unique element is on the right → start = mid + 2.
  6. → Else, the unique element is on the left → end = mid.
  7. → If mid is odd:
  8. → If arr[mid] == arr[mid - 1], the unique element is on the right → start = mid + 1.
  9. → Else, the unique element is on the left → end = mid - 1.
  10. After the loop, the start index points to the single element.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class SingleElementFinder {
  public static int singleNonDuplicate(int[] arr) {
    int start = 0, end = arr.length - 2;

    while (start <= end) {
      int mid = start + (end - start) / 2;

      // Pair index logic: even-indexed element should match with next, odd with previous
      if ((mid % 2 == 0 && arr[mid] == arr[mid + 1]) ||
          (mid % 2 == 1 && arr[mid] == arr[mid - 1])) {
        start = mid + 1;
      } else {
        end = mid - 1;
      }
    }
    return arr[start];
  }

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

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)If the unique element is found at the first mid index.
Average CaseO(log n)Binary search reduces the search space by half in every step.
Average CaseO(log n)Even in the worst case, binary search checks only log(n) elements.

Space Complexity

O(1)

Explanation: Only a few variables (start, end, mid) are used 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