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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5 return (*(int *)a - *(int *)b);
6}
7
8int countFairPairs(int *nums, int numsSize, int lower, int upper) {
9 qsort(nums, numsSize, sizeof(int), compare);
10 int count = 0;
11 for (int i = 0; i < numsSize; ++i) {
12 int left = i + 1, right = numsSize - 1;
13 while (left <= right) {
14 int mid = left + (right - left) / 2;
15 if (nums[i] + nums[mid] < lower) {
16 left = mid + 1;
17 } else {
18 right = mid - 1;
19 }
20 }
21 int lowIndex = left;
22 left = i + 1; right = numsSize - 1;
23 while (left <= right) {
24 int mid = left + (right - left) / 2;
25 if (nums[i] + nums[mid] <= upper) {
26 left = mid + 1;
27 } else {
28 right = mid - 1;
29 }
30 }
31 int highIndex = right;
32 count += (highIndex - lowIndex + 1);
33 }
34 return count;
35}
36
37int main() {
38 int nums[] = {0,1,7,4,4,5};
39 int lower = 3, upper = 6;
40 int result = countFairPairs(nums, 6, lower, upper);
41 printf("Number of fair pairs: %d\n", result);
42 return 0;
43}
This C implementation uses binary search after sorting the array. Two loops identify the lower and upper bounds of valid pair elements, and count their occurrences.
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#
The brute-force C implementation iterates over each element and checks every subsequent element for compliant pair conditions. This straightforward iteration checks all n^2 pairs.