Biggest Single Number - Problem
Given a database table MyNumbers containing integers, find the largest single number. A single number is defined as a number that appears exactly once in the table.
Table Structure:
MyNumbers +-------------+------+ | Column Name | Type | +-------------+------+ | num | int | +-------------+------+
Your Task: Write a SQL query to find the largest number that appears only once. If no such number exists, return null.
Example: If the table contains [8, 8, 3, 3, 1, 4, 5, 6], the single numbers are [1, 4, 5, 6], so the answer is 6.
Input & Output
example_1.sql โ Basic Case
$
Input:
MyNumbers table: [8, 8, 3, 3, 1, 4, 5, 6]
โบ
Output:
6
๐ก Note:
Numbers that appear only once: [1, 4, 5, 6]. The largest among them is 6.
example_2.sql โ No Singles
$
Input:
MyNumbers table: [1, 1, 2, 2, 3, 3]
โบ
Output:
null
๐ก Note:
All numbers appear more than once, so there are no single numbers. Return null.
example_3.sql โ All Singles
$
Input:
MyNumbers table: [10, 20, 30]
โบ
Output:
30
๐ก Note:
All numbers appear exactly once: [10, 20, 30]. The largest is 30.
Visualization
Tap to expand
Understanding the Visualization
1
Group Guests by Room
GROUP BY room_number creates groups of identical room numbers
2
Filter Single Visits
HAVING COUNT(*) = 1 keeps only rooms visited once
3
Find Highest Room
MAX(room_number) returns the highest single-visit room
Key Takeaway
๐ฏ Key Insight: GROUP BY with HAVING is like having a smart hotel manager who can instantly group guests by room and identify single-visit VIPs, all in one efficient operation.
Time & Space Complexity
Time Complexity
O(nยฒ)
For each of n distinct numbers, we scan the entire table
โ Quadratic Growth
Space Complexity
O(1)
No additional space needed beyond query processing
โ Linear Space
Constraints
- 1 โค table size โค 1000
- Numbers can be negative, zero, or positive
- -1000 โค num โค 1000
- Table may contain duplicates (no primary key constraint)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code