Skip to content

Commit ab5d099

Browse files
author
Prakhar Gupta
committed
Adding solution for Medium-SplashArrays
1 parent e903714 commit ab5d099

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.Arrays;
2+
import java.util.Map;
3+
import java.util.function.Function;
4+
import java.util.stream.Collectors;
5+
import java.util.stream.Stream;
6+
7+
public class Prakhar_SplashArrays {
8+
9+
/**
10+
* Instead of iterating, This approach creates a map of strings to occurence.
11+
* The map approach can be implemented from scratch by iterating and iterating the count, or leverage the existing groupBy provided by java8. I chose to do the later.
12+
* Once map is created, Its easy to look up.
13+
*
14+
* Complexity : O(n)
15+
*/
16+
static int[] matchingStrings(final String[] strings, final String[] queries) {
17+
18+
// Create a Map of each string to its occurence
19+
final Map<String, Long> stringToCountMap =
20+
Stream.of(strings).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
21+
// Get the result off the map
22+
return Arrays.stream(queries)
23+
.map(query -> stringToCountMap.getOrDefault(query, 0L))
24+
.mapToInt(Math::toIntExact).toArray();
25+
}
26+
27+
public static void main(String[] args) {
28+
29+
final String[] strings = {"aba", "baba", "aba", "xzxb"};
30+
final String[] queries = {"aba", "xzxb", "ab"};
31+
32+
final int[] output = matchingStrings(strings, queries);
33+
34+
Arrays.stream(output).forEach(System.out::println);
35+
}
36+
}

0 commit comments

Comments
 (0)