#1562
Find Latest Group of Size M
MediumArrayHash TableBinary SearchSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking the entire binary string after each step, we can maintain a count of contiguous ones and track the latest step where a group of size m exists using a HashMap.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a binary string of size n with all bits set to 0 and a HashMap to track the count of contiguous ones.
- 2Step 2: For each index i from 1 to n, set the bit at position arr[i] to 1.
- 3Step 3: Maintain a count of contiguous ones and update the HashMap with the latest step for each count of ones.
- 4Step 4: If the count of ones equals m, update the latest step.
- 5Step 5: Return the latest step where a group of size m was found, or -1 if none was found.
solution.py20 lines
1# Full working Python code
2
3def latestStep(arr, m):
4 n = len(arr)
5 binary = [0] * n
6 latest_step = -1
7 count = 0
8 for step in range(n):
9 binary[arr[step] - 1] = 1
10 count = 0
11 for i in range(n):
12 if binary[i] == 1:
13 count += 1
14 else:
15 if count == m:
16 latest_step = step + 1
17 count = 0
18 if count == m:
19 latest_step = step + 1
20 return latest_stepℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the array once, and the space complexity is O(n) for storing the binary representation.
- 1The problem requires tracking contiguous groups of ones efficiently.
- 2Using a HashMap can help in tracking the latest step for each group size.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.