L2 · Working engineerDictionaries & hashing~5 min · 4 tests#32

Invert a Dictionary (Swap Keys and Values)

Swap keys and values of a Python dictionary with a dict comprehension, and handle duplicate values by grouping keys. O(n) time with live tests.

The problem

Return a new dict whose keys are the values of d and whose values are the lists of keys that had them, in insertion order.

{'a': 1, 'b': 2, 'c': 1} → {1: ['a', 'c'], 2: ['b']}. Grouping keeps duplicate values from silently overwriting each other.

Examples

  1. Example 1

    Input

    invert({'a': 1, 'b': 2, 'c': 3})

    Expected output

    {1: ['a'], 2: ['b'], 3: ['c']}
  2. Example 2

    Input

    invert({'a': 1, 'b': 2, 'c': 1})

    Expected output

    {1: ['a', 'c'], 2: ['b']}

+ 2 hidden tests on Submit.

Edge cases to ask about

  • Duplicate values
  • Unhashable values (lists)
  • Empty dict

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · invert
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    {v: k for k, v in d.items()}O(n)O(n)Fine only when values are unique — duplicates overwrite.
    bestGroup with setdefaultO(n)O(n)Every key survives.
    Walkthrough of the optimal approach (try it yourself first)

    The one-line comprehension {v: k for k, v in d.items()} is the answer most people give — and it silently loses data when two keys share a value. Grouping keys into lists with setdefault keeps everything. Mention that values must be hashable to become keys.

    Complexity: O(n) time, O(n) space. One pass over the items; the new dict stores every key once.

    Reveal the reference solution
    def invert(d):
        out = {}
        for k, v in d.items():
            out.setdefault(v, []).append(k)
        return out

    Follow-ups interviewers ask

    • Assume unique values — write the one-liner.
    • Raise an error on duplicates instead.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Invert a Dictionary (Swap Keys and Values) in Python?

    The optimal solution runs in O(n) time and O(n) auxiliary space. One pass over the items; the new dict stores every key once.

    What is the brute-force approach, and how do you optimise it?

    {v: k for k, v in d.items()}: O(n) time, O(n) space. Fine only when values are unique — duplicates overwrite. Group with setdefault: O(n) time, O(n) space. Every key survives.

    What follow-up questions do interviewers ask about Invert a Dictionary (Swap Keys and Values)?

    Assume unique values — write the one-liner. Raise an error on duplicates instead.