Given your original code below:
private static Map<Character,Character> mapCharacters(String message){
Map<Character, Character> map = new HashMap<>();
char idx = 'a';
for (char ch : message.toCharArray()) {
if (!map.containsKey(ch)) {
map.put(ch, idx);
++idx;
}
}
return map;
}
Here are some observations about the time complexity:
- Iterating each character in
message
will be O(n) – pretty clearly if there are 10 characters it takes 10 steps, 10,000 characters will take 10,000 steps. The time complexity is directly proportional to n
.
- Inside the loop, you're checking if the map contains that character already – using
containsKey()
, this is a constant-time operation which is defined as O(1) time complexity. The idea is that the actual time to evaluate the result of containsKey()
should be the same whether your map has 10 keys or 10,000 keys.
- Inside the
if
, you have map.put()
which is another constant-time operation, another O(1) operation.
- Combined together: for every
nth
character, you spend time iterating it in the loop, checking if the map has it already, and adding it; all of this would be 3n (three times n
) which is just O(n).
Separately, you could make a small improvement to your code by replacing this block:
if (!map.containsKey(ch)) {
map.put(ch, idx);
++idx;
}
with something like below (which retains the same behavior of running ++idx
only if you've put something, and specifically if the previous thing was either "not present" or perhaps had been set with "null" - though the "set as null" doesn't apply from your code sample):
Character previousValue = map.putIfAbsent(ch, idx);
if (previousValue == null) {
++idx;
}
Though the time complexity wouldn't change, using containsKey()
makes the code clearer, and also takes advantage of well-tested, performant code that's available for free.
Under the covers, calling Map.putIfAbsent()
is implemented like below (as of OpenJDK 17) showing an initial call to get()
followed by put()
if the key isn't present.
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}