Sanjaay Gowda T S
All practice questions

ORIGINAL TECHNICAL PRACTICE

Make input mutation an explicit contract

Software engineeringEasyConcept

A helper sorts an array before calculating a result. What would you discuss before using it in a shared codebase?

Written for independent practice. The model answer presents one approach; clarify constraints and explain alternatives.

A REASONED APPROACH

Model answer.

Sorting may mutate the caller’s array, depending on the language and API. Decide whether mutation is intentional, document the contract, and use a copy when the caller’s order must remain available.

Work through it

  1. Inspect the language’s sorting API and comparator rules. In JavaScript, a numeric comparator is needed for numeric ascending order with Array.sort.
  2. If preserving input is required, copy the relevant data before sorting. A shallow copy protects the outer array’s order but not mutations to nested objects.
  3. Write tests that compare the original input before and after the call, as well as result correctness. Include repeated references and nested records when those are supported.

Tradeoffs to discuss

  • Copying requires additional memory and time. An in-place API can be appropriate for large data when its ownership and mutation semantics are explicit.

Common pitfalls

  • Assuming a shallow copy recursively clones records hides shared-object side effects. A comparator must be consistent; an inconsistent comparator can produce unreliable ordering.

KEEP PRACTISING

Related questions.

Keep learning beyond the interview.

Explore the Learning Hub