#180

Consecutive Numbers

Medium
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the logs while maintaining a count of consecutive occurrences. This is efficient because it only requires one traversal of the data.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a variable to keep track of the current number and its count.
  2. 2Step 2: Loop through the logs and for each number, check if it is the same as the previous one.
  3. 3Step 3: If it is the same, increment the count; if not, reset the count to 1.
  4. 4Step 4: If the count reaches 3, add the number to a result set.
  5. 5Step 5: Continue until all logs are processed.
  6. 6Step 6: Return the result set.
solution.py16 lines
1# Full working Python code
2SELECT DISTINCT num AS ConsecutiveNums
3FROM (
4    SELECT num,
5           COUNT(*) AS count
6    FROM (
7        SELECT num,
8               @prev AS prev,
9               @count := IF(num = @prev, @count + 1, 1) AS count,
10               @prev := num
11        FROM Logs,
12        (SELECT @prev := NULL, @count := 0) AS init
13        ORDER BY id
14    ) AS subquery
15    WHERE count >= 3
16) AS final_result;

Complexity note: This complexity is linear because we only traverse the logs once, maintaining a count of consecutive occurrences.

  • 1Consecutive counting requires careful tracking of the previous number.
  • 2Using a single pass can significantly improve performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.