Skip to content

Commit de76336

Browse files
committed
using hashtable
1 parent 6299130 commit de76336

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Super_30/findResturant.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public String[] findRestaurant(String[] list1, String[] list2) {
3+
// store string with index in hashmap, iterate over the second list and check
4+
/*
5+
T.C. - O(l1 + l2)
6+
Space - O(l1*avg length of string in l1)
7+
*/
8+
HashMap<String, Integer> hm = new HashMap<>();
9+
List<String> res = new ArrayList<>(); // to store result
10+
for (int i=0; i< list1.length; i++) {
11+
hm.put(list1[i], i);
12+
}
13+
int min_sum = Integer.MAX_VALUE;
14+
int sum = Integer.MAX_VALUE;
15+
for (int i=0; i<list2.length; i++) {
16+
if (hm.containsKey(list2[i])) {
17+
sum = i + hm.get(list2[i]);
18+
if (sum < min_sum) {
19+
res.clear(); // to clear the list of previous values
20+
res.add(list2[i]);
21+
min_sum = sum;
22+
} else if (sum == min_sum) {
23+
res.add(list2[i]);
24+
}
25+
}
26+
}
27+
return res.toArray(new String[res.size()]);
28+
}
29+
}

0 commit comments

Comments
 (0)