As regarding the following question I have completed the code as below.
But I am curious about other effective solutions. I am also curious about if there is any solution that could be applicable by using java stream API.
It is not mandatory to keep records at int[][]
matrix. Any data structure can be used.
My solution has O(n)
time complexity. If you have a better to solve the question please share your solution.
For a given retailer "100" function only needs to return 4 because product 1 exists in other retailers.
Thanks.
public class InterviewQuestion {
public static void main(String[] args) {
int[][] itemSeller = { {1, 100},
{2, 200},
{3, 300},
{4, 100},
{1, 200},
{2, 300} };
int target = 100;
getUniqueProduct(itemSeller,target);
}
private static void getUniqueProduct(int[][] itemSeller, int target) {
int count[] = new int[itemSeller.length];
for (int i = 0; i < itemSeller.length; i++) {
count[itemSeller[i][0]]++;
}
for (int i = 0; i < itemSeller.length; i++) {
if (target == itemSeller[i][1]) {
int item = itemSeller[i][0];
if (count[item] > 1) {
continue;
} else
System.out.println(item);
}
}
}
}