Python - K difference Consecutive Element

The K difference consecutive element problem involves checking if consecutive elements in a list have a specific difference value K. This is useful in data analysis and algorithm problems where you need to validate sequential patterns.

Let's understand with an example ?

Given list: [5, 6, 3, 2, 4, 3, 4] and K = 1

We check each consecutive pair: |5-6|=1 (True), |6-3|=3 (False), |3-2|=1 (True), etc.

Result: [True, False, True, False, True, True]

Method 1: Using Brute Force Approach

The simplest approach iterates through the list and compares each consecutive pair using the absolute difference ?

def k_diff_consecutive(numbers, K):
    result = []
    # Check each consecutive pair
    for i in range(len(numbers) - 1):
        if abs(numbers[i] - numbers[i+1]) == K:
            result.append(True)
        else:
            result.append(False)
    return result

# Test the function
numbers = [5, 6, 3, 2, 5, 3, 4]
K = 1
output = k_diff_consecutive(numbers, K)
print("K difference consecutive elements:", output)
K difference consecutive elements: [True, False, True, False, False, True]

Method 2: Using List Comprehension

A more concise approach using list comprehension for cleaner code ?

def k_diff_consecutive_compact(numbers, K):
    return [abs(numbers[i] - numbers[i+1]) == K for i in range(len(numbers) - 1)]

# Test the function
numbers = [5, 6, 3, 2, 5, 3, 4]
K = 1
output = k_diff_consecutive_compact(numbers, K)
print("Result using list comprehension:", output)
Result using list comprehension: [True, False, True, False, False, True]

Method 3: Checking Sorted Consecutive Differences

This approach sorts the list first, then checks consecutive differences in the sorted order ?

def k_diff_sorted(numbers, K):
    sorted_numbers = sorted(numbers)
    result = []
    
    for i in range(1, len(sorted_numbers)):
        if sorted_numbers[i] - sorted_numbers[i-1] == K:
            result.append(True)
        else:
            result.append(False)
    return result

# Test the function
numbers = [5, 6, 3, 2, 4, 3, 4]
K = 1
output = k_diff_sorted(numbers, K)
print("Sorted approach result:", output)
Sorted approach result: [True, False, True, False, True, True]

Comparison

Method Time Complexity Space Complexity Best For
Brute Force O(n) O(n) Original order preservation
List Comprehension O(n) O(n) Concise readable code
Sorted Approach O(n log n) O(n) Finding patterns in sorted data

Conclusion

Use the brute force approach for checking consecutive differences in original order. The list comprehension method provides cleaner code with the same functionality. Choose the sorted approach when you need to analyze patterns in ordered data.

Updated on: 2026-03-27T12:40:05+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements