Why is the closing bracket the key in the Map, and the opening bracket the value? What will change if you do the opposite? What is the complexity of containsValue vs get by key?
sobes.tech AI
Answer from AI
If in a Map the key is a closing bracket and the value is an opening bracket, this is usually related to the task of checking the correctness of bracket sequences, where a closing bracket can quickly lead to the corresponding opening bracket.
If you swap them (key — opening, value — closing), the checking logic will change: when traversing the string, you will need to find the closing bracket for the opening one, which is also possible, but it is usually more convenient to have the closing bracket as the key so that when you encounter a closing bracket, you can quickly check the top element of the stack.
Operation complexities:
getby key in a Map — O(1) on average (hash table).containsValue— O(n), as it requires iterating over all values.
Therefore, for checking bracket matching, it is better to use get by the key (closing bracket), rather than containsValue.