Magicsheet logo

Find Latest Group of Size M

Medium
25%
Updated 8/1/2025

Find Latest Group of Size M

What is this problem about?

In the Find Latest Group of Size M coding problem, you start with a binary string of length nn consisting entirely of '0's. You are given an array arr which is a permutation of integers from 1 to nn. Each element arr[i] represents an index where you flip a '0' to a '1' at step ii. A "group" is a contiguous sequence of '1's. You need to find the latest step ii such that there exists at least one group of '1's with length exactly mm.

Why is this asked in interviews?

Google asks this problem to evaluate a candidate's ability to maintain dynamic connectivity and state tracking. As you add '1's, groups merge, and their lengths change. The Union Find or Simulation interview pattern is tested here. It evaluation your understanding of how to update frequencies of properties (group lengths) in O(1)O(1) or O(logn)O(\log n) time as the underlying data structure evolves.

Algorithmic pattern used

This problem is best solved using Union Find or a Length Array with frequency tracking.

  1. Maintain an array length where length[i] stores the length of the group of '1's that index ii belongs to.
  2. Use a Hash Map or array count to store the frequency of each group length.
  3. When flipping a 0 to 1 at index xx:
    • Find the lengths of groups to its left (LL) and right (RR).
    • Update the count by decrementing frequencies of LL and RR and incrementing the frequency of the new merged group length L+R+1L + R + 1.
    • Update the boundary elements of the new group to reflect the new length L+R+1L + R + 1.
  4. After each step, if count[m] > 0, the current step is a candidate for the latest group of size mm.

Example explanation

arr = [3, 5, 1, 2, 4], m = 1

  1. Step 1: Flip index 3. Group: [3] (len 1). count[1] = 1. Latest step = 1.
  2. Step 2: Flip index 5. Groups: [3] (len 1), [5] (len 1). count[1] = 2. Latest step = 2.
  3. Step 3: Flip index 1. Groups: [1] (len 1), [3] (len 1), [5] (len 1). count[1] = 3. Latest step = 3.
  4. Step 4: Flip index 2. Group [1, 2, 3] (len 3) forms. count[1] becomes 1 (only the [5] remains). Latest step = 4.
  5. Step 5: Flip index 4. Group [1, 2, 3, 4, 5] (len 5) forms. count[1] becomes 0. Result: 4.

Common mistakes candidates make

  • Brute Force: Re-scanning the entire string at each step to count groups, resulting in O(n2)O(n^2) complexity.
  • Inefficient Updates: Failing to only update the boundaries of the merged group, which is sufficient to maintain the logic.
  • Resetting incorrectly: Forgetting to update the latestStep only when the condition is met.

Interview preparation tip

When dealing with "merging" contiguous segments, always think about tracking the left and right endpoints. This allows you to update the state of the entire segment in constant time without iterating through all its elements.

Similar Questions