Coding interviews
Reveal answer and reasoning
A read-only span prevents writes through that view but does not freeze the underlying array. Its lifetime cannot be stored in arbitrary heap objects, and callers must not assume snapshot consistency. A clear API can offer both a copying method and a borrowed-view method with distinct names and documented ownership requirements.
Validation is constant-time. Copying count elements takes O(count) time and O(count) result storage. Returning a span instead would change lifetime and aliasing constraints, while returning an array makes ownership simple. Auxiliary state is constant beyond the required copy; the input remains unchanged. Using start + count <= length without addressing overflow is not equivalent for arbitrary integer arguments. Off-by-one errors also appear when callers confuse count with an inclusive final index.
Null handling must be made explicit if this helper becomes a public API rather than relying on a later accidental exception.
The correctness argument is a numeric-bound proof followed by a well-defined copy operation. The interview answer should mention the exclusive end, the valid empty suffix and the reason for avoiding unchecked start-plus-count arithmetic. It should also account for required output allocation instead of calling the method constant-space. A useful review includes an aliasing test: modify the returned array and verify the original remains intact.
When proposing a span optimization, explain the changed lifetime and mutation contract first. Lower allocation is a tradeoff with callers, not an unconditional improvement over an owned result.
What a strong answer covers
- A read-only span prevents writes through that view but does not freeze the underlying array.
- Validation is constant-time.
- Using start + count <= length without addressing overflow is not equivalent for arbitrary integer arguments.
Common pitfall
Using start + count <= length without addressing overflow is not equivalent for arbitrary integer arguments. Off-by-one errors also appear when callers confuse count with an inclusive final index. Null handling must be made explicit if this helper becomes a public API rather than relying on a later accidental exception.
Follow-up questions
- Add start equal to length with count one, and start zero with count equal to length. Hint: one crosses the exclusive end and one copies the entire array. Verify that changing the returned array does not mutate the source.
- How would the ownership claim change for an array whose elements are mutable reference objects?
Self-review
Choose what to revisit. These marks are your own assessment and are separate from lesson completion.