Create Object from Two Arrays - Problem
You are given two arrays: keysArr containing potential object keys and valuesArr containing corresponding values. Your task is to merge these arrays into a single object where each key-value pair comes from keysArr[i] and valuesArr[i].
Key Rules:
- Duplicate Prevention: If a key appears multiple times, only the first occurrence should be included in the final object
- Type Conversion: All keys must be converted to strings using
String() - Index Matching:
keysArr[i]pairs withvaluesArr[i]
This problem simulates creating a configuration object from separate key and value arrays, commonly seen in data processing and API responses.
Input & Output
example_1.py โ Basic Case
$
Input:
keysArr = ["a", "b", "c"], valuesArr = [1, 2, 3]
โบ
Output:
{"a": 1, "b": 2, "c": 3}
๐ก Note:
No duplicate keys, so all key-value pairs are included in the result object.
example_2.py โ Duplicate Keys
$
Input:
keysArr = ["a", "b", "a", "c"], valuesArr = [1, 2, 3, 4]
โบ
Output:
{"a": 1, "b": 2, "c": 4}
๐ก Note:
The key "a" appears at indices 0 and 2. Only the first occurrence (index 0) with value 1 is kept, the duplicate at index 2 with value 3 is ignored.
example_3.py โ Type Conversion
$
Input:
keysArr = [1, "1", 2], valuesArr = ["first", "second", "third"]
โบ
Output:
{"1": "first", "2": "third"}
๐ก Note:
The number 1 and string "1" both convert to the same string key "1". Only the first occurrence (number 1) is kept with value "first".
Constraints
- 0 โค keysArr.length = valuesArr.length โค 104
- keysArr[i] can be any type that can be converted to string
- valuesArr[i] can be any valid JavaScript value
- Both arrays will always have the same length
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Tracking
Start with empty result object and Set to track processed keys
2
Process Each Pair
Convert key to string and check if we've seen it before
3
Add New Keys
If key is new, add to both tracking Set and result object
4
Skip Duplicates
If key already exists in Set, ignore this occurrence
Key Takeaway
๐ฏ Key Insight: Using a Hash Set for O(1) duplicate detection transforms an O(nยฒ) nested loop problem into an optimal O(n) single-pass solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code