Create Object from Two Arrays - 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].

Important rules:

  • If a duplicate key exists at a previous index, that key-value should be excluded. Only the first occurrence of each key should be added to the object.
  • If the key is not a string, it should be converted to a string by calling String() on it.

Input & Output

Example 1 — Basic Case
$ Input: keysArr = ["a", "b", "c"], valuesArr = [1, 2, 3]
Output: {"a":1,"b":2,"c":3}
💡 Note: All keys are unique strings, so all key-value pairs are added: a→1, b→2, c→3
Example 2 — Duplicate Keys
$ Input: keysArr = ["a", "b", "a"], valuesArr = [1, 2, 3]
Output: {"a":1,"b":2}
💡 Note: Key 'a' appears at indices 0 and 2. Only the first occurrence (a→1) is kept, the second is excluded
Example 3 — Non-String Keys
$ Input: keysArr = [1, 2, 1], valuesArr = ["x", "y", "z"]
Output: {"1":"x","2":"y"}
💡 Note: Numbers are converted to strings: 1→"1", 2→"2". The duplicate key "1" at index 2 is excluded

Constraints

  • 1 ≤ keysArr.length = valuesArr.length ≤ 50
  • 1 ≤ keysArr[i].length ≤ 10
  • keysArr[i] is made of alphanumeric characters

Visualization

Tap to expand
Create Object from Two Arrays INPUT keysArr "a" "b" "c" [0] [1] [2] valuesArr 1 2 3 [0] [1] [2] keysArr = ["a","b","c"] valuesArr = [1, 2, 3] Hash Set for Tracking seenKeys = new Set() ALGORITHM STEPS 1 Initialize Create empty obj and Set 2 Iterate Arrays Loop through both arrays 3 Check Duplicates Skip if key in Set 4 Add to Object obj[key] = value, add to Set Processing Steps i key value action 0 "a" 1 ADD 1 "b" 2 ADD 2 "c" 3 ADD FINAL RESULT Result Object "a" : 1 "b" : 2 "c" : 3 {"a":1,"b":2,"c":3} OK - All keys unique - 3 key-value pairs Key Insight: Using a Hash Set for O(1) lookup ensures we only add the FIRST occurrence of each key. This approach has O(n) time complexity where n is the length of the arrays. TutorialsPoint - Create Object from Two Arrays | Hash Set Tracking Approach
Asked in
Meta 15 Google 12 Amazon 8
25.0K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen