Find Latest Group of Size M - Problem

Given an array arr that represents a permutation of numbers from 1 to n.

You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.

You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.

Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.

Input & Output

Example 1 — Basic Case
$ Input: arr = [3,5,1,2,4], m = 3
Output: 4
💡 Note: Step 1: 001000 (no groups of size 3), Step 2: 001010 (no groups of size 3), Step 3: 101010 (no groups of size 3), Step 4: 111010 (group of size 3 at positions 1-3), Step 5: 111110 (group of size 4, no size 3). Latest step with size 3 is step 4.
Example 2 — No Valid Group
$ Input: arr = [3,1,5,4,2], m = 3
Output: -1
💡 Note: At no point during the process do we get exactly 3 consecutive 1's that cannot be extended further.
Example 3 — Early Formation
$ Input: arr = [1], m = 1
Output: 1
💡 Note: After step 1: binary string becomes '1', which is a group of size 1.

Constraints

  • n == arr.length
  • 1 ≤ n ≤ 105
  • 1 ≤ arr[i] ≤ n
  • All integers in arr are distinct
  • 1 ≤ m ≤ n

Visualization

Tap to expand
Find Latest Group of Size M INPUT arr = [3, 5, 1, 2, 4] 3 i=1 5 i=2 1 i=3 2 i=4 4 i=5 m = 3 (target group size) Binary String Evolution: Step 0: 0 0 0 0 0 Step 1: 0 0 1 0 0 Step 2: 0 0 1 0 1 Step 3: 1 0 1 0 1 Step 4: 1 1 1 0 1 Group of 3! Step 5: 1 1 1 1 1 Input Values: arr = [3,5,1,2,4], m = 3 ALGORITHM STEPS 1 Initialize Tracking count[size] = num of groups length[pos] = group length 2 Process Each Step Set bit at arr[i] to 1 Check left/right neighbors 3 Merge Groups newLen = left + 1 + right Update endpoints only 4 Track Group Count Decrement old sizes Increment new size HashMap at Step 4: count[1] = 1 (pos 5) count[3] = 1 (pos 1-3) length[1] = 3 length[3] = 3 m=3 exists! Save step=4 FINAL RESULT Final State Analysis: 1 1 1 0 1 Group of 3 Latest step with m=3: Step 4 At step 4, positions 1,2,3 form a group of exactly 3 At step 5, all merge into one group of 5 Output: 4 Key Insight: Instead of tracking entire binary string, use HashMap to track group sizes efficiently. Store length at endpoints only: when merging groups, update left-most and right-most positions. Time: O(n), Space: O(n). Check if count[m] > 0 at each step to find latest occurrence. TutorialsPoint - Find Latest Group of Size M | Track Groups with HashMap Approach
Asked in
Facebook 15 Google 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen