Similar Problems

Similar Problems not available

Grand Slam Titles - Leetcode Solution

Companies:

LeetCode:  Grand Slam Titles Leetcode Solution

Difficulty: Medium

Topics: database  

Problem statement:

Leetcode Grand Slam Titles problem is based on tennis Grand Slam tournaments. There are a total of four Grand Slam tournaments in tennis, they are:

  1. Australian Open
  2. French Open
  3. Wimbledon
  4. US Open

We are given a list of strings, each string contains the name of a tennis player followed by the year they won a Grand Slam title. We need to find the player(s) with the most number of Grand Slam titles and return their names in alphabetical order.

Solution:

To solve this problem, we can use a hash map to store the count of Grand Slam titles won by each player. We will then iterate through the list of strings, split each string into two parts (player name and year), and update the count of Grand Slam titles won by the player in the hash map.

After that, we can find the maximum count of Grand Slam titles won by any player and then iterate through the hash map to find all player(s) with the maximum count of Grand Slam titles. Finally, we will sort the list of player(s) and return the result.

Time Complexity:

The time complexity of this solution is O(n * log n), where n is the number of strings in the input list. The sorting step takes O(n * log n) time complexity.

Space Complexity:

The space complexity of this solution is O(n), where n is the number of strings in the input list. We are using a hash map to store the count of Grand Slam titles won by each player, which takes up space proportional to the number of players in the list.

Here's the Python implementation of the above solution:

from collections import defaultdict

class Solution:
    def findMostGrandSlamTitles(self, lst: List[str]) -> List[str]:
        
        # Create a hash map to store the count of Grand Slam titles won by each player
        count = defaultdict(int)
        
        # Iterate through the list of strings, split each string and update the hash map
        for s in lst:
            name, year = s.split()
            count[name] += 1
        
        # Find the maximum count of Grand Slam titles won by any player
        max_count = max(count.values())
        
        # Iterate through the hash map and find all player(s) with the maximum count of Grand Slam titles
        result = []
        for k, v in count.items():
            if v == max_count:
                result.append(k)

        # Sort the list of player(s) and return the result
        result.sort()
        return result

Example:

Input: ["Roger Federer 2003", "Rafael Nadal 2005", "Roger Federer 2004", "Novak Djokovic 2008", "Roger Federer 2006", "Rafael Nadal 2007"]

Output: ["Roger Federer"]

Grand Slam Titles Solution Code

1