Program to count how many blocks are covered k times by walking in Python

Suppose we have two lists called walks and target. At the beginning we are at position 0 in a one-dimensional line. Now |walks[i]| represents the number of steps we have walked. When walks[i] is positive it indicates we walked right, and negative for left. When we walk, we move one block at a time to the next or previous integer position. We have to find the number of blocks that have been walked on at least target number of times.

So, if the input is like walks = [3, -7, 2] and target = 2, then the output will be 5. From the following figure, we can see blocks [0, 1], [1, 2], [2, 3], [-4, -3], [-3, -2] are covered k = 2 times.

-4 -3 -2 -1 0 1 2 3 Walk 1: +3 Walk 2: -7 Walk 3: +2 Highlighted blocks are covered ? 2 times

Algorithm

To solve this, we will follow these steps ?

  • Initialize position to 0
  • Create a hash map to track coverage changes at each position
  • For each walk distance:
    • Increment coverage at start position
    • Decrement coverage at end position
    • Update current position
  • Use prefix sum technique to count blocks with coverage ? target

Example

Let us see the following implementation to get better understanding ?

from collections import defaultdict

def solve(walks, target):
    pos = 0
    jumps = defaultdict(int)
    
    for dist in walks:
        jumps[pos] += 1 if dist > 0 else -1
        jumps[pos + dist] -= 1 if dist > 0 else -1
        pos += dist
    
    lastpos = level = total = 0
    for pos, val in sorted(jumps.items()):
        if level >= target:
            total += pos - lastpos
        level += val
        lastpos = pos
    
    return total

walks = [3, -7, 2]
target = 2
result = solve(walks, target)
print(f"Blocks covered at least {target} times: {result}")

The output of the above code is ?

Blocks covered at least 2 times: 5

How It Works

The algorithm uses a difference array technique. Instead of tracking the actual coverage of each block, we record where coverage starts and ends. When we walk from position A to B, we increment the coverage counter at position A and decrement it at position B+1 (or B-1 for negative walks). Then we use a prefix sum to calculate the actual coverage levels and count blocks meeting the target threshold.

Conclusion

This solution efficiently counts blocks covered at least k times using difference arrays and prefix sums. The time complexity is O(n log n) due to sorting, where n is the number of walks.

Updated on: 2026-03-26T17:19:08+05:30

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements