Ctrl K

Remove One to Even Out

Hard
You are given an array of positive integers values. Find the longest prefix (leading part) of the array from which you can delete **exactly one** element so that every number left in it occurs the same number of times. If nothing remains after the deletion, the condition counts as met. Return the length of that prefix.
Example 1
values=[4, 4, 7, 7, 9, 9, 9, 2] → 7

The prefix of length 7, [4, 4, 7, 7, 9, 9, 9]: remove one 9 and every number occurs twice. The whole array cannot be fixed with one removal.

Example 2
values=[5, 5, 5, 1, 1, 1, 8] → 7

Remove the 8 and both 5 and 1 occur three times each, so the whole array works: 7.

Example 3
values=[3, 3] → 2
Constraints
  • 2 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsComplete the Sudoku HardSmallest Absent Positive HardEvery Way to Space the Words HardStars on One Straight Line HardIslands After Each Landfill Hard
loading Python…
Input
values=[4, 4, 7, 7, 9, 9, 9, 2]
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 107 tests on the server, hidden ones included.