![]() |
VOOZH | about |
Given an even-sized arrayarr[] of length n. A dominant pair (i, j) is defined as:
The task is to find the count of total number of dominant pairs in the array.
Examples:
Input: arr[] = [10, 2, 2, 1]
Output: 2
Explanation: First half: [10, 2], Second half: [2, 1]. So valid pairs are:
- {0, 2}: 10 >= 5 × 2
- {0, 3}: 10 >= 5 × 1
So, total dominant pairs = 2.
Input: arr[] = [10, 8, 2, 1, 1, 2]
Output: 5
Explanation: First half: [10, 8, 2], Second half: [1, 1, 2]. So valid pairs are:
- {0, 3}: 10 >= 5 × 1
- {0, 4}: 10 >= 5 × 1
- {0, 5}: 10 >= 5 × 2
- {1, 3}: 8 >= 5 × 1
- {1, 4}: 8 >= 5 × 1
So, total dominant pairs = 5.
Table of Content
The idea is to count dominant pairs by checking all possible (i, j) pairs where i belongs to the first half and j belongs to the second half of the array. The brute-force approach uses two nested loops to compare each element from the first half with every element from the second half, ensuring the dominance condition (arr[i] >=5 * arr[j]) holds.
2
Time Complexity: O(n²), due to two nested loops iterating.
Space Complexity: O(1), as only a few extra variables are used.
The idea is to efficiently count dominant pairs by leveraging sorting and the two-pointer technique. Instead of using nested loops, we sort the first half and second half separately to maintain order. Using a two-pointer approach, we iterate through the first half and move the right pointer in the second half until the dominance condition is violated. This ensures that for every valid left index, all valid right indices are counted efficiently.
Steps to implement the above idea:
Below is the implementation of the above approach:
2
Time Complexity:O(n*log(n)), as sorting takes O(n log n), and two-pointer traversal takes O(n).
Space Complexity:O(1), as sorting is done in-place, and only a few extra variables are used.