Find the element that appears more than n/2 times in an array

Quick Overview

Return the element that appears more than half the time in an integer array, given that such an element always exists. It tests simple counting approaches, whether you can reach linear time with constant extra space, and whether you can explain why your method always finds the right value.

Find the element that appears more than n/2 times in an array

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given an array `nums` of size `n`, return the leader element. The leader is the element that appears more than `n / 2` times in the array. You may assume that the leader always exists in the array. Try to solve the problem in linear time using constant extra space. ### Function Signature ```python def find_leader(nums: list[int]) -> int: ``` ### Constraints - `n == len(nums)` - `1 <= n <= 5 * 10^4` - `-10^9 <= nums[i] <= 10^9` - The leader always exists in `nums`. ### Examples ```text Input: nums = [3,2,3] Output: 3 ``` 3 appears 2 times out of 3, which is more than 3 / 2 = 1.5. ```text Input: nums = [2,2,1,1,1,2,2] Output: 2 ``` 2 appears 4 times out of 7, which is more than 7 / 2 = 3.5. The value 1 appears only 3 times. ```text Input: nums = [5,-3,-3,5,-3] Output: -3 ``` -3 appears 3 times out of 5, which is more than 5 / 2 = 2.5.

Overview: Return the element that appears more than half the time in an integer array, given that such an element always exists. It tests simple counting approaches, whether you can reach linear time with constant extra space, and whether you can explain why your method always finds the right value.

Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given an array nums of size n, return the leader element. The leader is the element that appears more than n / 2 times in the array.

You may assume that the leader always exists in the array. Try to solve the problem in linear time using constant extra space.

Function Signature

def find_leader(nums: list[int]) -> int:

Constraints

  • n == len(nums)
  • 1 <= n <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9
  • The leader always exists in nums .

Examples

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

3 appears 2 times out of 3, which is more than 3 / 2 = 1.5.

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

2 appears 4 times out of 7, which is more than 7 / 2 = 3.5. The value 1 appears only 3 times.

Input: nums = [5,-3,-3,5,-3]
Output: -3

-3 appears 3 times out of 5, which is more than 5 / 2 = 2.5.