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

Inversion of Object

Number: 2925

Difficulty: Easy

Paid? Yes

Companies: N/A


Problem Description

Given an object or an array obj, return an inverted object invertedObj in which the keys of obj become the values in invertedObj and the values of obj become the keys. For arrays, the indices are treated as keys. In case of duplicate values in obj, the corresponding key in invertedObj should map to an array of all keys that produced that value.


Key Insights

  • The input may be either an object or an array.
  • For arrays, use the indices (as strings) as keys.
  • When multiple keys in the input have the same value, store all corresponding keys in an array.
  • Conversion of keys to string is necessary to keep the inverted format consistent.

Space and Time Complexity

Time Complexity: O(n), where n is the number of key-value pairs in the input. Space Complexity: O(n), to store the inverted mapping.


Solution

Use a single pass over all entries in the given object or array. For each key-value pair, check if the value is already present as a key in the inverted object:

  • If not, add an entry mapping the value to the key (converted to a string).
  • If the value already exists, check if the current value is a list; if not, convert it into a list and then append the new key. This approach easily handles duplicates and maintains the required data structure transformation.

Code Solutions

def invert_object(obj):
    inverted_obj = {}
    # Determine if input is a list or dictionary
    if isinstance(obj, list):
        items = enumerate(obj)  # Use indices as keys for list elements
    else:
        items = obj.items()
    
    # Iterate over each key-value pair
    for key, value in items:
        key_str = str(key)  # Convert key to string
        if value in inverted_obj:
            # If already present, check the type and update accordingly
            if not isinstance(inverted_obj[value], list):
                # Convert to list if it is not already
                inverted_obj[value] = [inverted_obj[value]]
            inverted_obj[value].append(key_str)
        else:
            inverted_obj[value] = key_str
    return inverted_obj

# Example usage
input_obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
print(invert_object(input_obj))
← Back to All Questions