We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Create Object from Two Arrays

Number: 2861

Difficulty: Easy

Paid? Yes

Companies: N/A


Problem Description

Given two arrays keysArr and valuesArr of equal length, create a new object where each key-value pair is formed by keysArr[i] and valuesArr[i]. If a duplicate key (after converting to a string) appears later, it should be ignored and only the first occurrence maintained. If a key is not a string, it must be converted using String() before adding.


Key Insights

  • Iterate over the arrays simultaneously.
  • Convert each key to a string using String() (or equivalent in each language).
  • Use a data structure (like a set) to track keys that have already been added.
  • Only add a key-value pair if the key (after conversion) is not already present.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the arrays (each element is processed once).
Space Complexity: O(n), for storing the keys in an auxiliary set and the k-v pairs in the object.


Solution

The approach is to iterate index-by-index over keysArr and valuesArr. For each index, convert keysArr[i] to its string representation. Maintain a set of seen keys to check if the current key has been added before. If not, add the key and its corresponding value to the result object. This ensures that any duplicate key (after conversion to string) is ignored after its first occurrence. This method uses a hash set for fast O(1) lookups and yields an overall O(n) runtime.


Code Solutions

def create_object(keysArr, valuesArr):
    # Initialize an empty dictionary for the result.
    result = {}
    # Set to track keys that have already been added.
    seen_keys = set()
    
    # Process key-value pairs.
    for key, value in zip(keysArr, valuesArr):
        # Convert key to string.
        key_str = str(key)
        # Only add if key_str is not already seen.
        if key_str not in seen_keys:
            seen_keys.add(key_str)
            result[key_str] = value
    return result

# Example usage:
print(create_object(["a", "b", "c"], [1, 2, 3]))  # Output: {'a': 1, 'b': 2, 'c': 3}
print(create_object(["1", 1, False], [4, 5, 6]))  # Output: {'1': 4, 'false': 6}
← Back to All Questions