Find the smallest subarray covering all values

#1

In the java solution we have:

 Map<String, Integer> keywordsToCover = new HashMap<>();
    for (String keyword : keywords) {
        keywordsToCover.put(keyword,
                keywordsToCover.containsKey(keyword)
                        ? keywordsToCover.get(keyword) + 1
                        : 1);
    }

why not just have this as the for loop?

  Map<String, Integer> keywordsToCover = new HashMap<>();
    for (String keyword : keywords) {
        keywordsToCover.put(keyword, 1);
    }
0 Likes

#2

It is different operations on the Map, what yours cannot handle the situation when there are multiple keywords are the same.

1 Like

#3

But the argument you pass in is a Set, not a List of keywords:
Set keywords
You can’t have multiple keywords that are the same.

0 Likes

#4

I forgot that is a set so definitely it is fine to do the for loop directly. We rewrite that in Java 8 stream recently.

0 Likes

#5

Hi,

In the solution section to this problem we are saying:

Solution: The brute force approach is to iterate over all subarrays, testing if the
subarray contains all strings in the set. If the array length is n, there are 0(n^2)
subarrays.

I am not quite sure - how there could be n^2 subarray in an array of length n!

What am I missing?

0 Likes