Majority Element II | N/3 Repeated Number

In this tutorial, I am going to discuss a very interesting problem find N/3 repeated number in an array.

Given an array of size n, Write a code to find all the elements that appear more than n/3 times.

NOTE: We have to solve this problem in linear time and in O(1) space.

Example 1:

Input : [3, 2, 3]

Output: 3

In this example, The size of this array is 3. We have to find all the numbers which occurred more than n/3 where n is the size of the array. The number 3 appears more than 1 times.

Example 2:

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

Output:[1, 2]

This problem is a variation of find majority element in an array.

Before solving this problem, let’s discuss some important points which help us to solve this problem efficiently.

For an array of length n.

i) There can be at most one majority element which is more than n/2 times.

ii) There can be at most two majority elements which are more than n/3 times.

In this post, I am going to discuss three approaches and it’s java code to solve this problem.

Programming Video Tutorials

Method I – Brute Force Approach

The simplest approach is to use two for loops to find the numbers which appear more than n/3 times.

The time complexity of this approach is O(n^2).

Majority Element II ( > N/3 Times) using HashMap – Java Code

We can improve the time complexity by using HashMap. The idea here is to traverse an array and count the occurrences of each number. Put the number and it’s count in a HashMap.

Then traverse the map and check all the elements which has count greater n/3.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Programming Questions on Arrays

Find N/3 Repeated Number in O(1) Space – Java Code

In this example, let’s discuss how we can find number which appears more N/3 times in O(1) space. To solve this problem i am using Boyer-Moore majority vote algorithm.

Here i am using the observation that, There can be at most two majority elements which are more than n/3 times.

Boyer-Moore majority vote algorithm finds the majority element if it exists. In this algorithm, first we find the candidate for a majority element. After that we verify it whether this candidate element is the majority element or not.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Insert Delete GetRandom O(1) Solution

Sort a stack using recursion

Get minimum element from stack in O(1)

N/3 Repeat Number InterviewBit Solution – Java

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.