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:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
keysArr
andvaluesArr
are valid JSON arrays2 <= 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
- Initialize an empty object
obj
and an empty setseen
. - Iterate through
keysArr
andvaluesArr
in parallel:- Convert the key to a string.
- If the string key is not in
seen
, add it toobj
with the corresponding value and add the key toseen
.
- Return the resulting object.
Code
|
|
|
|
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.