← Back to list

DSA Leetcode 150 Top Interview Question

5. Majority Element

sreenivasulareddy · 2025-05-23 08:22 · 0 claps · 0.5 min read
#majority-element #majority
Open on Medium ↗

DSA Leetcode 150 Top Interview Question

5. Majority Element

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

Solution:

class Solution {
    func majorityElement(_ nums: [Int]) -> Int {
            var counts = [Int: Int]()
            let majority = nums.count / 2

            for num in nums {
                counts[num, default: 0] += 1
                if counts[num]! > majority {
                    return num
                }
            }

            return -1 
    }
}

메타데이터
post_id
b276a7d95e28
slug
dsa-leetcode-150-top-interview-question-b276a7d95e28
url
https://medium.com/@sreenu.ram2/dsa-leetcode-150-top-interview-question-b276a7d95e28
canonical_url
https://medium.com/@sreenu.ram2/dsa-leetcode-150-top-interview-question-b276a7d95e28
author_url
https://medium.com/@sreenu.ram2
status
ok
fetched_at
2026-07-15 21:22:01