Leetcode 1684 Solution

This article provides solution to leetcode question 1684 (find-latest-group-of-size-m)

https://leetcode.com/problems/find-latest-group-of-size-m

Solution

class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: n = len(arr) v = [-1] * n lens = collections.defaultdict(int)
ans = -1 for j, i in enumerate(arr): i -= 1
if i > 0 and v[i - 1] != -1: left = v[i - 1] lens[i - left] -= 1 else: left = i
if i < n - 1 and v[i + 1] != -1: right = v[i + 1] lens[right - i] -= 1 else: right = i
v[left] = right v[right] = left lens[right - left + 1] += 1
if lens[m] > 0: ans = max(ans, j)
return ans + 1 if ans != -1 else -1