Skip to main content

Create Object from Two Arrays - Solution & Explanation

EasyPremiumFree on FleetCode4 min read
Practice this problem

Problem Statement

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.

 

Example 1:

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:

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:

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 * 105
  • keysArr.length === valuesArr.length

Approach Overview

Problem Overview: You receive two arrays: one containing keys and the other containing values. The task is to create an object where keys[i] maps to values[i]. If the same key appears multiple times, the later value should overwrite the previous one.

Approach 1: Nested Scan for Duplicate Handling (O(n^2) time, O(n) space)

A straightforward but inefficient strategy is to iterate through the keys array and, for each element, scan earlier elements to check if the key already appeared. If it did, update the stored value; otherwise insert a new key-value pair into the object. This method works but repeatedly scanning the array causes quadratic time complexity. It’s mainly useful as a conceptual baseline when first reasoning about duplicate keys.

Approach 2: Single Pass Object / Hash Map (O(n) time, O(n) space)

The optimal approach uses a single iteration and stores results directly in an object (effectively a hash map). Iterate from index 0 to n - 1, assigning result[keys[i]] = values[i]. JavaScript objects perform average O(1) insertion and overwrite operations, so duplicates are naturally handled by replacing the previous value. This keeps the algorithm linear and avoids unnecessary lookups. The technique is a common pattern when combining parallel arrays and relies on constant‑time hash access from a hash table.

Approach 3: Functional Reduce Construction (O(n) time, O(n) space)

Another clean implementation uses Array.reduce(). The reducer accumulates an object while iterating through the keys array, assigning acc[key] = values[index] at each step. Internally this still performs one pass and the same constant-time assignments as the hash-map solution. The benefit is concise functional code, though the underlying algorithmic behavior remains identical to the iterative approach.

Both optimal approaches rely on basic array traversal and object property assignment, which acts as a hash lookup structure in JavaScript. The overwrite behavior ensures the final object reflects the last occurrence of each key.

Recommended for interviews: Use the single-pass hash map approach. Interviewers expect you to recognize that a direct mapping from the two arrays avoids unnecessary checks and runs in O(n) time. Mentioning the naive duplicate-checking method demonstrates reasoning from brute force to optimal, but implementing the linear solution shows strong understanding of arrays and hash-based data structures.

Solution

Code

TypeScript

JavaScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Nested Scan for Duplicate KeysO(n^2)O(n)Conceptual baseline or when exploring duplicate detection manually
Single Pass Hash Map / ObjectO(n)O(n)General case and the expected optimal interview solution
Functional Reduce ConstructionO(n)O(n)When writing concise functional JavaScript or TypeScript code

Video Solution

Avoid This Coding Interview Mistake!! | Stacks, Queues & Deques • Greg Hogg • 627,264 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Create Object from Two Arrays easy or hard?
Create Object from Two Arrays is considered an easy problem. It mainly tests understanding of arrays and hash maps, along with basic iteration and key-value mapping.
Create Object from Two Arrays Python/Java solution
In Python, iterate through indices and assign result[keys[i]] = values[i] using a dictionary. In Java, use a HashMap and call map.put(keys[i], values[i]) inside a loop. Both implementations run in O(n) time and store the mapping in a hash-based structure.
How to solve Create Object from Two Arrays in O(n)?
Traverse the arrays using a single loop. For each index i, insert or update the mapping using result[keys[i]] = values[i]. If a key appears multiple times, the assignment simply overwrites the earlier value, ensuring the last occurrence remains. This keeps the algorithm linear.
What is the best approach for Create Object from Two Arrays?
The best approach is a single-pass hash map construction. Iterate through the arrays once and assign result[keys[i]] = values[i]. Object property insertion and overwrite operations are O(1) on average, giving an overall time complexity of O(n) with O(n) space.
Is Create Object from Two Arrays asked at Google/Amazon/Meta?
This exact problem is categorized as an easy-level array and hash-table exercise. Variations of mapping keys to values and constructing hash maps from parallel arrays appear in coding screens and online assessments at large tech companies.
What data structure is used in Create Object from Two Arrays?
The core data structure is a hash table implemented as a JavaScript object or Map. Hash tables allow constant-time insertion and updates, which makes them ideal for building key-value mappings from arrays.
What is the time complexity of Create Object from Two Arrays?
The optimal solution runs in O(n) time where n is the number of elements in the arrays. Each index is processed exactly once and object assignments are constant time on average. Space complexity is O(n) because the resulting object may store up to n key-value pairs.

Ready to solve this problem?

Practice Create Object from Two Arrays with our built-in code editor and test cases.

Practice on FleetCode