Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python

We need to check if an array contains consecutive integers in O(n) time and O(1) space complexity. This algorithm works with both positive and negative numbers by using the arithmetic progression sum formula.

Algorithm Approach

The solution uses the mathematical property that consecutive integers form an arithmetic progression with common difference 1. We can verify if numbers are consecutive by comparing the actual sum with the expected sum of an arithmetic progression.

Step-by-Step Process

  • Find the minimum element (first term of AP)
  • Calculate expected sum using AP formula: n/2 × (2a + (n-1)d) where d=1
  • Compare with actual sum of array elements
  • Return true if sums match, false otherwise

Implementation

def solve(nums):
    size = len(nums)
    
    # Find minimum element (first term of AP)
    init_term = float('inf')
    for i in range(size):
        if nums[i] < init_term:
            init_term = nums[i]
    
    # Calculate expected sum using AP formula: n/2 * (2a + (n-1)*d)
    # where a = first term, n = number of terms, d = common difference (1)
    ap_sum = (size * (2 * init_term + (size - 1) * 1)) // 2
    
    # Calculate actual sum
    total = sum(nums)
    
    # Check if sums match
    return ap_sum == total

# Test with example
nums = [-3, 5, 1, -2, -1, 0, 2, 4, 3]
result = solve(nums)
print(f"Array: {nums}")
print(f"Are elements consecutive? {result}")
Array: [-3, 5, 1, -2, -1, 0, 2, 4, 3]
Are elements consecutive? True

How It Works

For the example array [-3, 5, 1, -2, -1, 0, 2, 4, 3], when sorted becomes [-3, -2, -1, 0, 1, 2, 3, 4, 5]. This forms a consecutive sequence from -3 to 5.

  • Minimum element: -3
  • Array size: 9
  • Expected AP sum: 9/2 × (2×(-3) + (9-1)×1) = 9/2 × (-6 + 8) = 9
  • Actual sum: -3 + 5 + 1 + (-2) + (-1) + 0 + 2 + 4 + 3 = 9

Testing with Different Cases

def solve(nums):
    size = len(nums)
    init_term = float('inf')
    
    for i in range(size):
        if nums[i] < init_term:
            init_term = nums[i]
    
    ap_sum = (size * (2 * init_term + (size - 1) * 1)) // 2
    total = sum(nums)
    return ap_sum == total

# Test cases
test_cases = [
    [1, 2, 3, 4, 5],           # Consecutive positive
    [-2, -1, 0, 1],            # Consecutive with negatives
    [1, 3, 5],                 # Non-consecutive
    [5, 4, 6, 3, 7]           # Consecutive but unsorted
]

for i, nums in enumerate(test_cases, 1):
    result = solve(nums)
    print(f"Test {i}: {nums} ? {result}")
Test 1: [1, 2, 3, 4, 5] ? True
Test 2: [-2, -1, 0, 1] ? True
Test 3: [1, 3, 5] ? False
Test 4: [5, 4, 6, 3, 7] ? True

Complexity Analysis

Aspect Complexity Explanation
Time O(n) Single pass to find minimum + O(n) for sum()
Space O(1) Only variables for calculations

Conclusion

This algorithm efficiently checks consecutive integers using arithmetic progression properties. It works with both positive and negative numbers while maintaining O(n) time and O(1) space complexity.

---
Updated on: 2026-03-25T14:22:21+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements