← Questions
Most equal values after shifting one subarray
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Aug 2025. It tests arrays, hashing and kadane.
You are given an integer array. You may perform at most one operation: pick a contiguous subarray and add the same integer delta (negative, zero or positive) to every element in it. Return the highest frequency any single value can reach afterwards, together with one operation that achieves it.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
max_equal_after_shift(a: list[int]) -> tuple[int, int, int, int]— returns(count, l, r, delta)with 0-based inclusivel <= r. If no shift helps, return a no-op such as(count, 0, 0, 0). Any optimal operation is accepted.
Example
max_equal_after_shift([2, 4, 6, 2, 4, 7]) -> (3, 1, 1, -2) # [2, 2, 6, 2, 4, 7]; shifting [4, 6, 2, 4]
# (l=1, r=4) by -2 also gives three 2s
max_equal_after_shift([1, 3, 1, 3, 3, 1]) -> (5, 1, 4, -2) # [1, 1, -1, 1, 1, 1]
max_equal_after_shift([5]) -> (1, 0, 0, 0)
Constraints
-
1 <= len(a) <= 10^4;-10^9 <= a[i] <= 10^9. -
deltamay be any integer, including 0.
Clarifying questions
- Is not using the operation allowed (so the answer is at least the current highest frequency)?
- Do you need the operation back, or only the count? If several are optimal, is any one fine?
- How many distinct values can the array hold?
What a strong answer covers
- The key observation: inside the window only one source value
wcan be turned into the targetv(withdelta = v - w), and anyvalready inside the window is lost. - For a fixed pair
(v, w), score +1 for eachw, -1 for eachv, 0 otherwise; the best window is a maximum-sum subarray (Kadane), and the result iscount(v)plus that sum. - Running Kadane only over the positions of
vandwkeeps the total work near O(n · d) forddistinct values instead of O(n · d²), with a note on when even that is too slow. - Keeping the no-op baseline and recovering
(l, r, delta)from the best window. - Testing against brute force over all windows and shifts on small arrays.
Follow-ups
- You may apply the operation twice, on two different subarrays.
- The shift is multiplication by a constant instead of addition.
- Only
deltain a given range[-d, d]is allowed.
Where it's asked
- Amazon · Online assessment · Last asked Aug 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
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
