Finding Consecutive Number Sequences
This challenge requires you to identify and extract sequences of consecutive numbers from a given list of integers. This skill is fundamental in data processing and analysis, often used for tasks like identifying date ranges, detecting patterns in sensor data, or simplifying data representation.
Problem Description
Your task is to write a function that takes an unsorted list of distinct integers as input and returns a list of strings, where each string represents a sequence of consecutive numbers.
- A consecutive sequence is defined as a series of numbers where each number is exactly one greater than the preceding number.
- Sequences of length 1 should also be represented as a string.
- If a sequence contains more than two numbers, it should be represented as a range (e.g., "3->7").
- If a sequence contains exactly two numbers, they should be represented separated by a comma (e.g., "1,2").
- The output should maintain the order of the original input list, meaning sequences should appear in the output in the order their first element appears in the input.
- The input list contains distinct integers.
Examples
Example 1:
Input: [1, 2, 3, 4, 6, 7, 9]
Output: ["1->4", "6,7", "9"]
Explanation: The numbers 1, 2, 3, 4 form a consecutive sequence of length 4, so it's represented as "1->4". The numbers 6, 7 form a consecutive sequence of length 2, represented as "6,7". The number 9 is a sequence of length 1, represented as "9".
Example 2:
Input: [100, 4, 200, 1, 3, 2]
Output: ["1,2,3", "4", "100", "200"]
Explanation: After sorting conceptually (though your algorithm shouldn't rely on pre-sorting the input array for output order), we find the sequence 1, 2, 3 which is represented as "1,2,3". Then 4 is a single element sequence "4". 100 is "100", and 200 is "200". The output order reflects the first appearance of a number from a sequence in the original input. For instance, '100' appears before '4' in the input, so its sequence (just '100') comes first.
Example 3:
Input: [5]
Output: ["5"]
Explanation: A single number is a sequence of length 1.
Constraints
- The input list can contain between 0 and 1000 integers.
- Each integer in the list will be between -2,147,483,648 and 2,147,483,647.
- The input list contains distinct integers.
- Your solution should aim for an efficient time complexity, ideally close to O(n) where n is the number of integers in the input list.
Notes
- Consider how you will efficiently check for consecutive numbers.
- The order of output strings is determined by the first appearance of any number belonging to that consecutive sequence in the original input list. For instance, if the input is
[10, 1, 2], the sequence1, 2should appear after the sequence10in the output, because10appeared first in the input. - Think about data structures that might help you quickly check for the existence of numbers.