Find all elements that appear more than n/3 times in an array

Quick Overview

Write a function that takes an integer array and returns every value appearing more than floor(n/3) times, in ascending order. It tests reasoning about how many values can pass that threshold and finding them in linear time with constant extra space.

Find all elements that appear more than n/3 times in an array

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given an integer array `nums` of length $n$, find all values that appear more than $\lfloor n/3 \rfloor$ times. ### Function Signature ```python def majority_elements(nums: list[int]) -> list[int]: ``` ### Rules - Return the qualifying values in ascending order, each value once. - Return an empty list when no value qualifies. ### Constraints - `1 <= len(nums) <= 5 * 10^4` - `-10^9 <= nums[i] <= 10^9` ### Examples ```text Input: nums = [3,2,3] Output: [3] ``` Here $n = 3$, so the threshold is $\lfloor 3/3 \rfloor = 1$. The value 3 appears 2 times, which is more than 1, while 2 appears only once. ```text Input: nums = [1] Output: [1] ``` The threshold is $\lfloor 1/3 \rfloor = 0$, and 1 appears once, which is more than 0. ```text Input: nums = [9,9,4,4,4,9,1] Output: [4,9] ``` Here $n = 7$ and the threshold is 2. Both 4 and 9 appear 3 times, 1 appears once, and the two qualifying values are listed in ascending order.

Overview: Write a function that takes an integer array and returns every value appearing more than floor(n/3) times, in ascending order. It tests reasoning about how many values can pass that threshold and finding them in linear time with constant extra space.

Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given an integer array nums of length nn, find all values that appear more than ⌊n/3⌋\lfloor n/3 \rfloor times.

Function Signature

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

Rules

  • Return the qualifying values in ascending order, each value once.
  • Return an empty list when no value qualifies.

Constraints

  • 1 <= len(nums) <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

Examples

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

Here n=3n = 3, so the threshold is ⌊3/3⌋=1\lfloor 3/3 \rfloor = 1. The value 3 appears 2 times, which is more than 1, while 2 appears only once.

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

The threshold is ⌊1/3⌋=0\lfloor 1/3 \rfloor = 0, and 1 appears once, which is more than 0.

Input: nums = [9,9,4,4,4,9,1]
Output: [4,9]

Here n=7n = 7 and the threshold is 2. Both 4 and 9 appear 3 times, 1 appears once, and the two qualifying values are listed in ascending order.