Program to find the final ranking of teams in order from highest to lowest rank in python

When we have a list of voting strings where each string represents votes on candidates in order from highest to lowest preference, we need to rank candidates based on their voting positions. The ranking follows a specific priority: first by highest preference votes, then by second preference votes if tied, and finally alphabetically if still tied.

So, if the input is like votes = ["zyx", "zxy", "xyz"], then the output will be "zxy". Here's why: 'z' received 2 votes for highest preference (position 0), 'x' received 1 vote for highest preference, and 'y' received 0 votes for highest preference.

Algorithm Steps

To solve this problem, we follow these steps ?

  • count := length of strings in votes (number of positions)
  • cand := a dictionary where each key maps to a list tracking votes at each position
  • for each vote string v in votes, do
    • for each position i and candidate c in v, do
      • increment cand[c][i] by 1
  • sort candidates based on their vote arrays (descending) and alphabetically for ties
  • return the concatenated sorted candidates as final ranking

Example

Let's implement the solution step by step ?

from collections import defaultdict

class Solution:
    def solve(self, votes):
        count = len(votes[0])
        cand = defaultdict(lambda: [0] * count)
        
        # Count votes for each candidate at each position
        for v in votes:
            for i, c in enumerate(v):
                cand[c][i] += 1
        
        # Sort by vote counts (descending) then alphabetically
        return "".join(sorted(cand.keys(), key=lambda x: (cand[x], -ord(x)), reverse=True))

# Test the solution
ob = Solution()
votes = ["zyx", "zxy", "xyz"]
result = ob.solve(votes)
print("Final ranking:", result)
Final ranking: zxy

How It Works

Let's trace through the example with votes = ["zyx", "zxy", "xyz"] ?

# Analyzing the vote counting
votes = ["zyx", "zxy", "xyz"]

# Vote counting breakdown:
# Position 0 (highest preference): z=2, x=1, y=0  
# Position 1 (second preference): y=2, x=1, z=0
# Position 2 (third preference): x=2, z=1, y=1

# Candidate vote arrays:
# z: [2, 0, 1]  
# x: [1, 1, 2]
# y: [0, 2, 1]

print("Vote analysis:")
print("z gets 2 votes at position 0, 0 at position 1, 1 at position 2")
print("x gets 1 vote at position 0, 1 at position 1, 2 at position 2") 
print("y gets 0 votes at position 0, 2 at position 1, 1 at position 2")
print("\nRanking: z first (most position-0 votes), then x, then y")
Vote analysis:
z gets 2 votes at position 0, 0 at position 1, 1 at position 2
x gets 1 vote at position 0, 1 at position 1, 2 at position 2
y gets 0 votes at position 0, 2 at position 1, 1 at position 2

Ranking: z first (most position-0 votes), then x, then y

Key Points

  • The sorting key (cand[x], -ord(x)) ensures vote arrays are compared first, then alphabetical order
  • Using reverse=True sorts vote counts in descending order
  • -ord(x) handles alphabetical sorting when vote counts are tied
  • The algorithm efficiently handles any number of candidates and positions

Conclusion

This solution ranks voting candidates by comparing their vote arrays position by position, with alphabetical tie-breaking. The time complexity is O(n*m + k*log(k)) where n is the number of votes, m is candidate count, and k is unique candidates.

Updated on: 2026-03-25T13:00:12+05:30

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements