Check if an Array Is Consecutive

To solve this problem, you can find the minimum number in the list, then calculate the expected sum of the consecutive sequence using the formula for the sum of an arithmetic sequence: (n/2) * (first_num + last_num). Then compare this sum with the actual sum of the numbers in the list. If the sums are equal and the length of the list equals to the length of the set of the list (no duplicates), then the list is consecutive.

Python solution:

1
2
3
4
5
6
7
8
class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        min_num = min(nums)
        max_num = min_num + len(nums) - 1
        expected_sum = len(nums) * (min_num + max_num) // 2
        actual_sum = sum(nums)

        return actual_sum == expected_sum and len(nums) == len(set(nums))

In the code, min_num is the smallest number in the list, max_num is the last number in the expected consecutive sequence, expected_sum is the sum of the consecutive sequence from min_num to max_num, actual_sum is the sum of the actual numbers in the list. The function returns True only if the actual_sum equals expected_sum and there are no duplicate numbers in the list, which means the list is consecutive.