Problem Description
Given an object or an array obj, return an inverted object invertedObj in which the keys of obj become the values in invertedObj and the values of obj become the keys. For arrays, the indices are treated as keys. In case of duplicate values in obj, the corresponding key in invertedObj should map to an array of all keys that produced that value.
Key Insights
- The input may be either an object or an array.
- For arrays, use the indices (as strings) as keys.
- When multiple keys in the input have the same value, store all corresponding keys in an array.
- Conversion of keys to string is necessary to keep the inverted format consistent.
Space and Time Complexity
Time Complexity: O(n), where n is the number of key-value pairs in the input. Space Complexity: O(n), to store the inverted mapping.
Solution
Use a single pass over all entries in the given object or array. For each key-value pair, check if the value is already present as a key in the inverted object:
- If not, add an entry mapping the value to the key (converted to a string).
- If the value already exists, check if the current value is a list; if not, convert it into a list and then append the new key. This approach easily handles duplicates and maintains the required data structure transformation.