LeetCode 2794 - Create Object from Two Arrays

The problem provides two arrays, keysArr and valuesArr, which always have the same length. Each position in the arrays represents a potential key-value pair.

LeetCode Problem 2794

Difficulty: 🟢 Easy
Topics:

Solution

LeetCode 2794 - Create Object from Two Arrays

Problem Understanding

The problem provides two arrays, keysArr and valuesArr, which always have the same length. Each position in the arrays represents a potential key-value pair. The element at index i in keysArr should become the key, and the element at index i in valuesArr should become the corresponding value.

The goal is to construct a JavaScript-style object where each key comes from keysArr and each value comes from valuesArr.

There are two important rules:

First, every key must be converted to a string using String(). This means values such as 1, "1", and true become "1" and "true" when used as object keys.

Second, if multiple elements in keysArr become the same string after conversion, only the first occurrence should be used. Any later occurrences should be ignored entirely.

For example, if keysArr = ["1", 1], both keys become "1" after conversion. The first occurrence creates the mapping "1" -> 4, and the second occurrence is discarded.

The constraints indicate that the serialized arrays can be very large, up to hundreds of thousands of characters. This suggests that the solution should process the arrays in a single pass whenever possible. An algorithm with quadratic behavior could become too slow on large inputs.

Several edge cases are important:

  • The arrays may be empty, producing an empty object.
  • Different values may convert to the same string key, such as "1" and 1.
  • Boolean values become string keys like "true" and "false".
  • Multiple duplicate keys may appear, and only the first occurrence should be preserved.
  • The input guarantees both arrays have the same length, so index mismatches never occur.

Approaches

Brute Force Approach

A straightforward solution is to process each key and determine whether the same stringified key has already appeared earlier in the array.

For every index i, we convert keysArr[i] to a string and then scan all previous indices from 0 to i - 1. If the same stringified key is found, we skip the current entry. Otherwise, we insert the key-value pair into the result object.

This approach is correct because every key checks all previous occurrences and therefore guarantees that only the first occurrence is preserved.

The problem is that each element may need to compare against many previous elements. With n elements, this can require approximately comparisons in the worst case.

Optimal Approach

The key observation is that we only need to know whether a stringified key has already been seen.

A hash-based data structure provides constant-time average lookup. As we iterate through the arrays, we convert each key to its string representation and check whether it already exists in the result object.

If the key is not present, we insert the key-value pair. If it already exists, we ignore the current occurrence.

Since each key is processed exactly once and each lookup is constant time on average, the entire algorithm runs in linear time.

Comparison of Approaches

Approach Time Complexity Space Complexity Notes
Brute Force O(n²) O(n) For each key, scan all previous keys to detect duplicates
Optimal O(n) O(n) Use a hash table or object for constant-time duplicate detection

Algorithm Walkthrough

  1. Create an empty object called result.
  2. Iterate through the arrays from index 0 to n - 1.
  3. For each index, convert keysArr[i] into a string using String().
  4. Check whether this string key already exists in result.
  5. If the key does not exist, insert the pair:

result[key] = valuesArr[i] 6. If the key already exists, do nothing because the first occurrence must be preserved. 7. Continue until all indices have been processed. 8. Return the completed object.

Why it works

The algorithm maintains the invariant that result contains exactly the first occurrence of every stringified key encountered so far. When a new key appears, it is added immediately. When a duplicate appears later, the key already exists in result, so the duplicate is ignored. Because every index is processed in order, the stored value always corresponds to the first occurrence, which matches the problem requirements.

Python Solution

from typing import List, Any

class Solution:
    def createObject(self, keysArr: List[Any], valuesArr: List[Any]) -> dict:
        result = {}

        for key, value in zip(keysArr, valuesArr):
            string_key = str(key)

            if string_key not in result:
                result[string_key] = value

        return result

The implementation starts by creating an empty dictionary called result. The zip() function allows both arrays to be traversed simultaneously.

For every key-value pair, the key is converted to a string using str(), which corresponds to JavaScript's String() behavior for the purposes of this problem.

The dictionary is then checked to determine whether the stringified key already exists. If it does not exist, the key-value pair is inserted. If it already exists, the insertion is skipped, preserving the first occurrence.

After all pairs have been processed, the dictionary is returned.

Go Solution

func createObject(keysArr []interface{}, valuesArr []interface{}) map[string]interface{} {
	result := make(map[string]interface{})

	for i := 0; i < len(keysArr); i++ {
		key := fmt.Sprint(keysArr[i])

		if _, exists := result[key]; !exists {
			result[key] = valuesArr[i]
		}
	}

	return result
}

The Go solution uses a map[string]interface{} to represent the resulting object.

Since keys may have different underlying types, fmt.Sprint() is used to convert each key into its string representation.

Go maps provide average O(1) lookup and insertion time, making the duplicate detection logic equivalent to the Python dictionary approach.

Unlike Python, Go requires explicit handling of generic values through interface{}. Otherwise, the algorithm remains identical.

Worked Examples

Example 1

Input

keysArr   = ["a", "b", "c"]
valuesArr = [1, 2, 3]
Iteration String Key Value Result
Start - - {}
0 "a" 1 {"a": 1}
1 "b" 2 {"a": 1, "b": 2}
2 "c" 3 {"a": 1, "b": 2, "c": 3}

Output

{"a":1,"b":2,"c":3}

Example 2

Input

keysArr   = ["1", 1, false]
valuesArr = [4, 5, 6]

After string conversion:

["1", "1", "false"]
Iteration String Key Value Action Result
Start - - - {}
0 "1" 4 Insert {"1": 4}
1 "1" 5 Duplicate, skip {"1": 4}
2 "false" 6 Insert {"1": 4, "false": 6}

Output

{"1":4,"false":6}

Example 3

Input

keysArr   = []
valuesArr = []
Iteration Result
Start {}

No elements are processed.

Output

{}

Complexity Analysis

Measure Complexity Explanation
Time O(n) Each key-value pair is processed exactly once
Space O(n) In the worst case, every key is unique and stored in the result

The algorithm performs one pass through the arrays. Each iteration performs a constant-time average dictionary or hash map lookup and possibly an insertion. Therefore, the total running time is linear in the number of elements. The output object may contain up to n unique keys, requiring linear additional space.

Test Cases

from typing import Any, List

class Solution:
    def createObject(self, keysArr: List[Any], valuesArr: List[Any]) -> dict:
        result = {}

        for key, value in zip(keysArr, valuesArr):
            string_key = str(key)

            if string_key not in result:
                result[string_key] = value

        return result

sol = Solution()

assert sol.createObject(["a", "b", "c"], [1, 2, 3]) == {
    "a": 1,
    "b": 2,
    "c": 3,
}  # basic unique keys

assert sol.createObject(["1", 1, False], [4, 5, 6]) == {
    "1": 4,
    "False": 6,
}  # duplicate after string conversion

assert sol.createObject([], []) == {}  # empty arrays

assert sol.createObject(["x", "x"], [1, 2]) == {
    "x": 1
}  # keep first duplicate

assert sol.createObject([True, "True"], [10, 20]) == {
    "True": 10
}  # duplicate after conversion

assert sol.createObject([1, 2, 3], [7, 8, 9]) == {
    "1": 7,
    "2": 8,
    "3": 9,
}  # numeric keys

assert sol.createObject([False, False, False], [1, 2, 3]) == {
    "False": 1
}  # many duplicates

assert sol.createObject(["a", "b", "a", "c"], [1, 2, 3, 4]) == {
    "a": 1,
    "b": 2,
    "c": 4,
}  # duplicate appears later

Test Summary

Test Why
["a","b","c"] Verifies normal unique-key behavior
["1",1,False] Verifies string conversion and duplicate detection
[] Verifies empty input handling
["x","x"] Verifies first occurrence is preserved
[True,"True"] Verifies duplicates after conversion
[1,2,3] Verifies numeric keys become strings
[False,False,False] Verifies repeated duplicates
["a","b","a","c"] Verifies later duplicates are ignored

Edge Cases

Empty Arrays

When both arrays are empty, there are no key-value pairs to process. A careless implementation might assume at least one element exists and perform invalid indexing operations. The presented solution simply performs zero iterations and returns an empty object.

Duplicate Keys After String Conversion

Different original values can become identical after conversion to strings. For example, "1" and 1 both become "1". An implementation that checks duplicates before conversion would incorrectly treat them as different keys. The solution converts every key first and then performs duplicate detection, ensuring correct behavior.

Multiple Repeated Duplicates

A key may appear many times throughout the array. The problem requires keeping only the value associated with the first occurrence. Because the algorithm inserts a key only when it is absent from the result object, all later occurrences are automatically ignored, regardless of how many times they appear.

Non-String Keys

Keys may be numbers, booleans, or other JSON-compatible values. Since object keys must ultimately be strings, failing to convert them can produce incorrect results. The solution explicitly converts every key before any lookup or insertion, guaranteeing consistent behavior and proper duplicate handling.