KatInterview

Python Tuples, Dict Internals, and Error Handling in a Record Store

Data Structure DesignModel answer
EasyModel answerData Structure Designpythonimmutabilitytuples

Last updated

Answer three fundamentals questions: tuple rebinding and shallow immutability, how a hash table handles insert, lookup, update and delete, and where to raise and catch errors in a record class.

You are asked three connected fundamentals questions in the context of a small Python class that manages records. Answer each in prose, with short code where it helps.

Part 1: Immutability and tuples

  1. Define an immutable object. How is it different from a name that happens to point at one?
  2. Suppose items = (3,) and a second name, backup = items. You then run items += (1, 2). What are items and backup afterwards, and why?
  3. Compare the costs of indexing a tuple, testing membership with in, and concatenating two tuples.
  4. If a tuple contains a list, is the tuple deeply immutable? Explain.

Part 2: Hash table behavior

Explain how a hash table supports inserting, finding, updating, and removing an entry in a dictionary. Cover:

  • hashing and how a hash maps to a slot,
  • collisions and at least one way to resolve them,
  • resizing,
  • expected versus worst-case cost,
  • why keys need a stable hash and a consistent equality.

Do not assume every language or every Python implementation uses the same collision strategy.

Part 3: Errors in a record-management class

The class exposes insert, update, and remove. Explain:

  • when each method should raise an error,
  • how a caller can catch an expected failure around a call,
  • what an exception should and should not do to the stored data.

Give one concrete example of an expected error, and explain why catching every exception silently is harmful.

Assumptions

  • Use ordinary Python semantics. Tuple elements are references to objects.
  • Constant-time claims for key operations assume hashing and equality comparison have bounded cost.
  • Behavior on duplicate inserts and missing keys is an API decision. State the choice you make rather than assuming one.

Clarifying questions worth raising

  • Should inserting an existing key overwrite it or be rejected?
  • Is a missing record an expected user error or an internal bug?

Hints

Hint 1

Separate the object from the name. Augmented assignment on an immutable type cannot change the object, so think about what the name does instead.

Hint 2

For the hash table, trace one insert end to end: compute the hash, pick a slot, compare on collision, and decide when to grow. Then ask what breaks if a key's hash changes after insertion.

Hint 3

For errors, ask who owns the decision. The class protects its invariants and reports violations; the caller decides whether to retry, show a message, or give up. Think about whether data is half-modified when an exception fires.