
You are given data representing a list of cities. Each city has a name and a temperature. You are also given an integer 'K'.
The task is to find the top 'K' cities with the highest temperatures from this data.
Let 'N' = 4, 'K' = 2. The cities are:
Delhi 30
Mumbai 35
Chennai 32
Kolkata 28
The cities sorted by temperature descending are: Mumbai (35), Chennai (32), Delhi (30), Kolkata (28).
The top 2 cities are Mumbai and Chennai.
Therefore, the answer is Mumbai Chennai.
The first line contains two integers, 'N' and 'K'.
The following 'N' lines each contain a string representing the city name and an integer representing its temperature, separated by a space.
Output Format :
Return a list of strings representing the names of the top 'K' cities with the highest temperatures, sorted in descending order of temperature. If two cities have the same temperature, their relative order in the output doesn't matter.
Note :
You don’t need to print anything. Just implement the given function.
1 <= 'N' <= 10^5
1 <= 'K' <= 'N'
-100 <= temperature <= 100
City names consist of lowercase and uppercase English letters.
Time Limit: 1 sec
3 1
Pune 25
Bangalore 28
Hyderabad 26
Bangalore
There are 3 cities: Pune (25), Bangalore (28), and Hyderabad (26). We need the top K = 1 city.
Sorting the cities by temperature descending gives: Bangalore (28), Hyderabad (26), Pune (25).
The top 1 city is Bangalore.
Thus, the answer is Bangalore.
4 4
Jaipur 40
Agra 38
Varanasi 39
Lucknow 37
Jaipur Varanasi Agra Lucknow
Sorting the cities based on their temperature will help in easily identifying the top 'K' cities.
Approach:
Algorithm:
O(N log N), where 'N' is the number of cities.
We read 'N' cities and store them, which takes O(N) time. Sorting the list of 'N' cities takes O(N log N) time. Extracting the top 'K' city names takes O(K) time. Since K <= N and O(N log N) dominates O(N) and O(K), the overall time complexity is of the order O(N log N).
O(N), where 'N' is the number of cities.
We store the data for 'N' cities in a list of pairs, which requires O(N) space. The resulting list of top 'K' city names requires O(K) space. Since K <= N, the overall space complexity is of the order O(N).