Put ages within a supplied range into a HashMap
range.put(age, range.get(age) + " and " + name);


This is expensive.

Specifically, string construction that is done over and over via creating longer and longer strings. You're basically building the same string over and over and over. And strings are basically arrays of char, so that's a lot of copying.

And there's nothing you can do about it because of this rule:


  You will need to construct a map to store your results, but you may not use any other structures (arrays, lists, etc.) as auxiliary storage. (You can have as many simple variables as you like.)


If you were to ignore this one rule for a moment, what you could do is make a Map&lt;Integer, List&lt;String&gt;&gt;. And then put the names of people in the list. Then, when you're done, as per this stackoverflow answer... https://stackoverflow.com/a/22577565/540837

You can use a stream and Collectors.joining.

But you can't, because you're not allowed any other lists or arrays or whatnot.

I'd personally consider the problem unsolvable because the strings could get very long and become a larger part of the problem than the actual pairs would.

What I'd change about your code is this bit:

for (String name : namesAges.keySet()) {
    int age = namesAges.get(name);


You're first getting the keys, and then you're using the keys to get the value. Maps have .entrySet to get a set of entries, and then you can have the key and the value in one go.

Also, "Your result map's pairs should be sorted in ascending order by age (keys)." sorting already takes O(N log N) time, so basically your instructors are expecting that you'll find a way to get N log N string concatenation which doesn't exist when you're not allowed to create arrays.