#1211
Queries Quality and Percentage
EasyDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass through the data to aggregate the necessary information for each query_name. This approach is efficient and avoids unnecessary computations by leveraging a single data structure.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a dictionary to store total quality, count of queries, and poor count for each query_name.
- 2Step 2: Loop through each row in the Queries table and update the dictionary with quality and counts.
- 3Step 3: After processing all queries, compute the average quality and poor query percentage for each query_name.
- 4Step 4: Round the results to 2 decimal places and prepare the final output.
solution.py22 lines
1# Full working Python code
2import pandas as pd
3
4def query_quality(queries):
5 result = {}
6 for _, row in queries.iterrows():
7 name = row['query_name']
8 rating = row['rating']
9 position = row['position']
10 quality = rating / position
11 if name not in result:
12 result[name] = {'total_quality': 0, 'count': 0, 'poor_count': 0}
13 result[name]['total_quality'] += quality
14 result[name]['count'] += 1
15 if rating < 3:
16 result[name]['poor_count'] += 1
17 output = []
18 for name, data in result.items():
19 avg_quality = data['total_quality'] / data['count']
20 poor_percentage = (data['poor_count'] / data['count']) * 100
21 output.append({'query_name': name, 'quality': round(avg_quality, 2), 'poor_query_percentage': round(poor_percentage, 2)})
22 return pd.DataFrame(output)ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the queries to gather all necessary data, making it efficient. The space complexity is O(n) due to the storage of results in a dictionary.
- 1Understanding how to aggregate data efficiently is crucial in database queries.
- 2Recognizing the importance of average calculations and percentage computations in data analysis.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.