Junior · Explain · Contracts

Which contract decisions must be settled before aggregating the quantity rows, and what costs are hidden by saying dictionary lookup is constant-time?

Think through your answer before opening the explanation.

Coding interviews

Reveal answer and reasoning

Aggregate quantities by an exact ordinal key. Empty keys and negative quantities are invalid; zero is permitted. Repeated keys add into a checked long total. The result does not promise dictionary enumeration order, so the display explicitly sorts keys. This contract distinguishes Tea from tea rather than silently applying a culture or a case-folding rule. The useful first questions are whether case distinguishes products, whether negative rows represent corrections, and whether the result order matters.

Record those answers before choosing a data structure. Here a dictionary represents membership and totals, while the final ordering is a presentation step with its own cost and comparer.

For n rows and u distinct keys, aggregation uses expected O(n) dictionary operations and O(u) stored totals; string hashing also examines key text. Display sorting costs O(u log u) comparisons and additional sorting storage. Checked long arithmetic rejects overflow rather than silently changing an otherwise valid total. Count key storage and the final ordered enumeration separately from the row array supplied by the caller.

The algorithm does not clone each key string, but retaining dictionary entries retains references to those strings. If key lengths vary widely, describing work only in row count hides significant hashing and comparison work.

What a strong answer covers

  • Aggregate quantities by an exact ordinal key.
  • A loop invariant makes the reasoning concise: after each accepted row, every stored total equals the sum of quantities for that exact key in the processed prefix.
  • For n rows and u distinct keys, aggregation uses expected O(n) dictionary operations and O(u) stored totals; string hashing also examines key text.

Common pitfall

Case normalization, negative adjustments and blank-key handling are business decisions, not harmless implementation details. Returning a partially filled dictionary after an exception would create a different contract. Local construction makes failure discard the unpublished result; it does not provide a database transaction or a thread-safe aggregation service.

Follow-up questions

  1. Add zero-quantity rows and an empty key as separate cases. Predict that zero preserves the total while an empty key fails. Hint: validity and contribution are different questions, so do not use quantity greater than zero as the only admission rule.
  2. How would ordinal-ignore-case grouping change the sample and the displayed representative key policy?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions