← Questions
Most distinct values after shifting each element by at most k
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in SpaceXAI's technical phone screen, last asked Jan 2026. It tests greedy and sorting.
You are given an integer array nums and a non-negative integer k. You may add any integer from -k to k to each element, chosen independently for each element, and each element is changed at most once. Return the largest number of distinct values the array can contain afterwards.
Interface
Unless you agree on a different interface with the interviewer, assume:
max_distinct(nums: list[int], k: int) -> int
Example
max_distinct([1, 2, 2, 3, 3, 4], 2) -> 6 # e.g. -1, 0, 1, 2, 3, 4 (1-2, 2-2, 2-1, 3-1, 3+0, 4+0)
max_distinct([4, 4, 4, 4], 1) -> 3 # 3, 4, 5; the fourth 4 must repeat one of them
max_distinct([1, 1, 5], 0) -> 2
Constraints
1 <= len(nums) <= 10^5-
1 <= nums[i] <= 10^9,0 <= k <= 10^9
Clarifying questions
- Is the change per element any integer in
[-k, k], including 0? - Can values become negative or exceed the original range?
- Is the answer just the count, or also one resulting array?
- Must the offsets themselves be distinct, or only the final values?
What a strong answer covers
- Sort, then greedily give each element the smallest value it can reach that is above the last value used:
max(prev + 1, x - k), counted only if it is<= x + k. - Why the greedy is optimal: each element takes the leftmost free slot in its interval
[x - k, x + k], an interval-scheduling exchange argument. - O(n log n) time for the sort, O(1) extra space.
- Edge cases:
k = 0(the answer is the number of distinct values), all equal, very largek(the answer isn), and values near the integer limits. - Tests against a brute force on small arrays.
Follow-ups
- Return one array that reaches the maximum.
- Each element has its own
k[i]. - Elements arrive as a stream: maintain the answer after each insertion.
- The offsets used must also be pairwise distinct.
Where it's asked
- SpaceXAI · Technical phone screen · Last asked Jan 202645 min · Live applied coding on a shared platform such as CoderPad · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
