Minimum Cost to Move Chips to The Same Position

EasyGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n chips on a number line; position[i] is where chip i sits (several chips may share a position). You want all chips on the same position. In one move you can shift a single chip by 2 in either direction for free, or by 1 in either direction at a cost of 1. Return the minimum total cost to gather all chips at one position.

Examples

Input: position = [1,2,3]
Output: 1
Move chip 3 to position 1 for free, then move chip 2 to position 1 for a cost of 1.
Input: position = [2,2,2,3,3]
Output: 2
Moving the two chips at 3 onto 2 costs 1 each.
Input: position = [1,1000000000]
Output: 1
The chips are an odd distance apart, so whichever chip moves pays for exactly one 1-step move.

Constraints

  • 1 <= position.length <= 100
  • 1 <= position[i] <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems