Inversion of Object - Problem
Inversion of Object is a fundamental data transformation problem that challenges you to flip the relationship between keys and values in JavaScript objects or arrays.
Given an object or array
• Keys become values and values become keys
• For arrays, indices are treated as keys
• When multiple keys share the same value, the inverted object maps that value to an array of all corresponding keys
This problem simulates real-world scenarios like creating reverse lookup tables, building search indices, or transforming database query results for efficient access patterns.
Given an object or array
obj, return an inverted version invertedObj where:• Keys become values and values become keys
• For arrays, indices are treated as keys
• When multiple keys share the same value, the inverted object maps that value to an array of all corresponding keys
This problem simulates real-world scenarios like creating reverse lookup tables, building search indices, or transforming database query results for efficient access patterns.
Input & Output
example_1.py — Basic Object Inversion
$
Input:
{"a": "1", "b": "2", "c": "3"}
›
Output:
{"1": "a", "2": "b", "3": "c"}
💡 Note:
Simple one-to-one mapping where each value becomes a key mapped to its original key. No duplicates exist.
example_2.py — Handling Duplicates
$
Input:
{"a": "1", "b": "2", "c": "1"}
›
Output:
{"1": ["a", "c"], "2": "b"}
💡 Note:
Value "1" appears twice (keys "a" and "c"), so it maps to an array ["a", "c"]. Value "2" appears once, so it maps to string "b".
example_3.py — Array Input
$
Input:
["hello", "world", "hello"]
›
Output:
{"hello": ["0", "2"], "world": "1"}
💡 Note:
Array indices become keys: index 0 and 2 have "hello", so "hello" maps to ["0", "2"]. Index 1 has "world", so "world" maps to "1".
Constraints
- 1 ≤ Object.keys(obj).length ≤ 104
- All values in the object are strings only
- Keys can be any valid object key (string or number)
- For arrays, indices are treated as string keys ("0", "1", etc.)
Visualization
Tap to expand
Understanding the Visualization
1
Original Structure
Start with object mapping keys to values
2
Single Pass Processing
For each key-value pair, add value->key to result
3
Handle Duplicates
When value already exists, convert to array or extend array
4
Complete Inversion
Final result has all values as keys, mapped to original keys
Key Takeaway
🎯 Key Insight: One-pass hash table approach efficiently handles both unique values and duplicates by checking existence and converting to arrays when needed.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code