Write a Python function that uses `requests.get()` to fetch data from `https://sormock.hackerrank.com/api/universities`, filters by `location.country`, and returns the university with the lowest `rank_display`.
💡 Model Answer
Here’s a concise implementation:
import requests
def get_best_university(country: str) -> str:
url = 'https://sormock.hackerrank.com/api/universities'
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
except requests.RequestException:
return ''
data = resp.json().get('data', [])
filtered = [u for u in data if u.get('location', {}).get('country', '') == country]
if not filtered:
return ''
best = min(filtered, key=lambda u: u.get('rank_display', float('inf')))
return best.get('university', '')This approach ensures that the function is robust to missing fields and network failures, and it scales linearly with the size of the API response.
The function runs in O(n) time and uses O(n) memory for the filtered list.
The function handles network errors gracefully by catching RequestException and returning an empty string. It also accounts for missing rank_display values by treating them as infinity, ensuring that only valid ranks are considered. The filtering step runs in linear time relative to the number of universities returned by the API, and the min operation also runs in linear time. Therefore, the overall time complexity is O(n) and the space complexity is O(n) due to the filtered list. This implementation is suitable for small to medium-sized datasets and can be easily extended to handle pagination if the API returns multiple pages.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500