702662. Find Unique pair in an array with pairs of numbers
Find Unique pair in an array with pairs of numbers2425
Summary
Find a unique pair in an array where each element is given as a pair of two numbers. The problem asks you to find and return the first unique pair in the array.
The key concept involved here is finding unique pairs in an array, which can be solved using bit manipulation or sorting techniques.
Detailed Explanation
To solve this problem, we will iterate over the array once and keep track of all the pairs we have seen so far. For each pair, we check if it's already present in our set or not. If it is not present, we add it to our set and update our result with the current pair.
Here is a step-by-step breakdown of the solution:
- Initialize an empty set
seento store all the pairs we have seen so far. - Iterate over the array once using a for loop.
- For each pair in the array, check if it's already present in our set
seen. - If the pair is not present in our set
seen, add it to our set and update our result with the current pair. - Continue this process until we have processed all pairs in the array.
The time complexity of this solution is O(n), where n is the number of elements in the array, because we are iterating over the array once. The space complexity is also O(n) for storing all the unique pairs in our set seen.
Here's a diagram illustrating the problem:
+---------------+
| Array |
| (pairs) |
+---------------+
|
| Iterate
| over array
v
+---------------+
| Seen |
| (set of pairs) |
+---------------+
|
| Check if pair is seen before
| or not
v
+---------------+
| Result |
| (first unique pair)|
+---------------+
Optimized Solutions
Java
import java.util.*;
public class Main {
public static int[] findUniquePair(int[][] arr) {
Set<String> seen = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
String pair = arr[i][0] + "," + arr[i][1];
if (!seen.contains(pair)) {
seen.add(pair);
return arr[i];
}
}
return null;
}
public static void main(String[] args) {
int[][] arr = {{1, 2}, {3, 4}, {5, 6}, {1, 2}};
int[] result = findUniquePair(arr);
if (result != null) {
System.out.println("First unique pair is: " + result[0] + ", " + result[1]);
} else {
System.out.println("No unique pair found");
}
}
}