Program to find latest group of size M using Python

Suppose we have an array arr holding a permutation of numbers from 1 to n. We have a binary string of size n with all bits initially set to zero. At each step i (1-indexed), we set the bit at position arr[i] to 1. Given a value m, we need to find the latest step at which there exists a group of ones of size exactly m.

A group of ones means a contiguous substring of 1s that cannot be extended in either direction. If no such group exists, we return -1.

Example Walkthrough

If the input is arr = [3,5,1,2,4] and m = 3, the binary string evolves as follows ?

  • Step 1: "00100", groups: ["1"]

  • Step 2: "00101", groups: ["1", "1"]

  • Step 3: "10101", groups: ["1", "1", "1"]

  • Step 4: "11101", groups: ["111", "1"] ? group of size 3 exists

  • Step 5: "11111", groups: ["11111"]

The latest step with a group of size 3 is step 4.

Algorithm

We track contiguous groups using two arrays ?

  • l[i]: length of the group extending to the left from position i

  • r[i]: length of the group extending to the right from position i

  • num: current count of groups with size exactly m

For each step, when we set bit at position idx, we merge adjacent groups and update our tracking arrays.

Implementation

def solve(arr, m):
    n = len(arr)
    num = 0  # count of groups with size m
    ans = -1
    l = [0] * n  # left extension lengths
    r = [0] * n  # right extension lengths
    
    for i in range(n):
        cur = 1  # current position contributes 1
        idx = arr[i] - 1  # convert to 0-indexed
        
        # Remove count if adjacent groups had size m
        if r[idx] == m:
            num -= 1
        if l[idx] == m:
            num -= 1
        
        # Merge with adjacent groups
        cur += l[idx] + r[idx]
        
        # Add count if new merged group has size m
        num += (cur == m)
        
        # Update answer if we have groups of size m
        if num > 0:
            ans = max(ans, i + 1)
        
        # Update boundary positions
        if idx - l[idx] > 0:
            r[idx - l[idx] - 1] = cur
        if idx + r[idx] < n - 1:
            l[idx + r[idx] + 1] = cur
    
    return ans

# Test the function
arr = [3, 5, 1, 2, 4]
m = 3
result = solve(arr, m)
print(f"Latest step with group of size {m}: {result}")
Latest step with group of size 3: 4

How It Works

The algorithm efficiently tracks group sizes without reconstructing the binary string at each step. When we add a new bit, we ?

  • Check if merging destroys existing groups of size m

  • Calculate the new merged group size

  • Check if the new group has size m

  • Update boundary information for future merges

Time complexity is O(n) and space complexity is O(n).

Conclusion

This solution efficiently tracks contiguous groups of 1s without rebuilding the binary string at each step. The key insight is using boundary arrays to maintain group size information and count groups of the target size m.

Updated on: 2026-03-25T21:03:49+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements