Program to find latest group of size M using Python


Suppose we have an array arr this is holding a permutation of numbers from 1 to n. If we have a binary string of size n and initially all its bits set to zero. Now at each step i (Indexing starts from 1 for both the binary string and arr) from 1 to n, the bit at position arr[i] is set to 1. We also have another value m, and we need to find the latest step at which there exists a group of ones of size m. Here a group of ones means a contiguous substring of 1s such that it cannot be extended in either direction. We have to find the latest step at which there exists a group of ones of length exactly m. If we cannot find any such group, then return -1.

So, if the input is like arr = [3,5,1,2,4] m = 3, then the output will be 4 because, initial binary string is "00000" then following steps −

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

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

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

  • "11101", groups: ["111", "1"]

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

Here the latest step at which there exists a group of size 3 is step 4.

To solve this, we will follow these steps −

  • n := size of arr

  • num := 0

  • ans := -1

  • l := an array of size n, and fill with 0

  • r := an array of size n, and fill with 0

  • for i in range 0 to n - 1, do

    • cur := 1

    • idx := arr[i] - 1

    • if r[idx] is same as m, then

      • num := num - 1

    • if l[idx] is same as m, then

      • num := num - 1

    • cur := cur + l[idx] + r[idx]

    • num := num + cur is same as m

    • if num > 0, then

      • ans := maximum of ans, i + 1

    • if idx - l[idx] > 0, then

      • r[idx - l[idx] - 1] := cur

    • if idx + r[idx] < n - 1, then

      • l[idx + r[idx] + 1] := cur

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(arr, m):
   n = len(arr)
   num = 0
   ans = -1
   l = [0] * n
   r = [0] * n
   for i in range(n):
      cur = 1
      idx = arr[i] - 1
      if r[idx] == m:
         num -= 1
      if l[idx] == m:
         num -= 1
      cur += l[idx] + r[idx]
      num += cur == m
      if num > 0:
         ans = max(ans, i + 1)
      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
arr = [3,5,1,2,4]
m = 3
print(solve(arr, m))

Input

[3,5,1,2,4], 3

Output

4

Updated on: 29-May-2021

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements