ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

MySQL: Find Longest Consecutive Sequence

SQL MySQL

Goal -- WPM

Ready
Exercise Algorithm Area
1DELIMITER //
2
3CREATE FUNCTION GetLongestConsecutiveSequenceLength()
4RETURNS INT
5READS SQL DATA
6BEGIN
7DECLARE max_length INT DEFAULT 0;
8DECLARE current_length INT DEFAULT 0;
9DECLARE previous_number INT DEFAULT NULL;
10DECLARE current_number INT DEFAULT NULL;
11DECLARE done INT DEFAULT FALSE;
12
13-- Cursor to iterate through sorted numbers
14DECLARE cur CURSOR FOR
15SELECT number FROM numbers ORDER BY number ASC;
16DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
17
18-- Handle empty table case
19IF (SELECT COUNT(*) FROM numbers) = 0 THEN
20RETURN 0;
21END IF;
22
23OPEN cur;
24
25read_loop: LOOP
26FETCH cur INTO current_number;
27IF done THEN
28LEAVE read_loop;
29END IF;
30
31-- Check if it's the first number or if it's consecutive
32IF previous_number IS NULL OR current_number = previous_number + 1 THEN
33SET current_length = current_length + 1;
34ELSE
35-- Sequence broken, reset current_length
36SET current_length = 1;
37END IF;
38
39-- Update max_length if current_length is greater
40IF current_length > max_length THEN
41SET max_length = current_length;
42END IF;
43
44-- Update previous_number for the next iteration
45SET previous_number = current_number;
46END LOOP;
47
48CLOSE cur;
49RETURN max_length;
50END //
51
52DELIMITER ;
53
54-- Example Usage:
55-- Assume 'numbers' table has columns: id INT, number INT
56-- INSERT INTO numbers (number) VALUES (100), (4), (200), (1), (3), (2);
57-- SELECT GetLongestConsecutiveSequenceLength(); -- Expected output: 4 (for sequence 1, 2, 3, 4)
58-- INSERT INTO numbers (number) VALUES (101), (102), (103);
59-- SELECT GetLongestConsecutiveSequenceLength(); -- Expected output: 4 (for sequence 100, 101, 102, 103)
60-- DELETE FROM numbers;
61-- SELECT GetLongestConsecutiveSequenceLength(); -- Expected output: 0
Algorithm description viewbox

MySQL: Find Longest Consecutive Sequence

Algorithm description:

This MySQL function, `GetLongestConsecutiveSequenceLength`, calculates the length of the longest sequence of consecutive integers present in a 'numbers' table. It iterates through the numbers, sorted in ascending order, using a cursor. The function maintains a `current_length` for the ongoing sequence and a `max_length` to store the longest sequence found so far. It correctly handles duplicate numbers by simply continuing the sequence if the current number is the same as the previous, and resets `current_length` when a break in consecutiveness is detected. The function also gracefully handles an empty 'numbers' table by returning 0.

Algorithm explanation:

The `GetLongestConsecutiveSequenceLength` function aims to find the maximum length of a contiguous sequence of integers within the `numbers` table. It initializes `max_length` and `current_length` to 0. A cursor `cur` is declared to iterate through the `numbers` table, ordered by the `number` column. This ordering is critical for identifying consecutive sequences. Before starting the loop, it checks if the table is empty; if so, it returns 0 immediately. Inside the loop, for each `current_number` fetched, it compares it with the `previous_number`. If it's the first number or if `current_number` is exactly one greater than `previous_number`, `current_length` is incremented, extending the current sequence. Otherwise, the sequence is broken, and `current_length` is reset to 1 (for the current number starting a new potential sequence). After updating `current_length`, it's compared with `max_length`, and `max_length` is updated if `current_length` is larger. Finally, `previous_number` is updated to `current_number` for the next iteration. The time complexity is O(N log N) due to the sorting step required by the cursor, where N is the number of rows in the `numbers` table. The space complexity is O(1) if we consider the cursor's internal state as constant, or O(N) if the sorted data needs to be materialized. The correctness relies on the sorted iteration and the state variables (`current_length`, `max_length`) accurately tracking the sequence progression.

Pseudocode:

FUNCTION GetLongestConsecutiveSequenceLength():
  max_length = 0
  current_length = 0
  previous_number = NULL
  current_number = NULL
  done = FALSE

  IF numbers table is empty THEN
    RETURN 0
  END IF

  DECLARE cursor FOR SELECT number FROM numbers ORDER BY number ASC
  CONTINUE HANDLER FOR NOT FOUND SET done = TRUE

  OPEN cursor
  LOOP
    FETCH cursor INTO current_number
    IF done THEN EXIT LOOP

    IF previous_number IS NULL OR current_number = previous_number + 1 THEN
      current_length = current_length + 1
    ELSE
      current_length = 1
    END IF

    IF current_length > max_length THEN
      max_length = current_length
    END IF

    previous_number = current_number
  END LOOP
  CLOSE cursor
  RETURN max_length
END FUNCTION