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
๐Ÿจ Hotel Guest Registry AnalysisGuest Registry: Room VisitsRooms: [101, 101, 203, 203, 305, 402, 506, 608]Some guests stayed multiple times, others just onceStep 1: Group by Room Number (GROUP BY)Room 1012 visits โŒRoom 2032 visits โŒRoom 3051 visit โœ“Room 4021 visit โœ“Room 5061 visit โœ“Room 6081 visit โœ“Step 2: Filter Single Visits (HAVING COUNT(*) = 1)Multiple visits - removed305402506608Step 3: Find Highest Room (MAX)Room 608Highest Single-Visit Room
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

No additional space needed beyond query processing

n
2n
โœ“ 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)
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
52.3K Views
High Frequency
~8 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen