<?php
function longestConsecutive($nums) {
if (empty($nums)) {
return 0;
}
// array_flip() returns an array in flip order,
// keys from array become values and values from array become keys.
$numSet = array_flip($nums);
$longestStreak = 0;
foreach ($nums as $num) {
// Check if it's the start of a sequence
// Example: for 680 -> 679 ($num - 1) not exists = Undefined array key = not set =
// = start at the beginning of a sequence.
if (!isset($numSet[$num - 1])) {
$currentNum = $num;
$currentStreak = 1;
// Count consecutive numbers
while (isset($numSet[$currentNum + 1])) {
$currentNum++;
$currentStreak++;
}
$longestStreak = max($longestStreak, $currentStreak);
}
}
return $longestStreak;
}
$nums = [680, 4, 590, 3, 1, 2];
echo "Length of the longest consecutive sequence: " . longestConsecutive($nums);
/*
run:
Length of the longest consecutive sequence: 4
*/