It took me more than an hour to understand how this solution worked. In particular, I was confused about what the map.containsKey(sum - k) was getting, so for those who are also confused, here's an explanation:

Let's say you've iterated to index 5 (randomly chosen) and your sum from index 0 to 5 so far is 7, and k is 3. sum - k in this case is 4.

What map.containsKey(sum - k) returns is the index where the sum of every element up to that index from index 0 is sum - k, or (7 - 4) == 3, in our example. Let's say that that index returned by map.containsKey(sum - k) is 2 (randomly chose one that is before index 5). So knowing that at index 2 the total sum is 4, and at index 5, the total sum is 7, that means the elements between index 2 and index 5 incremented the total sum by 3, or k!

Hope this helps!