Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Majority element in an array

Posted on June 6, 2022June 6, 2022 by admin

Overview

The objective is to find the majority element in a given array. A majority element is an element that occurs more than n/2 times in a given array where n is the length of the array

Example 1

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

Example 2

Input: [1]
Output: 1

Program

Below is the program for the same

package main

import "fmt"

func majorityElement(nums []int) int {
	lenNums := len(nums)

	if lenNums == 1 {
		return nums[0]
	}

	numsMap := make(map[int]int)

	for i := 0; i < lenNums; i++ {
		_, ok := numsMap[nums[i]]
		if ok {
			numsMap[nums[i]] = numsMap[nums[i]] + 1
			if numsMap[nums[i]] > lenNums/2 {
				return nums[i]
			}
		} else {
			numsMap[nums[i]] = 1
		}
	}

	return 0

}

func main() {
	output := majorityElement([]int{2, 1, 2, 2, 3})
	fmt.Println(output)

	output = majorityElement([]int{1})
	fmt.Println(output)
}

Output:

2
1

Also, check out our system design tutorial series here – System Design Tutorial Series

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme