Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1783. Grand Slam Titles

Database

Explanation:

To solve this problem, we can iterate through the given array of strings representing the Grand Slam titles. We can use a HashMap to keep track of the count of each player's titles. We will also maintain a separate variable to keep track of the maximum number of titles won by any player. Finally, we will return the list of players who have won the maximum number of titles.

  1. Create a HashMap to store the count of titles won by each player.
  2. Iterate through the given array and update the count of titles for each player.
  3. Keep track of the maximum number of titles won by any player.
  4. Iterate through the HashMap to find players with the maximum number of titles.
  5. Return the list of players with the maximum number of titles.

Time complexity: O(n) where n is the number of titles. Space complexity: O(n) for the HashMap.

:

import java.util.*;

class Solution {
    public List<String> grandSlamTitles(String[] titles) {
        Map<String, Integer> playerTitles = new HashMap<>();
        int maxTitles = 0;
        
        for (String title : titles) {
            playerTitles.put(title, playerTitles.getOrDefault(title, 0) + 1);
            maxTitles = Math.max(maxTitles, playerTitles.get(title));
        }
        
        List<String> maxTitlePlayers = new ArrayList<>();
        for (String player : playerTitles.keySet()) {
            if (playerTitles.get(player) == maxTitles) {
                maxTitlePlayers.add(player);
            }
        }
        
        return maxTitlePlayers;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.