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 Majority Element in Array Using Boyer-Moore Voting Algorithm - Optimal Solution



Problem Statement

Given an array of integers, your task is to find the majority element, which is defined as the element that appears more than ⌊n/2⌋ times in the array (where n is the size of the array).

If a majority element exists, return it. If no such element exists, return -1.

This problem assumes that the array may or may not contain a valid majority element.

Examples

Input ArrayExpected OutputDescription
[3, 3, 4, 2, 3, 3, 3]33 appears 5 times in an array of size 7 → majority element
[1, 2, 3, 4, 5]-1No element appears more than n/2 = 2.5 times
[2, 2, 1, 1, 1, 2, 2]22 appears 4 times → majority in size 7 array
[7]7Single element is always the majority (n=1)
[]-1Empty array, so no majority element
[5, 5, 5, 5, 5, 1, 2]55 appears more than half the time
[1, 1, 2, 2, 3, 3]-1No element appears more than n/2 = 3 times

Solution

To solve the problem of finding the majority element (if it exists), we need to understand what 'majority' means in this context. A majority element is the one that occurs more than n/2 times in the array, where n is the total number of elements.

Different Situations to Consider

  • Case 1: A clear majority element exists
    For example, in the array [3, 3, 3, 2, 3, 3], the number 3 appears more than half the time. So it is the majority element and should be returned.
  • Case 2: No element appears enough times
    In an array like [1, 2, 3, 4], each number appears only once. Since none appear more than n/2 times, the result should be -1.
  • Case 3: Single-element array
    If the array has just one element, like [7], that element is automatically the majority because it satisfies the condition (appearing more than n/2 = 0.5 → at least once).
  • Case 4: Empty array
    An empty array has no elements, so clearly there is no majority. We return -1.
  • Case 5: Two or more elements with equal counts
    If the array has balanced occurrences (e.g., [1, 1, 2, 2, 3, 3]), no one element crosses the majority threshold. Again, return -1.

How Does the Boyer-Moore Voting Algorithm Help?

The Boyer-Moore Voting Algorithm is a clever trick that helps us find the majority element in just one pass using constant space. Here's the core idea:

We keep a candidate and a count. Initially, count is 0. As we scan the array:

  • If count is 0, we choose the current element as a new candidate.
  • If the current element equals the candidate, we increase the count.
  • If it does not match, we decrease the count.

By the end of the loop, the candidate is the majority element if one exists. (You can optionally verify it in a second pass.)

Why This Works

When there is a majority element, the increment and decrement of the count cancel out the influence of non-majority elements. The real majority will always survive this cancellation and remain as the candidate.

This method works in O(n) time and O(1) space, which is optimal for this problem.

Visualization

Algorithm Steps

  1. Given an array arr of size n.
  2. Initialize count = 0 and candidate = None.
  3. Traverse the array:
  4. → If count == 0, set candidate = current element.
  5. → If current element == candidate, increment count, else decrement count.
  6. After the loop, candidate is the majority element.
  7. (Optional: Verify candidate by counting its actual occurrences if required.)

Code

Python
JavaScript
Java
C++
C
def majority_element(arr):
    count = 0
    candidate = None

    for num in arr:
        if count == 0:
            candidate = num
        count += (1 if num == candidate else -1)

    return candidate

# Sample Input
arr = [2, 2, 1, 1, 1, 2, 2]
print("Majority Element:", majority_element(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)The algorithm always traverses the entire array once, even if the majority element appears early.
Average CaseO(n)Regardless of element distribution, a single pass over the array is required to maintain count and candidate.
Average CaseO(n)In the worst case, the candidate may flip multiple times, but the loop still only runs once over the array.

Space Complexity

O(1)

Explanation: Only two variables—count and candidate—are used throughout the algorithm, making the space constant.



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