FunctionRacerProblemsRace

Longest Fair Prefix

HardHash mapsPython, JavaScript, TypeScript, Java, C++

A list is fair when every distinct value in it appears the same number of times; the empty list is fair too.

Return the length of the longest prefix of nums (its first n items, for some n) that becomes fair after deleting exactly one of its items. Deleting the only item of a one-item prefix leaves the empty list, which is fair, so the answer is at least 1 whenever nums is not empty. The empty list gives 0.

Example 1

nums [2,2,1,1,5,3,3,5]
returns 7

The first 7 items are 2, 2, 1, 1, 5, 3, 3; deleting the 5 leaves every value appearing twice. The whole list cannot be fixed with one deletion.

Example 2

nums [1,1,1,2,2,2,3,3,3,4,4,4,5]
returns 13

Deleting the 5 at the end leaves 1, 2, 3 and 4 each three times.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Hash maps problems