1. Brute Force

class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        n = len(nums)
        mn = min(nums)
        for val in range(mn, mn + n):
            found = False
            for num in nums:
                if num == val:
                    found = True
                    break
            if not found:
                return False
        return True

Time & Space Complexity

  • Time complexity: O(n2)O(n ^ 2)
  • Space complexity: O(1)O(1)

Where nn is the length of the array numsnums.


2. Sorting

class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1] + 1:
                return False
        return True

Time & Space Complexity

  • Time complexity: O(nlog⁡n)O(n \log n)
  • Space complexity: O(1)O(1) or O(n)O(n) depending on the sorting algorithm.

Where nn is the length of the array numsnums.


3. Hash Set

class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        n = len(nums)
        return len(set(nums)) == n and max(nums) - min(nums) == n - 1

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Where nn is the length of the array numsnums.


4. Boolean Array

class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        n = len(nums)
        mn = min(nums)
        seen = [False] * n
        for num in nums:
            idx = num - mn
            if idx >= n or seen[idx]:
                return False
            seen[idx] = True
        return True

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Where nn is the length of the array numsnums.


5. Cycle Sort

class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        n = len(nums)
        mn = min(nums)
        i = 0
        while i < n:
            index = nums[i] - mn
            if index >= n:
                return False
            if index == i:
                i += 1
            elif nums[index] == nums[i]:
                return False
            else:
                nums[i], nums[index] = nums[index], nums[i]
        return True

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1) extra space.

Where nn is the length of the array numsnums.