|
| 1 | +/** |
| 2 | + * 1562. Find Latest Group of Size M |
| 3 | + * https://leetcode.com/problems/find-latest-group-of-size-m/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an array arr that represents a permutation of numbers from 1 to n. |
| 7 | + * |
| 8 | + * You have a binary string of size n that initially has all its bits set to zero. At each step |
| 9 | + * i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position |
| 10 | + * arr[i] is set to 1. |
| 11 | + * |
| 12 | + * You are also given an integer m. Find the latest step at which there exists a group of ones |
| 13 | + * of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended |
| 14 | + * in either direction. |
| 15 | + * |
| 16 | + * Return the latest step at which there exists a group of ones of length exactly m. If no such |
| 17 | + * group exists, return -1. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} arr |
| 22 | + * @param {number} m |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var findLatestStep = function(arr, m) { |
| 26 | + const lengths = new Array(arr.length + 2).fill(0); |
| 27 | + const count = new Map(); |
| 28 | + let result = -1; |
| 29 | + |
| 30 | + for (let step = 0; step < arr.length; step++) { |
| 31 | + const pos = arr[step]; |
| 32 | + const left = lengths[pos - 1]; |
| 33 | + const right = lengths[pos + 1]; |
| 34 | + const newLength = left + right + 1; |
| 35 | + |
| 36 | + lengths[pos - left] = newLength; |
| 37 | + lengths[pos + right] = newLength; |
| 38 | + lengths[pos] = newLength; |
| 39 | + |
| 40 | + count.set(left, (count.get(left) || 0) - 1); |
| 41 | + count.set(right, (count.get(right) || 0) - 1); |
| 42 | + count.set(newLength, (count.get(newLength) || 0) + 1); |
| 43 | + |
| 44 | + if (count.get(m) > 0) result = step + 1; |
| 45 | + } |
| 46 | + |
| 47 | + return result; |
| 48 | +}; |
0 commit comments