LeetCode 2519: Count the Number of K-Big Indices

Problem Description

Explanation

Given an array nums of integers and an integer k, we are to count the number of indices i such that nums[i] is greater than or equal to k.

To solve this problem, we can use a binary search algorithm. We first sort the array nums, and for each element in the array, we perform a binary search to find the index of the first element that is greater than or equal to k. The count of such indices will give us the result.

Algorithm:

  1. Sort the input array nums.
  2. Initialize a counter count to 0.
  3. For each element num in nums, do a binary search to find the index of the first element in the sorted array that is greater than or equal to k. Increment count by the index found.
  4. Return the final count.

Time Complexity: O(nlogn) - Sorting the array takes O(nlogn) time, and for each element, a binary search operation takes O(logn) time. Space Complexity: O(1) - Constant extra space is used.

Solutions

import java.util.Arrays;

class Solution {
    public int countKBigIndices(int[] nums, int k) {
        Arrays.sort(nums);
        int count = 0;
        for (int num : nums) {
            int index = binarySearch(nums, k);
            count += index;
        }
        return count;
    }
    
    private int binarySearch(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}

Loading editor...