Check if a key is present in every segment of size k in an array in Python

Suppose we have an array A with N elements, we have another value p and a segment size k, we have to check whether key p is present in every segment of size k in A.

So, if the input is like A = [4, 6, 3, 5, 10, 4, 2, 8, 4, 12, 13, 4], p = 4 and k = 3, then the output will be True because:

  • Segment 1: [4, 6, 3] contains 4 ?
  • Segment 2: [5, 10, 4] contains 4 ?
  • Segment 3: [2, 8, 4] contains 4 ?
  • Remaining elements: [12, 13, 4] contains 4 ?

Algorithm

To solve this, we will follow these steps ?

  • i := 0
  • while i < n is non-zero, do
    • j := 0
    • while j < k, do
      • if arr[j + i] is same as p, then
        • break
      • j := j + 1
    • if j is same as k, then
      • return False
    • i := i + k
  • if i is same as n, then
    • return True
  • j := i - k
  • while j < n, do
    • if arr[j] is same as p, then
      • break
    • j := j + 1
  • if j is same as n, then
    • return False
  • return True

Example

Let us see the following implementation to get better understanding ?

def key_in_segment_k(arr, p, k, n):
    i = 0
    while i < n:
        j = 0
        while j < k:
            if arr[j + i] == p:
                break
            j += 1
        if j == k:
            return False
        i = i + k
    if i == n:
        return True
    j = i - k
    while j < n:
        if arr[j] == p:
            break
        j += 1
    if j == n:
        return False
    return True

arr = [4, 6, 3, 5, 10, 4, 2, 8, 4, 12, 13, 4]
p, k = 4, 3
n = len(arr)
print(key_in_segment_k(arr, p, k, n))

The output of the above code is ?

True

How It Works

The algorithm divides the array into segments of size k and checks each segment for the presence of key p:

  • First loop processes complete segments of size k
  • If any segment doesn't contain p, return False immediately
  • Handle remaining elements (if array length isn't divisible by k)
  • Check if the remaining elements contain p

Alternative Approach

Here's a more readable implementation using list slicing ?

def check_key_in_segments(arr, p, k):
    n = len(arr)
    
    # Check complete segments of size k
    for i in range(0, n, k):
        segment = arr[i:i+k]
        if p not in segment:
            return False
    
    return True

arr = [4, 6, 3, 5, 10, 4, 2, 8, 4, 12, 13, 4]
p, k = 4, 3
print(check_key_in_segments(arr, p, k))

# Test with negative case
arr2 = [4, 6, 3, 5, 10, 7, 2, 8, 4]  # Second segment lacks 4
print(check_key_in_segments(arr2, 4, 3))

The output of the above code is ?

True
False

Conclusion

This problem efficiently checks if a key exists in every segment by iterating through the array in chunks of size k. The algorithm returns False as soon as any segment lacks the key, making it time-efficient with O(n) complexity.

Updated on: 2026-03-25T10:04:09+05:30

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements