714333. Dominant Pairs
Easy
Dominant Pairs
Summary
Given an array of integers, find all dominant pairs. A pair (i, j) is considered dominant if arr[i] and arr[j] are the same and i < j. The function should return a list of these dominant pairs.
This problem involves sorting and using two-pointer technique to solve this issue efficiently.
Detailed Explanation
To solve this problem, we can sort the array first. Then, we use two pointers, one at the start of the array and another at the end. As long as the elements at these positions are equal, we move the pointers towards each other until they're not equal anymore. At this point, all dominant pairs have been identified.
Here's a step-by-step breakdown:
- Sort the input array.
- Initialize two pointers
iandj, whereiis at the start of the array andjis at the end. - As long as
arr[i]andarr[j]are equal, move both pointers towards each other (i++andj--). - Once
arr[i]andarr[j]become unequal, all dominant pairs have been identified.
Time complexity: O(n log n) due to sorting. Space complexity: O(1), as we only use a constant amount of space.
Optimized Solutions
Java
import java.util.*;
public class DominantPairs {
public static List<List<Integer>> findDominantPairs(int[] arr) {
Arrays.sort(arr);
List<List<Integer>> dominantPairs = new ArrayList<>();
int i = 0, j = arr.length - 1;
while (i < j) {
if (arr[i] == arr[j]) {
dominantPairs.add(Arrays.asList(arr[i], i, j));
i++;
j--;
} else if (arr[i] < arr[j]) {
i++;
} else {
j--;
}
}
return dominantPairs;
}
}