8. Find Majority element

8. Find Majority element


Problem link :- click here


package program;

public class Searching__8
{

	/*
	 	Given an array of n elements. Find the majority element in the array.
	 	A majority element in an array of size n is an element that appears 
	 	more than n/2 times in the array.
	 			arr[] = {3, 1, 3, 3, 2}\
	 			output : 3
	 			
	 	We have solved a problem in arrays where we have to find the element 
	 	which has repeated more than n/k times 
	 	we solved that problem in steps as follows 
	 	step 1 :- we selected (k-1) elements which has repeated most 
	 	step 2 :- we returned the array of elements which repeated more 
	 			than n/k times among those selected (k-1) elements
	 			
	 	Here we have to find element which has repeated more than n/2 times 
	 		k = 2 		k - 1 = 1
	 	therefore we have to select only one element
	 	and check if that element is repeated n/2 times
	 */
	
	static int majorityElement(int arr[], int n)
	{
		int element = arr[0];
		int count = 0;
		//finding one element which has occurred most
		for(int i=0; i<n; i++)
		{
			if(count == 0)
			{
				element = arr[i];
				count++;
			}
			else if(arr[i] == element)
				count++;
			else
				count--;
		}
		
		//checking if that element has occurred more than n/2 times
		count = 0;
		for(int i=0; i<n; i++)
		{
			if(arr[i] == element)
				count++;
		}
		
		if(count > n/2)
			return element;
		else
			return -1;
	}
	
	
	public static void main(String[] args)
	{
		int arr[] = {3, 2, 2, 3, 2};
		int ans = majorityElement(arr, arr.length);
		System.out.println("Majority element is : " + ans);
	}

}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree