Sponsored
Sponsored
This approach leverages sorting and a two-pointer technique to efficiently find the number of fair pairs. By sorting the array, we bring potential fair pairs closer, simplifying the conditions checking. Two pointers are then used to find suitable pairs within the bounds.
First, sort the array nums
. As we iterate through each element as one half of the pair, use two pointers to find elements that complete the pair within the given range of sums.
Time Complexity: O(n log n), where the sorting step dominates the complexity. Each binary search operation runs in O(log n).
Space Complexity: O(1), as we sort in-place.
Python's solution involves sorting and utilizing internal methods lowerBound
and upperBound
to localize and calculate fair pairs, iterating through the array.
A simpler, brute-force approach involves examining every possible pair (i, j) to determine if it fits the 'fair pair' criteria. While this method is easier to understand and implement, it becomes inefficient as the input size increases.
Time Complexity: O(n^2), as it examines every possible pair.
Space Complexity: O(1), since no additional space is utilized.
1#include <iostream>
2#include <vector>
3
4class Solution {
5public:
6 int countFairPairs(std::vector<int>& nums, int lower, int upper) {
7 int count = 0;
8 for (int i = 0; i < nums.size(); ++i) {
9 for (int j = i + 1; j < nums.size(); ++j) {
10 int sum = nums[i] + nums[j];
11 if (sum >= lower && sum <= upper) {
12 count++;
13 }
14 }
15 }
16 return count;
17 }
18};
19
20int main() {
21 Solution sol;
22 std::vector<int> nums = {0, 1, 7, 4, 4, 5};
23 int result = sol.countFairPairs(nums, 3, 6);
24 std::cout << "Number of fair pairs: " << result << std::endl;
25 return 0;
26}
This C++ implementation evaluates each potential pair from the start of the list using nested loops to find and count fair pairs.