Shift security units left to protect the most population
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 Apr 2026. It tests greedy, arrays and strings.
Cities stand in a row, numbered 0 to n - 1. You are given an integer array population of length n (all values >= 0) and a binary string unit of the same length. unit[i] == '1' means city i starts with one security unit; '0' means it has none.
Each unit may do one of two things: stay in its city, or move exactly one city to the left (from i to i - 1). A unit in city 0 cannot move. Each unit moves at most once.
After all units are placed, a city is protected if it holds at least one unit. Several units in one city still protect it only once.
Implement:
def max_protected(population: list[int], unit: str) -> int
Return the largest possible total population of protected cities.
Constraints
0 <= n <= 10^5-
0 <= population[i] <= 10^9(the answer may need 64 bits) -
unitcontains only'0'and'1'
Example 1
population = [4, 1, 9]
unit = "011"
output = 13
Move the unit in city 1 to city 0 and keep the unit in city 2. Cities 0 and 2 are protected: 4 + 9 = 13.
Example 2
population = [2, 9, 9, 9]
unit = "0111"
output = 27
City 0 is the cheapest one to leave unprotected, so no unit moves: 9 + 9 + 9 = 27.
Clarifying questions
- Can a unit move only one city left, never right?
- Does a unit in city
0stay put? - Is an empty input answered with
0? - Is only the total returned, or also where each unit ends up?
What a strong answer covers
- Splits
unitinto maximal runs of'1'. A run covering citiesl..rwithl > 0hasr - l + 1units for ther - l + 2citiesl - 1..r: it can protect all of them but one, and any one can be the one left out. - So each such run adds the sum of those cities minus their minimum population; a run starting at city
0protects exactly its own cities. - One pass,
O(n)time andO(1)space, with 64-bit totals. A DP over cities with "a unit moved in from the right or not" also works. - Tests both examples, no units, all units, and alternating units.
Follow-ups
- Units may move left or right by one city.
- A unit may move up to
dcities to the left. - Each move has a cost, and the goal is protected population minus moving cost.
Where it's asked
- Amazon · Online assessment · Last asked Apr 2026Coding 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
