BackeasyHashingSwiggy

Majority Element Identifier Solution

Problem Statement

Given an array of integers, find and return the integer that appears more than half of the time. If no such integer exists, return -1. The input array will have at least one element and at most 10^5 elements.

Example 1
Input
[3, 2, 3]
Output
3

Explanation: Step-by-step: with input [3, 2, 3], we first count the occurrences of each number. 3 occurs twice, which is more than half of the total count (3). So, the output is 3.

Example 2
Input
[2, 2, 1, 1, 1, 2, 2]
Output
2

Explanation: Step-by-step: with input [2, 2, 1, 1, 1, 2, 2], we first count the occurrences of each number. 2 occurs 4 times, which is more than half of the total count (7). So, the output is 2.

Constraints

  • 1 <= n <= 5 * 10^4
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Majority Element Identifier — Problem Statement & Solution Guide

HashingEasyBoyer-Moore Voting
TimeO(n)
|
SpaceO(1)

Problem Description

Given an array of integers, find and return the integer that appears more than half of the time. If no such integer exists, return -1. The input array will have at least one element and at most 10^5 elements.

Examples

Example 1

Input

[3, 2, 3]

Output

3

Explanation: Step-by-step: with input [3, 2, 3], we first count the occurrences of each number. 3 occurs twice, which is more than half of the total count (3). So, the output is 3.

Example 2

Input

[2, 2, 1, 1, 1, 2, 2]

Output

2

Explanation: Step-by-step: with input [2, 2, 1, 1, 1, 2, 2], we first count the occurrences of each number. 2 occurs 4 times, which is more than half of the total count (7). So, the output is 2.

Constraints

  • 1 <= n <= 5 * 10^4

Optimal Approach & Strategy

Use Boyer-Moore Voting Algorithm. Maintain a candidate and a count. If count is 0, pick current element as candidate. If same, increment count, else decrement. Time O(N), Space O(1).

Brute Force Approach

Count occurrences of each element. Time O(N^2).

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
       let count = 0;
       let candidate = null;
       for (let num of nums) {
           if (count === 0) {
               candidate = num;
               count = 1;
           } else if (candidate === num) {
               count++;
           } else {
               count--;
           }
       }
       let occurrences = 0;
       for (let num of nums) {
           if (num === candidate) {
               occurrences++;
           }
       }
       return occurrences > nums.length / 2 ? candidate : -1;
   }

Asked in Top Tech Interviews

Swiggy

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.