Finding Occurrence of a Number More Than N/2 Times in a Sorted Array in Java


In Java, there may be instances when we need to determine whether a specific number occurs more than half of the time in a sorted array. This article explores different approaches to solve this problem efficiently. We will discuss the syntax and provide detailed explanations for each approach. By the conclusion, you will clearly grasp how to use Java to identify a number that appears more than N/2 times in a sorted array.

Syntax

Let's start by examining the syntax employed for the algorithms described in this article −

public class Main {
   public static int findMajorityElement(int[] nums) {
      // Your code here
   }
    
   public static void main(String[] args) {
      int[] nums = { /* Initialize your sorted array here */ };
      int majorityElement = findMajorityElement(nums);
      System.out.println("Majority Element: " + majorityElement);
   }
}

Explanation of Syntax

  • We define a public class named Main.

  • Inside the Main class, we declare a public static method findMajorityElement that takes an integer array nums as its parameter. This method will return the majority element if it exists; otherwise, it will return -1.

  • In the main method, we initialize a sorted array named nums.

  • We call the findMajorityElement method, passing nums as an argument, and store the result in the majorityElement variable.

  • Finally, we print the majority element, if found, using System.out.println().

Approach 1

Algorithm

  • Initialize a variable count as 1 and majorityElement as nums[0].

  • Start at list 1 and emphasize over the entire exhibit.

  • Assuming the ongoing component matches the majorityElement, increment the count by one; in any case, drop the count by one. If count becomes 0, assign the current element as majorityElement and set count to 1.

  • Finally, return majorityElement as the result.

Example

public class Main {
   public static int findMajorityElement(int[] nums) {
      int count = 1;
      int majorityElement = nums[0];
        
      for (int i = 1; i < nums.length; i++) {
         if (nums[i] == majorityElement)
            count++;
         else
            count--;
            
         if (count == 0) {
            majorityElement = nums[i];
            count = 1;
         }
      }
        
      return majorityElement;
   }
    
   public static void main(String[] args) {
      int[] nums = {2, 2, 2, 3, 4, 2, 2}; // Example array initialization
      int majorityElement = findMajorityElement(nums);
      System.out.println("Majority Element: " + majorityElement);
   }
}

Output

Majority Element: 2

Explanation of Code in Approach 1

The code starts by initializing count as 1 and majorityElement as the first element of the array. Then, it iterates through the array from the second element onwards. For each element, it checks if it is equal to majorityElement. If so, it increments count; otherwise, it decrements count. This approach takes advantage of the fact that the majority element will occur more than N/2 times.

If count becomes 0, it means the previous element is no longer a candidate for the majority element. In this case, we update majorityElement to the current element and reset count to 1. At the end of the iteration, we return the majorityElement as the result.

Approach 2

Algorithm

  • Initialize a variable midIndex as nums.length / 2.

  • Iterate through the array from index 0 to midIndex - 1.

  • Check if the element at the current index is equal to the element at index midIndex.

  • Return the element that makes up the majority if the elements are equal.

  • Return -1 if the first half of the array contains no majority entry.

Example

public class Main {
   public static int findMajorityElement(int[] nums) {
      int midIndex = nums.length / 2;
        
      for (int i = 0; i < midIndex; i++) {
         if (nums[i] == nums[midIndex])
            return nums[i];
      }
      
      return -1;
   }
    
   public static void main(String[] args) {
      int[] nums = { /* Initialize your sorted array here */ };
      int majorityElement = findMajorityElement(nums);
      System.out.println("Majority Element: " + majorityElement);
   }
}

Output

Majority Element: -1

Explanation of Code in Approach 2

In this method, the array is split into two equal parts, and each member in the first half is compared to the middle element (nums[midIndex]). The element is returned as the majority element if a match is found. We return -1, which denotes that there is no majority element, if there is no match in the first half.

Approach 3

Algorithm

  • Iterate through the array from index 0 to nums.length - 1.

  • Check if the element at the current index is equal to the element at index nums.length / 2.

  • Initialize a variable count as 0.

  • If the elements are equal, increment count by 1.

  • If count is greater than nums.length / 2, return the element as the majority element.

  • If no majority element is found, return -1.

Example

public class Main {
   public static int findMajorityElement(int[] nums) {
      int midIndex = nums.length / 2;
      int majorityElement = nums[midIndex];
      int count = 0;
        
      for (int i = 0; i < nums.length; i++) {
         if (nums[i] == majorityElement)
            count++;
            
         if (count > midIndex)
            return majorityElement;
      }
        
      return -1;
   }
    
   public static void main(String[] args) {
      int[] nums = {2, 2, 2, 3, 4, 2, 2}; // Example array initialization
      int majorityElement = findMajorityElement(nums);
      System.out.println("Majority Element: " + majorityElement);
   }
}

Output

Majority Element: -1

Explanation of Code in Approach 3

In this approach, we iterate through the entire array and keep track of the count of the element at nums.length / 2. If the count exceeds nums.length / 2, we return the element as the majority element. If no majority element is found, we return -1.

Approach 4

Algorithm

  • Initialize a variable candidate as nums[0] and count as 1.

  • Iterate through the array from index 1 to nums.length - 1.

  • If the current element is equal to candidate, increment count by 1.

  • If the current element is different from the candidate, decrement count by 1.

  • If count becomes 0, update the candidate to the current element and set count to 1.

  • After the iteration, iterate through the array again and count the occurrences of candidates.

  • If the count is greater than nums.length / 2, return candidate as the majority element; otherwise, return -1.

Example

public class Main {
   public static int findMajorityElement(int[] nums) {
      int candidate = nums[0];
      int count = 1;
        
      for (int i = 1; i < nums.length; i++) {
         if (nums[i] == candidate)
            count++;
         else
            count--;
            
         if (count == 0) {
            candidate = nums[i];
            count = 1;
         }
      }
        
      count = 0;
        
      for (int num : nums) {
         if (num == candidate)
            count++;
      }
        
      if (count > nums.length / 2)
         return candidate;
      else
         return -1;
   }
    
   public static void main(String[] args) {
      int[] nums = {2, 2, 2, 3, 4, 2, 2}; // Example array initialization
      int majorityElement = findMajorityElement(nums);
      System.out.println("Majority Element: " + majorityElement);
   }
}

Output

Majority Element: 2

Explanation of Code in Approach 4

This approach follows the Boyer-Moore Voting Algorithm. Each time the array is iterated over, a candidate element is kept with a count of 1. The count is decreased each time a new element is encountered. A new candidate is chosen if the count is zero. After the iteration, we iterate through the array again to count the occurrences of the candidate. If the count exceeds nums.length / 2, we return the candidate as the majority element; otherwise, we return -1.

Conclusion

In this article, we explored four different approaches to finding the occurrence of a number more than N/2 times in a sorted array using Java. Each strategy offers a special resolution with varied degrees of effectiveness. You now possess the skills to approach this issue successfully in your Java projects by comprehending the algorithms, looking at the ready-to-run code, and paying attention to the step-by-step instructions.

Updated on: 31-Jul-2023

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements