Check Invertible Mapping for Duplicate Values in Python
Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.
Python code
20 linesdef invertible_after_dedup(pairs):
"""
Check whether a set of (key, value) pairs is invertible,
i.e., no duplicate values exist for different keys.
"""
seen = {}
for key, value in pairs:
if value in seen and seen[value] != key:
return False, f"Duplicate value '{value}' for keys '{seen[value]}' and '{key}'"
seen[value] = key
return True, "All values are unique"
if __name__ == "__main__":
data = [("a", 1), ("b", 2), ("c", 1)]
ok, msg = invertible_after_dedup(data)
print(f"Invertible: {ok} — {msg}")
data2 = [("x", 10), ("y", 20), ("z", 30)]
ok2, msg2 = invertible_after_dedup(data2)
print(f"Invertible: {ok2} — {msg2}")
Output
Invertible: False — Duplicate value '1' for keys 'a' and 'c'
Invertible: True — All values are unique
How it works
The function iterates through each (key, value) pair and stores the value as a key in a dictionary, mapping to the original key. On subsequent pairs, if the same value appears and the stored key differs, it immediately returns False, indicating non-invertibility. If no duplicates are found, it returns True. This algorithm runs in O(n) time and O(n) space, making it efficient for large datasets. The function also provides a descriptive message for debugging, helping identify which duplicated value and keys caused the failure.
Common mistakes
- Forgetting to check if the existing key is different, which would incorrectly flag identical keys as duplicates.
- Overwriting seen[value] without first verifying, causing missed duplicate detections.
- Assuming duplicate values are always an error without considering same-key repeats.
Variations
- Use a set to track seen values, but lose the ability to report which keys conflict.
- Return only a boolean if you don't need diagnostic messages.
Real-world use cases
- Validating that a user-to-email mapping has unique emails before saving to a database.
- Checking that a config file maps each port to exactly one service to avoid conflicts.
- Verifying that API response IDs are unique when building an index from fetched data.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Compare Two Dictionaries in Python easy
- Convert Lists and Dictionaries to Sets in Python easy
Keep learning
Related tutorials and quizzes for this topic.