Problem Description
Given an array arr representing a permutation of numbers from 1 to n, we simulate a binary string of length n that starts with all zeros. At each step i (using 1-indexing for both arr and the binary string), the bit at position arr[i] is set to 1. We must determine the latest step (i.e., the maximum step index) at which there exists a contiguous group of 1s of exactly length m. If such a group never exists, return -1.
Key Insights
- Instead of simulating the entire string at every step, we maintain information about contiguous segments (groups) of 1s.
- Use an auxiliary array (or similar data structure) to store the length of the segment at the boundaries.
- When a bit changes to 1, check its left and right neighbors to merge segments if they exist.
- Maintain a count of segments that are exactly of length m. When merging segments, update the counts accordingly.
- This efficient approach ensures that each insertion only requires constant time checks and updates.
Space and Time Complexity
Time Complexity: O(n), as each insertion and merge operation is performed in constant time. Space Complexity: O(n), due to the auxiliary arrays used to track segment boundaries and counts.
Solution
We simulate the process by keeping track of contiguous segments using an extra array that marks the length of each segment at its boundaries. For each step:
- Retrieve the segment lengths immediately to the left and right of the bit that is being flipped.
- Combine these lengths with the current bit to form a new segment.
- Update the boundaries of the new segment.
- Adjust the count for segments of exactly length m by decrementing counts for segments that are merged and increasing if the new segment is of size m.
- Record the step if any segment of size m exists. The final answer is the last step (1-indexed) when such a segment exists.