Skip to content
Home » LeetCode – Consecutive Numbers

LeetCode – Consecutive Numbers

Question

Write a SQL query to find all numbers that appear at least three times consecutively in the Logs table.
Return the result in any order.




Table Schema

CREATE TABLE Logs ( id INT PRIMARY KEY IDENTITY(1,1), num VARCHAR(50) );)
);
INSERT INTO Logs (num) VALUES
('1'),
('1'),
('1'),
('2'),
('1'),
('2'),
('2');

Solution

SELECT DISTINCT num AS ConsecutiveNums
FROM (
SELECT 
num,
LAG(num, 1) OVER (ORDER BY id) AS prev1,
LAG(num, 2) OVER (ORDER BY id) AS prev2
FROM Logs
) t
WHERE num = prev1 AND num = prev2;

Explanation

  • LAG(num, 1) : looks at the previous row’s number.

  • LAG(num, 2): looks at the two rows before.

  • If num = prev1 = prev2, that means the number appeared 3 times consecutively.

  • DISTINCT avoids duplicates.




Loading

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from SQL BI Tutorials

Subscribe now to keep reading and get access to the full archive.

Continue reading