Coding interviews
Reveal answer and reasoning
Define a slice using a start index and a count, with an exclusive end implied by their relationship. A zero-length slice at the array end is valid; negative values, starts beyond the end and ranges extending past the array are invalid. The result is an independent array copy. The supplied function assumes a non-null array and validates the numeric bounds before constructing a span.
Write the accepted range as zero less than or equal to start, zero less than or equal to count, and count no greater than length minus start after start is known valid. The validation order matters because subtraction is safe only after the start bound has been established.
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. A returned copy has a useful ownership guarantee: later mutations to that copy do not change the original elements.
An array of reference-type elements would still share the referenced objects, however. Distinguish copying the container from deeply cloning every object when generalizing this integer-only helper.
What a strong answer covers
- Define a slice using a start index and a count, with an exclusive end implied by their relationship.
- Short-circuit evaluation rejects negative starts and starts beyond the length before evaluating the final difference.
- Validation is constant-time.
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.