Problem
Given an object or an array obj
, return an inverted object or array
invertedObj
.
The invertedObj
should have the keys of obj
as values and the values of
obj
as keys. The indices of array should be treated as keys.
The function should handle duplicates, meaning that if there are multiple keys in obj
with the same value, the invertedObj
should map the value to an array containing all corresponding keys.
It is guaranteed that the values in obj
are only strings.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
obj
is a valid JSON object or arraytypeof obj[key] === "string"
2 <= JSON.stringify(obj).length <= 10^5
Solution
Method 1 – Hash Map Inversion
Intuition
We want to invert the keys and values of an object or array. If multiple keys have the same value, the inverted object should map that value to an array of keys. For arrays, indices are treated as keys.
Approach
- Initialize an empty object for the result.
- Iterate over the keys of the input object (or indices for arrays).
- For each key-value pair:
- If the value is not in the result, set it to the key.
- If the value is already in the result:
- If it’s not an array, convert it to an array with the previous key and the current key.
- If it’s already an array, push the current key.
- Return the result object.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— Each key-value pair is processed once. - 🧺 Space complexity:
O(n)
— For the result object.