← Questions

Most distinct values of B[i] mod A[i]

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's online assessment, last asked Sep 2025. It tests greedy, sorting and math.

You get an array A of n positive integers. You choose any integer array B of the same length, and then compute C[i] = B[i] mod A[i] for every i. Return the largest number of distinct values C can contain.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • max_distinct_remainders(a: list[int]) -> int

Example

max_distinct_remainders([2, 7, 11, 15])  ->  4    # remainders 0, 1, 2, 3 are each reachable
max_distinct_remainders([1, 1, 1])       ->  1    # mod 1 is always 0
max_distinct_remainders([1, 2, 2, 5])    ->  3    # 0 (mod 1), 1 (mod 2), then the other 2 can only give 0 or 1; 2 (mod 5)
max_distinct_remainders([3, 3, 3, 3])    ->  3    # only 0, 1 and 2 exist mod 3

Constraints

  • 0 <= n <= 10^5; 1 <= A[i] <= 10^9.

Clarifying questions

  • Can B[i] be any integer, including negative? (Yes, so C[i] can be any value from 0 to A[i] - 1.)
  • Is it the count of distinct values only, or also a choice of B?

What a strong answer covers

  • The reduction: since B[i] is free, index i can take any value in [0, A[i] - 1], so the task is to give each index a value from its range, maximising the number of distinct values.
  • Greedy: sort A ascending and hand out 0, 1, 2, … in order; an index takes the next value cur only if cur < A[i]. Small ranges go first because they can only use small values. O(n log n).
  • Why the answer is also bounded by n and by the largest A[i].
  • Building an actual B (B[i] = cur for the indices that took a value).

Follow-ups

  • Each B[i] must lie in a given range [L_i, R_i].
  • Maximise the sum of the distinct remainders instead of their count.

Where it's asked

  • Amazon · Online assessment · Last asked Sep 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

greedy · sorting · math

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding