Coding interviews
Reveal answer and reasoning
An IEnumerable is a recipe for obtaining an enumerator, not necessarily a saved collection. The task asks for both sum and count from a repeatable source while making source visits visible. One version enumerates twice; the other materializes once. Both return the same values, but they deliberately trade a stored array for one fewer traversal. Ask whether the source is repeatable and whether the statistics must describe the same observation.
A lazy query over mutable state might produce different data on the second traversal. A snapshot can therefore provide semantic consistency in addition to reducing repeated source work, although concurrent writers still need a defined snapshot boundary.
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. Compare three implementations rather than assuming a copy is the only remedy: repeated enumeration, one materialized snapshot and one fused aggregate.
For a finite stream needed only once, the fused version can use constant extra state. If later consumers need individual values, that optimization may fail their actual requirements.
What a strong answer covers
- An IEnumerable is a recipe for obtaining an enumerator, not necessarily a saved collection.
- The local counter increments immediately before each yielded value, which makes it an observation of original-source production.
- Both versions are O(n) in big-O time because two times n remains linear.
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.