Consecutive Numbers - Problem

You are given a Logs table with an auto-incrementing id starting from 1 and a num column containing various numbers.

Find all numbers that appear at least three times consecutively.

Return the result in any order. The result should contain only the distinct numbers that meet this criteria.

Table Schema

Logs
Column Name Type Description
id PK int Primary key, auto-incrementing starting from 1
num varchar Number value that may appear consecutively
Primary Key: id
Note: The id column represents consecutive row positions starting from 1

Input & Output

Example 1 — Basic Consecutive Pattern
Input Table:
id num
1 1
2 1
3 1
4 2
5 1
Output:
ConsecutiveNums
1
💡 Note:

The number 1 appears in rows with consecutive IDs 1, 2, and 3. This satisfies the requirement of appearing at least three times consecutively.

Example 2 — No Consecutive Pattern
Input Table:
id num
1 1
2 2
3 1
4 2
5 1
Output:
ConsecutiveNums
💡 Note:

No number appears three times consecutively. Each number alternates, so the result is empty.

Example 3 — Multiple Consecutive Patterns
Input Table:
id num
1 3
2 3
3 3
4 3
5 5
6 5
7 5
Output:
ConsecutiveNums
3
5
💡 Note:

The number 3 appears four times consecutively (rows 1-4) and 5 appears three times consecutively (rows 5-7). Both numbers qualify.

Constraints

  • 1 ≤ id ≤ 1000
  • num is a varchar that can contain any string value
  • The id column is auto-incrementing and starts from 1

Visualization

Tap to expand
Consecutive Numbers Problem INPUT: Logs Table id num 1 1 2 1 3 1 4 1 5 2 6 2 7 3 3+ times Find numbers appearing 3+ consecutive times ALGORITHM STEPS 1 Self-Join Table Join Logs 3 times (L1, L2, L3) 2 Check Consecutive IDs L1.id = L2.id - 1 L2.id = L3.id - 1 3 Match Same Numbers L1.num = L2.num = L3.num 4 Select Distinct Remove duplicates SELECT DISTINCT L1.num FROM Logs L1, L2, L3 WHERE L1.id = L2.id-1 AND L2.id = L3.id-1 AND L1.num=L2.num=L3.num FINAL RESULT Numbers appearing 3+ times: ConsecutiveNums 1 Verification: - Number 1 appears at: id: 1, 2, 3, 4 (4 times!) - Number 2 appears at: id: 5, 6 (only 2 times) OK - Found! Key Insight: Self-joining the table 3 times with consecutive ID conditions (L1.id+1=L2.id, L2.id+1=L3.id) allows us to check if the same number appears in 3 adjacent rows. The DISTINCT keyword ensures we only return each qualifying number once, even if it appears more than 3 times. TutorialsPoint - Consecutive Numbers | Optimal Solution (Self-Join)
Asked in
Facebook 28 LinkedIn 22 Amazon 18
52.0K Views
High Frequency
~18 min Avg. Time
985 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