2563. Count the Number of Fair Pairs

Explanation:

To solve this problem, we can iterate through all pairs of indices (i, j) with 0 <= i < j < n and count the pairs that satisfy the condition lower <= nums[i] + nums[j] <= upper. We can achieve this by maintaining a HashMap to store the count of each prefix sum from the beginning of the array up to the current index.

  1. Initialize a HashMap prefixSums to store the count of each prefix sum.
  2. Initialize a variable fairPairs to keep track of the number of fair pairs.
  3. Iterate through the array nums and for each element at index j:
    • Calculate the current prefix sum currentSum by adding nums[j] to the previous prefix sum.
    • Increment the fairPairs count by the value in prefixSums.getOrDefault(currentSum - lower, 0).
    • Increment the count of currentSum in the prefixSums HashMap.
  4. Return the total count of fair pairs.

Time Complexity: O(n), where n is the length of the input array nums. Space Complexity: O(n) for the HashMap prefixSums.

:

class Solution {
    public int countPairs(int[] nums, int lower, int upper) {
        Map<Integer, Integer> prefixSums = new HashMap<>();
        int fairPairs = 0;
        for (int j = 0; j < nums.length; j++) {
            int currentSum = nums[j] + (j > 0 ? nums[j - 1] : 0);
            for (int i = 0; i < j; i++) {
                if (lower <= currentSum && currentSum <= upper) {
                    fairPairs++;
                }
                currentSum += nums[i];
            }
            prefixSums.put(currentSum, prefixSums.getOrDefault(currentSum, 0) + 1);
        }
        return fairPairs;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.