invertObject

Medium · Object Manipulation · 3 test cases

Given an object, create a new object where the keys become the values and the values become the keys. If multiple original keys have the same value, the last key will overwrite the previous ones.

Examples

invertObject({a: 1, b: 2, c: 3}) → {1: 'a', 2: 'b', 3: 'c'}
invertObject({name: 'John', role: 'user'}) → {John: 'name', user: 'role'}
invertObject({a: 1, b: 2, c: 1}) → {1: 'c', 2: 'b'}

Starter code

function invertObject(obj) {

}

Complexity of the optimal solution

Time O(n), space O(n). The function iterates through all 'n' properties of the input object once. It creates a new object that will also have 'n' properties in the case where all values are unique. Therefore, both time and space complexity are linear.

Solve invertObject in the browser