AO
Back

Minimum Replacements to Make Every Value Contiguous

Also reported as Minimum Operations to Make Array Contiguous

OAAsync OALast reported August 2026Medium Frequency

Problem Overview

The round: the coding half of Amazon's online assessment (one new-grad report gives it 40 minutes), next to an AI-assisted task in a code repository. Four candidates reported it between April and August 2026, three of them in the version below; nobody posted constraints or an example, so the examples here are ours. The function names are ours too.

Problem

You are given an array of integers. In one operation you pick two values x and y and replace every occurrence of x with y. Return the minimum number of operations after which the array is contiguous: each value's occurrences form one unbroken block, with no two equal values separated by a different value.

def minOperations(arr: list[int]) -> int: ...

Examples (ours)

[1, 1, 2, 2, 3]        -> 0   already contiguous
[1, 2, 1]              -> 1   replace 2 with 1 (or 1 with 2)
[1, 2, 1, 3, 2, 4]     -> 2   1, 2 and 3 must all become one value; 4 is fine

Reported variant: minimum cost. One candidate had the same operation with a different objective: an operation costs the number of elements it rewrites, and you return the minimum total cost. On [1, 2, 1, 2, 2] one operation is enough, but the cheapest is to rewrite the two 1s (cost 2) rather than the three 2s. Ask which objective you are given. The last two tests call the variant:

def minReplacementCost(arr: list[int]) -> int: ...

What Reports Emphasize

What candidates report: Three reports ask for the fewest replace-all operations; one asks for the fewest elements rewritten.; One candidate compressed runs of equal values, then merged greedily, and spent a while on edge cases; they say LeetCode 56 (Merge Intervals) helps.; The cost-variant candidate merged each value's first-to-last span with every span it overlaps, and charged each group its total count minus its largest count.

Our note (not from the reports): A merged group of d values needs d - 1 operations, so the operation count is the number of distinct values minus the number of groups. Ask which objective you have.

Practice

Write your own against 7 test cases, or read the worked solution — approach, complexity, and code that runs.

Prepping for Amazon with friends?

Send them this page. It is free to read, no account needed.

More Amazon Questions

Free preview

Every question in the Amazon catalog gets this depth

What you just read — canonical solution, follow-up arc, what passing candidates actually did — exists for all 57 Amazon questions, refreshed monthly from new candidate reports.

$59/mo — or $50/mo with the 3-month pass · cancel anytime
Amazon · OA · Reported 4× across candidate reports
Is this helpful?