First Unique Character and Highest Class Average
StringsAuto-graded · 18 test casesLast updated
Tests hash-based frequency counting for strings and grouped numeric aggregation with exact average comparison.
You are given two independent tasks to solve in a single function.
Task 1: First Unique Character
Given a string s, find the first character that appears exactly once in the entire string. Return that character as a string.
- If no character appears exactly once, return an empty string
"". - Characters are case-sensitive:
'a'and'A'are distinct. - The string may contain any ASCII characters including spaces and punctuation.
Task 2: Highest Average Score
You are given a list of score records, where each record is a two-element list [name, score] containing a student name (string) and their score (integer).
Calculate the average score for each student across all their records, then return the highest average among all students as a float.
- A student may have multiple score records; compute their mean score.
- Scores can be negative, zero, or positive integers.
- Each student is guaranteed to have at least one score record.
- When comparing averages, use exact arithmetic (avoid floating-point comparison errors).
Function Signature
Your function receives both inputs and returns both results as a two-element list: [first_unique_char, highest_avg].
Constraints
1 ≤ len(s) ≤ 100,0001 ≤ len(records) ≤ 100,000- Each score is an integer in the range
[-1,000,000, 1,000,000] - Student names are non-empty strings
Examples
Example 1
Input: first_unique_and_best_average('swiss', [['Alice', 80], ['Bob', 90], ['Alice', 100]])
Output: ['w', 90]
Example 2
Input: first_unique_and_best_average('aabb', [['A', 70], ['B', 60], ['A', 50]])
Output: ['', 60]
Hints
Hint 1
For the string task, maintain character frequencies and scan the original string in order to preserve position.
Hint 2
For the scoring task, aggregate totals and counts per student, then compute averages only when finding the maximum.
Hint 3
Be careful with negative scores when tracking the maximum average—don't initialize to zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines two independent hash-based tasks that each require a single pass through the input.
Task 1: First Unique Character
The key insight is that "first" refers to position in the original string, while "unique" refers to frequency. We solve this with two passes:
- Frequency pass: Build a hash map counting how many times each character appears in the entire string.
- Position pass: Iterate through the string in its original order. Return the first character whose count equals exactly 1.
If we finish the second pass without finding a character with count 1, we return an empty string. We must scan the original string (not the hash map) to preserve positional order.
Task 2: Highest Average Score
We aggregate scores per student, then find the maximum average:
- Aggregation pass: For each record, accumulate the score sum and count for that student using two hash maps.
- Maximum finding: Compute each student's average as
total / countand track the maximum.
Storing sums and counts (rather than lists of all scores) keeps space usage at O(distinct students). When comparing averages, Python's arbitrary-precision integers and float arithmetic naturally handle exact comparison for the values in our constraints.
A critical detail: when all scores are negative, the maximum average will also be negative. We must not initialize our maximum to 0, or use max() on a generator expression which handles this correctly.
Why This Is Correct
Task 1: After building the frequency map, every character's exact occurrence count is known. Scanning the original string in order guarantees we find the leftmost character with count 1, which is the definition of "first unique."
Task 2: Each record contributes to exactly one student's sum and count. The ratio sum / count is that student's true arithmetic mean. Taking the maximum of all these means yields the highest average by definition.
Complexity
- Time: O(n + m) where n is the length of the string and m is the number of records. Both tasks make a constant number of linear passes with O(1) hash operations.
- Space: O(k + p) where k is the number of distinct characters in the string and p is the number of distinct students. For ASCII strings, k ≤ 128, effectively O(1). Overall space is O(distinct_chars + distinct_students).
Edge Cases
- Single character string: returns that character if it appears once
- All repeating characters: returns empty string
- All negative scores: correctly returns the highest (least negative) average
- Single student with one record: returns that score as the average
- Student names are case-sensitive: "Bob" and "bob" are different students
Solution
from collections import Counter
from typing import List
def first_unique_and_best_average(s: str, records: List[List]) -> List:
# Task 1: First unique character
char_counts = Counter(s)
first_unique = ""
for character in s:
if char_counts[character] == 1:
first_unique = character
break
# Task 2: Highest average score
student_totals = {}
student_counts = {}
for name, score in records:
if name not in student_totals:
student_totals[name] = 0
student_counts[name] = 0
student_totals[name] += score
student_counts[name] += 1
highest_avg = max(student_totals[name] / student_counts[name]
for name in student_totals)
return [first_unique, highest_avg]
Time Complexity: O(n + m)
Space Complexity: O(k + p) where k = distinct characters, p = distinct students