LeetCode 2563: Count the Number of Fair Pairs Solution

Master LeetCode problem 2563 (Count the Number of Fair Pairs), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2563. Count the Number of Fair Pairs

Problem Explanation

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.

:

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2563 (Count the Number of Fair Pairs)?

This page provides optimized solutions for LeetCode problem 2563 (Count the Number of Fair Pairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2563 (Count the Number of Fair Pairs)?

The time complexity for LeetCode 2563 (Count the Number of Fair Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2563 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2563 in Java, C++, or Python.

Back to LeetCode Solutions