LeetCode 2377: Sort the Olympic Table Solution

Master LeetCode problem 2377 (Sort the Olympic Table), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2377. Sort the Olympic Table

Problem Explanation

Explanation

To sort the Olympic table, we can use a custom comparator to sort the teams based on their number of gold medals. If two teams have the same number of gold medals, we can compare their number of silver medals. If both gold and silver medals are equal, we can compare their number of bronze medals. If all medals are equal, we can sort based on the team name in lexicographical order.

  1. Create a custom comparator function to compare teams based on their medals.
  2. Sort the teams using the custom comparator.
  3. Return the sorted table.

Time Complexity: O(n log n) - where n is the number of teams Space Complexity: O(1)

Solution Code

import java.util.*;

class Solution {
    public String[] sortTable(String[][] table) {
        Arrays.sort(table, new Comparator<String[]>() {
            @Override
            public int compare(String[] a, String[] b) {
                int goldA = Integer.parseInt(a[1]);
                int silverA = Integer.parseInt(a[2]);
                int bronzeA = Integer.parseInt(a[3]);
                
                int goldB = Integer.parseInt(b[1]);
                int silverB = Integer.parseInt(b[2]);
                int bronzeB = Integer.parseInt(b[3]);
                
                if (goldA != goldB) {
                    return Integer.compare(goldB, goldA);
                } else if (silverA != silverB) {
                    return Integer.compare(silverB, silverA);
                } else if (bronzeA != bronzeB) {
                    return Integer.compare(bronzeB, bronzeA);
                } else {
                    return a[0].compareTo(b[0]);
                }
            }
        });
        
        return Arrays.stream(table).map(row -> String.join(" ", row)).toArray(String[]::new);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2377 (Sort the Olympic Table)?

This page provides optimized solutions for LeetCode problem 2377 (Sort the Olympic Table) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2377 (Sort the Olympic Table)?

The time complexity for LeetCode 2377 (Sort the Olympic Table) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2377 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2377 in Java, C++, or Python.

Back to LeetCode Solutions