Talentd
FleetCode
Make and follow sheets.Sign in

Rank Teams by Votes solution and explanation

MediumArrayCountingHash TableSorting6 min read60.1% acceptanceUpdated 9 Apr 2026
1366. Rank Teams by Votes (LeetCode)hakunamatasq · 11:19 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. 1366. Rank Teams by Votes (LeetCode)hakunamatasq · 11:19 · 6K views
  2. Leetcode (1366) rank teams by votes using comparatorsHarshavardhan · 5:25 · 3K views
  3. 1366. Rank Teams by VotesMuerde un zombie · 14:20 · 2K views
  4. Rank Teams by Votes - Tricky Sorting Problem in PythonPrograamer (A Programmer) · 6:13 · 2K views
  5. 1366 Rank Teams by Votes(Python & sorting & full walkthru)AlgBreaker · 3:19 · 1K views
  6. Rank Teams by Votes | LeetCode-1366byteprint · 40:09 · 1K views
  7. Leetcode 1366: Rank Teams by VotesMike the Coder · 1:48:28 · 1K views
  8. Leetcode 1366. Rank Teams by Votes (sorting)LetsCode · 8:59 · 916 views
  9. 小飞羊 LeetCode 1366. Rank Teams by Votes [套路得人薪C++]Willy小飞羊 DJ · 4:45 · 797 views
  10. 【Leetcode Premium 24/30】1366. Rank Teams by Votes (~Medium) Recommended.思臉AI · 6:53 · 195 views

The problem

In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.

The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.

You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.

Return a string of all teams sorted by the ranking system.

Example 1:

Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: 
Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.
Team B was ranked second by 2 voters and ranked third by 3 voters.
Team C was ranked second by 3 voters and ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team, and team B is the third.

Example 2:

Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation:
X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position. 

Example 3:

Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter, so their votes are used for the ranking.

Constraints:

  • 1 <= votes.length <= 1000
  • 1 <= votes[i].length <= 26
  • votes[i].length == votes[j].length for 0 <= i, j < votes.length.
  • votes[i][j] is an English uppercase letter.
  • All characters of votes[i] are unique.
  • All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.

Approach overview

Problem Overview: Each voter submits a ranking of teams. Higher positions carry more weight than lower ones. The task is to aggregate all votes and return the final team order based on how many first-place, second-place, third-place votes, and so on each team receives.

Approach 1: Counting Votes by Position (O(v * n + n log n * n) time, O(n^2) space)

The key observation: rankings are decided lexicographically by vote counts at each position. For example, if two teams have the same number of first-place votes, compare second-place votes, then third-place votes. Create a count[team][position] structure that records how many times each team appears at each ranking position across all votes. Iterate through every vote string and increment the appropriate counter.

Once the counting phase is complete, sort the list of teams. The sorting comparator checks vote counts from position 0 to n-1. The team with more votes at the earliest differing position ranks higher. If two teams have identical counts at every position, break the tie using the team letter (lexicographical order). This approach works well because the number of teams is small (at most 26), making the comparison cost manageable during sorting.

The algorithm relies heavily on array indexing for vote storage and counting frequency occurrences per position. Sorting then determines the final ranking.

Approach 2: Using a Custom Comparator (O(v * n + n log n * n) time, O(n^2) space)

This method builds the same vote frequency matrix but focuses on designing a comparator that directly compares two teams during sorting. Instead of preprocessing rankings into a separate structure, the comparator checks their vote distribution arrays position by position whenever the sorting algorithm compares them.

The comparator logic: iterate through all ranking positions and return the team with the higher count at the first mismatch. If all counts match, return the lexicographically smaller team ID. Languages like Java, Python, and C++ make this clean using custom comparison functions or key transformations.

This approach emphasizes sorting behavior and comparison logic. It mirrors how ranking systems work in real competitions where multiple tie-breaking layers exist.

Recommended for interviews: The counting-by-position approach is what interviewers usually expect. It shows that you recognized the lexicographic ranking rule and converted it into a structured frequency matrix before sorting. Implementing the custom comparator on top of that matrix demonstrates strong understanding of string iteration, counting, and multi-key sorting. Brute force reasoning about vote comparisons shows intuition, but the counting strategy demonstrates algorithmic clarity.

Approach 1: Counting Votes by Position

