Consecutive Numbers solution and explanation
9 more videos on this problem
LeetCode 180: Consecutive Numbers [SQL]Frederik Müller · 5:27 · 27K views
Consecutive Numbers | Leetcode 180 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 7:13 · 14K views
LeetCode Medium 180 "Consecutive Numbers" Amazon Uber Interview SQL Question Detailed ExplanationEveryday Data Science · 6:46 · 14K views
Leetcode 180 - Consecutive Numbers - Python Solution | FAANG InterviewsEveryday Data Science · 11:06 · 1K views
180. Consecutive Numbers | LeetCode SQL Solution [MEDIUM]Code with Carter · 8:03 · 1K views
Consecutive Numbers | Leetcode 180 | Week 2 | QS 12The Big Data Show · 7:13 · 990 views
Solving LeetCode SQL Question with Explanation | LeetCode 180Balaji Srinivasan · 10:37 · 848 views
LeetCode in MySQL 180. Consecutive Numbers - Michelle小梦想家 (English Version)Michelle小梦想家 · 5:47 · 723 views
LeetCode 180 - Consecutive Numbers (Python and SQL) [MEDIUM]Ryan & Matt Data Science · 9:28 · 638 views
180ConsecutiveNumbersVideo - Solution to LeetCode 180 Consecutive NumbersLEETCODE MASTER · 5:01 · 602 views
The problem
Table: Logs
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ In SQL, id is the primary key for this table. id is an autoincrement column starting from 1.
Find all numbers that appear at least three times consecutively.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input: Logs table: +----+-----+ | id | num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+ Output: +-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+ Explanation: 1 is the only number that appears consecutively for at least three times.
Approach overview
Problem Overview: You are given a table or sequence of logged numbers. The task is to return all values that appear at least three times consecutively. Order matters: the same number must appear in three adjacent records, not just three total occurrences.
Approach 1: Sliding Window Using Array Traversal (O(n) time, O(1) space)
Traverse the ordered records and examine a window of three consecutive positions at a time. For index i, compare nums[i], nums[i-1], and nums[i-2]. If all three values match, you found a valid consecutive sequence. This works because a run of three identical adjacent values guarantees the requirement. The algorithm performs a single linear scan and only stores the result set, so space complexity stays constant. This approach is conceptually identical to a sliding window over a fixed window size of three.
In SQL-based versions of the problem, the same logic is implemented using self joins or window functions like LAG() and LEAD() to compare neighboring rows. In imperative languages such as Python, Java, or C++, you simply iterate through the array and compare neighbors directly.
Approach 2: HashMap / Dictionary to Count Consecutive Streaks (O(n) time, O(n) space)
Track consecutive streaks while iterating through the sequence. Maintain a dictionary where the current number maps to its ongoing streak length. When the current value equals the previous value, increment the streak; otherwise reset the streak to 1. Once the streak reaches 3, record that number in the result. The hash map allows flexible tracking if the dataset is processed as a stream or if multiple sequences must be monitored simultaneously. Lookups and updates run in constant time using a hash map.
This approach is slightly more general than the sliding window technique because it explicitly tracks streak lengths rather than checking a fixed window. It is useful when the problem changes to "k consecutive occurrences" instead of exactly three.
Recommended for interviews: The sliding window traversal is the most expected solution. It shows you recognize that only adjacent comparisons are required and that a constant-size window solves the problem in O(n) time and O(1) space. Mentioning the hash map streak approach demonstrates deeper understanding and adaptability if the requirement changes to variable-length sequences. Both approaches are common patterns when working with ordered datasets or database logs.
Approach 1: Sliding Window Using Array Traversal
We can use a sliding window approach with a counter to track consecutive numbers as we iterate through the list.
def find_consecutive_numbers(nums):
result = []
count = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
count += 1
if count == 3 and (not result or result[-1] != nums[i]):
result.append(nums[i])
else:
count = 1
return result
nums = [1, 1, 1, 2, 1, 2, 2]
print(find_consecutive_numbers(nums))import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<Integer> findConsecutiveNumbers(int[] nums) {
List<Integer> result = new ArrayList<>();
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
count++;
if (count == 3 && !result.contains(nums[i])) {
result.add(nums[i]);
}
} else {
count = 1;
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 1, 2, 2};
System.out.println(findConsecutiveNumbers(nums));
}
}#include <iostream>
#include <vector>
using namespace std;
vector<int> findConsecutiveNumbers(vector<int> nums) {
vector<int> result;
int count = 1;
for (size_t i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i - 1]) {
count++;
if (count == 3) result.push_back(nums[i]);
} else {
count = 1;
}
}
return result;
}
int main() {
vector<int> nums = {1, 1, 1, 2, 1, 2, 2};
vector<int> result = findConsecutiveNumbers(nums);
for (int num : result) cout << num << endl;
return 0;
}function findConsecutiveNumbers(nums) {
let result = [];
let count = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] === nums[i - 1]) {
count++;
if (count === 3 && !result.includes(nums[i])) {
result.push(nums[i]);
}
} else {
count = 1;
}
}
return result;
}
const nums = [1, 1, 1, 2, 1, 2, 2];
console.log(findConsecutiveNumbers(nums));#include <stdio.h>
#include <stdlib.h>
void findConsecutiveNumbers(int nums[], int size) {
int count = 1, lastNum = nums[0];
for (int i = 1; i < size; i++) {
if (nums[i] == lastNum) {
count++;
if (count == 3) {
printf("%d\n", lastNum);
return; // Return immediately after finding the first number
}
} else {
count = 1;
lastNum = nums[i];
}
}
}
int main() {
int nums[] = {1, 1, 1, 2, 1, 2, 2};
int size = sizeof(nums) / sizeof(nums[0]);
findConsecutiveNumbers(nums, size);
return 0;
}using System;
using System.Collections.Generic;
class Program {
static List<int> FindConsecutiveNumbers(int[] nums) {
var result = new List<int>();
int count = 1;
for (int i = 1; i < nums.Length; i++) {
if (nums[i] == nums[i - 1]) {
count++;
if (count == 3 && !result.Contains(nums[i])) {
result.Add(nums[i]);
}
} else {
count = 1;
}
}
return result;
}
static void Main() {
int[] nums = {1, 1, 1, 2, 1, 2, 2};
var result = FindConsecutiveNumbers(nums);
foreach (var num in result) {
Console.WriteLine(num);
}
}
}Python's version is simple and utilizes a list to track any numbers that are tri-consecutive in the sequence. The variable 'count' tracks the current streak of identical numbers.
Time Complexity: O(n). Space Complexity: O(k) for the result list.
Approach 2: HashMap/Dictionary to Count Occurrences and Track Sequences
This approach uses a HashMap (or Dictionary in Python) to keep track of the sequence counts of numbers. This way, we can determine if any number is repeated consecutively at least three times.
def find_consecutive_numbers(nums):
count = {}
result = []
consecutive = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
consecutive += 1
if consecutive == 3 and nums[i] not in count:
result.append(nums[i])
count[nums[i]] = True
else:
consecutive = 1
return result
nums = [1, 1, 1, 2, 1, 2, 2]
print(find_consecutive_numbers(nums))import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static List<Integer> findConsecutiveNumbers(int[] nums) {
HashMap<Integer, Boolean> count = new HashMap<>();
List<Integer> result = new ArrayList<>();
int consecutive = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
consecutive++;
if (consecutive == 3 && !count.containsKey(nums[i])) {
result.add(nums[i]);
count.put(nums[i], true);
}
} else {
consecutive = 1;
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 1, 2, 2};
System.out.println(findConsecutiveNumbers(nums));
}
}#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> findConsecutiveNumbers(vector<int>& nums) {
unordered_map<int, int> count;
vector<int> result;
int consecutive = 1;
for (size_t i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i - 1]) {
consecutive++;
if (consecutive == 3 && count[nums[i - 1]] != 1) {
result.push_back(nums[i]);
count[nums[i]] = 1;
}
} else {
consecutive = 1;
}
}
return result;
}
int main() {
vector<int> nums = {1, 1, 1, 2, 1, 2, 2};
vector<int> result = findConsecutiveNumbers(nums);
for (int num : result) cout << num << endl;
return 0;
}function findConsecutiveNumbers(nums) {
let count = {};
let result = [];
let consecutive = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] === nums[i - 1]) {
consecutive++;
if (consecutive === 3 && !count[nums[i]]) {
result.push(nums[i]);
count[nums[i]] = true;
}
} else {
consecutive = 1;
}
}
return result;
}
const nums = [1, 1, 1, 2, 1, 2, 2];
console.log(findConsecutiveNumbers(nums));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void findConsecutiveNumbers(int nums[], int size) {
int *count = (int *)calloc(1001, sizeof(int));
int consecutiveNum = nums[0], maxCount = 1;
for (int i = 1; i < size; i++) {
if (nums[i] == consecutiveNum) {
maxCount++;
if (maxCount == 3) {
printf("%d", consecutiveNum);
break;
}
} else {
maxCount = 1;
consecutiveNum = nums[i];
}
}
free(count);
}
int main() {
int nums[] = {1, 1, 1, 2, 1, 2, 2};
int size = sizeof(nums) / sizeof(nums[0]);
findConsecutiveNumbers(nums, size);
return 0;
}using System;
using System.Collections.Generic;
class Program {
static List<int> FindConsecutiveNumbers(int[] nums) {
var count = new Dictionary<int, bool>();
var result = new List<int>();
int consecutive = 1;
for (int i = 1; i < nums.Length; i++) {
if (nums[i] == nums[i - 1]) {
consecutive++;
if (consecutive == 3 && !count.ContainsKey(nums[i])) {
result.Add(nums[i]);
count[nums[i]] = true;
}
} else {
consecutive = 1;
}
}
return result;
}
static void Main() {
int[] nums = {1, 1, 1, 2, 1, 2, 2};
var result = FindConsecutiveNumbers(nums);
foreach (var num in result) {
Console.WriteLine(num);
}
}
}In Python, the dictionary is utilized to track numbers identified as tri-consecutive, ensuring each is only considered once, along with a counter to maintain consecutive patterns.
Time Complexity: O(n). Space Complexity: O(k).
Approach 3: Two Joins
We can use two joins to solve this problem.
First, we perform a self-join with the condition l1.num = l2.num and l1.id = l2.id - 1, so that we can find all numbers that appear at least twice in a row. Then, we perform another self-join with the condition l2.num = l3.num and l2.id = l3.id - 1, so that we can find all numbers that appear at least three times in a row. Finally, we only need to select the distinct l2.num.
# Write your MySQL query statement below
SELECT DISTINCT l2.num AS ConsecutiveNums
FROM
Logs AS l1
JOIN Logs AS l2 ON l1.id = l2.id - 1 AND l1.num = l2.num
JOIN Logs AS l3 ON l2.id = l3.id - 1 AND l2.num = l3.num;Approach 4: Window Function
We can use the window functions LAG and LEAD to obtain the num of the previous row and the next row of the current row, and record them in the fields a and b, respectively. Finally, we only need to filter out the rows where a = num and b = num, which are the numbers that appear at least three times in a row. Note that we need to use the DISTINCT keyword to remove duplicates from the results.
We can also group the numbers by using the IF function to determine whether the num of the current row is equal to the num of the previous row. If they are equal, we set it to 0, otherwise we set it to 1. Then, we use the window function SUM to calculate the prefix sum, which is the grouping identifier. Finally, we only need to group by the grouping identifier and filter out the numbers with a row count greater than or equal to 3 in each group. Similarly, we need to use the DISTINCT keyword to remove duplicates from the results.
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
LAG(num) OVER () AS a,
LEAD(num) OVER () AS b
FROM Logs
)
SELECT DISTINCT num AS ConsecutiveNums
FROM T
WHERE a = num AND b = num;Approach 5: Default Approach
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
IF(num = (LAG(num) OVER ()), 0, 1) AS st
FROM Logs
),
S AS (
SELECT *, SUM(st) OVER (ORDER BY id) AS p
FROM T
)
SELECT DISTINCT num AS ConsecutiveNums
FROM S
GROUP BY p
HAVING COUNT(1) >= 3;Complexity comparison
| Approach | Complexity |
|---|---|
| Sliding Window Using Array Traversal | Time Complexity: O(n). Space Complexity: O(k) for the result list. |
| HashMap/Dictionary to Count Occurrences and Track Sequences | Time Complexity: O(n). Space Complexity: O(k). |
| Two Joins | – |
| Window Function | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sliding Window Using Array Traversal | O(n) | O(1) | Best general solution when data is ordered and you only need to check fixed-length consecutive values |
| HashMap / Dictionary Streak Tracking | O(n) | O(n) | Useful when tracking variable-length sequences or processing streaming data |
Frequently asked questions
Is Consecutive Numbers easy or hard?
Consecutive Numbers is generally considered a medium-level problem because the logic is simple but requires recognizing that only adjacent comparisons matter. Once you identify the sliding window pattern, the implementation becomes straightforward.
How to solve Consecutive Numbers in O(n)?
Iterate through the ordered numbers and check whether the current value matches the previous two values. If nums[i] == nums[i-1] and nums[i] == nums[i-2], record that number as a valid result. This linear scan ensures O(n) time complexity.
What is the best approach for Consecutive Numbers?
The most efficient approach is a sliding window that checks three adjacent records at a time. By comparing nums[i], nums[i-1], and nums[i-2], you can detect consecutive duplicates in a single pass. This runs in O(n) time and O(1) space.
What data structure is used in Consecutive Numbers?
The simplest solution uses direct array traversal with a fixed-size sliding window. An alternative implementation uses a hash map or dictionary to track consecutive streak counts for numbers while iterating.
What is the time complexity of Consecutive Numbers?
The optimal solution runs in O(n) time because it scans the dataset once while comparing neighboring values. Space complexity is O(1) for the sliding window approach, since only a few variables are needed during traversal.
Consecutive Numbers Python or Java solution approach?
In Python or Java, iterate through the array and compare the current element with the two previous elements. If all three match, add the value to the result set. The implementation uses simple loops and conditional checks, giving O(n) time complexity.
Is Consecutive Numbers asked at Google, Amazon, or Meta?
Consecutive sequence detection problems appear frequently in database and data-processing interview rounds at companies like Amazon and Meta. Variations often involve detecting streaks, repeated events, or consecutive records in logs.
