Problem

Given two arrays keysArr and valuesArr, return a new object obj. Each key-value pair in obj should come from keysArr[i] and valuesArr[i].

If a duplicate key exists at a previous index, that key-value should be excluded. In other words, only the first key should be added to the object.

If the key is not a string, it should be converted into a string by calling String() on it.

Examples

Example 1:

1
2
3
Input: keysArr = ["a", "b", "c"], valuesArr = [1, 2, 3]
Output: {"a": 1, "b": 2, "c": 3}
Explanation: The keys "a", "b", and "c" are paired with the values 1, 2, and 3 respectively.

Example 2:

1
2
3
Input: keysArr = ["1", 1, false], valuesArr = [4, 5, 6]
Output: {"1": 4, "false": 6}
Explanation: First, all the elements in keysArr are converted into strings. We can see there are two occurrences of "1". The value associated with the first occurrence of "1" is used: 4.

Example 3:

1
2
3
Input: keysArr = [], valuesArr = []
Output: {}
Explanation: There are no keys so an empty object is returned.

Constraints:

  • keysArr and valuesArr are valid JSON arrays
  • 2 <= JSON.stringify(keysArr).length, JSON.stringify(valuesArr).length <= 5 * 10^5
  • keysArr.length === valuesArr.length

Solution

Method 1 – Hash Set for Uniqueness and String Conversion

Intuition

The key idea is to iterate through both arrays, convert each key to a string, and add it to the result object only if it hasn’t been seen before. A set is used to track which keys have already been added, ensuring only the first occurrence is used.

Approach

  1. Initialize an empty object obj and an empty set seen.
  2. Iterate through keysArr and valuesArr in parallel:
    • Convert the key to a string.
    • If the string key is not in seen, add it to obj with the corresponding value and add the key to seen.
  3. Return the resulting object.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function createObject(keysArr, valuesArr) {
    const obj = {};
    const seen = new Set();
    for (let i = 0; i < keysArr.length; i++) {
        const k = String(keysArr[i]);
        if (!seen.has(k)) {
            obj[k] = valuesArr[i];
            seen.add(k);
        }
    }
    return obj;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function createObject(keysArr: any[], valuesArr: any[]): Record<string, any> {
    const obj: Record<string, any> = {};
    const seen = new Set<string>();
    for (let i = 0; i < keysArr.length; i++) {
        const k = String(keysArr[i]);
        if (!seen.has(k)) {
            obj[k] = valuesArr[i];
            seen.add(k);
        }
    }
    return obj;
}

Complexity

  • ⏰ Time complexity: O(n), where n is the length of the arrays, as each element is processed once.
  • 🧺 Space complexity: O(n), for the result object and set.