Last Updated: 22 Apr, 2025

High Temperature

Easy
Asked in company
Intuit

Problem statement

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.


For Example :
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.
Input Format :
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.
Constraints :
1 <= 'N' <= 10^5
1 <= 'K' <= 'N'
-100 <= temperature <= 100
City names consist of lowercase and uppercase English letters.

Time Limit: 1 sec

Approaches

01 Approach

Approach:

  • Read the input data, storing each city's name and temperature.
  • Sort the cities based on their temperature in descending order.
  • Take the first 'K' cities from the sorted list.
  • Extract the names of these 'K' cities.

Algorithm:

  • Read the integers 'N' and 'K'.
  • Create a list of pairs (temperature, city_name) to store the city data.
  • Iterate 'N' times:
    • Read the city name and temperature.
    • Add the pair (temperature, city_name) to the list.
  • Sort the list in descending order based on the temperature.
  • Create an empty list called 'top_cities_names'.
  • Iterate using 'i' from 0 to 'K - 1':
    • Add the city name from the i-th pair in the sorted list to 'top_cities_names'.
  • Return the 'top_cities_names' list.