Coding interviews
Reveal answer and reasoning
A bounded statistics API can accept a maximum element count, stop with a named over-limit failure and dispose its enumerator through a using scope. It should say whether partial statistics are observable after failure. Returning a result only on successful completion preserves a simple all-or-error contract without retaining every input value.
Both versions are O(n) in big-O time because two times n remains linear. The snapshot version allocates O(n) additional storage, whereas a fused one-pass sum-and-count loop can use O(1) auxiliary state for this task. Source cost and repeatability can matter more than the asymptotic label. A second enumeration might perform I/O again, observe changed values or be unsupported. Calling ToArray everywhere is not a free optimization: it changes evaluation timing and retains all items.
An array visit counter is evidence about traversal count, not proof of zero allocation or a performance benchmark.
Review the claimed optimization along three axes: source traversals, retained storage and result semantics. The supplied output proves six original visits versus three while both versions compute twelve and three. It proves neither allocation freedom nor universal speed. A good answer explains why big-O can remain linear despite a meaningful reduction in costly traversal, then considers a fused aggregate when values need not be retained.
For one-shot or changing inputs, correctness can determine the design before performance does. That distinction is more useful in an interview than replacing every query with an array by habit.
What a strong answer covers
- A bounded statistics API can accept a maximum element count, stop with a named over-limit failure and dispose its enumerator through a using scope.
- Both versions are O(n) in big-O time because two times n remains linear.
- A second enumeration might perform I/O again, observe changed values or be unsupported.
Common pitfall
A second enumeration might perform I/O again, observe changed values or be unsupported. Calling ToArray everywhere is not a free optimization: it changes evaluation timing and retains all items. An array visit counter is evidence about traversal count, not proof of zero allocation or a performance benchmark.
Follow-up questions
- Replace the snapshot with one foreach loop that accumulates sum and count using checked arithmetic. Hint: no downstream consumer needs the individual elements here. Verify the same twelve and three while keeping source visits at three.
- What should happen if a one-shot source throws when a second enumerator is requested?
Self-review
Choose what to revisit. These marks are your own assessment and are separate from lesson completion.