Inversion of Object - Problem

Given a table containing key-value pairs, create an inverted table where the original keys become values and the original values become keys. When multiple keys have the same value, the inverted table should group those keys together.

Requirements:

  • Transform keys to values and values to keys
  • Handle duplicate values by grouping the corresponding keys
  • All values are guaranteed to be strings
  • Array indices should be treated as keys

Table Schema

KeyValuePairs
Column Name Type Description
id PK int Primary key identifier
key_name varchar The original key or index
value_content varchar The original value content
Primary Key: id
Note: Each row represents a key-value pair from the original object or array

Input & Output

Example 1 — Simple Object Inversion
Input Table:
id key_name value_content
1 name John
2 age 25
3 city NYC
Output:
inverted_key inverted_value
25 age
John name
NYC city
💡 Note:

Each key-value pair is inverted: the original values become the new keys, and the original keys become the new values. Since all values are unique, no aggregation is needed.

Example 2 — Handling Duplicate Values
Input Table:
id key_name value_content
1 a hello
2 b world
3 c hello
Output:
inverted_key inverted_value
hello a,c
world b
💡 Note:

When multiple keys have the same value ('hello'), the inverted result groups those keys together using comma separation. The value 'hello' maps to both 'a' and 'c', so the result shows 'a,c'.

Example 3 — Array Indices as Keys
Input Table:
id key_name value_content
1 0 apple
2 1 banana
3 2 apple
Output:
inverted_key inverted_value
apple 0,2
banana 1
💡 Note:

Array indices are treated as keys. The value 'apple' appears at indices 0 and 2, so it maps to '0,2' in the inverted result. The value 'banana' appears only at index 1.

Constraints

  • 1 ≤ number of key-value pairs ≤ 1000
  • All values are guaranteed to be strings
  • Keys can be either string names or array indices

Visualization

Tap to expand
Object Inversion: Key-Value TransformationOriginal DatakeyvalueahellobworldchelloGROUP BYvalueGroupedvaluekeyshelloa,cworldbINVERTFinal Resultkeyvaluehelloa,cworldbKeys → Values, Values → Keys
Understanding the Visualization
1
Input
Original key-value pairs table
2
Group By Value
Group rows by their value content
3
Aggregate Keys
Collect all keys for each value
4
Output
Inverted table with values as keys
Key Takeaway
🎯 Key Insight: Use GROUP BY with STRING_AGG to handle duplicate values when inverting key-value relationships
Asked in
Meta 15 Google 12 Amazon 8
23.4K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen