MySQL: Find Longest Consecutive Sequence
DELIMITER // CREATE FUNCTION GetLongestConsecutiveSequenceLength() RETURNS INT READS SQL DATA BEGIN DECLARE max_length INT DEFAULT 0; DECLARE current_length INT DEFAULT 0; DECLARE previous_number INT DEFAULT NULL; DECLARE current_number INT DEFAULT NULL; DECLARE done INT DEFAULT...
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,...
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.
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...