How to create a utility to invert an object? | Frontend Problem Solving | JavaScript Interview Question
@Devtools Tech
In this question, you need to implement a function called invert
that takes an object
as input parameter and inverts it i.e. return an object where the keys as values and values as keys.
Specifications
- If the input is invalid then the function must throw a TypeError i.e. null/undefined.
- All keys and values are of type
String
. - Final object must maintain the original order of the keys.
- Object might contain duplicate values. Handle the duplicate values by appending the original position (index starting from
0
) of the key to the value. Please seeSyntax
section for examples. - Try to minimise the use of additional space required to create the final object.
- Try to minimise the time complexity.
Syntax
- Without duplicate values
const data = { 'a': 'one', 'b': 'two' };
const inverted = invert(data);
// prints { 'one': 'a', 'two': 1 }
console.log(inverted);
- With duplicate values
const data = { 'a': 'one', 'b': 'one' };
const inverted = invert(data);
// prints { 'one': 'a', 'one_1': 1 }
console.log(inverted);
Submission
Please start the timer before starting and finish your solution within 30-45 mins. Share your solution with us on Twitter or LinkedIn.