FastPrepPreference List Majority Winner

Preference List Majority Winner

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Each row of preferences represents one voter and lists that voter's acceptable candidates from most preferred to least preferred.

Consider complete vote assignments in depth-first order: process voters from left to right, and for each voter try the candidates in that voter's listed order. A candidate wins an assignment when they receive strictly more than half of all votes.

Return the winner of the first assignment in this order that has a majority. Return -1 if no assignment can produce a majority.

Function

rankedChoiceWinner(preferences: int[][]) → int

Examples

Example 1

preferences = [[1],[1],[2]]return = 1

The only assignment gives candidate 1 two of the three votes, which is a strict majority.

Example 2

preferences = [[1],[1],[2],[2],[3,1]]return = 1

The all-first-choice assignment has no majority. Trying the fifth voter's next choice gives candidate 1 three of five votes.

Example 3

preferences = [[1,2],[1,2],[2,1],[2,3],[3,1]]return = 1

The first choices split 2-2-1. The earliest winning assignment keeps the first four choices and uses candidate 1 as the fifth voter's second choice.

Constraints

  • 1 <= preferences.length <= 20
  • 1 <= preferences[i].length <= 8
  • 1 <= preferences[i][j] <= 1000000
  • Each voter's preference list contains distinct candidates.
  • The product of all preference-list lengths is at most 1000000.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int rankedChoiceWinner(int[][] preferences) {
    // Write your code here.
}
preferences[[1],[1],[2]]
expected1
Checking account…