Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # O(n), Space: O(n) n = len(arr) min_lens = [sys.maxsize] * n l = 0 min_len = sys.maxsize prefix = 0 ans = sys.maxsize for r in range(n): prefix += arr[r] while prefix > target: prefix -= arr[l] l += 1 if prefix == target: cur_len = r - l + 1 if l > 0 and min_lens[l - 1] != sys.maxsize: ans = min(ans, cur_len + min_lens[l - 1]) # find previous (before l - 1) sub-arrays, avoid overlapping min_len = min(min_len, cur_len) min_lens[r] = min_len return -1 if ans == sys.maxsize else ans
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: LARGE_NUMBER = 1000000000 if not arr: return -1 psum = [0]*(len(arr)+1) sum2i = {} for i in range(len(arr)): psum[i+1] = psum[i] + arr[i] res = LARGE_NUMBER dp = [LARGE_NUMBER]*(len(arr)+1) for i,x in enumerate(psum): assert x not in sum2i sum2i[x]=i if i>0: dp[i]=dp[i-1] if psum[i]-target in sum2i: j = sum2i[psum[i]-target] dp[i] = min(dp[i],i-j) if dp[j]!=LARGE_NUMBER: res = min(res, dp[j]+i-j) return res if res!=LARGE_NUMBER else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: presum = [0] * len(arr) c = 0 for i in range(len(arr)): c += arr[i] presum[i] = c dic ={0:-1} index = [0] * len(arr) short = [0] * len(arr) temp = sys.maxsize for i in range(len(arr)): if presum[i] - target in dic: index[i] = (i - dic[ presum[i] - target ] ) temp = min(temp, i - dic[ presum[i] - target ] ) dic[ presum[i] ] = i short[i] = temp ans = sys.maxsize print((index, short)) for i in range(1, len(arr)): if index[i] > 0 and i - index[i] >= 0 and (short[i - index[i]] != sys.maxsize): ans = min(ans, short[i - index[i]] + index[i]) if ans == sys.maxsize: return -1 return ans #[3,1,1,1,5,1,2,1] #3 4 5 6 11 12 14 15 # 1 0 0 3 0 0. 2. 2
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
from collections import deque from itertools import accumulate class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # TC: O(N), SC: O(N), prefix sum + deque x, n = list(accumulate(arr, initial=0)), len(arr) s, d = [], {} for i in range(n + 1): y = x[i] - target if y in d: s.append([i - d[y], d[y], i]) d[x[i]] = i # min length beyond index i-th for k in range(len(s) - 2, -1, -1): s[k][0] = min(s[k][0], s[k + 1][0]) ans, queue = float('inf'), deque([]) for d, i, j in s: while queue and queue[0][-1] <= i: ans = min(ans, queue.popleft()[0] + d) queue.append((j - i, i, j)) return ans if ans < float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
from collections import defaultdict class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: prefix = defaultdict(list) best_till = [sys.maxsize] * len(arr) res = sys.maxsize prefix[0].append(-1) temp_s = 0 for i, ele in enumerate(arr): temp_s += ele prefix[temp_s].append(i) #print(i, temp_s) if temp_s - target in prefix: for index in prefix[temp_s - target]: best_till[i] = min(best_till[i - 1], i - index) if index != -1: res = min(res, best_till[index] + i - index) #print(\"found\", i, index, temp_s, best_till[i], res) else: if i >= 1: best_till[i] = best_till[i - 1] #print(\"best_till\", best_till) return -1 if res == sys.maxsize else res
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # m[i]: min length and and in i, included ptr1, ptr2 = 0, 0 # both inclusive s = arr[0] # cum sum m = [-1]*len(arr) ans = -1 global_min = -1 while ptr2 < len(arr): if global_min>0: m[ptr2] = global_min if s == target: m[ptr2] = min(global_min, ptr2-ptr1+1) if global_min> 0 else ptr2-ptr1+1 global_min = m[ptr2] if ptr1-1>=0 and m[ptr1-1]>0: ans = min(ans, m[ptr1-1]+ptr2-ptr1+1) if ans >0 else m[ptr1-1]+ptr2-ptr1+1 ptr1 += 1 ptr2 += 1 if ptr2 < len(arr): s = s- arr[ptr1-1] + arr[ptr2] elif s> target: ptr1 += 1 s = s- arr[ptr1-1] if ptr1 > ptr2 and ptr2+1 < len(arr): ptr2 += 1 s = s+arr[ptr2] else: ptr2 += 1 if ptr2 < len(arr): s = s+arr[ptr2] return ans
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: nums=[0 for i in range(len(arr))] nums[0]=arr[0] for i in range(1,len(arr)): nums[i]=nums[i-1]+arr[i] best=[float('inf') for i in range(len(arr))] ans=float('inf') size=float('inf') # count=2 l=0 r=0 window=0 while l<=r and r<len(arr): window+=arr[r] while l<=r and window>target: # print(l,r) window-=arr[l] l+=1 if window==target: ans=min(ans,r-l+1+best[l-1]) best[r]=min(best[r-1],r-l+1) else: best[r]=best[r-1] r+=1 if ans==float('inf'): return -1 else: return ans # dp=[0 for i in range(len(arr)+1)] # currSum=0 # l=[] # i=0 # j=0 # while i<=j and j<len(arr): # currSum=currSum+arr[j] # print(i,j,currSum) # if currSum==target or arr[j]==target: # l.append(j-i+1) # currSum=0 # j+=1 # i=j # elif currSum<target: # currSum+=arr[j] # j+=1 # else: # # print(\"h\",currSum) # currSum=currSum-arr[i] # # print(currSum,arr[i]) # i+=1 # print(l)
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
import bisect class Solution: def minSumOfLengths(self, arr, target): # inclusive, inclusive sliding window pointers lo = 0 hi = 0 cur = arr[0] # store (end, start) pairs of valid subarrays running_min = [] ans = 1e9 while lo <= hi and hi < len(arr): if cur >= target: if cur == target: best_range = hi - lo + 1 if len(running_min): best_range = min(best_range, running_min[-1][1]) prev_index = bisect.bisect(running_min, (lo, -1)) - 1 if 0 <= prev_index < len(running_min): ans = min(ans, hi - lo + 1 + running_min[prev_index][1]) running_min.append((hi, best_range)) cur -= arr[lo] lo += 1 if hi < lo: hi = lo else: continue else: hi += 1 if hi < len(arr): cur += arr[hi] return ans if ans != 1e9 else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: best_so_far = [float('inf') for i in range(len(arr)+1)] prefix_sum = 0 prefix_sum_to_idx = {0:-1} res = float('inf') for i,v in enumerate(arr): prefix_sum += v best_so_far[i+1] = best_so_far[i] prev_sum = prefix_sum - target if prev_sum in prefix_sum_to_idx: res = min(res, best_so_far[prefix_sum_to_idx[prev_sum]+1] + i - prefix_sum_to_idx[prev_sum]) best_so_far[i+1] = min(best_so_far[i], i - prefix_sum_to_idx[prev_sum]) prefix_sum_to_idx[prefix_sum] = i return -1 if res == float('inf') else res
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # 1. Iterate i: 0 ~ n-2 # 1a. find min length to make target number in 0 ~ i # 1b. if found, see if possible to make target number with consequent numbers starting from i+1 # 1c. if found, update min n = len(arr) best_to = [n + 1 for _ in range(n)] best_from = dict() min_total = n + 1 # Naturally impossible length. Will be updated if any possible case exist. Will tell when no possible case min_left = n + 1 sum_left = 0 s_left = 0 e_left = 0 for i in range(n): sum_left += arr[i] if sum_left == target: best_to[i] = i - s_left + 1 best_from[s_left] = i - s_left + 1 elif sum_left > target: while s_left < i and sum_left > target: sum_left -= arr[s_left] s_left += 1 if sum_left == target: best_to[i] = i - s_left + 1 best_from[s_left] = i - s_left + 1 for i in range(1, n): best_to[i] = min(best_to[i], best_to[i-1]) for i in range(n - 1): if best_to[i] > n: continue if i + 1 in best_from: min_total = min(min_total, best_to[i] + best_from[i + 1]) # for i in range(n - 1): # sum_left += arr[i] # if sum_left == target: # # print(str(s_left) + '->' + str(e_left)) # best[s_left] = e_left - s_left + 1 # min_left = min(min_left, best[s_left]) # elif sum_left > target: # # Need to drop some numbers # while s_left < e_left and sum_left > target: # sum_left -= arr[s_left] # s_left += 1 # if sum_left == target: # min_left = min(min_left, e_left - s_left + 1) # # Skip if a subarray is not found on left # if min_left > n: # continue # if i + 1 in # sum_right = 0 # for j in range(i + 1, n): # sum_right += arr[j] # if sum_right == target: # min_total = min(min_total, min_left + j - i) # elif sum_right > target: # # Stop following as already exceeded # break if min_total > n: return -1 return min_total
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: prefix = {0: -1} best_till = [math.inf] * len(arr) ans = best = math.inf curr = 0 for i in range(len(arr)): curr += arr[i] if curr - target in prefix: end = prefix[curr - target] if end > -1: ans = min(ans, i - end + best_till[end]) best = min(best, i - end) best_till[i] = best prefix[curr] = i return -1 if ans == math.inf else ans
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
from collections import defaultdict as ddic class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: dic = ddic(int) sum_ = 0 dic[0] = -1 L = len(arr) dp = [0]*L dp2 = [-1]*L res = float('inf') for i in range(L): sum_ += arr[i] dic[sum_] = i if sum_ - target in dic: dp[i] = i - dic[sum_-target] dp2[i] = i - dic[sum_-target] if i!=0: if dp2[i-1]!=-1: dp2[i] = min(dp2[i],dp2[i-1]) if dp2[dic[sum_-target]]!=-1: res = min(res, dp[i]+dp2[dic[sum_-target]]) if dp2[i]==-1: if i!=0: dp2[i] = dp2[i-1] #print(dp,dp2) if res>L: return -1 return res
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: n=len(arr) minlens=[float('inf')]*n #min length of a valid subarray ends or before i. res=float('inf') sum1=0 s=0 min_len=float('inf') for e in range(n): sum1+=arr[e] while sum1>target: sum1-=arr[s] s+=1 if sum1==target: cur_len=e-s+1 if s>0 and minlens[s-1]!=float('inf'): res=min(res,cur_len+minlens[s-1]) min_len=min(min_len,cur_len) minlens[e]=min_len if res!=float('inf'): return res return -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # subarr that has target sum len_to_start = collections.defaultdict(list) # find start, end = 0, 1 tmp_sum = arr[0] earliest_end, latest_start = len(arr), 0 while start<len(arr): while end<len(arr) and tmp_sum<target: tmp_sum += arr[end] end += 1 if tmp_sum==target: len_to_start[end-start].append(start) earliest_end = min(earliest_end, end) latest_start = max(latest_start, start) tmp_sum -= arr[start] start += 1 if earliest_end>latest_start: return -1 # find shortest for l, starts in list(len_to_start.items()): if len(starts)>2: len_to_start[l] = [starts[0],starts[-1]] shortest=len(arr) for l1 in len_to_start: for s1 in len_to_start[l1]: for l2 in len_to_start: for s2 in len_to_start[l2]: if l1+l2>=shortest: continue if s1<s2 and s1+l1<=s2: shortest = l1+l2 if s2<s1 and s2+l2<=s1: shortest = l1+l2 return shortest
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: # 864 ms def minSumOfLengths(self, arr, target): result = inf = 2**31-1 i = window = count = 0 # preMin: store previous shortest length preMin = [(-1, inf)] # i: window start, j: window end for j, num in enumerate(arr): window += num while window > target: window -= arr[i] i += 1 if window == target: # curr: current length curr = j - i + 1 n = 0 # find first minimal length n before window start i for index, length in preMin[::-1]: if index <= i-1: n = length break # update result if less if result > curr + n: result = curr + n # update shortest length if less if curr < preMin[-1][-1]: preMin.append((j, curr)) # early stopping if found two single targets # if curr == 1: count += 1 # if count == 2: return 2 return result if result < inf else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: left, right = 0, 0 valid_subarray_lengths = [0 for _ in range(len(arr))] cum_sum = 0 for i in range(len(arr)): cum_sum += arr[i] right = i while cum_sum > target: cum_sum -= arr[left] left += 1 if cum_sum == target: valid_subarray_lengths[i] = right - left + 1 prefix_min_lengths = [None for _ in range(len(valid_subarray_lengths))] prefix_min = float('inf') for i in range(len(valid_subarray_lengths)): prefix_min = min(prefix_min, valid_subarray_lengths[i] if valid_subarray_lengths[i] else float('inf')) prefix_min_lengths[i] = prefix_min res = float('inf') for i in range(len(valid_subarray_lengths)): if valid_subarray_lengths[i] != 0 and i - valid_subarray_lengths[i] >= 0 and prefix_min_lengths[i - valid_subarray_lengths[i]] > 0: res = min(res, valid_subarray_lengths[i] + prefix_min_lengths[i - valid_subarray_lengths[i]]) return res if res != float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: # 864 ms def minSumOfLengths(self, arr, target): result = inf = 2**31-1 i = window = count = 0 # preMin: store previous shortest length preMin = [(-1, inf)] # i: window start, j: window end for j, num in enumerate(arr): window += num while window > target: window -= arr[i] i += 1 if window == target: # curr: current length curr = j - i + 1 n = 0 # find first minimal length before window start i for index, length in preMin[::-1]: if index <= i-1: n = length break # update result if less if result > curr + n: result = curr + n # update shortest length if less if curr < preMin[-1][-1]: preMin.append((j, curr)) # early stopping if found two single targets if curr == 1: count += 1 if count == 2: return 2 return result if result < inf else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: lens_s = [math.inf] * len(arr) lens_e = [math.inf] * len(arr) cs = s = e = 0 for i in range(len(arr)): cs += arr[e] while cs >= target: if cs == target: lens_e[e] = lens_s[s] = e + 1 - s cs -= arr[s] s += 1 e += 1 forward = [math.inf] * (len(arr) + 1) for i in range(1, len(arr)): forward[i] = min(lens_e[i-1], forward[i-1]) backward = [math.inf] * (len(arr) + 1) for i in reversed(list(range(0, len(arr)))): backward[i] = min(lens_s[i], backward[i+1]) best = math.inf for f, b in zip(forward, backward): best = min(best, f + b) if best == math.inf: return -1 return best
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: n=len(arr) min_lens=[float('inf')]*n ans=float('inf') cur_sum=0 min_len=float('inf') s=0 for e in range(n): cur_sum+=arr[e] while cur_sum>target: cur_sum-=arr[s] s+=1 if cur_sum==target: cur_len=e-s+1 if s>0 and min_lens[s-1]!=float('inf'): ans=min(ans, cur_len+min_lens[s-1]) min_len=min(cur_len, min_len) min_lens[e]=min_len return (-1 if ans==float('inf') else ans)
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # They are all positive n = len(arr) # DP is shortest array up to i dp = [float('inf') for _ in range(n+1)] ans = float('inf') start = 0 curr_sum = 0 for end in range(n): curr_sum += arr[end] while start < end and curr_sum > target: curr_sum -= arr[start] start += 1 if curr_sum == target: print(start, end) ans = min(ans, end - start + 1 + dp[start-1]) # or start - 1 dp[end] = min(dp[end-1], end - start + 1) else: dp[end] = dp[end-1] print(dp) return ans if ans != float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: prefix = {0: -1} res, best, dp = sys.maxsize, sys.maxsize, [sys.maxsize]*len(arr) for i, acc in enumerate(itertools.accumulate(arr)): if acc-target in prefix: end = prefix[acc-target] if end > -1: res = min(res, i-end+dp[end]) best = min(best, i-end) dp[i] = best prefix[acc] = i return -1 if res==sys.maxsize else res
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
import bisect, heapq class Solution: def minSumOfLengths(self, arr, target): # inclusive, inclusive sliding window pointers lo = 0 hi = 0 cur = arr[0] # store (end, start) pairs of valid subarrays pairs = [] running_min = [] ans = 1e9 while lo <= hi and hi < len(arr): # print(running_min) # print(lo, hi, cur) if cur >= target: if cur == target: best_range = hi - lo + 1 if len(running_min): best_range = min(best_range, running_min[-1][1]) prev_index = bisect.bisect(running_min, (lo, -1)) - 1 # print(\"Attempting to find %d... got %d\" % (lo, prev_index)) if 0 <= prev_index < len(running_min): ans = min(ans, hi - lo + 1 + running_min[prev_index][1]) running_min.append((hi, best_range)) heapq.heappush(pairs, (hi, lo)) cur -= arr[lo] lo += 1 if hi < lo: hi = lo else: continue else: hi += 1 if hi < len(arr): cur += arr[hi] return ans if ans != 1e9 else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: n = len(arr) # def aux(arr): # h = {0:0} # preSum = 0 # left = [n+1 for i in range(n)] # for i in range(1, n+1): # preSum = preSum + arr[i-1] # h[preSum] = i # if preSum-target in h: # left[i-1] = i-h[preSum-target] # if i > 1: # left[i-1] = min(left[i-2], left[i-1]) # return left # left = aux(arr) # arr.reverse() # right = aux(arr) # ans = n+1 # for i in range(n): # ans = min(ans, left[i] + right[n-1-(i+1)]) # return ans if ans < n+1 else -1 h = {0:-1} preSum = [0 for i in range(n)] for i in range(n): preSum[i] = preSum[i-1] + arr[i] if i > 0 else arr[0] h[preSum[i]] = i left = [n+1 for i in range(n)] ans = n+1 for i in range(n): if preSum[i]-target in h: left[i] = i-h[preSum[i]-target] if i > 0: left[i] = min(left[i-1], left[i]) if left[i] < n+1 and preSum[i]+target in h: right = h[preSum[i]+target]-i ans = min(ans, left[i]+right) return ans if ans < n+1 else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: s = 0 j = 0 ans = float('inf') res = [float('inf')] * len(arr) currMin = float('inf') for i in range(len(arr)): s += arr[i] while s > target: s -= arr[j] j += 1 if s == target: currMin = min(currMin, i - j + 1) ans = min(ans, res[j-1] + i - j + 1) res[i] = currMin return ans if ans < float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: l = len(arr) left, right, pre = [l]*l, [l]*l, {0:-1} p = 0 for i in range(l): p += arr[i] if p - target in pre: prev = pre[p - target] left[i] = i - prev if prev >= 0: right[prev] = min(right[prev], i - prev) pre[p] = i for i in range(1, l): left[i] = min(left[i], left[i-1]) for i in range(l-2, -1, -1): right[i] = min(right[i], right[i+1]) ans = l + 1 # for i in range(l): # if left[i] < l and right[i] < l: # ans = min(ans, left[i] + right[i]) ans = min( left[i] + right[i] if left[i] < l and right[i] < l else l + 1 for i in range(l) ) return ans if ans < l + 1 else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: n = len(arr) left = [float('inf')]*n memo = {0:-1} current = 0 for k in range(n): if k > 0: left[k] = left[k-1] current += arr[k] if current - target in memo: left[k] = min(left[k], k - memo[current - target]) memo[current] = k #print(left) right = [float('inf')]*n memo = {0:n} current = 0 for k in range(n-1, -1, -1): if k < n-1: right[k] = right[k+1] current += arr[k] if current - target in memo: right[k] = min(right[k], memo[current-target] - k) memo[current] = k ans = float('inf') for k in range(n-1): ans = min(ans, left[k] + right[k+1]) return ans if ans != float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: prefix = {0: -1} best_till = [math.inf] * len(arr) ans = best = math.inf for i, curr in enumerate(itertools.accumulate(arr)): if curr - target in prefix: end = prefix[curr - target] if end > -1: ans = min(ans, i - end + best_till[end]) best = min(best, i - end) best_till[i] = best prefix[curr] = i return -1 if ans == math.inf else ans
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: def getPrefix(arr): m = {0:-1} prefix = [float('inf')] s = 0 for i, n in enumerate(arr): s += n minn = prefix[-1] if (s - target) in m: minn = min(i - m[s-target], minn) prefix.append(minn) m[s] = i prefix.pop(0) return prefix prefix = getPrefix(arr) sufix = list(reversed(getPrefix(reversed(arr)))) ans = float('inf') for i in range(len(arr)-1): ans = min(ans, prefix[i] + sufix[i+1]) return ans if ans != float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: d = {} d[0] = -1 possible_sum = {0} cur_sum = 0 for i,a in enumerate(arr): cur_sum += a possible_sum.add(cur_sum) d[cur_sum] = i till_len = [float('inf')] * len(arr) for s in possible_sum: if s + target in possible_sum: till_len[d[s+target]] = d[s+target] - d[s] ans = float('inf') pre_min = [float('inf')] * len(arr) for i, t in enumerate(till_len): # t is the length of good subarrays until index i. # if t == float('inf'): continue if i == t - 1: pre_min[i] = t else: pre_min[i] = min(t, pre_min[i-1]) if t < float('inf') and pre_min[i-t] < float('inf'): ans = min(ans, t + pre_min[i-t]) return ans if ans < float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: n = len(arr) prefixSum = [0] * n targetSum = [sys.maxsize] * n beforeSum = [sys.maxsize] * n afterSum = [sys.maxsize] * n sumDict = {0:-1} total = 0 for i in range(n): total += arr[i] prefixSum[i] = total if (total - target) in sumDict: index = sumDict[total - target] targetSum[i] = i - index sumDict[total] = i minValue = sys.maxsize for i in range(n): # if (targetSum[i] > 0): minValue = min(targetSum[i], minValue) beforeSum[i] = minValue minValue = sys.maxsize for i in reversed(list(range(1, n))): # print(targetSum[i]) startIndex = i - targetSum[i] if (startIndex >= 0): afterSum[startIndex] = min(afterSum[startIndex], targetSum[i]) # print(f\"Setting aftersum[{startIndex}] = {afterSum[startIndex]}\") # minValue = min(targetSum[i], minValue) # afterSum[i - 1] = minValue # print(f\"targetSum = {targetSum}\") # print(f\"afterSum = {afterSum}\") # print(f\"beforeSum = {beforeSum}\") minValue = sys.maxsize for i in range(len(arr)): minValue = min(minValue, beforeSum[i] + afterSum[i]) if (minValue == sys.maxsize): minValue = -1 return minValue
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: curr_sum = 0 intervals = [(-200002, -100001), (-200002, -100001)] h = {0 : -1} f = [[100001] * len(arr) for i in range(2)] for index, a in enumerate(arr): curr_sum += a f[1][index] = min(f[0][h[curr_sum - target]] + index - h[curr_sum - target] if curr_sum - target in h else 100001, f[1][index - 1]) f[0][index] = min(f[0][index - 1] if index >= 1 else 100001, index - h[curr_sum - target] if curr_sum - target in h else 100001) h[curr_sum] = index return -1 if f[-1][-1] >= 100001 else f[-1][-1]
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: n = len(arr) left = [float('inf')]*n memo = {0:-1} current = 0 for k in range(n): if k > 0: left[k] = left[k-1] current += arr[k] if current - target in memo: left[k] = min(left[k], k - memo[current - target]) memo[current] = k print(left) right = [float('inf')]*n memo = {0:n} current = 0 for k in range(n-1, -1, -1): if k < n-1: right[k] = right[k+1] current += arr[k] if current - target in memo: right[k] = min(right[k], memo[current-target] - k) memo[current] = k ans = float('inf') for k in range(n-1): ans = min(ans, left[k] + right[k+1]) return ans if ans != float('inf') else -1
Given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Example 1: Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2. Example 2: Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2. Example 3: Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6. Example 4: Input: arr = [5,5,4,4,5], target = 3 Output: -1 Explanation: We cannot find a sub-array of sum = 3. Example 5: Input: arr = [3,1,1,1,5,1,2,1], target = 3 Output: 3 Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 1000 1 <= target <= 10^8
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: l = len(arr) left, right, pre = [l]*l, [l]*l, {0:-1} p = 0 for i in range(l): p += arr[i] if p - target in pre: prev = pre[p - target] left[i] = i - prev if prev >= 0: right[prev] = min(right[prev], i - prev) pre[p] = i for i in range(1, l): left[i] = min(left[i], left[i-1]) for i in range(l-2, -1, -1): right[i] = min(right[i], right[i+1]) ans = l + 1 for i in range(l): if left[i] < l and right[i] < l: ans = min(ans, left[i] + right[i]) if ans < l + 1: return ans return -1
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: n = len(grid) m = len(grid[0]) F = [i for i in range(m * n)] def find(x): if x == F[x]: return x else: F[x] = find(F[x]) return F[x] for i in range(n): for j in range(m): if i > 0 and grid[i-1][j] == grid[i][j]: f1 = find((i-1)*m+j) f2 = find((i)*m+j) if f1 == f2: return True F[f1] = f2 if j > 0 and grid[i][j-1] == grid[i][j]: f1 = find((i)*m+j-1) f2 = find((i)*m+j) if f1 == f2: return True F[f1] = f2 return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited = set() m = len(grid) if m==1: return False n = len(grid[0]) dirs = [(0,-1),(-1,0),(0,1),(1,0)] def dfs(prev, curr): if curr in visited: return True visited.add(curr) for dirn in dirs: nei = (dirn[0]+curr[0], dirn[1]+curr[1]) if 0<=nei[0]<m and 0<=nei[1]<n and nei != prev and grid[nei[0]][nei[1]] == grid[curr[0]][curr[1]]: if dfs(curr, nei): return True return False for i in range(m): for j in range(n): if (i,j) not in visited: if dfs(None, (i,j)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
import collections class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: if ranks[parent2] > ranks[parent1]: parents[parent1] = parent2 else: parents[parent2] = parent1 if ranks[parent1] == ranks[parent2]: ranks[parent1] += 1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} ranks = collections.Counter() for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter: union((i, j), (r, c)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: if ranks[parent2] > ranks[parent1]: parents[parent1] = parent2 else: parents[parent2] = parent1 if ranks[parent1] == ranks[parent2]: ranks[parent1] += 1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} ranks = collections.Counter() for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter: union((i, j), (r, c)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UnionFind: def __init__(self,n): self.parent = [i for i in range(n)] self.size = [1]*n def find(self,A): root=A while root!=self.parent[root]: root=self.parent[root] while A!=root: old_parent=self.parent[A] self.parent[A]=root A=old_parent return(root) def union(self,A,B): root_A = self.find(A) root_B = self.find(B) if root_A==root_B: return(False) if self.size[root_A]<self.size[root_B]: self.parent[root_A]=root_B self.size[root_B]+=self.size[root_A] else: self.parent[root_B]=root_A self.size[root_A]+=self.size[root_B] return(True) class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: R = len(grid) ; C = len(grid[0]) dsu = UnionFind(R*C) def encode(r,c): return(r*C+c) for r in range(R): for c in range(C): if c+1<C and grid[r][c]==grid[r][c+1]: if not dsu.union( encode(r,c),encode(r,c+1) ): return(True) if r+1<R and grid[r][c]==grid[r+1][c]: if not dsu.union( encode(r,c),encode(r+1,c) ): return(True) return(False)
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: vis = [[False for i in range(len(grid[0]))] for j in range(len(grid))] dirx = [0,0,-1,+1] diry = [-1,+1, 0,0] def check(i,j): if 0<= i < len(grid) and 0<= j< len(grid[0]): return True return False def dfs(r,c,pr,pc, no): flag = False vis[r][c] = True for i in range(4): nr,nc = r+dirx[i], c+diry[i] if not (nr == pr and nc == pc) and check(nr,nc) and grid[nr][nc] == grid[r][c]: if vis[nr][nc] : print((nr,nc)); return True if dfs(nr,nc,r,c,no+1): return True return False for i in range(len(grid)): for j in range(len(grid[0])): if not vis[i][j]: if(dfs(i,j, -1,-1, 0)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UnionFind: def __init__(self,n): self.parent = [i for i in range(n)] # i is the parent of i , initially self.size = [1 for i in range(n)] def find(self,A): root = A while root!=self.parent[root]: root = self.parent[root] while A!=root: old_parent = self.parent[A] self.parent[A]=root A = old_parent return(root) def union(self,A,B): root_A = self.find(A) root_B = self.find(B) if root_A == root_B: return(False) if self.size[root_A] < self.size[root_B]: self.parent[A]= root_B self.size[root_B]+=self.size[root_A] else: self.parent[B]= root_A self.size[root_A]+=self.size[root_B] return(True) class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: R = len(grid) ; C = len(grid[0]) dsu = UnionFind(R*C) def encode(r,c): return(r*C+c) for r in range(R): for c in range(C): if c+1<C and grid[r][c]==grid[r][c+1]: if not dsu.union( encode(r,c),encode(r,c+1) ): return(True) if r+1<R and grid[r][c]==grid[r+1][c]: if not dsu.union( encode(r,c),encode(r+1,c) ): return(True) return(False)
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: disjoint = {} def find(x): while disjoint[x] != x: x = disjoint[x] return disjoint[x] def union(x, y): disjoint[find(y)] = find(x) for i in range(len(grid)): for j in range(len(grid[0])): disjoint[(i, j)] = (i, j) for i in range(len(grid)): for j in range(len(grid[0])): for di, dj in [[0, 1], [1, 0]]: if 0 <= i + di < len(grid) and 0 <= j + dj < len(grid[0]) and grid[i][j] == grid[i + di][j + dj]: if find((i, j)) == find((i + di, j + dj)): return True union((i, j), (i + di, j + dj)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited = set() m = len(grid) n = len(grid[0]) if m == 1 or n == 1: return False dir = [(0,-1), (-1,0), (0,1), (1,0)] def dfs(prev, curr): if (curr in visited): return True visited.add(curr) for d in dir: x = (curr[0] + d[0], curr[1] + d[1]) if (x != prev and 0<= x[0] < m and 0<=x[1]<n and grid[x[0]][x[1]] == grid[curr[0]][curr[1]]): if dfs(curr, x): return True else: return False for i in range(m): for j in range(n): node = (i,j) if node not in visited: if dfs(None, node) == True: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited = set() m = len(grid) if m==1: return False n = len(grid[0]) dirs = [(0,-1),(-1,0),(0,1),(1,0)] def dfs(prev, curr): if curr in visited: return True visited.add(curr) for dirn in dirs: nei = (dirn[0]+curr[0], dirn[1]+curr[1]) if 0<=nei[0]<m and 0<=nei[1]<n and nei != prev and grid[nei[0]][nei[1]] == grid[curr[0]][curr[1]]: if dfs(curr, nei): return True return False for i in range(m): for j in range(n): if (i,j) not in visited: if dfs(None, (i,j)): return True return False # for each cell, if not in visited, do a DFS # DFS (prev->(x,y), curx, cury, visited): # if cur is visited: return True # for each cell, # if nei is not prev and nei == cur: # if (DFS on the nei) return True # return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UnionFind: def __init__(self,n): self.parent = [i for i in range(n)] self.size = [1 for i in range(n)] def find(self,A): root = A while root !=self.parent[root]: root = self.parent[root] while A!=root: old_parent = self.parent[A] self.parent[A]=root A=old_parent return(root) def union(self,A,B): root_A= self.find(A) root_B= self.find(B) if root_A==root_B: return(False) if self.size[root_A]<self.size[root_B]: self.parent[root_A] = root_B self.size[root_B]+=self.size[root_A] else: self.parent[root_B]=root_A self.size[root_A]+=self.size[root_B] return(True) class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: R = len(grid) ; C = len(grid[0]) dsu = UnionFind(R*C) def encode(r,c): return(r*C+c) for r in range(R): for c in range(C): if c+1<C and grid[r][c]==grid[r][c+1]: if not dsu.union( encode(r,c),encode(r,c+1) ): return(True) if r+1<R and grid[r][c]==grid[r+1][c]: if not dsu.union( encode(r,c),encode(r+1,c) ): return(True) return(False)
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UnionFind: def __init__(self, row_size, col_size): self.roots = [[(i, j) for j in range(col_size)] for i in range(row_size)] def get_rank(self, node): return -node[0] * len(self.roots[0]) - node[1] def union(self, node1, node2): root1 = self.find(node1) root2 = self.find(node2) if root1 != root2: if self.get_rank(root1) > self.get_rank(root2): self.roots[root2[0]][root2[1]] = root1 else: self.roots[root1[0]][root1[1]] = root2 def find(self, node): if self.roots[node[0]][node[1]] != node: self.roots[node[0]][node[1]] = self.find(self.roots[node[0]][node[1]]) return self.roots[node[0]][node[1]] class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: row_size, col_size = len(grid), len(grid[0]) uf = UnionFind(row_size, col_size) for i in range(row_size): for j in range(col_size): for (x, y) in [(i - 1, j), (i, j - 1)]: if x >= 0 and y >= 0 and grid[x][y] == grid[i][j]: if uf.find((i, j)) == uf.find((x, y)): return True uf.union((i, j), (x, y)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: parent = {} def find(u): parent.setdefault(u, u) if parent[u] != u: parent[u] = find(parent[u]) return parent[u] def union(u, v): x, y = find(u), find(v) if x != y: parent[y] = x return x != y m, n = len(grid), len(grid[0]) for i, row in enumerate(grid): for j, cell in enumerate(row): if i + 1 < m and grid[i][j] == grid[i + 1][j]: if not union((i, j), (i + 1, j)): return True if j + 1 < n and grid[i][j] == grid[i][j + 1]: if not union((i, j), (i, j + 1)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class DSU: def __init__(self,m,n): self.par = {(i,j):(i,j) for i in range(m) for j in range(n)} def find(self,x): if self.par[x]!=x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self,x,y): xp,yp = self.find(x),self.find(y) if xp == yp: return False self.par[xp] = yp return True dirs = [(0,1),(1,0)] class Solution: def containsCycle(self, grid): R,C = len(grid),len(grid[0]) dsu = DSU(R,C) for r in range(R): for c in range(C): for x,y in dirs: nr,nc = r+x,c+y if 0<=nr<R and 0<=nc<C and grid[r][c] == grid[nr][nc]: if dsu.union((r,c),(nr,nc)) == False: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: x = [0,0,-1,1] y = [-1,1,0,0] def findCycle(self,grid,i,j,li,lj,path,vis): if vis[i][j]: return False for k in range(4): nx = i + Solution.x[k] ny = j + Solution.y[k] if nx == li and ny == lj: continue if nx < 0 or ny < 0 or nx >= len(grid) or ny >= len(grid[0]): continue if (nx,ny) in path and path[(nx,ny)] == 1: vis[i][j] = 1 return True if grid[nx][ny] == grid[i][j]: path[(nx,ny)] = 1 isfind = self.findCycle(grid,nx,ny,i,j,path,vis) if isfind: vis[i][j] = 1 return True path[(nx,ny)] = 0 vis[i][j] = 1 return False def containsCycle(self, grid: List[List[str]]) -> bool: h = len(grid) if h == 0: return False w = len(grid[0]) vis = [ [0 for i in range(w)] for j in range(h)] path = {} for i in range(h): for j in range(w): if not vis[i][j]: isfind = self.findCycle(grid,i,j,-1,-1,path,vis) if isfind: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class DSU: def __init__(self): # representer self.reps = {} def add(self, x): self.reps[x] = x def find(self, x): if not x == self.reps[x]: self.reps[x] = self.find(self.reps[x]) return self.reps[x] def union(self, x, y): self.reps[self.find(y)] = self.find(x) class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: # detect cycle, often dfs, but use dsu in this problem due to its special graph structure. m, n = len(grid), len(grid[0]) dsu = DSU() for i in range(m): for j in range(n): dsu.add((i, j)) if i - 1 >= 0 and j - 1 >= 0 and grid[i - 1][j] == grid[i][j - 1] == grid[i][j] and dsu.find((i - 1, j)) == dsu.find((i, j - 1)): return True if i - 1 >= 0 and grid[i - 1][j] == grid[i][j]: dsu.union((i - 1, j), (i, j)) if j - 1 >= 0 and grid[i][j - 1] == grid[i][j]: dsu.union((i, j - 1), (i, j)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) visited = {} def dfs(i, j, k): c = i * n + j if c in visited: return k - visited[c] >= 4 visited[c] = k a = grid[i][j] for di, dj in [[0, -1], [0, 1], [-1, 0], [1, 0]]: ii = i + di jj =j + dj if not (0 <= ii < m and 0 <= jj < n) or grid[ii][jj] != a: continue if dfs(ii, jj, k + 1): return True return False for i in range(m): for j in range(n): c = i * n + j if c in visited: continue if dfs(i, j, 0): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
import collections class Solution: def containsCycle(self, grid): if not grid: return False M = len(grid) N = len(grid[0]) parent = {} def find(x, y): if parent[(x, y)] != (x, y): parent[(x, y)] = find(parent[(x, y)][0], parent[(x, y)][1]) return parent[(x, y)] def union(x1, y1, x2, y2): p1 = find(x1, y1) p2 = find(x2, y2) if p1 == p2: return True parent[p1] = p2 return False def move(x, y, grid): for i, j in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: if 0 <= i < M and 0 <= j < N: yield i, j seen = set() for i in range(M): for j in range(N): seen.add((i, j)) for x1, y1 in move(i, j, grid): if (i, j) not in parent: parent[(i, j)] = (i, j) if (x1, y1) not in parent: parent[(x1, y1)] = (x1, y1) if grid[i][j] == grid[x1][y1] and (x1, y1) not in seen: if union(i, j, x1, y1): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: # public solution ... 3384 ms ... 0 % ... 216 MB ... 0 % # time: O(n*m) # space: O(n*m) def dfs(pi, pj, i, j): visited[i][j] = True for ni, nj in [(i-1, j), (i, j-1), (i, j+1), (i+1, j)]: if 0 <= ni < n and 0 <= nj < m and grid[ni][nj] == grid[i][j]: if visited[ni][nj]: if (ni,nj) != (pi,pj): return True else: if dfs(i, j, ni, nj): return True return False n, m = len(grid), len(grid[0]) if n < 2 or m < 2: return False visited = [[False]*m for _ in range(n)] for i in range(n): for j in range(m): if not visited[i][j] and dfs(-1, -1, i, j): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) dirs = [[0,-1], [0,1], [-1,0], [1,0]] visited = [[False]*n for i in range(m)] def dfs(y, x, py, px, c): visited[y][x] = True for d in dirs: ny, nx = y+d[0], x+d[1] if ny < 0 or ny >= m or nx < 0 or nx >= n or (ny == py and nx == px) or grid[ny][nx] != c: continue if visited[ny][nx] or dfs(ny, nx, y, x, c): return True return False for i in range(m): for j in range(n): if not visited[i][j] and dfs(i, j, -1, -1, grid[i][j]): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
sys.setrecursionlimit(10000000) class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited = set() m = len(grid) if m==1: return False n = len(grid[0]) dirs = [(0,-1),(-1,0),(0,1),(1,0)] def dfs(prev, curr): if curr in visited: return True visited.add(curr) for dirn in dirs: nei = (dirn[0]+curr[0], dirn[1]+curr[1]) if 0<=nei[0]<m and 0<=nei[1]<n and nei != prev and grid[nei[0]][nei[1]] == grid[curr[0]][curr[1]]: if dfs(curr, nei): return True return False for i in range(m): for j in range(n): if (i,j) not in visited: if dfs(None, (i,j)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
#from collections import deque #from random import randint class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: h, w = len(grid), len(grid[0]) #------------------------------------------ def in_range(x, y): return (0 <= x < w) and (0 <= y < h) #------------------------------------------ def four_neighbors(x, y): for dx, dy in {(+1, 0), (-1, 0), (0, +1), (0, -1)}: next_x, next_y = x + dx, y + dy if in_range(next_x, next_y): yield (next_x, next_y) #------------------------------------------ def dfs(x, y, prev_x, prev_y, grid): if grid[y][x] == dfs.cur_symbol: # this grid has a cycle with current symbol return True # mark to uppercase letter as visited grid[y][x] = dfs.cur_symbol for next_x, next_y in four_neighbors(x, y): if (next_x, next_y) == (prev_x, prev_y): # avoid backward visit continue elif grid[next_y][next_x].upper() != dfs.cur_symbol: # different symbol continue if dfs(next_x, next_y, x, y, grid): return True #print(f'terminate with {x} {y} {grid[y][x]}') return False #------------------------------------------ failed_symbol = set() for y in range(h): for x in range(w): dfs.cur_symbol = grid[y][x] if dfs.cur_symbol in failed_symbol: # skip search on failed symbol continue dfs.cur_symbol = grid[y][x].upper() if dfs(x,y,-1,-1, grid): return True else: failed_symbol.add( dfs.cur_symbol ) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) visited = [[0] * n for i in range(m)] def dfs(i, j, k): if visited[i][j]: return k - visited[i][j] >= 4 visited[i][j] = k a = grid[i][j] for di, dj in [[0, -1], [0, 1], [-1, 0], [1, 0]]: ii = i + di jj =j + dj if not (0 <= ii < m and 0 <= jj < n) or grid[ii][jj] != a: continue if dfs(ii, jj, k + 1): return True return False for i in range(m): for j in range(n): if visited[i][j]: continue if dfs(i, j, 1): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) root = {} size = {} def find(t): if root[t] != t: root[t] = find(root[t]) return root[t] for i in range(m): for j in range(n): root[(i,j)] = (i,j) size[(i,j)] = 1 if 0<=i-1 and grid[i-1][j] == grid[i][j]: top = (i-1, j) rt = find(top) root[(i,j)] = rt size[rt] += 1 if 0<=j-1 and grid[i][j-1] == grid[i][j]: left = (i, j-1) rl = find(left) root[(i,j)] = rl size[rl] += 1 if 0<=i-1 and 0<=j-1 and grid[i-1][j] == grid[i][j] and grid[i][j-1] == grid[i][j]: rl = root[(i,j-1)] rt = root[(i-1,j)] if rl == rt: return True if size[rt] >= size[rl]: root[rl] = rt size[rt] += size[rl] else: root[rt] = rl size[rl] += size[rt] #print(root) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: for x, row in enumerate(grid): for y,num in enumerate(row): if self.containsCycleInComponent(grid, (x,y)): return True return False def adjCells(self, x, y): yield x-1, y yield x+1, y yield x, y-1 yield x, y+1 def containsCycleInComponent(self, grid, startPoint): # startPoint is the position (x,y) startX,startY = startPoint value = grid[startX][startY] if value is None: return False checkedPoints = set() uncheckedPoints = [startPoint] while uncheckedPoints: point = uncheckedPoints.pop() checkedPoints.add(point) x,y = point grid[x][y] = None adjKnownPoints = 0 for nextPoint in self.adjCells(x,y): if nextPoint in checkedPoints or self.hasValue(grid, nextPoint, value): if nextPoint not in checkedPoints: uncheckedPoints.append(nextPoint) else: adjKnownPoints += 1 if adjKnownPoints > 1: return True return False def hasValue(self, grid, point, value): x, y = point return 0<=x<len(grid) and 0<=y<len(grid[x]) and grid[x][y]==value
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: R = len(grid) C = len(grid[0]) N = R * C parents = [i for i in range(N)] def ufind(a): if parents[a] == a: return a parents[a] = ufind(parents[a]) return parents[a] def uunion(a, b): aa = ufind(a) bb = ufind(b) if aa == bb: return False parents[bb] = aa return True def decode(row, col): return row * C + col for row in range(R): for col in range(C): if row + 1 < R and grid[row + 1][col] == grid[row][col]: if not uunion(decode(row, col), decode(row + 1, col)): return True if col + 1 < C and grid[row][col + 1] == grid[row][col]: if not uunion(decode(row, col), decode(row, col + 1)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) visited = [[0] * n for i in range(m)] def dfs(i, j, pi, pj): if visited[i][j]: return True visited[i][j] = 1 a = grid[i][j] for di, dj in [[0, -1], [0, 1], [-1, 0], [1, 0]]: ii = i + di jj =j + dj if not (0 <= ii < m and 0 <= jj < n) or grid[ii][jj] != a or (ii == pi and jj == pj): continue if dfs(ii, jj, i, j): return True return False for i in range(m): for j in range(n): if visited[i][j]: continue if dfs(i, j, -1, -1): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, g: List[List[str]]) -> bool: def find(u): if u != UF[u]: u = find(UF[u]) return UF[u] UF, m, n = {}, len(g), len(g[0]) for i in range(m): for j in range(n): u = (i, j); UF.setdefault(u, u) for x, y in [(i, j-1), (i-1, j)]: if not (0 <= x < m and 0 <= y < n): continue if g[x][y] == g[i][j]: v = (x, y) UF.setdefault(v, v) pu, pv = find(u), find(v) if pu != pv: UF[pv] = pu else: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: # public solution ... def dfs(pi, pj, i, j): visited[i][j] = True for ni, nj in [(i-1, j), (i, j-1), (i, j+1), (i+1, j)]: if 0 <= ni < n and 0 <= nj < m and grid[ni][nj] == grid[i][j]: if visited[ni][nj]: if (ni,nj) != (pi,pj): return True else: if dfs(i, j, ni, nj): return True return False n, m = len(grid), len(grid[0]) if n < 2 or m < 2: return False visited = [[False]*m for _ in range(n)] for i in range(n): for j in range(m): if not visited[i][j] and dfs(-1, -1, i, j): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
import collections class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: if ranks[parent1] > ranks[parent2]: parents[parent2] = parent1 else: parents[parent1] = parent2 if ranks[parent1] == ranks[parent2]: ranks[parent1] += 1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} ranks = collections.Counter() for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter: union((i, j), (r, c)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class DSU: def __init__(self, N): self.par = list(range(N)) self.sz = [1] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return False if self.sz[xr] < self.sz[yr]: xr, yr = yr, xr self.par[yr] = xr self.sz[xr] += self.sz[yr] self.sz[yr] = self.sz[xr] return True class Solution: def containsCycle(self, A: List[List[str]]) -> bool: R, C = len(A), len(A[0]) def encode(r, c): return r * C + c dsu = DSU(R * C) for r in range(R): for c in range(C): if c + 1 < C and A[r][c] == A[r][c+1]: if not dsu.union(encode(r, c), encode(r, c + 1)): return True if r + 1 < R and A[r][c] == A[r+1][c]: if not dsu.union(encode(r, c), encode(r + 1, c)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: if ranks[parent2] > ranks[parent1]: parents[parent1] = parent2 else: parents[parent2] = parent1 if ranks[parent1] == ranks[parent2]: ranks[parent1] += 1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} ranks = collections.Counter() for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter: union((i, j), (r, c)) return False # def dfs(node, parent): # if node in visited: return True # visited.add(node) # nx,ny = node # childs = [(cx,cy) for cx,cy in [[nx+1,ny],[nx-1, ny],[nx,ny+1],[nx,ny-1]] # if 0 <= cx < m and 0 <= cy < n # and grid[cx][cy] == grid[nx][ny] and (cx,cy) != parent] # for x in childs: # if dfs(x, node): return True # return False # m, n = len(grid), len(grid[0]) # visited = set() # for i in range(m): # for j in range(n): # if (i,j) in visited: continue # if dfs((i,j), None): return True # return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid) -> bool: if not grid or not grid[0]: return False directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] visited=[[False] * len(grid[i]) for i in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[i])): if not visited[i][j]: stack = [(i, j, 0, 0)] visited[i][j] = True symbol = grid[i][j] while stack: row, col, prev_row, prev_col = stack.pop() for direction in directions: nr = row + direction[0] nc = col + direction[1] if nr == prev_row and nc == prev_col: continue if len(grid) > nr >= 0 and len(grid[nr]) > nc >= 0 and grid[nr][nc] == symbol: if visited[nr][nc]: return True else: visited[nr][nc] = True stack.append((nr, nc, row, col)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: for x, row in enumerate(grid): for y,num in enumerate(row): if self.containsCycleInComponent(grid, (x,y)): return True else: self.eraseComponent(grid, (x,y)) return False def eraseComponent(self, grid, startPoint): # startPoint is the position (x,y) startX,startY = startPoint value = grid[startX][startY] if value is None: return pointsToErase = [startPoint] while pointsToErase: point = pointsToErase.pop() x,y = point grid[x][y] = None for nextPoint in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]: if self.hasValue(grid, nextPoint, value): pointsToErase.append(nextPoint) def containsCycleInComponent(self, grid, startPoint): # startPoint is the position (x,y) startX,startY = startPoint value = grid[startX][startY] if value is None: return False checkedPoints = set() uncheckedPoints = [startPoint] componentPointsCount = 0 componentEdgesDoubleCount = 0 while uncheckedPoints: point = uncheckedPoints.pop() componentPointsCount += 1 checkedPoints.add(point) x,y = point for nextPoint in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]: if self.hasValue(grid, nextPoint, value): componentEdgesDoubleCount += 1 if nextPoint not in checkedPoints: uncheckedPoints.append(nextPoint) return componentPointsCount <= componentEdgesDoubleCount // 2 def hasValue(self, grid, point, value): x, y = point return 0<=x<len(grid) and 0<=y<len(grid[x]) and grid[x][y]==value
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
import sys input = sys.stdin.readline class Unionfind: def __init__(self, n): self.par = [-1]*n self.rank = [1]*n def root(self, x): r = x while not self.par[r]<0: r = self.par[r] t = x while t!=r: tmp = t t = self.par[t] self.par[tmp] = r return r def unite(self, x, y): rx = self.root(x) ry = self.root(y) if rx==ry: return if self.rank[rx]<=self.rank[ry]: self.par[ry] += self.par[rx] self.par[rx] = ry if self.rank[rx]==self.rank[ry]: self.rank[ry] += 1 else: self.par[rx] += self.par[ry] self.par[ry] = rx def is_same(self, x, y): return self.root(x)==self.root(y) def count(self, x): return -self.par[self.root(x)] class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: n = len(grid) m = len(grid[0]) uf = Unionfind(n*m) for i in range(n): for j in range(m): if i+1<n and grid[i][j]==grid[i+1][j]: if uf.is_same(m*i+j, m*(i+1)+j): return True uf.unite(m*i+j, m*(i+1)+j) if j+1<m and grid[i][j]==grid[i][j+1]: if uf.is_same(m*i+j, m*i+j+1): return True uf.unite(m*i+j, m*i+j+1) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) visited = set() def dfs(i, j, pi, pj): k = i * n + j if k in visited: return True visited.add(k) a = grid[i][j] for di, dj in [[0, -1], [0, 1], [-1, 0], [1, 0]]: ii = i + di jj =j + dj if not (0 <= ii < m and 0 <= jj < n) or grid[ii][jj] != a or (ii == pi and jj == pj): continue if dfs(ii, jj, i, j): return True return False for i in range(m): for j in range(n): if (i * n + j) in visited: continue if dfs(i, j, -1, -1): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(coords): if coords != parents[coords]: parents[coords] = find(parents[coords]) return parents[coords] def union(point_one, point_two): parx, pary = find(point_one), find(point_two) if parx != pary: if rank[parx] > rank[pary]: parents[pary] = parx else: parents[parx] = pary if rank[parx] == rank[pary]: rank[parx] += 1 if not grid or not grid[0]: return False m, n = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(m) for j in range(n)} rank = collections.Counter() for i in range(m): for j in range(n): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == grid[i][j] and find((i-1, j)) == find((i, j-1)): return True for r, c in (i-1, j), (i, j-1): if r >= 0 and c >= 0 and grid[r][c] == grid[i][j]: union((r, c), (i, j)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited = set() def dfs(i, j, pre_i, pre_j): visited.add((i, j)) for x, y in [(0, -1), (0, 1), (-1, 0), (1, 0)]: if 0 <= x + i < len(grid) and 0 <= y + j < len(grid[0]) and grid[i][j] == grid[i + x][j + y] and (i + x != pre_i or j + y != pre_j): if (i + x, j + y) in visited or dfs(i + x, j + y, i, j): return True return False for i in range(len(grid)): for j in range(len(grid[i])): if (i, j) not in visited: if dfs(i, j, -1, -1): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UnionFind: def __init__(self, n): self.parents = [i for i in range(n)] def find(self, i): if self.parents[i] == i: return i self.parents[i] = self.find(self.parents[i]) return self.parents[i] def unite(self, a, b): pa = self.find(a) pb = self.find(b) self.parents[pb] = pa return def same(self, a, b): pa = self.find(a) pb = self.find(b) return pa==pb class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: dx = [ 1, 0] dy = [ 0, 1] N = len(grid) M = len(grid[0]) ALL = N*M # print(\"size\", N, M, ALL) tree = UnionFind(ALL) for i in range(N): for j in range(M): for k in range(2): if 0<=i +dx[k] <N and 0<= j+dy[k]<M: if grid[i][j] == grid[i+dx[k]][j+dy[k]]: # print(i, j, k) # print((i+dx[k])*M+j+dy[k]) if tree.same(i*M+j, (i+dx[k])*M+j+dy[k]): return True tree.unite(i*M+j, (i+dx[k])*M+j+dy[k]) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: ''' [[\"a\",\"b\",\"b\"], [\"b\",\"z\",\"b\"], [\"b\",\"b\",\"a\"]] [[\"a\",\"b\",\"b\"], [\"b\",\"b\",\"b\"], [\"b\",\"b\",\"a\"]] dfs(pre_i,pre_j, i,j):-> bool: hasLoop ''' label = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))] def dfs(pre_i,pre_j, i,j): if label[i][j] == 1: # is being visited return True if label[i][j] == -1:# visited return False label[i][j] = 1 for ii, jj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]: if 0<=ii<len(grid) and 0<=jj<len(grid[ii]): if grid[ii][jj] == grid[i][j] and (not (ii==pre_i and jj==pre_j)): if dfs(i,j,ii,jj): return True label[i][j] = -1 return False for i in range(len(grid)): for j in range(len(grid[i])): if dfs(-1,-1, i,j): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]] def dfs(m, n, pm, pn): if m < 0 or m >= len(grid) or n < 0 or n >= len(grid[m]): return False if grid[m][n].lower() != grid[pm][pn].lower(): return False if grid[m][n].isupper(): return True grid[m][n] = grid[m][n].upper() for dir in dirs: if m + dir[0] != pm or n + dir[1] != pn: if (dfs(m + dir[0], n + dir[1], m, n)): return True return False for m in range(len(grid)): for n in range(len(grid[m])): if grid[m][n].islower(): if dfs(m, n, m, n): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: if not grid: return(False) visited = [[0 for i in grid[0]] for j in grid] def ExplorePath(rowIn,colIn, value, previous): current = [rowIn, colIn] #print(rowIn,colIn) if visited[rowIn][colIn]==1: return(True) #print('hi') else: visited [rowIn][colIn] =1 #print(temp1[0][0]) output = False if rowIn<len(grid)-1 and previous != [rowIn+1,colIn] and grid[rowIn+1][colIn]==value: output = ExplorePath(rowIn+1,colIn,value, current) if colIn<len(grid[0])-1 and previous != [rowIn,colIn+1] and grid[rowIn][colIn+1]==value: output = output or ExplorePath(rowIn,colIn+1, value, current) if rowIn>0 and previous != [rowIn-1,colIn] and grid[rowIn-1][colIn]==value: output = output or ExplorePath(rowIn-1,colIn, value, current) if colIn>0 and previous != [rowIn,colIn-1] and grid[rowIn][colIn-1]==value: output = output or ExplorePath(rowIn,colIn-1, value, current) return(output) for rowIn in range(len(grid)-1): for colIn in range(len(grid[0])-1): if grid[rowIn+1][colIn]== grid[rowIn][colIn]: if grid[rowIn+1][colIn+1]== grid[rowIn][colIn]: if grid[rowIn][colIn+1]== grid[rowIn][colIn]: #print(rowIn,colIn) return(True) for rowIn in range(len(grid)): for colIn in range(len(grid[0])): if visited[rowIn][colIn]==0: #print(grid[rowIn][colIn]) tempVisited = [] #print(tempVisited[0][0]) length = 0 if (ExplorePath(rowIn,colIn, grid[rowIn][colIn], [rowIn,colIn])): return(True) return(False) def containsCycle2(self, grid: List[List[str]]) -> bool: if not grid: return(False) visited = [[0 for i in grid[0]] for j in grid] def ExplorePath(rowIn,colIn, length, tempV, value, previous): current = [rowIn, colIn] #print(rowIn,colIn) if grid[rowIn][colIn] != value: return(False) if [rowIn,colIn] in tempV: #print('hi') if length >= 3: return(True) else: return(False) else: tempV.append([rowIn,colIn]) visited [rowIn][colIn] =1 temp1, temp2, temp3, temp4 = deepcopy(tempV), deepcopy(tempV), deepcopy(tempV), deepcopy(tempV) #print(temp1[0][0]) output = False if rowIn<len(grid)-1 and previous != [rowIn+1,colIn]: output = ExplorePath(rowIn+1,colIn, length+1, temp1, value, current) if colIn<len(grid[0])-1 and previous != [rowIn,colIn+1]: output = output or ExplorePath(rowIn,colIn+1, length+1, temp2, value, current) if rowIn>0 and previous != [rowIn-1,colIn]: output = output or ExplorePath(rowIn-1,colIn, length+1, temp3, value, current) if colIn>0 and previous != [rowIn,colIn-1]: output = output or ExplorePath(rowIn,colIn-1, length+1, temp4, value, current) return(output) for rowIn in range(len(grid)-1): for colIn in range(len(grid[0])-1): if grid[rowIn+1][colIn]== grid[rowIn][colIn]: if grid[rowIn+1][colIn+1]== grid[rowIn][colIn]: if grid[rowIn][colIn+1]== grid[rowIn][colIn]: #print(rowIn,colIn) return(True) for rowIn in range(len(grid)): for colIn in range(len(grid[0])): if visited[rowIn][colIn]==0: #print(grid[rowIn][colIn]) tempVisited = [] #print(tempVisited[0][0]) length = 0 if (ExplorePath(rowIn,colIn, length, tempVisited, grid[rowIn][colIn], [rowIn,colIn])): return(True) return(False)
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class DSU: def __init__(self, N): self.par = list(range(N)) self.sz = [1] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return False if self.sz[xr] < self.sz[yr]: xr, yr = yr, xr self.par[yr] = xr self.sz[xr] += self.sz[yr] self.sz[yr] = self.sz[xr] return True def size(self, x): return self.sz[self.find(x)] class Solution: def containsCycle(self, A): R, C = len(A), len(A[0]) def encode(r, c): return r * C + c dsu = DSU(R * C) for r in range(R): for c in range(C): if c + 1 < C and A[r][c] == A[r][c+1]: if not dsu.union(encode(r, c), encode(r, c + 1)): if dsu.size(encode(r, c)) >= 4: return True if r + 1 < R and A[r][c] == A[r+1][c]: if not dsu.union(encode(r, c), encode(r + 1, c)): if dsu.size(encode(r, c)) >= 4: return True return False # bac # cac # ddc # bcc
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UF: def __init__(self, m, n): self.p = {(i, j): (i, j) for i in range(m) for j in range(n)} def union(self, ti, tj): pi, pj = self.find(*ti), self.find(*tj) if pi != pj: self.p[pj] = pi return False return True def find(self, i, j): if (i, j) != self.p[i,j]: self.p[i,j] = self.find(*self.p[i,j]) return self.p[i,j] class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: # 如何定义cycle:同一个点的两个不同方向的path,最终汇聚到非自身的同一点 m, n = len(grid), len(grid[0]) uf = UF(m, n) for i in range(m): for j in range(n): if i > 0 and grid[i][j] == grid[i-1][j]: uf.union((i-1, j), (i, j)) if j > 0 and grid[i][j] == grid[i][j-1]: if uf.union((i, j-1), (i, j)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: if ranks[parent2] > ranks[parent1]: parents[parent1] = parent2 else: parents[parent2] = parent1 if ranks[parent1] == ranks[parent2]: ranks[parent1] += 1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} ranks = collections.Counter() for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if r >= 0 and c >= 0 and grid[r][c] == letter: union((i, j), (r, c)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: M, N = len(grid), len(grid[0]) dp = [[set() for j in range(N)] for i in range(M)] dv = [(0,-1),(-1,0)] for i in range(M): for j in range(N): for x,y in dv: if 0 <= i+x < M and 0 <= j+y < N: if grid[i][j] == grid[i+x][j+y]: if not dp[i+x][j+y]: dp[i][j].add(((i+x,j+y),1)) else: for entry in dp[i+x][j+y]: prnt, dist = entry if (prnt, dist+1) in dp[i][j] and dist+1 >= 2: return True dp[i][j].add((prnt, dist+1)) #print(i,j, prnt, dist, dp[i][j]) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid) -> bool: if not grid or not grid[0]: return False directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] visited=[[False] * len(grid[i]) for i in range(len(grid))] def dfs(grid, symbol, row, col, prev_row, prev_col): nonlocal directions nonlocal visited visited[row][col] = True for direction in directions: nr = row + direction[0] nc = col + direction[1] if nr == prev_row and nc == prev_col: continue if len(grid) > nr >= 0 and len(grid[nr]) > nc >= 0: if grid[nr][nc] == symbol and (visited[nr][nc] or dfs(grid, symbol, nr, nc, row , col)): return True return False for i in range(len(grid)): for j in range(len(grid[i])): if not visited[i][j]: if dfs(grid, grid[i][j], i, j, 0, 0): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) class roots(): def __init__(self, val): self.val = val self.par = None def root(self): if self.par == None: return self.val return self.par.root() chains = {} for i in range(m): for j in range(n): if i > 0 and grid[i-1][j] == grid[i][j]: chains[(i,j)]=roots((i,j)) chains[(i,j)].par = chains[(i-1,j)] if j > 0 and grid[i][j-1] == grid[i][j]: if (i,j) in chains: if chains[(i,j)].root() == chains[(i,j-1)].root(): return True else: chains[chains[(i,j-1)].root()].par = chains[(i,j)] else: chains[(i,j)]=roots((i,j)) chains[(i,j)].par = chains[(i,j-1)] if (i,j) not in chains: chains[(i,j)]=roots((i,j)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: n,m = len(grid),len(grid[0]) root = {(i,j):(i,j) for i in range(n) for j in range(m)} rank = collections.defaultdict(int) def find(x): if root[x]==x: return x root[x] == find(root[x]) return root[x] def union(a,b): ra,rb = find(a),find(b) if ra!=rb: if rank[rb]>rank[ra]: root[ra] = rb else: root[rb] = ra if rank[ra]==rank[rb]: rank[ra]+=1 for i in range(n): for j in range(m): #print(i,j) val = grid[i][j] # parent: i-1,j and i,j-1 if i>0 and j>0 and grid[i-1][j] == grid[i][j-1]==val and find((i-1,j))==find((i,j-1)): #print(find((i-1,j)),find((i,j-1))) return True for ni,nj in [(i-1,j),(i,j-1)]: if 0<=ni<n and 0<=nj<m and grid[ni][nj]==val: #print((i,j),(ni,nj),val,grid[ni][nj]) union((i,j),(ni,nj)) #print(find((ni,nj))) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: row , col = len(grid), len(grid[0]) track = {} dx, dy = [0,0,-1,1], [-1,1,0,0] def check(i,j, parent): # print('outside',i,j) for k in range(4): xx, yy = dx[k] + i, dy[k] + j if xx in range(row) and yy in range(col) and parent!=(xx,yy) and grid[i][j]== grid[xx][yy] and grid[i][j]!='checked': if (xx,yy) in track: return True track[(xx,yy)] = True if check(xx,yy,(i,j)): return True grid[xx][yy]='checked' return False for i in range(row): for j in range(col): track[(i,j)] = True if check(i,j,None): return True grid[i][j] = 'checked' return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def find(self, n1): if n1 == self.par[n1[0]][n1[1]]: return n1 else: return self.find(self.par[n1[0]][n1[1]]) def union(self, n1, n2): p1 = self.find(n1) p2 = self.find(n2) self.par[p1[0]][p1[1]] = p2 def containsCycle(self, grid: List[List[str]]) -> bool: n_row, n_col = len(grid), len(grid[0]) self.par = [] for r in range(n_row): self.par.append([(r,c) for c in range(n_col)]) for r in range(n_row): for c in range(n_col): # check right if r+1 < n_row and grid[r][c]==grid[r+1][c]: if self.find((r,c)) == self.find((r+1,c)): return True self.union((r,c), (r+1,c)) # check down if c+1 < n_col and grid[r][c]==grid[r][c+1]: if self.find((r,c)) == self.find((r,c+1)): return True self.union((r,c), (r,c+1)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: parents[parent2] = parent1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter: union((i, j), (r, c)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(coords): if coords != parents[coords]: parents[coords] = find(parents[coords]) return parents[coords] def union(point_one, point_two): parx, pary = find(point_one), find(point_two) if parx != pary: if rank[parx] > rank[pary]: parents[pary] = parx else: parents[parx] = pary if rank[parx] == rank[pary]: rank[parx] += 1 # elif rank[parx] < rank[pary]: # parents[parx] = pary # else: # parents[parx] = pary # rank[pary] += 1 if not grid or not grid[0]: return False m, n = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(m) for j in range(n)} rank = collections.Counter() for i in range(m): for j in range(n): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == grid[i][j] and find((i-1, j)) == find((i, j-1)): return True for r, c in (i-1, j), (i, j-1): if r >= 0 and c >= 0 and grid[r][c] == grid[i][j]: union((r, c), (i, j)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: # public solution ... 3020 ms ... 0 % ... 215 MB ... 0 % # time: O(n*m) # space: O(n*m) def dfs(pi, pj, i, j): visited[i][j] = True for ni, nj in [(i-1, j), (i, j-1), (i, j+1), (i+1, j)]: if 0 <= ni < n and 0 <= nj < m and grid[ni][nj] == grid[i][j]: if visited[ni][nj]: if (ni,nj) != (pi,pj): return True else: if dfs(i, j, ni, nj): return True return False n, m = len(grid), len(grid[0]) if n < 2 or m < 2: return False visited = [[False]*m for _ in range(n)] for i in range(n): for j in range(m): if not visited[i][j] and dfs(-1, -1, i, j): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def detect_cycle(self, grid, visited, rec_stack, i, j, M, N, prev): visited[i][j] = True rec_stack.append([i, j]) for k, l in [[i, j-1], [i-1, j], [i, j+1], [i+1, j]]: if k >= 0 and l >= 0 and k < M and l < N and grid[i][j] == grid[k][l] and [k, l] != prev: if not visited[k][l]: if self.detect_cycle(grid, visited, rec_stack, k, l, M, N, [i, j]) == True: return True elif [k, l] in rec_stack: return True rec_stack.pop() def containsCycle(self, grid: List[List[str]]) -> bool: M, N = len(grid), len(grid[0]) visited = [[False]*N for _ in range(M)] rec_stack = [] for i in range(M): for j in range(N): if not visited[i][j]: if self.detect_cycle(grid, visited, rec_stack, i, j, M, N, [i, j]) == True: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: n,m = len(grid),len(grid[0]) root = {(i,j):(i,j) for i in range(n) for j in range(m)} def find(x): i,j = x if root[i,j]==x: return x root[i,j] = find(root[i,j]) return root[i,j] def union(a,b): ra,rb = find(a),find(b) if ra!=rb: root[rb] = ra return False return True for i in range(n): for j in range(m): val = grid[i][j] if i > 0 and grid[i][j] == grid[i-1][j]: union((i-1, j), (i, j)) if j > 0 and grid[i][j] == grid[i][j-1]: if union((i, j-1), (i, j)): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
from collections import defaultdict class Solution: DELTA = [(0,-1),(0,1),(-1,0),(1,0)] def containsCycle(self, grid: List[List[str]]) -> bool: def dfsCycle(grid, R, C, p_r, p_c, r, c, visited, grp, grp_num): if (r, c) in grp[grp_num]: return True # check 4 directions visited.add((r,c)) grp[grp_num].add((r,c)) result = False for d in Solution.DELTA: n_r = r + d[0] n_c = c + d[1] if 0 <= n_r < R and 0 <= n_c < C and not (p_r == n_r and p_c == n_c) and grid[n_r][n_c] == grid[r][c]: result |= dfsCycle(grid, R, C, r, c, n_r, n_c, visited, grp, grp_num) if result: break return result R = len(grid) C = len(grid[0]) visited = set() grp_num = 0 grp = defaultdict(set) for r in range(R): for c in range(C): if (r,c) not in visited: grp_num += 1 if dfsCycle(grid, R, C, r, c, r, c, visited, grp, grp_num): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: n,m = len(grid),len(grid[0]) root = {(i,j):(i,j) for i in range(n) for j in range(m)} def find(x): if root[x]==x: return x root[x] = find(root[x]) return root[x] def union(a,b): ra,rb = find(a),find(b) if ra!=rb: root[ra] = rb return False return True for i in range(n): for j in range(m): val = grid[i][j] for ni,nj in [(i+1,j),(i,j+1)]: if ni<n and nj<m and grid[ni][nj]==val: t = union((ni,nj),(i,j)) if t: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def ff(grid,i,j,n,c): grid[i][j]=c c+=1 if i>0 : #print(grid) if type(grid[i-1][j])==int and c-grid[i-1][j]>2 and c//250000==grid[i-1][j]//250000: return True elif type(grid[i-1][j])==str and grid[i-1][j]==n: #print(grid) if ff(grid,i-1,j,n,c): return True if j<len(grid[i])-1: #print(grid) if type(grid[i][j+1])==int and c-grid[i][j+1]>2 and c//250000==grid[i][j+1]//250000: return True elif type(grid[i][j+1])==str and grid[i][j+1]==n: if ff(grid,i,j+1,n,c): return True if j>0: #print(grid,n) if type(grid[i][j-1])==int and c-grid[i][j-1]>2 and c//250000==grid[i][j-1]//250000: return True elif type(grid[i][j-1])==str and grid[i][j-1]==n: if ff(grid,i,j-1,n,c): return True if i<len(grid)-1 : #print(grid,n) if type(grid[i+1][j])==int and c-grid[i+1][j]>2 and c//250000==grid[i+1][j]//250000: return True elif type(grid[i+1][j])==str and grid[i+1][j]==n: #print(grid) if ff(grid,i+1,j,n,c): return True return False cc=0 for i in range(len(grid)): for j in range(len(grid[0])): if type(grid[i][j])!=int: cc+=1 if ff(grid,i,j,grid[i][j],cc*250000): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
import collections class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def find(pos): if parents[pos] != pos: parents[pos] = find(parents[pos]) return parents[pos] def union(pos1, pos2): parent1, parent2 = find(pos1), find(pos2) if parent1 != parent2: if ranks[parent2] > ranks[parent1]: parents[parent1] = parent2 else: parents[parent2] = parent1 if ranks[parent1] == ranks[parent2]: ranks[parent1] += 1 rows, cols = len(grid), len(grid[0]) parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)} ranks = collections.Counter() for i, row in enumerate(grid): for j, letter in enumerate(row): if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)): return True for r, c in (i - 1, j), (i, j - 1): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter: union((i, j), (r, c)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class UnionFindSet: def __init__(self, n): self.parents = list(range(n)) self.ranks = [1] * n def find(self, u): if u != self.parents[u]: self.parents[u] = self.find(self.parents[u]) return self.parents[u] def union(self, u, v): pu, pv = self.find(u), self.find(v) if pu == pv: return False if self.ranks[pu] > self.ranks[pv]: self.parents[pv] = pu elif self.ranks[pv] > self.ranks[pu]: self.parents[pu] = pv else: self.parents[pu] = pv self.ranks[pv] += 1 return True class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) dirs = ((0, 1), (0, -1), (1, 0), (-1, 0)) uf = UnionFindSet(m*n) for i in range(m): for j in range(n): if i > 0 and grid[i][j] == grid[i-1][j] and not uf.union(i*n+j, (i-1)*n+j): return True if j > 0 and grid[i][j] == grid[i][j-1] and not uf.union(i*n+j, i*n+j-1): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: parents = {} def find(p): if p not in parents: parents[p] = p if parents[p] != p: parents[p] = find(parents[p]) return parents[p] def is_connected(p, q): return find(p) == find(q) def union(p, q): i, j = find(p), find(q) parents[j] = i R, C = len(grid), len(grid[0]) for r in range(R): for c in range(C): for nr, nc in [r+1, c], [r, c+1]: if nr < R and nc < C and grid[r][c] == grid[nr][nc]: if is_connected((r, c), (nr, nc)): return True union((r, c), (nr, nc)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited = {} def dfs(x, y, u, v): if not 0 <= x < len(grid): return False if not 0 <= y < len(grid[x]): return False if grid[x][y] != grid[u][v]: return False if (x,y) in visited: return True visited[(x,y)] = True if (x, y+1) != (u,v) and dfs(x, y+1,x,y): return True if (x-1, y) != (u,v) and dfs(x-1, y,x,y): return True if (x+1, y) != (u,v) and dfs(x+1, y, x, y): return True if (x, y-1) != (u,v) and dfs(x, y-1, x, y): return True return False for i in range(len(grid)): for j in range(len(grid[i])): if (i,j) not in visited and dfs(i,j,i,j): return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: if not grid: return False m, n = len(grid), len(grid[0]) nbrs = [(-1,0), (0,1),(0,-1),(1, 0)] def isValid(x,y): return x>=0 and x<m and y>=0 and y<n def hasCycle(x, y, vis, parentX, parentY): vis.add((x,y)) for nbr in nbrs: newX, newY = x + nbr[0], y+nbr[1] if isValid(newX, newY) and grid[newX][newY] == grid[x][y] and not(parentX == newX and parentY == newY): if (newX, newY) in vis: return True else: if hasCycle(newX, newY, vis,x,y): return True return False vis = set() for i in range(m): for j in range(n): if (i,j) not in vis: ans = hasCycle(i,j, vis, -1, -1) if ans: return True return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid) -> bool: if not grid or not grid[0]: return False directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] for i in range(len(grid)): for j in range(len(grid[i])): if '#' not in grid[i][j]: stack = [(i, j, 0, 0)] symbol = grid[i][j] grid[i][j] = '#' + symbol while stack: row, col, prev_row, prev_col = stack.pop() for direction in directions: nr = row + direction[0] nc = col + direction[1] if nr == prev_row and nc == prev_col: continue if len(grid) > nr >= 0 and len(grid[nr]) > nc >= 0 and symbol in grid[nr][nc]: if '#' in grid[nr][nc]: return True else: grid[nr][nc] = '#' + symbol stack.append((nr, nc, row, col)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def find(self, n): if n == self.par[n[0]][n[1]]: return n else: p = self.find(self.par[n[0]][n[1]]) # path compression self.par[n[0]][n[1]] = p return p def union(self, n1, n2): p1 = self.find(n1) p2 = self.find(n2) # union by rank if self.rank[p1[0]][p1[1]] > self.rank[p2[0]][p2[1]]: self.par[p2[0]][p2[1]] = p1 else: self.par[p1[0]][p1[1]] = p2 self.rank[p1[0]][p1[1]] += 1 def containsCycle(self, grid: List[List[str]]) -> bool: n_row, n_col = len(grid), len(grid[0]) self.rank = [[1]*n_col for _ in range(n_row)] self.par = [] for r in range(n_row): self.par.append([(r,c) for c in range(n_col)]) for r in range(n_row): for c in range(n_col): # check right if r+1 < n_row and grid[r][c]==grid[r+1][c]: if self.find((r,c)) == self.find((r+1,c)): return True self.union((r,c), (r+1,c)) # check down if c+1 < n_col and grid[r][c]==grid[r][c+1]: if self.find((r,c)) == self.find((r,c+1)): return True self.union((r,c), (r,c+1)) return False
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m <= 500 1 <= n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: dsu = DSU() m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if i != 0 and grid[i - 1][j] == grid[i][j]: dsu.union((i - 1, j), (i, j)) if grid[i][j - 1] == grid[i][j]: if dsu.find((i, j - 1)) == dsu.find((i, j)): return True dsu.union((i, j - 1), (i, j)) return False class DSU: def __init__(self): self.father = {} def find(self, a): self.father.setdefault(a, a) if a != self.father[a]: self.father[a] = self.find(self.father[a]) return self.father[a] def union(self, a, b): _a = self.find(a) _b = self.find(b) if _a != _b: self.father[_a] = self.father[_b]