This approach involves counting the votes each team receives for each position. We store these counts in a dictionary, where each team has a list representing its vote count for each position. Then, by sorting the teams based on these counts (and alphabetically in case of ties), we can determine the final ranking.

from typing import List

def rankTeams(votes: List[str]) -> str:
    from collections import defaultdict
    vote_count = defaultdict(lambda: [0] * len(votes[0]))
    for vote in votes:
        for i, team in enumerate(vote):
            vote_count[team][i] += 1
    teams = list(votes[0])
    teams.sort(key=lambda x: (vote_count[x], -ord(x)), reverse=True)
    return ''.join(teams)

# Example use
votes = ["ABC", "ACB", "ABC", "ACB", "ACB"]
print(rankTeams(votes))
import java.util.*;

public class Solution {
    public String rankTeams(String[] votes) {
        int numTeams = votes[0].length();
        int[][] voteCount = new int[26][numTeams];
        for (String vote : votes) {
            for (int i = 0; i < numTeams; i++) {
                voteCount[vote.charAt(i) - 'A'][i]++;
            }
        }
        List<Character> teams = new ArrayList<>();
        for (char c : votes[0].toCharArray()) {
            teams.add(c);
        }
        Collections.sort(teams, (a, b) -> {
            for (int i = 0; i < numTeams; i++) {
                if (voteCount[a - 'A'][i] != voteCount[b - 'A'][i]) {
                    return voteCount[b - 'A'][i] - voteCount[a - 'A'][i];
                }
            }
            return a - b;
        });
        StringBuilder result = new StringBuilder();
        for (char c : teams) {
            result.append(c);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        String[] votes = {"ABC", "ACB", "ABC", "ACB", "ACB"};
        System.out.println(sol.rankTeams(votes));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

string rankTeams(vector<string>& votes) {
    int numTeams = votes[0].size();
    vector<vector<int>> voteCount(26, vector<int>(numTeams, 0));
    for (string& vote : votes) {
        for (int i = 0; i < numTeams; ++i) {
            voteCount[vote[i] - 'A'][i]++;
        }
    }
    string teams = votes[0];
    sort(teams.begin(), teams.end(), [&](char a, char b) {
        for (int i = 0; i < numTeams; ++i) {
            if (voteCount[a - 'A'][i] != voteCount[b - 'A'][i]) {
                return voteCount[a - 'A'][i] > voteCount[b - 'A'][i];
            }
        }
        return a < b;
    });
    return teams;
}

int main() {
    vector<string> votes = {"ABC","ACB","ABC","ACB","ACB"};
    cout << rankTeams(votes) << endl;
    return 0;
}
function rankTeams(votes) {
    const len = votes[0].length;
    const voteCount = {};
    for (const vote of votes) {
        for (let i = 0; i < len; i++) {
            const team = vote[i];
            if (!voteCount[team]) {
                voteCount[team] = Array(len).fill(0);
            }
            voteCount[team][i]++;
        }
    }
    const teams = votes[0].split('');
    teams.sort((a, b) => {
        for (let i = 0; i < len; i++) {
            if (voteCount[a][i] !== voteCount[b][i]) {
                return voteCount[b][i] - voteCount[a][i];
            }
        }
        return a < b ? -1 : 1;
    });
    return teams.join('');
}

console.log(rankTeams(["ABC", "ACB", "ABC", "ACB", "ACB"]));
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_TEAMS 26

int compare(const void *a, const void *b, void *param) {
    char teamA = *(char *)a;
    char teamB = *(char *)b;
    int (*votes)[MAX_TEAMS] = param;
    for (int i = 0; i < MAX_TEAMS; i++) {
        if (votes[teamA-'A'][i] != votes[teamB-'A'][i]) {
            return votes[teamB-'A'][i] - votes[teamA-'A'][i];
        }
    }
    return teamA - teamB;
}

char* rankTeams(char **votes, int votesSize) {
    int len = strlen(votes[0]);
    int voteCount[MAX_TEAMS][MAX_TEAMS] = {{0}};
    char teams[MAX_TEAMS + 1];
    for (int i = 0; i < len; i++) {
        teams[i] = votes[0][i];
    }
    teams[len] = '\0';
    
    for (int i = 0; i < votesSize; i++) {
        for (int j = 0; j < len; j++) {
            voteCount[votes[i][j]-'A'][j]++;
        }
    }

    qsort_r(teams, len, sizeof(char), compare, voteCount);
    return strdup(teams);
}

int main() {
    char *votes[] = {"ABC","ACB","ABC","ACB","ACB"};
    int votesSize = 5;
    char *result = rankTeams(votes, votesSize);
    printf("%s\n", result);
    free(result);
    return 0;
}
using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public string RankTeams(string[] votes) {
        int numTeams = votes[0].Length;
        var voteCount = new int[26, numTeams];
        foreach (string vote in votes) {
            for (int i = 0; i < numTeams; i++) {
                voteCount[vote[i] - 'A', i]++;
            }
        }
        List<char> teams = votes[0].ToList();
        teams.Sort((a, b) => {
            for (int i = 0; i < numTeams; i++) {
                if (voteCount[a - 'A', i] != voteCount[b - 'A', i]) {
                    return voteCount[b - 'A', i] - voteCount[a - 'A', i];
                }
            }
            return a - b;
        });
        return new string(teams.ToArray());
    }

    public static void Main() {
        var sol = new Solution();
        string[] votes = {"ABC", "ACB", "ABC", "ACB", "ACB"};
        Console.WriteLine(sol.RankTeams(votes));
    }
}

This Python solution uses a defaultdict to handle vote counting and sorts the team list with custom keys, sorting by vote counts and resolving ties based on alphabetical order.

Complexity

O(N * P * log(P)) is the time complexity, with P as the number of teams and N as the votes. Space complexity is O(P^2), stored in the vote_count dictionary.

Try this approach in the editor

Approach 2: Using a Custom Comparator

This approach defines a custom comparator function to sort the teams according to the given ranking rules. We count the votes similarly, but rather than sorting explicitly with nested loops, we rely on a sophisticated comparator that resolves conflicts directly during the sorting process.

from typing import List
from functools import cmp_to_key

class Team:
    def __init__(self, name, size):
        self.name = name
        self.votes = [0] * size

    def __lt__(self, other):
        return (self.votes, -ord(self.name)) > (other.votes, -ord(other.name))


def rankTeams(votes: List[str]) -> str:
    size = len(votes[0])
    teams = {c: Team(c, size) for c in votes[0]}
    for vote in votes:
        for i in range(size):
            teams[vote[i]].votes[i] += 1
    sorted_teams = list(teams.values())
    sorted_teams.sort()  # Uses the defined __lt__ method
    return ''.join(team.name for team in sorted_teams)

# Example
votes = ["ABC", "ACB", "ABC", "ACB", "ACB"]
print(rankTeams(votes))
import java.util.*;

class Team {
    int[] votes;
    char name;

    public Team(char n, int len) {
        name = n;
        votes = new int[len];
    }
}

public class Solution {
    public String rankTeams(String[] votes) {
        int n = votes[0].length();
        Map<Character, Team> teamMap = new HashMap<>();
        for (char c : votes[0].toCharArray()) {
            teamMap.put(c, new Team(c, n));
        }

        for (String vote : votes) {
            for (int i = 0; i < n; i++) {
                Team t = teamMap.get(vote.charAt(i));
                t.votes[i]++;
            }
        }

        List<Team> teams = new ArrayList<>(teamMap.values());
        Collections.sort(teams, (a, b) -> {
            if (!Arrays.equals(b.votes, a.votes)) {
                return -Arrays.compare(a.votes, b.votes);
            }
            return a.name - b.name;
        });

        StringBuilder result = new StringBuilder();
        for (Team t : teams) {
            result.append(t.name);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        String[] votes = {"ABC", "ACB", "ABC", "ACB", "ACB"};
        System.out.println(sol.rankTeams(votes));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Team {
    vector<int> votes;
    char name;

    Team(char n, int size) : name(n) {
        votes = vector<int>(size, 0);
    }

    bool operator<(const Team &other) const {
        if (votes != other.votes) {
            return votes > other.votes;
        }
        return name < other.name;
    }
};

string rankTeams(vector<string>& votes) {
    int size = votes[0].size();
    vector<Team> teams;
    for (char team : votes[0]) {
        teams.push_back(Team(team, size));
    }

    for (string vote : votes) {
        for (int place = 0; place < size; ++place) {
            for (Team &team : teams) {
                if (team.name == vote[place]) {
                    team.votes[place]++;
                }
            }
        }
    }

    sort(teams.begin(), teams.end());

    string result = "";
    for (Team &team : teams) {
        result += team.name;
    }
    return result;
}

int main() {
    vector<string> votes = {"ABC", "ACB", "ABC", "ACB", "ACB"};
    cout << rankTeams(votes) << endl;
    return 0;
}
function rankTeams(votes) {
    class Team {
        constructor(name, size) {
            this.name = name;
            this.votes = new Array(size).fill(0);
        }
    }

    const size = votes[0].length;
    const teams = {};
    for (const char of votes[0]) {
        teams[char] = new Team(char, size);
    }

    for (const vote of votes) {
        for (let i = 0; i < size; i++) {
            teams[vote[i]].votes[i]++;
        }
    }

    const teamArray = Object.values(teams);
    teamArray.sort((a, b) => {
        for (let i = 0; i < size; i++) {
            if (a.votes[i] !== b.votes[i]) {
                return b.votes[i] - a.votes[i];
            }
        }
        return a.name < b.name ? -1 : 1;
    });

    return teamArray.map(team => team.name).join('');
}

console.log(rankTeams(["ABC", "ACB", "ABC", "ACB", "ACB"]));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int votes[26];
    char team;
} TeamVotes;

int cmp(const void *a, const void *b) {
    TeamVotes *teamA = (TeamVotes *)a;
    TeamVotes *teamB = (TeamVotes *)b;
    for (int i = 0; i < 26; ++i) {
        if (teamA->votes[i] != teamB->votes[i])
            return teamB->votes[i] - teamA->votes[i];
    }
    return teamA->team - teamB->team;
}

char* rankTeams(char **votes, int votesSize) {
    int len = strlen(votes[0]);
    TeamVotes teams[26] = {0};
    for (int i = 0; i < len; ++i) {
        teams[i].team = votes[0][i];
    }

    for (int i = 0; i < votesSize; ++i) {
        for (int j = 0; j < len; ++j) {
            teams[votes[i][j] - 'A'].votes[j]++;
        }
    }

    qsort(teams, len, sizeof(TeamVotes), cmp);

    char *result = (char *)malloc((len + 1) * sizeof(char));
    for (int i = 0; i < len; ++i) {
        result[i] = teams[i].team;
    }
    result[len] = '\0';
    return result;
}

int main() {
    char *votes[] = {"ABC", "ACB", "ABC", "ACB", "ACB"};
    char *result = rankTeams(votes, 5);
    printf("%s\n", result);
    free(result);
    return 0;
}
using System;
using System.Collections.Generic;
using System.Linq;

public class Team {
    public int[] Votes;
    public char Name;

    public Team(char name, int size) {
        Name = name;
        Votes = new int[size];
    }
}

public class Solution {
    public string RankTeams(string[] votes) {
        int len = votes[0].Length;
        var teams = new Dictionary<char, Team>();
        foreach (char c in votes[0]) {
            teams[c] = new Team(c, len);
        }

        foreach (string vote in votes) {
            for (int i = 0; i < len; i++) {
                teams[vote[i]].Votes[i]++;
            }
        }

        List<Team> teamList = teams.Values.ToList();
        teamList.Sort((a, b) => {
            for (int i = 0; i < len; i++) {
                if (a.Votes[i] != b.Votes[i])
                    return b.Votes[i] - a.Votes[i];
            }
            return a.Name - b.Name;
        });

        return new string(teamList.Select(t => t.Name).ToArray());
    }

    public static void Main() {
        var sol = new Solution();
        string[] votes = { "ABC", "ACB", "ABC", "ACB", "ACB" };
        Console.WriteLine(sol.RankTeams(votes));
    }
}

Python's solution uses a class with a custom less-than method for sorting. List.sort() is used which inherently relies on this method to sort objects as required by the problem's rules.

Complexity

Time complexity: O(P * log(P)), Space complexity: O(P).

Try this approach in the editor

Approach 3: Counting + Custom Sorting

For each candidate, we can count the number of votes they receive at each rank, then compare the vote counts for different ranks in order. If the vote counts are the same, we compare the letters.

The time complexity is O(n times m + m^2 times log m), and the space complexity is O(m^2). Here, n is the length of votes, and m is the number of candidates, i.e., the length of votes[0].

function rankTeams(votes: string[]): string {
    const m = votes[0].length;
    const cnt: number[][] = Array.from({ length: 26 }, () => Array(m + 1).fill(0));
    for (const vote of votes) {
        for (let i = 0; i < m; i++) {
            cnt[vote.charCodeAt(i) - 65][i]++;
        }
    }
    const s: string[] = votes[0].split('');
    s.sort((a, b) => {
        const i = a.charCodeAt(0) - 65;
        const j = b.charCodeAt(0) - 65;
        for (let k = 0; k < m; k++) {
            if (cnt[i][k] !== cnt[j][k]) {
                return cnt[j][k] - cnt[i][k];
            }
        }
        return a.localeCompare(b);
    });
    return s.join('');
}
func rankTeams(votes []string) string {
	m := len(votes[0])
	cnt := [26][27]int{}
	for _, vote := range votes {
		for i, ch := range vote {
			cnt[ch-'A'][i]++
		}
	}
	s := []rune(votes[0])
	sort.Slice(s, func(i, j int) bool {
		a, b := s[i]-'A', s[j]-'A'
		for k := 0; k < m; k++ {
			if cnt[a][k] != cnt[b][k] {
				return cnt[a][k] > cnt[b][k]
			}
		}
		return s[i] < s[j]
	})
	return string(s)
}
impl Solution {
    pub fn rank_teams(votes: Vec<String>) -> String {
        let m = votes[0].len();
        let mut cnt = vec![vec![0; m + 1]; 26];

        for vote in &votes {
            for (i, ch) in vote.chars().enumerate() {
                cnt[(ch as u8 - b'A') as usize][i] += 1;
            }
        }

        let mut s: Vec<char> = votes[0].chars().collect();

        s.sort_by(|&a, &b| {
            let i = (a as u8 - b'A') as usize;
            let j = (b as u8 - b'A') as usize;

            for k in 0..m {
                if cnt[i][k] != cnt[j][k] {
                    return cnt[j][k].cmp(&cnt[i][k]);
                }
            }
            a.cmp(&b)
        });

        s.into_iter().collect()
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Counting Votes by Position

O(N * P * log(P)) is the time complexity, with P as the number of teams and N as the votes. Space complexity is O(P^2), stored in the vote_count dictionary.

Using a Custom Comparator

Time complexity: O(P * log(P)), Space complexity: O(P).

Counting + Custom Sorting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Counting Votes by PositionO(v * n + n log n * n)O(n^2)Standard solution. Best when team count is small and rankings require multi-level tie-breaking.
Custom Comparator with Vote MatrixO(v * n + n log n * n)O(n^2)Useful when the language provides flexible comparator functions for sorting complex ranking rules.

Frequently asked questions

Is Rank Teams by Votes easy or hard?

Rank Teams by Votes is generally rated Medium difficulty. The main challenge is translating the tie-breaking rules into a structured comparison using counting arrays and a custom sorting strategy.

How to solve Rank Teams by Votes in O(n)?

A strict O(n) solution is not practical because the final ranking requires sorting teams based on multiple vote counts. The closest optimal method counts votes in O(v * n) and then sorts teams in O(n log n * n) due to multi-position comparisons.

What is the best approach for Rank Teams by Votes?

The best approach counts how many votes each team receives at every ranking position and then sorts teams using those counts as a lexicographic priority. This counting-by-position strategy runs in O(v * n + n log n * n) time and ensures ties are resolved correctly by comparing second, third, and later positions.

What data structure is used in Rank Teams by Votes?

The main structure is a 2D array or hash map storing vote counts for each team at every position. Each row represents a team and each column represents a ranking position, enabling quick comparison during sorting.

What is the time complexity of Rank Teams by Votes?

The typical solution runs in O(v * n + n log n * n) time, where v is the number of voters and n is the number of teams. Counting votes requires scanning each vote string, and sorting teams requires comparing up to n positions during each comparison.

Rank Teams by Votes Python or Java solution approach?

Both Python and Java implementations usually build a vote count matrix and then sort the teams using a custom comparator or sorting key. The comparator checks counts from the highest priority position to the lowest and falls back to lexicographical order if needed.

Is Rank Teams by Votes asked at Google, Amazon, or Meta?

Ranking and vote aggregation problems appear in interviews at companies like Amazon and Google because they test sorting with custom comparison logic. The problem combines counting, arrays, and tie-breaking rules, which are common interview patterns.

Comments

Now write it yourselfClose this page and solve Rank Teams by Votes in the editor, without looking.
Practise Rank Teams by Votes