Majority Element Problem

Why you have taken only 2 elements for N/3?
What would be the value for N/4?

because those are the 2 elements with freq more than floor(n/3)
ie floor(8/3)->2

then 3 would be included in the answer
o/p
would be
1 2 3

import java.util.*; public class Main { public static void main (String args[]) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if(n == 0) { return; } int a[] = new int[n]; for(int i = 0; i <n; i++) { a[i] = scan.nextInt(); } printMajorityElement(a); } private static void printMajorityElement(int[] inputArray) { HashMap<Integer,Integer> dataMap = new HashMap<Integer,Integer>(); for(int j = 0; j < inputArray.length; j++) { if(dataMap.containsKey(inputArray[j])) { dataMap.put(inputArray[j],(dataMap.get(inputArray[j]) + 1)); } else { dataMap.put(inputArray[j],1); } } int iterateCount = (inputArray.length)/3; StringBuilder output = new StringBuilder(); for (Map.Entry<Integer, Integer> entry : dataMap.entrySet()) { if(entry.getValue() > iterateCount) { output.append(entry.getKey()); } } if(output.length() != 0) { System.out.println(output.toString()); } else { System.out.println(“No Majority Elements”); } } }

please share code in cb ide

can you please check my code as i am unable to pass 2 test case. Don’t know the reason.

…share code in cb ide

please check i have shared with ide geekeforgeeks

8
2 2 3 1 3 2 1 1

ur o/p is coming 12
it should be space separated

i think some issue with the test case the code seems perfectly fine

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.