Element Appearing More Than 25% in Sorted Array.

Element Appearing More Than 25% in Sorted Array.

Q - Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.

LeetCode Problem: Link | Click Here

class Solution {
    public int findSpecialInteger(int[] arr) {
        int n = arr.length; // Find the length of the array
        int percent25 = n / 4; // Calculate the threshold value, a quarter of the array length
        int result = 0; // Initialize the result variable to store the special integer

        Arrays.sort(arr); // Sort the array in ascending order

        // Loop through the array with a step of 'percent25'
        // Ensure enough elements are available for comparison by looping until (n - percent25)
        for (int i = 0; i < n - percent25; i++) {
            // Check if the current element is equal to an element 'percent25' positions ahead
            if (arr[i] == arr[i + percent25]) {
                result = arr[i]; // If found, update the 'result' variable with the special integer
            }
        }

        return result; // Return the special integer found
    }
}