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
Understanding the Visualization
1
Input
Array [3,5,1,2,4] and target size m=3
2
Process
Set bits step by step, track group sizes
3
Output
Latest step (4) where group of size 3 exists
Key Takeaway
🎯 Key Insight: Track group sizes efficiently as bits are set, watching for the target size m
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code