Leetcode 1562: Find Latest Group of Size M

grid47
grid47
Exploring patterns and algorithms
Jun 3, 2024 6 min read

You are given a permutation of integers from 1 to n, where each integer represents a position in a binary string of size n that is initially filled with zeros. At each step, you will flip the bit at the position specified by the current element of the array. You are also given an integer m, and your task is to determine the latest step at which there exists a contiguous substring of exactly m ones in the binary string.
Problem
Approach
Steps
Complexity
Input: The input consists of an array arr representing a permutation of numbers from 1 to n, and an integer m representing the length of the contiguous group of ones to look for.
Example: Input: arr = [4, 2, 5, 1, 3], m = 2
Constraints:
• 1 <= arr.length == n <= 10^5
• 1 <= m <= n
• arr[i] is a distinct number between 1 and n
Output: Return the latest step at which there exists a contiguous substring of exactly m ones. If no such group exists, return -1.
Example: Output: 4
Constraints:
Goal: Find the latest step at which there is a group of exactly m consecutive 1's.
Steps:
• Simulate each step where a bit is set to 1 based on the current position in arr.
• At each step, check if there is a group of exactly m ones.
• Track the step at which the first group of exactly m ones occurs, and return the latest step.
Goal: The number of elements in arr will be between 1 and 100,000, and the value of m will be between 1 and n.
Steps:
• 1 <= arr.length == n <= 10^5
• 1 <= m <= n
• arr[i] is a distinct number between 1 and n
Assumptions:
• The input array arr is a valid permutation of numbers from 1 to n.
• At each step, you only flip one bit.
Input: Example 1: arr = [4, 2, 5, 1, 3], m = 2
Explanation: In this case, after the first 4 steps, the binary string looks like: 01100. At step 4, we have a group of exactly 2 ones (11), which is the latest occurrence of such a group. Hence, the output is 4.

Input: Example 2: arr = [1, 3, 2], m = 1
Explanation: In this case, the binary string evolves as: 100, 110, 111. After all steps, a group of size 1 can be found at each step, but the latest step when a group of size 1 exists is step 3. Hence, the output is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus