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:

1
2
3
Input: obj = {"a": "1", "b": "2", "c": "3", "d": "4"}
Output: invertedObj = {"1": "a", "2": "b", "3": "c", "4": "d"}
Explanation: The keys from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.

Example 2:

1
2
3
Input: obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
Output: invertedObj = {"1": "a", "2": ["b", "c"], "4": "d"}
Explanation: There are two keys in obj with the same value, the invertedObj mapped the value to an array containing all corresponding keys.

Example 3:

1
2
3
Input: obj = ["1", "2", "3", "4"]
Output: invertedObj = {"1": "0", "2": "1", "3": "2", "4": "3"}
Explanation: Arrays are also objects therefore array has changed to an object and the keys (indices) from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.

Constraints:

  • obj is a valid JSON object or array
  • typeof 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

  1. Initialize an empty object for the result.
  2. Iterate over the keys of the input object (or indices for arrays).
  3. 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.
  4. Return the result object.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function invertObject(obj) {
  const ans = {};
  for (const k in obj) {
    const v = obj[k];
    if (!(v in ans)) ans[v] = k;
    else if (Array.isArray(ans[v])) ans[v].push(k);
    else ans[v] = [ans[v], k];
  }
  return ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function invertObject(obj: Record<string, string> | string[]): Record<string, string | string[]> {
  const ans: Record<string, string | string[]> = {};
  for (const k in obj) {
    const v = obj[k];
    if (!(v in ans)) ans[v] = k;
    else if (Array.isArray(ans[v])) (ans[v] as string[]).push(k);
    else ans[v] = [ans[v] as string, k];
  }
  return ans;
}

Complexity

  • ⏰ Time complexity: O(n) — Each key-value pair is processed once.
  • 🧺 Space complexity: O(n) — For the result object.