Given an array of integers, find the length of the longest consecutive sequence.
Explanation: Step-by-step: with input [100, 4, 200, 1, 3, 2], we first sort the array to get [1, 3, 4, 100, 200, 2]. Then, we initialize the longest chain length to 1 and the current chain length to 1. We iterate through the array, and for each element, we check if it is equal to the current chain length plus 1. If it is, we increment the current chain length. If it is not, we update the longest chain length if the current chain length is greater than the longest chain length. Finally, we return the longest chain length, which is 4.
Explanation: Step-by-step: with input [1, 9, 3, 10, 4, 20, 2], we first sort the array to get [1, 2, 3, 4, 9, 10, 20]. Then, we initialize the longest chain length to 1 and the current chain length to 1. We iterate through the array, and for each element, we check if it is equal to the current chain length plus 1. If it is, we increment the current chain length. If it is not, we update the longest chain length if the current chain length is greater than the longest chain length. Finally, we return the longest chain length, which is 4.
Analyze constraints and compute optimal solutions step-by-step.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak