post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/task-scheduler-ii/discuss/2388794/Python3-O(n)-with-last-time-updated-and-simulation
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: time = 0 n = len(tasks) ht = {} for i in range(n): if ht.get(tasks[i]) is None or (time-ht[tasks[i]]-1)>=space: time = time + 1 ht[tasks[i]] = time else: time = ht[tasks[i]] + space + 1 ht[tasks[i]] = time pass return time pass
task-scheduler-ii
[Python3] O(n) with last time updated and simulation
dntai
0
3
task scheduler ii
2,365
0.462
Medium
32,400
https://leetcode.com/problems/task-scheduler-ii/discuss/2388467/Simple-Python-Solution-using-Dictionary
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: ld={} d=0 for t in tasks: ld[t]=0 for t in tasks: if ld[t]==0: d+=1 ld[t]=d else: nd=ld[t]+space ld[t]=max(nd+1,d+1) d=ld[t] return d
task-scheduler-ii
Simple Python Solution using Dictionary
shreyasjain0912
0
4
task scheduler ii
2,365
0.462
Medium
32,401
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2388550/Python-oror-One-reversed-pass-oror-Easy-Approaches
class Solution: def minimumReplacement(self, nums: List[int]) -> int: n = len(nums) k = nums[n - 1] ans = 0 for i in reversed(range(n - 1)): if nums[i] > k: l = nums[i] / k if l == int(l): ans += int(l) - 1 k = nums[i] / int(l) else: ans += int(l) k = int(nums[i] / (int(l) + 1)) else: k = nums[i] return ans
minimum-replacements-to-sort-the-array
✅Python || One reversed pass || Easy Approaches
chuhonghao01
2
84
minimum replacements to sort the array
2,366
0.399
Hard
32,402
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2409182/Python3-loop-backward
class Solution: def minimumReplacement(self, nums: List[int]) -> int: ans = 0 prev = 1_000_000_001 for x in reversed(nums): d = ceil(x/prev) ans += d-1 prev = x//d return ans
minimum-replacements-to-sort-the-array
[Python3] loop backward
ye15
0
63
minimum replacements to sort the array
2,366
0.399
Hard
32,403
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2408985/python-3-or-simple-one-pass-solution-or-O(n)O(1)
class Solution: def minimumReplacement(self, nums: List[int]) -> int: res = 0 prev = nums[-1] for i in range(len(nums) - 2, -1, -1): if nums[i] <= prev: prev = nums[i] continue q, r = divmod(nums[i], prev) ops = q if r else q - 1 res += ops prev = nums[i] // (ops + 1) return res
minimum-replacements-to-sort-the-array
python 3 | simple one pass solution | O(n)/O(1)
dereky4
0
49
minimum replacements to sort the array
2,366
0.399
Hard
32,404
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2394555/Python3-Optimal-Time-O(n)-Space-O(1)
class Solution: def minimumReplacement(self, nums: List[int]) -> int: ret = 0 i = len(nums) - 1 R = float('inf') while i >= 0: num_of_splits = (nums[i] - 1) // R ret += num_of_splits R = nums[i] // (num_of_splits + 1) i -= 1 return int(ret)
minimum-replacements-to-sort-the-array
[Python3] Optimal - Time O(n), Space O(1)
leet_aiml
0
10
minimum replacements to sort the array
2,366
0.399
Hard
32,405
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2390349/Easy-optimization-problem-or-Google-Interview-Problem-or-Python3-or-division-with-remainder
class Solution: def minimumReplacement(self, nums: List[int]) -> int: ref = nums[-1] n = len(nums) res = 0 for i in range(n-2, -1, -1): if nums[i] <= ref: ref = nums[i] continue q, r = divmod(nums[i], ref) # 1-item in strategy if r == 0: res += q - 1 # 2-item in strategy else: res += q ref = nums[i] // (q + 1) return res
minimum-replacements-to-sort-the-array
Easy optimization problem | Google Interview Problem? | Python3 | division with remainder
wxy0925
0
17
minimum replacements to sort the array
2,366
0.399
Hard
32,406
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2388953/Python-3Hint-solution
class Solution: def minimumReplacement(self, nums: List[int]) -> int: prev = nums[-1] ans = 0 for num in nums[:-1][::-1]: if num > prev: # equally divide num to make part as large as possible # prev = 6, num = 15 # then we could divide into 3 parts: 5 + 5 + 5 # prev = 6, num = 7 # then we could divide into 2 parts: 3 + 4 a, b = divmod(num, prev) parts = a + int(b > 0) prev = num // parts ans += parts - 1 else: prev = num return ans
minimum-replacements-to-sort-the-array
[Python 3]Hint solution
chestnut890123
0
19
minimum replacements to sort the array
2,366
0.399
Hard
32,407
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2388186/Python-easy-understanding-solution
class Solution: def minimumReplacement(self, nums: List[int]) -> int: if len(nums) == 1: return 0 def helper(n, to_deal): # return (times needed to divide, biggest left-most num) if n <= to_deal: return (0, n) if n % to_deal == 0: # For example: [9, 3] return (n//to_deal - 1, to_deal) else: times = n // to_deal # For example: [10, 4], it should at least deivide (n1 // to_deal) times x = n // (times+1) # Since we know 10 must divided into 3 num, the biggest left-most num will be 10//3 = 3 return (times, x) to_deal = nums[-1] res = 0 i = len(nums) - 2 # Iterate from the second-last element. while i >= 0: times, left_most_num = helper(nums[i], to_deal) res += times to_deal = left_most_num # Update to_deal to the left_most_num . i -= 1 return res
minimum-replacements-to-sort-the-array
Python easy-understanding solution
byroncharly3
0
16
minimum replacements to sort the array
2,366
0.399
Hard
32,408
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2395275/Python-oror-Easy-Approach
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 n = len(nums) for i in range(n): if nums[i] + diff in nums and nums[i] + 2 * diff in nums: ans += 1 return ans
number-of-arithmetic-triplets
✅Python || Easy Approach
chuhonghao01
19
1,200
number of arithmetic triplets
2,367
0.837
Easy
32,409
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2393465/Python-easy-understand-solution-O(n)-space-O(n)-time
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: s = set(nums) count = 0 for num in nums: if (num + diff) in s and (num + diff + diff) in s: count += 1 return count
number-of-arithmetic-triplets
Python easy understand solution O(n) space, O(n) time
amikai
6
499
number of arithmetic triplets
2,367
0.837
Easy
32,410
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2498311/python-95-fast-and-97-memory
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: dic = {} # store nums[i] quest = {} # store require number you possible find after nums[i] count = 0 # count answer for i in nums: dic[i] = True if i in quest: count += 1 # meet damand if i - diff in dic: quest[i + diff] = True return count
number-of-arithmetic-triplets
python 95% fast and 97% memory
TUL
3
234
number of arithmetic triplets
2,367
0.837
Easy
32,411
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2391706/Python-easy-solution-for-beginners-using-slightly-optimized-brute-force
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: res = 0 for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[j] - nums[i] == diff: for k in range(j+1, len(nums)): if nums[k] - nums[j] == diff: res += 1 return res
number-of-arithmetic-triplets
Python easy solution for beginners using slightly optimized brute force
alishak1999
3
113
number of arithmetic triplets
2,367
0.837
Easy
32,412
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2415108/Python-Elegant-and-Short-or-Two-solutions-or-O(n)-and-O(n*log(n))-or-Binary-search
class Solution: """ Time: O(n*log(n)) Memory: O(1) """ def arithmeticTriplets(self, nums: List[int], diff: int) -> int: count = 0 left, right = 0, len(nums) - 1 for j, num in enumerate(nums): if self.binary_search(nums, num - diff, left, j - 1) != -1 and \ self.binary_search(nums, num + diff, j + 1, right) != -1: count += 1 return count @staticmethod def binary_search(nums: List[int], target: int, left: int, right: int) -> int: while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid if nums[mid] > target: right = mid - 1 else: left = mid + 1 return -1 class Solution: """ Time: O(n) Memory: O(n) """ def arithmeticTriplets(self, nums: List[int], diff: int) -> int: uniq_nums = set(nums) return sum(num + diff in uniq_nums and num + 2 * diff in uniq_nums for num in nums)
number-of-arithmetic-triplets
Python Elegant & Short | Two solutions | O(n) and O(n*log(n)) | Binary search
Kyrylo-Ktl
2
138
number of arithmetic triplets
2,367
0.837
Easy
32,413
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2390909/Secret-Python-Answer-Binary-Search-Right-and-Left
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: t = len(nums) def binary_search(arr, low, high, x): if high >= low: mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binary_search(arr, low, mid - 1, x) else: return binary_search(arr, mid + 1, high, x) else: return -1 count = 0 for i,n in enumerate(nums): if binary_search(nums, 0, i-1, n-diff) != -1 and binary_search(nums, i+1, t-1,n + diff) != -1: count+=1 return count
number-of-arithmetic-triplets
[Secret Python Answer🤫🐍👌😍] Binary Search Right and Left
xmky
2
141
number of arithmetic triplets
2,367
0.837
Easy
32,414
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2587110/Python-or-Easy-or-O(n)-Solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: dict_ = {} for num in nums: dict_[num] = dict_.get(num,0) + 1 ##To keep the count of each num's occurence count = 0 for num in nums: if dict_.get(num+diff) and dict_.get(num+diff*2): #Check if any number with 3 and 6 more than present in dictionary count += 1 return count
number-of-arithmetic-triplets
Python | Easy | O(n) Solution
anurag899
1
130
number of arithmetic triplets
2,367
0.837
Easy
32,415
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2392027/Python-Simple-Python-Solution-Using-Bute-Force
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: check = [] for index1 in range(len(nums) - 2): for index2 in range(index1 + 1, len(nums) - 1): current_diffrence = nums[index2] - nums[index1] if current_diffrence == diff: check.append([index1, index2 , current_diffrence]) result = 0 for array in check: index1, index2 , diffrence = array for j in range(index2 + 1, len(nums)): current_diffrence = nums[j] - nums[index2] if current_diffrence == diff: result = result + 1 return result
number-of-arithmetic-triplets
[ Python ] ✅✅ Simple Python Solution Using Bute Force 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
1
62
number of arithmetic triplets
2,367
0.837
Easy
32,416
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2850945/Python-O(n)-solution-with-explanation
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 nums_to_pos = {num:index for index, num in enumerate(nums)} for i in range(len(nums)): a = nums[i] b, c = a + diff, a + 2 * diff if b in nums_to_pos and c in nums_to_pos: j, k = nums_to_pos[b], nums_to_pos[c] if i < j < k: ans += 1 return ans
number-of-arithmetic-triplets
Python O(n) solution with explanation
besiobu
0
2
number of arithmetic triplets
2,367
0.837
Easy
32,417
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2849788/COMPACT-Python-solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans=0 for i in range(-1,-1*len(nums)-1,-1): n1=nums[i] n2=n1-diff n3=n2-diff if n2 in nums: if n3 in nums: ans+=1 return ans
number-of-arithmetic-triplets
[COMPACT] Python solution
hanifrizal
0
1
number of arithmetic triplets
2,367
0.837
Easy
32,418
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2844634/Clean-and-fast-one-liner
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: return sum(1 if {n + diff, n + 2*diff}.issubset(nums) else 0 for n in nums)
number-of-arithmetic-triplets
Clean and fast one-liner
user4248gf
0
1
number of arithmetic triplets
2,367
0.837
Easy
32,419
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2824582/PYTHON3-BEST
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: a = set() b = 0 for i in nums: if i - diff in a and i - diff * 2 in a: b += 1 a.add(i) return b
number-of-arithmetic-triplets
PYTHON3 BEST
Gurugubelli_Anil
0
2
number of arithmetic triplets
2,367
0.837
Easy
32,420
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2812553/Easiest-way
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: res=0 n=len(nums) for i in range (n): for j in range (i+1,n): if nums[j]-nums[i]==diff: for k in range (j+1,n): if nums[k]-nums[j]==diff: res+=1 return res
number-of-arithmetic-triplets
Easiest way
nishithakonuganti
0
3
number of arithmetic triplets
2,367
0.837
Easy
32,421
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2798365/simple-AP-concept-48ms
class Solution: def arithmeticTriplets(self, nums, diff): cnt = 0 for i in range(len(nums)): if i < len(nums)-1 and (nums[i] + diff) in nums[i+1:] and (nums[i]-diff) in nums[:i]: cnt += 1 return cnt
number-of-arithmetic-triplets
simple AP concept-48ms
alamwasim29
0
2
number of arithmetic triplets
2,367
0.837
Easy
32,422
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2797253/Python-easy-code-solution.
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: l = len(nums) count = 0 for i in range(l): for j in range(i+1,l): for k in range(j+1,l): if(((nums[j] - nums[i]) == diff) and ((nums[k] - nums[j]) == diff)): count += 1 return count
number-of-arithmetic-triplets
Python easy code solution.
anshu71
0
7
number of arithmetic triplets
2,367
0.837
Easy
32,423
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2769661/Python-solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 n = len(nums) for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if nums[j] - nums[i] == nums[k] - nums[j] == diff: ans += 1 return ans
number-of-arithmetic-triplets
Python solution
kruzhilkin
0
1
number of arithmetic triplets
2,367
0.837
Easy
32,424
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2746875/EASY-PYTHON-SOLUTION-WITH-EXPLANATION
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 n = len(nums) for i in range(n): if nums[i] + diff in nums and nums[i] + 2 * diff in nums: ans += 1 return ans
number-of-arithmetic-triplets
EASY PYTHON SOLUTION WITH EXPLANATION
sowmika_chaluvadi
0
3
number of arithmetic triplets
2,367
0.837
Easy
32,425
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2688015/Python3-Solution-one-line-solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: return sum([1 for i in nums if i-diff in nums and i+diff in nums])
number-of-arithmetic-triplets
Python3 Solution - one-line solution
sipi09
0
4
number of arithmetic triplets
2,367
0.837
Easy
32,426
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2653124/python-easy-solution-using-loop
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: c=0 for i in range(len(nums)): o=nums[i] for j in range(i,len(nums)): if abs(nums[j]-o)==diff: t=nums[j] for k in range(j+1,len(nums)): if abs(t-nums[k])==diff: c+=1 return c
number-of-arithmetic-triplets
python easy solution using loop
lalli307
0
2
number of arithmetic triplets
2,367
0.837
Easy
32,427
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2619104/Simple-code-easy-to-understand
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: c=0 for i in range(len(nums)): a=nums[i]+diff if a in nums: b=a+diff if b in nums: c=c+1 return c
number-of-arithmetic-triplets
Simple code easy to understand
Prabal_Nair
0
34
number of arithmetic triplets
2,367
0.837
Easy
32,428
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2535471/Python-Two-Solutions-Linear-Time-or-Constant-Space
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: # make a set from numbers numset = set() result = 0 # check whether the other two numbers exist for num in nums: if (num-2*diff) in numset and (num-diff) in numset: result += 1 numset.add(num) return result
number-of-arithmetic-triplets
[Python] - Two Solutions - Linear Time or Constant Space
Lucew
0
51
number of arithmetic triplets
2,367
0.837
Easy
32,429
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2535471/Python-Two-Solutions-Linear-Time-or-Constant-Space
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: # get the array highest integer result = 0 # we could do this using binary search for index, num in enumerate(nums): if binary_search(nums[index+1:], num+2*diff) and binary_search(nums[index+1:], num+diff): result += 1 return result def binary_search(array, target): left = 0 right = len(array)-1 while left <= right: mid = left + (right-left)//2 curr = array[mid] if curr == target: return True elif curr < target: left = mid+1 else: right = mid-1 return False
number-of-arithmetic-triplets
[Python] - Two Solutions - Linear Time or Constant Space
Lucew
0
51
number of arithmetic triplets
2,367
0.837
Easy
32,430
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2530238/Python-easy-and-fast-solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: count = [0]*201 res = 0 for n in nums: res += count[n-diff] and count[n-diff*2] count[n] = True return res
number-of-arithmetic-triplets
[Python] easy and fast solution
yhc22593
0
24
number of arithmetic triplets
2,367
0.837
Easy
32,431
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2464065/Solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 for i in range(len(nums)): num = 0 num = nums[i] + diff if ((num in nums) and (num + diff in nums)): ans += 1 return ans
number-of-arithmetic-triplets
Solution
fiqbal997
0
23
number of arithmetic triplets
2,367
0.837
Easy
32,432
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2446767/The-simplest-solution-in-python
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: visited = set(nums) res = 0 for n in nums: if n + diff in visited and n + 2*diff in visited: res += 1 return res
number-of-arithmetic-triplets
The simplest solution in python
byuns9334
0
38
number of arithmetic triplets
2,367
0.837
Easy
32,433
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2446636/python-solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: c=0 for i in range(0,len(nums)-2): for j in range(i+1,len(nums)-1): for k in range(0,len(nums)): if nums[j]-nums[i]==diff and nums[k] - nums[j] == diff: c=c+1 return c
number-of-arithmetic-triplets
python solution
keertika27
0
26
number of arithmetic triplets
2,367
0.837
Easy
32,434
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2402581/Python-brute-force-solution
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 ln = len(nums) for i in range(ln): for j in range(i+1, ln): for k in range(j+1, ln): if nums[j] - nums[i] == diff and nums[k] - nums[j] == diff: ans += 1 return ans
number-of-arithmetic-triplets
Python brute force solution
StikS32
0
15
number of arithmetic triplets
2,367
0.837
Easy
32,435
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2394452/Python-Faster-Solution-oror-Documented
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: # convert list into dictionary dct = {} for i, num in enumerate(nums): dct[num] = i # for each num, count when num+diff and num+diff+diff exist in dct cnt = 0 for num in nums: if num+diff in dct and num+diff+diff in dct: cnt += 1 return cnt
number-of-arithmetic-triplets
[Python] Faster Solution || Documented
Buntynara
0
6
number of arithmetic triplets
2,367
0.837
Easy
32,436
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2390517/Python3-hash-set
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 seen = set() for x in nums: if x-diff in seen and x-2*diff in seen: ans += 1 seen.add(x) return ans
number-of-arithmetic-triplets
[Python3] hash set
ye15
0
31
number of arithmetic triplets
2,367
0.837
Easy
32,437
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2395280/Python-oror-Graph-oror-UnionFind-oror-Easy-Approach
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: restrictedSet = set(restricted) uf = UnionFindSet(n) for edge in edges: if edge[0] in restrictedSet or edge[1] in restrictedSet: continue else: uf.union(edge[0], edge[1]) ans = 1 rootNode = uf.find(0) for i in range(1, n): if uf.find(i) == rootNode: ans += 1 return ans class UnionFindSet: def __init__(self, size): self.root = [i for i in range(size)] # Use a rank array to record the height of each vertex, i.e., the "rank" of each vertex. # The initial "rank" of each vertex is 1, because each of them is # a standalone vertex with no connection to other vertices. self.rank = [1] * size # The find function here is the same as that in the disjoint set with path compression. def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x] # The union function with union by rank def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: if self.rank[rootX] > self.rank[rootY]: self.root[rootY] = rootX elif self.rank[rootX] < self.rank[rootY]: self.root[rootX] = rootY else: self.root[rootY] = rootX
reachable-nodes-with-restrictions
✅Python || Graph || UnionFind || Easy Approach
chuhonghao01
3
152
reachable nodes with restrictions
2,368
0.574
Medium
32,438
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2402181/Python3%3A-BFT-Using-Sets.-Comments-and-Explanation.
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: #Convert restricted list into restricted set to increase processing speed #Create a dictionary of non-restricted nodes #Thus the key is the node and the value is the adjacency set for that node resSet = set(restricted) nodes_dict = dict() for x in range(0, n): if(x not in resSet): nodes_dict[x] = set() #Fill adjacency set only with non-restricted nodes #We can check for non-restricted nodes by using the keys of the dict for pair0, pair1 in edges: if(pair0 in nodes_dict and pair1 in nodes_dict): nodes_dict[pair0].add(pair1) nodes_dict[pair1].add(pair0) #We will always start at node 0, so I add 0 to the traversalQueue #Add 0 to counting set since we always have 0 traversalQueue = deque([0]) count = {0} #Utilize set operations #Starting at 0 look at 0's adjacency set #Use difference operation to find which of 0's neighbors are not visited to add to the traversalQueue ##### #Obviously none of 0's neighbors have been visited but... #...for rest of the nodes, you don't want to traverse backwards and get stuck #The reason why you will get stuck if you don't do the difference operation is because: #The edge comes in pairs. So [0,1] means that 0 will have 1 in its adjacency set. However... #...1 will also have 0. If you do not account for this, when you get to node 1 in the dict... #...all of 1's neighbors INCLUDING 0 will be added to the traversalQueue. Thus an infinite loop occurs. ##### #Add the neighbors to the traversalQueue #Add all neighbors to counting set #Remove node from traversalQueue FIFO style. At the start that will obviously be node 0. #Repeat until you have traversed all nodes while(len(traversalQueue) != 0): current = traversalQueue[0] diff = nodes_dict[current].difference(count) traversalQueue.extend(diff) count.update(diff) traversalQueue.popleft() return len(count)
reachable-nodes-with-restrictions
Python3: BFT Using Sets. Comments & Explanation.
tinyspidey
1
54
reachable nodes with restrictions
2,368
0.574
Medium
32,439
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2390856/Secret-Python-Answer-DFS
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: e = defaultdict(set) restricted = set(restricted) for ed in edges: if ed[1] not in restricted and ed[0] not in restricted: e[ed[0]].add(ed[1]) e[ed[1]].add(ed[0]) visited = set() def dfs(node): if node in visited: return visited.add(node) self.total+=1 for s in e[node]: dfs(s) self.total = 1 visited.add(0) for s in e[0]: dfs(s) return self.total
reachable-nodes-with-restrictions
[Secret Python Answer🤫🐍👌😍] DFS
xmky
1
46
reachable nodes with restrictions
2,368
0.574
Medium
32,440
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2390664/Python3-dfs
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) ans = 0 seen = set(restricted) stack = [0] while stack: u = stack.pop() ans += 1 seen.add(u) for v in graph[u]: if v not in seen: stack.append(v) return ans
reachable-nodes-with-restrictions
[Python3] dfs
ye15
1
17
reachable nodes with restrictions
2,368
0.574
Medium
32,441
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2733693/python-non-recursive-DFS-(faster-than-93-of-python-solutions)
class Solution(object): def reachableNodes(self, n, edges, restricted): """ :type n: int :type edges: List[List[int]] :type restricted: List[int] :rtype: int """ restricted = set(restricted) adj_list = {i: [] for i in range(n)} for (u, v) in edges: adj_list[u].append(v) adj_list[v].append(u) stack = [0] n_reachable = 1 visited = set([]) while len(stack) > 0: u = stack.pop(0) visited.add(u) done_edges = [] for v in adj_list[u]: if v not in visited and v not in restricted: stack.append(v) n_reachable += 1 return n_reachable
reachable-nodes-with-restrictions
python non-recursive DFS (faster than 93% of python solutions)
juliejiang112
0
1
reachable nodes with restrictions
2,368
0.574
Medium
32,442
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2686644/Python3-or-Simple-DFS
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: def dfs(node): nonlocal ans for it in adj[node]: if it in res: continue elif it not in vis: ans+=1 vis.add(it) dfs(it) return ans=1 adj=[[] for i in range(n)] vis=set() res=set(restricted) for u,v in edges: adj[u].append(v) adj[v].append(u) vis.add(0) dfs(0) return ans
reachable-nodes-with-restrictions
[Python3] | Simple DFS
swapnilsingh421
0
7
reachable nodes with restrictions
2,368
0.574
Medium
32,443
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2536108/Python-easy-to-read-and-understand-or-DFS
class Solution: def dfs(self, g, node, visit, restricted): # print(node) self.cnt += 1 for nei in g[node]: if nei not in visit and nei not in restricted: visit.add(nei) self.dfs(g, nei, visit, restricted) def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: g = {i: [] for i in range(n)} for u, v in edges: g[u].append(v) g[v].append(u) self.cnt = 0 visit = set() visit.add(0) self.dfs(g, 0, visit, restricted) return self.cnt
reachable-nodes-with-restrictions
Python easy to read and understand | DFS
sanial2001
0
18
reachable nodes with restrictions
2,368
0.574
Medium
32,444
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2532131/python3-or-Clear-and-concise-dfs-AND-bfs-solutions
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: restricted = set(restricted) graph = defaultdict(set) visited = set() for source, destination in edges: graph[source].add(destination) graph[destination].add(source) reachable = 0 def dfs(node): nonlocal reachable reachable += 1 visited.add(node) for connected_node in graph[node]: if connected_node not in visited and connected_node not in restricted: dfs(connected_node) dfs(0) return reachable
reachable-nodes-with-restrictions
[python3] | Clear and concise dfs AND bfs solutions
_snake_case
0
13
reachable nodes with restrictions
2,368
0.574
Medium
32,445
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2532131/python3-or-Clear-and-concise-dfs-AND-bfs-solutions
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: restricted = set(restricted) graph = defaultdict(set) visited = set() reachable = 0 queue = collections.deque([0]) for source, destination in edges: graph[source].add(destination) graph[destination].add(source) while queue: node = queue.popleft() reachable += 1 visited.add(node) for connected_node in graph[node]: if connected_node not in restricted and connected_node not in visited: queue.append(connected_node) return reachable
reachable-nodes-with-restrictions
[python3] | Clear and concise dfs AND bfs solutions
_snake_case
0
13
reachable nodes with restrictions
2,368
0.574
Medium
32,446
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2418231/python-simple-dfs-solution
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: res = 1 restricted = set(restricted) visited = {0} graph = defaultdict(set) for x, y in edges: graph[x].add(y) graph[y].add(x) stack = [0] while stack: node = stack.pop() for neighbor in graph[node]: if neighbor not in visited and neighbor not in restricted: res += 1 stack.append(neighbor) visited.add(neighbor) return res
reachable-nodes-with-restrictions
python simple dfs solution
byuns9334
0
65
reachable nodes with restrictions
2,368
0.574
Medium
32,447
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2407639/Count-visited-with-sets
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: neighbors = defaultdict(set) for a, b in edges: neighbors[a].add(b) neighbors[b].add(a) set_restricted = set(restricted) visited = {0} frontier = neighbors[0] while frontier: new_frontier = set() for node in frontier: if node not in set_restricted and node not in visited: visited.add(node) new_frontier.update(neighbors[node]) frontier = new_frontier return len(visited)
reachable-nodes-with-restrictions
Count visited with sets
EvgenySH
0
21
reachable nodes with restrictions
2,368
0.574
Medium
32,448
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2394644/Python-Accurate-Solution-Adjacency-List-oror-Documented
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: # Generate Adjacency List representing graph adjList = [[] for i in range(n)] for a, b in edges: adjList[a].append(b) # we can move from a to b adjList[b].append(a) # we can move from b to a # Iterative DFS stk = [0] # add the root 0 on the stack seen = [False] * n # no single node is visited initially restricted = set(restricted) # convert list to set for fast searching # visit the nodes until stack is empty while stk: curNode = stk.pop() # pop next node from stack seen[curNode] = True # mark the node as seen # append the children of the node if they are not seen &amp; restricted for child in adjList[curNode]: if not seen[child] and child not in restricted: stk.append(child) return sum(seen) # return sum of the visited nodes
reachable-nodes-with-restrictions
[Python] Accurate Solution - Adjacency List || Documented
Buntynara
0
11
reachable nodes with restrictions
2,368
0.574
Medium
32,449
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2394024/Python3-or-Easy-Fix-to-Avoid-TLE(Typecast-restricted-from-list-to-set)
class Solution: #T.C = O(n + n + n-1), in worst case total number of vistable nodes from 0 is n-1, where #only one node from 0...n-1th node is restricted! -> O(n) #S.C = O(n*n-1 + n-1 + n-1) -> O(n^2) def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: adj = [[] for _ in range(n)] for x, y in edges: adj[x].append(y) adj[y].append(x) visited = set() restricted = set(restricted) ans = 0 def dfs(node): nonlocal visited, restricted, ans visited.add(node) ans += 1 for n in adj[node]: if(n not in restricted and n not in visited): dfs(n) dfs(0) return ans
reachable-nodes-with-restrictions
Python3 | Easy Fix to Avoid TLE(Typecast restricted from list to set)
JOON1234
0
9
reachable nodes with restrictions
2,368
0.574
Medium
32,450
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2393925/Python3-or-Mad-that-my-approach-not-meeting-Time-Constraint
class Solution: #I tried two approaches: #1. Generic processing each and every edge in edges set! #2. Performing generic bfs starting from node 0 with queue DS! #3. Used a dfs helper function that will only visit every non-restricted and previously unvisited nodes! #-> Both resulted in TLE?? -> What other angles/approaches could I possibly attempt? #No infinite loop so TLE is probably they are looking for even more optimal runtime sol! -> Maybe #they want me to find answer without having to process each and every edge #Hints didn't help because my thought process/approach is basically already doing what the hint was #telling me to do! def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: #output max. number of #reachable nodes starting from and including node 0! adj = [[] for _ in range(n)] #build adj. list rep! for x,y in edges: if(x in restricted or y in restricted): continue elif(x in restricted): adj[y].append(x) elif(y in restricted): adj[x].append(y) else: adj[x].append(y) adj[y].append(x) #make sure we never visit a node more than once! visited = set() ans = 0 #dfs helper! def dfs(node): nonlocal restricted, visited, adj, ans #check if node is already visited! if(node in visited): return #otherwise, mark current node as visited! ans += 1 visited.add(node) neighbors = adj[node] for neighbor in neighbors: #only if neighboring node is not already visited and not restricted would we recursively #dfs on it! if(neighbor not in restricted and neighbor not in visited): dfs(neighbor) dfs(0) return ans
reachable-nodes-with-restrictions
Python3 | Mad that my approach not meeting Time Constraint
JOON1234
0
11
reachable nodes with restrictions
2,368
0.574
Medium
32,451
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2391308/Python-DFS
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: def dfs(node, prev): self.result += 1 for neighbor in adj[node]: if neighbor != prev and neighbor not in restricted: dfs(neighbor, node) restricted = set(restricted) adj = defaultdict(list) for a, b in edges: adj[a].append(b) adj[b].append(a) self.result = 0 dfs(0, -1) return self.result
reachable-nodes-with-restrictions
Python, DFS
blue_sky5
0
27
reachable nodes with restrictions
2,368
0.574
Medium
32,452
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2390452/Python3-Iterative-DFS
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: g = defaultdict(list) restrict = set(restricted) for u, v in edges: g[u].append(v) g[v].append(u) seen = set() stack = [0] res = 0 while stack: node = stack.pop() if node not in seen: res += 1 seen.add(node) for adj in g[node]: if adj not in seen and adj not in restrict: stack.append(adj) return res
reachable-nodes-with-restrictions
[Python3] Iterative DFS
0xRoxas
0
25
reachable nodes with restrictions
2,368
0.574
Medium
32,453
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2390552/Python3-Iterative-DFS
class Solution: def validPartition(self, nums: List[int]) -> bool: idxs = defaultdict(list) n = len(nums) #Find all doubles for idx in range(1, n): if nums[idx] == nums[idx - 1]: idxs[idx - 1].append(idx + 1) #Find all triples for idx in range(2, n): if nums[idx] == nums[idx - 1] == nums[idx - 2]: idxs[idx - 2].append(idx + 1) #Find all triple increments for idx in range(2, n): if nums[idx] == nums[idx - 1] + 1 == nums[idx - 2] + 2: idxs[idx - 2].append(idx + 1) #DFS seen = set() stack = [0] while stack: node = stack.pop() if node not in seen: if node == n: return True seen.add(node) for adj in idxs[node]: if adj not in seen: stack.append(adj) return False
check-if-there-is-a-valid-partition-for-the-array
[Python3] Iterative DFS
0xRoxas
2
106
check if there is a valid partition for the array
2,369
0.401
Medium
32,454
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2403935/Python3-state-machine-(accepted)-and-regular-expression-(TLE)
class Solution: def validPartition(self, nums: List[int]) -> bool: f3,f2,f1 = False,False,True for i,v in enumerate(nums): f = f2 and (v==nums[i-1]) f = f or f3 and (v==nums[i-1]==nums[i-2]) f = f or f3 and (v==nums[i-1]+1==nums[i-2]+2) f3,f2,f1 = f2,f1,f return f1
check-if-there-is-a-valid-partition-for-the-array
Python3 state machine (accepted) and regular expression (TLE)
vsavkin
1
22
check if there is a valid partition for the array
2,369
0.401
Medium
32,455
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2813842/Python-(Simple-Dynamic-Programming)
class Solution: def validPartition(self, nums): n = len(nums) dp = [False]*(n+1) dp[0] = True for i in range(2,n+1): dp[i] |= nums[i-1] == nums[i-2] and dp[i-2] dp[i] |= i>2 and nums[i-1] == nums[i-2] == nums[i-3] and dp[i-3] dp[i] |= i>2 and nums[i-1] - nums[i-2] == nums[i-2] - nums[i-3] == 1 and dp[i-3] return dp[-1]
check-if-there-is-a-valid-partition-for-the-array
Python (Simple Dynamic Programming)
rnotappl
0
1
check if there is a valid partition for the array
2,369
0.401
Medium
32,456
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2419691/Python3-O(n)-DP-Solution
class Solution: def validPartition(self, nums: List[int]) -> bool: grid = [0] * (len(nums) + 1) grid[0] = 1 if nums[0] == nums[1]: grid[2] = 1 for t in range(3, len(nums)+1): if nums[t-1] == nums[t-2]: grid[t] = (grid[t-2] or grid[t]) if nums[t-1] == nums[t-2] == nums[t-3] or \ nums[t-1] == nums[t-2] + 1 == nums[t-3] + 2: grid[t] = (grid[t-3] or grid[t]) return grid[-1]
check-if-there-is-a-valid-partition-for-the-array
Python3 O(n) DP Solution
xxHRxx
0
61
check if there is a valid partition for the array
2,369
0.401
Medium
32,457
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2391048/Python3-O(n)-Dynamic-Programming-1D
class Solution: def validPartition(self, nums: List[int]) -> bool: a = nums dp = [False] * len(a) for i in range(1, len(a)): ret = False if i-1>=0 and a[i]==a[i-1]: ret = ret or (True if i-2<0 else dp[i-2]) if i-2>=0 and a[i]==a[i-1] and a[i-1]==a[i-2]: ret = ret or (True if i-3<0 else dp[i-3]) if i-2>=0 and a[i]==a[i-1]+1 and a[i-1]==a[i-2]+1: ret = ret or (True if i-3<0 else dp[i-3]) dp[i] = ret ans = dp[-1] return ans
check-if-there-is-a-valid-partition-for-the-array
[Python3] O(n) Dynamic Programming 1D
dntai
0
14
check if there is a valid partition for the array
2,369
0.401
Medium
32,458
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2390606/Python3-dp
class Solution: def validPartition(self, nums: List[int]) -> bool: @cache def fn(i): if i == len(nums): return True if i+1 < len(nums) and nums[i] == nums[i+1] and fn(i+2): return True if i+2 < len(nums) and nums[i] == nums[i+1] == nums[i+2] and fn(i+3): return True if i+2 < len(nums) and nums[i]+2 == nums[i+1]+1 == nums[i+2] and fn(i+3): return True return False return fn(0)
check-if-there-is-a-valid-partition-for-the-array
[Python3] dp
ye15
0
15
check if there is a valid partition for the array
2,369
0.401
Medium
32,459
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2390606/Python3-dp
class Solution: def validPartition(self, nums: List[int]) -> bool: dp = [False]*(len(nums)+1) dp[-1] = True for i in range(len(nums)-1, -1, -1): if i+1 < len(nums) and dp[i+2] and nums[i] == nums[i+1] \ or i+2 < len(nums) and dp[i+3] and (nums[i] == nums[i+1] == nums[i+2] or nums[i]+2 == nums[i+1]+1 == nums[i+2]): dp[i] = True return dp[0]
check-if-there-is-a-valid-partition-for-the-array
[Python3] dp
ye15
0
15
check if there is a valid partition for the array
2,369
0.401
Medium
32,460
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2390471/DP
class Solution: def longestIdealString(self, s: str, k: int) -> int: dp = [0] * 26 for ch in s: i = ord(ch) - ord("a") dp[i] = 1 + max(dp[max(0, i - k) : min(26, i + k + 1)]) return max(dp)
longest-ideal-subsequence
DP
votrubac
34
2,300
longest ideal subsequence
2,370
0.379
Medium
32,461
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2489080/Python-3.-O(n)-Solution-DP
class Solution: def longestIdealString(self, s: str, k: int) -> int: # For storing the largest substring ending at that character psum=[0]*26 ans=1 for i in range(len(s)): element=ord(s[i])-97 # Checking for k characters left to current element i.e. 2 characters left to c will be 'a' and 'b' j=element while j>-1 and j>=element-k: psum[element]=max(psum[element],psum[j]+1) j-=1 # Checking for k characters right to current element i.e. 2 characters left to c will be 'd' and 'e' j=element+1 while j<26 and j<=element+k: psum[element]=max(psum[element],psum[j]+1) j+=1 ans=max(ans,psum[element]) return ans
longest-ideal-subsequence
Python 3. O(n) Solution - DP
Harsha138
1
76
longest ideal subsequence
2,370
0.379
Medium
32,462
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2808439/Python3-DP-O(n)-time-beats-90-space-beats-96
class Solution: def longestIdealString(self, s: str, k: int) -> int: lis = [0] * 26 for ch in s: idx = ord(ch) - ord("a") mi, ma = max(0, idx - k), min(25, idx + k) last_lis = max(lis[mi: ma + 1]) lis[idx] = last_lis + 1 return max(lis)
longest-ideal-subsequence
[Python3] DP O(n), time beats 90%, space beats 96%
huangweijing
0
3
longest ideal subsequence
2,370
0.379
Medium
32,463
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2691172/Python3-O(n)-Dynamic-Programming-Solution
class Solution: def longestIdealString(self, s: str, k: int) -> int: grid = [0] * 26 data = [ord(_) - 97 for _ in s] for element in data: mini, maxi = max(0, element - k), min(25, element + k) longest = 0 for t in range(mini, maxi+1): longest = max(longest, grid[t]) grid[element] = longest + 1 return max(grid)
longest-ideal-subsequence
Python3 O(n) Dynamic Programming Solution
xxHRxx
0
5
longest ideal subsequence
2,370
0.379
Medium
32,464
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2448962/Python-Solution-or-Memoization-or-Tabulation-or-DP-or-TLE
class Solution: def longestIdealString(self, s: str, k: int) -> int: n=len(s) # Memoization # dp=[[-1]*(n+1) for i in range(n+1)] # def helper(ind, prev_ind): # if ind==n: # return 0 # if dp[ind][prev_ind]!=-1: # return dp[ind][prev_ind] # notTake=helper(ind+1, prev_ind) # take=0 # if prev_ind==-1 or abs(ord(s[ind])-ord(s[prev_ind]))<=k: # take=1+helper(ind+1, ind) # dp[ind][prev_ind] = max(take, notTake) # return dp[ind][prev_ind] # return helper(0, -1) # Tabulation dp=[1]*(n+1) maxi=0 for ind in range(1, n): for prev_ind in range(ind): if abs(ord(s[ind])-ord(s[prev_ind]))<=k and dp[ind]<dp[prev_ind]+1: dp[ind]=dp[prev_ind]+1 maxi=max(maxi, dp[ind]) return maxi
longest-ideal-subsequence
Python Solution | Memoization | Tabulation | DP | TLE
Siddharth_singh
0
106
longest ideal subsequence
2,370
0.379
Medium
32,465
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2424999/python3-Hashmap-solution-for-reference
class Solution: def longestIdealString(self, s: str, k: int) -> int: N = len(s) c = "abcdefghijklmnopqrstuvwxyz" zipped = zip(c, range(26)) h = defaultdict(int) for a,v in zipped: h[a] = v O = [0]*len(c) for c in s: r = O[max(0,h[c]-k):h[c]+k+1] O[h[c]] = (max(r) if r else 0) + 1 return max(O)
longest-ideal-subsequence
[python3] Hashmap solution for reference
vadhri_venkat
0
51
longest ideal subsequence
2,370
0.379
Medium
32,466
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2409282/Python3-dp
class Solution: def longestIdealString(self, s: str, k: int) -> int: dp = [0]*26 for ch in s: i = ord(ch)-97 dp[i] = 1 + max(dp[max(0, i-k) : i+k+1], default=0) return max(dp)
longest-ideal-subsequence
[Python3] dp
ye15
0
14
longest ideal subsequence
2,370
0.379
Medium
32,467
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2393736/Python-3One-dimension-DP-O(n-*-(2-*-k-%2B-1))
class Solution: def longestIdealString(self, s: str, k: int) -> int: n = len(s) dp = [0] * 26 for i in range(n): loc = ord(s[i]) - ord('a') new_dp = dp[:] for j in range(loc - k, loc + k + 1): new_dp[loc] = max(new_dp[loc], 1 + dp[j % 26]) dp = new_dp return max(dp)
longest-ideal-subsequence
[Python 3]One-dimension DP O(n * (2 * k + 1))
chestnut890123
0
16
longest ideal subsequence
2,370
0.379
Medium
32,468
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2390838/Secret-Python-AnswerHashmap-to-Remember-the-current-max-set-size-for-each-letter-seen
class Solution: def longestIdealString(self, s: str, k: int) -> int: s = [ord(c) - ord('a') for c in s] m = 0 hm = {} for i,v in enumerate(s) : m = 1 for h in hm: if abs(v - h) <= k: m = max(m, hm[h] +1) hm[v] = m return max(hm.values())
longest-ideal-subsequence
[Secret Python Answer🤫🐍👌😍]Hashmap to Remember the current max set size for each letter seen
xmky
0
26
longest ideal subsequence
2,370
0.379
Medium
32,469
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422191/Python3-simulation
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ans = [[0]*(n-2) for _ in range(n-2)] for i in range(n-2): for j in range(n-2): ans[i][j] = max(grid[ii][jj] for ii in range(i, i+3) for jj in range(j, j+3)) return ans
largest-local-values-in-a-matrix
[Python3] simulation
ye15
14
1,200
largest local values in a matrix
2,373
0.839
Easy
32,470
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422317/Python-oror-Easy-Approach-oror-Brute-force
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ans = [] for i in range(n - 2): res = [] for j in range(n - 2): k = [] k.append(grid[i][j]) k.append(grid[i][j + 1]) k.append(grid[i][j + 2]) k.append(grid[i + 1][j]) k.append(grid[i + 1][j + 1]) k.append(grid[i + 1][j + 2]) k.append(grid[i + 2][j]) k.append(grid[i + 2][j + 1]) k.append(grid[i + 2][j + 2]) m = max(k) res.append(m) ans.append(res) return ans
largest-local-values-in-a-matrix
✅Python || Easy Approach || Brute force
chuhonghao01
9
803
largest local values in a matrix
2,373
0.839
Easy
32,471
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2428294/Python-Elegant-and-Short-or-100-faster
class Solution: """ Time: O(n^2) Memory: O(1) """ def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) return [[self.local_max(grid, r, c, 1) for c in range(1, n - 1)] for r in range(1, n - 1)] @staticmethod def local_max(grid: List[List[int]], row: int, col: int, radius: int) -> int: return max( grid[r][c] for r in range(row - radius, row + radius + 1) for c in range(col - radius, col + radius + 1) )
largest-local-values-in-a-matrix
Python Elegant & Short | 100% faster
Kyrylo-Ktl
6
698
largest local values in a matrix
2,373
0.839
Easy
32,472
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422186/Python-Two-loop-solution
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) matrix = [[1]* (n-2) for i in range(n-2)] for i in range(1, n - 1): for j in range(1, n - 1): matrix[i-1][j-1] = max(grid[i-1][j-1], grid[i-1][j], grid[i-1][j+1], grid[i][j-1], grid[i][j], grid[i][j+1], grid[i+1][j-1], grid[i+1][j], grid[i+1][j+1]) return matrix
largest-local-values-in-a-matrix
✅ [Python] Two loop solution
amikai
6
370
largest local values in a matrix
2,373
0.839
Easy
32,473
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2425602/Python3-oror-6-lines-chain-oror-TM%3A-145-ms14.2-MB
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid)-2 ans = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): ans[i][j] = max(chain(grid[i ][j:j+3], grid[i+1][j:j+3], grid[i+2][j:j+3])) return ans
largest-local-values-in-a-matrix
Python3 || 6 lines, chain || T/M: 145 ms/14.2 MB
warrenruud
3
211
largest local values in a matrix
2,373
0.839
Easy
32,474
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2824565/PYTHON3-BEST
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ans = [[0]*(n-2) for _ in range(n-2)] for i in range(n-2): for j in range(n-2): ans[i][j] = max(grid[ii][jj] for ii in range(i, i+3) for jj in range(j, j+3)) return ans
largest-local-values-in-a-matrix
PYTHON3 BEST
Gurugubelli_Anil
1
12
largest local values in a matrix
2,373
0.839
Easy
32,475
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2814349/Python-or-BRUTAL-FORCE-w-thoughts-on-better-implementation
class Solution: def largestLocal(self, grid: List[List[int]]): ''' THOUGHTS THAT CAME LATER: Ultimately the amount of comparisions can be massively Reduced. If you've just looked at a 3x3 section and then Only increment over by one, then you're readdressing a 2x3 section for which you already know the max I think that this could be solved with some kind of stack. I'll try to come back later and implement something like this ''' # I'm sure that there is a prettier and more efficient # solution to this problem, but this felt like a straight # forward Brutal Force approach to solving the problem # It looks pretty gnarly so I'll try to suscinctly # describe the variables and logic in the code local_maxes = [] # g_ht represents "Global Height" for g_ht in range(0, len(grid)-2): # curr_ht represents "Current Height" the maxes for each 3x3 window # at the given iteration through the grid are added to this holder curr_ht = [] # For each height (i.e. row) that we visit we also need to visit # all ofThe columns at that given height for width in range(0,len(grid)-2): # Here I am using the variable lh to represent "Local Height" # This is simply creating our sub-grid where we find the max temp = [grid[lh][width:width+3] for lh in range(g_ht,g_ht+3)] # I flatten the grid and add the max value to current height curr_ht.append(max([flat for pack in temp for flat in pack])) # Once, we've gotten here, we have found all the maxes for the # current heigth, and can add them to our return grid and continue local_maxes.append(curr_ht) return local_maxes
largest-local-values-in-a-matrix
Python | BRUTAL FORCE w/ thoughts on better implementation
jessewalker2010
0
5
largest local values in a matrix
2,373
0.839
Easy
32,476
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2801766/Python-multiple-loops
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) x = n-2 res = [] answer = [] i_ = 0 j_ = 0 while i_ < x: while j_ < x: max_ = 0 for i in range(i_, i_+3): for j in range(j_, j_+3): max_ = max(max_, grid[i][j]) answer.append(max_) if j_ < x: j_+=1 i_+=1 j_=0 idx = 0 for i in range(0, x): ans = [] for j in range(0, x): ans.append(answer[idx]) idx+=1 res.append(ans) return res
largest-local-values-in-a-matrix
Python multiple loops
mani-cash
0
4
largest local values in a matrix
2,373
0.839
Easy
32,477
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2784835/python-image-deep-learning
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: rows, cols = len(grid), len(grid[0]) res = [[0] * (cols - 2) for i in range(rows - 2)] for i in range(rows - 2): for j in range(cols - 2): local = float('-inf') for ii in range(i, i + 3): for jj in range(j, j + 3): local = max(local, grid[ii][jj]) res[i][j] = local return res
largest-local-values-in-a-matrix
python image deep learning
JasonDecode
0
2
largest local values in a matrix
2,373
0.839
Easy
32,478
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2743683/Python3-one-liner
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: return [[max(grid[i][j] for j in range(c -1, c + 2) for i in range(r -1, r + 2)) for c in range(1, len(grid) - 1)] for r in range(1, len(grid) - 1)]
largest-local-values-in-a-matrix
[Python3] one-liner
avishaitsur
0
6
largest local values in a matrix
2,373
0.839
Easy
32,479
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2741410/PYTHON
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: N = len(grid) ans = [[0] * (N-2) for _ in range(N-2)] for i in range(N-2): for j in range(N-2): for di in range(3): for dj in range(3): ans[i][j] = max(ans[i][j], grid[i + di][j + dj]) return ans
largest-local-values-in-a-matrix
PYTHON🐍
shubhamdraj
0
11
largest local values in a matrix
2,373
0.839
Easy
32,480
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2713759/Python-or-Original-Solution-or-Easy-to-understand
class Solution: def largestLocal(self, grid: list[list[int]]) -> list[list[int]]: maxVal = 0 row = [] col = [] n = len(grid[0]) endRow = 3 endCol = 3 startRow = 0 startCol = 0 # [[9,9],[8,6]] while True: for i in range(startRow, endRow): for j in range(startCol, endCol): maxVal = max(maxVal, grid[i][j]) row.append(maxVal) maxVal = 0 if len(row) == n - 2: col.append(row.copy()) row.clear() if len(col) == n - 2: break endRow += 1 startRow += 1 endCol = 3 startCol = 0 else: endCol += 1 startCol += 1 return col # 00 01 10 11 # 01 02 11 12 # 02 03 12 13 # 10 11 20 21 # 11 12 21 22 # 12 13 22 23 # 20 21 30 31 # 21 22 31 32 # 22 23 32 33
largest-local-values-in-a-matrix
Python | Original Solution | Easy to understand
flufe
0
8
largest local values in a matrix
2,373
0.839
Easy
32,481
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2706112/Python-Simple-brute-force-solution
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: res = [] for r in range(0, len(grid) - 2): mx = [] for c in range(0, len(grid[0]) - 2): v1 = max(grid[r][c], grid[r][c + 1], grid[r][c + 2]) v2 = max(grid[r + 1][c], grid[r + 1][c + 1], grid[r + 1][c + 2]) v3 = max(grid[r + 2][c], grid[r + 2][c + 1], grid[r + 2][c + 2]) mx.append(max(v1, v2, v3)) res.append(mx) return res
largest-local-values-in-a-matrix
[Python] Simple brute force solution
casshsu
0
9
largest local values in a matrix
2,373
0.839
Easy
32,482
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2678057/Python3-Solution
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: size = len(grid) ans = [] i = 0 while i + 3 <= size: j = 0 a = [] while j + 3 <= size: a.append(max([max(g[j:j+3]) for g in grid[i:i+3]])) j += 1 i += 1 ans.append(a) return ans
largest-local-values-in-a-matrix
Python3 Solution
sipi09
0
5
largest local values in a matrix
2,373
0.839
Easy
32,483
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2669689/python-solution-easy
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: m = len(grid) n = len(grid) def findMax(x, y): print(x, y) maxi = -1 for i in range(3): maxi = max(maxi, max(grid[x + i][y:3 + y])) return maxi array = [[0 for j in range(n - 2)] for i in range(m - 2)] for i in range(m - 2): for j in range(n - 2): array[i][j] = findMax(i, j) return array
largest-local-values-in-a-matrix
python solution easy
MaryLuz
0
3
largest local values in a matrix
2,373
0.839
Easy
32,484
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2652201/Python3-One-Liner-With-List-Comprehension
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: return [[max([grid[i+o1][j+o2] for o1 in range(-1,2) for o2 in range(-1, 2)]) for j in range(1,len(grid)-1)] for i in range(1,len(grid)-1)]
largest-local-values-in-a-matrix
Python3 One Liner With List Comprehension
godshiva
0
7
largest local values in a matrix
2,373
0.839
Easy
32,485
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2587521/Primitive-solution-or-Python-3
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: # print(grid[0]) -> [9,9,8,1] # print(grid[0][0]) -> 9 # print(grid[3][3]) -> 2 # print(len(grid)) -> 4 # print(max(grid[0])) -> 9 newgrid = [] for m in range(len(grid) - 2): for n in range(len(grid) - 2): for i in range(3): for j in range(3): newgrid.append(grid[i + m][j + n]) tempoutput = [] start = 0 end = len(newgrid) step = 9 for i in range(start, end, step): tempoutput.append(max(newgrid[i:i+step])) x = len(grid) - 2 xlist = [] output = [] for i in range(x): for j in range(x): xlist.append(tempoutput[j + i * x]) output.append(xlist) xlist = [] return(output)
largest-local-values-in-a-matrix
Primitive solution | Python 3
aglona
0
37
largest local values in a matrix
2,373
0.839
Easy
32,486
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2513130/Python-3-greater-Elegant-way-that-avoids-repetition-as-much-as-possible
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: result= [] for row in range(len(grid)-2): self.countMap = collections.defaultdict(int) temp = [] for col in range(len(grid[0])): self.addColumn(grid, row, col) if col>2: self.removeColumn(grid, row, col-3) if col>=2: maxKey = max(key for key in self.countMap.keys()) temp.append(maxKey) result.append(temp) return result def addColumn(self, grid, row, col): for rowId in range(3): newRow = row + rowId self.countMap[grid[newRow][col]] += 1 def removeColumn(self, grid, row, col): for rowId in range(3): newRow = row + rowId self.countMap[grid[newRow][col]] -= 1 if self.countMap[grid[newRow][col]] == 0: del self.countMap[grid[newRow][col]]
largest-local-values-in-a-matrix
Python 3 -> Elegant way that avoids repetition as much as possible
mybuddy29
0
29
largest local values in a matrix
2,373
0.839
Easy
32,487
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2472350/Python3-or-with-assert
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: length = len(grid) - 2 res_matrix = [[0 for x in range(length)] for x in range(length)] for i in range(length): for j in range(length): max_line_matrix_3x3 = [max(grid[x][j:j+3]) for x in range(i, i + 3)] res_matrix[i][j] = max(max_line_matrix_3x3) return res_matrix # test1 = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]] # test2 = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]] # test3 = [[9,9,8],[5,6,2],[8,2,6]] # test4 = [[1 for i in range(100)] for i in range(100)] # assert Solution().largestLocal(test1) == [[9,9],[8,6]] # assert Solution().largestLocal(test2) == [[2,2,2],[2,2,2],[2,2,2]] # assert Solution().largestLocal(test3) == [[9]] # assert Solution().largestLocal(test4) == [[1 for i in range(98)] for i in range(98)]
largest-local-values-in-a-matrix
Python3 | with assert
Sergei_Gusev
0
26
largest local values in a matrix
2,373
0.839
Easy
32,488
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2445224/Largest-Local-Values-in-a-Matrix
class Solution: def maximum(self ,arr): m = 0 for i in arr: for j in i: if j>m: m = j return m def largestLocal(self, arr: List[List[int]]) -> List[List[int]]: n = len(arr) out = [["#" for i in range(n-2)] for i in range(n-2)] for i in range (n-2): for j in range(n-2): checkArray = [[arr[i][j],arr[i+1][j],arr[i+2][j]], [arr[i][j+1],arr[i+1][j+1],arr[i+2][j+1]] ,[arr[i][j+2],arr[i+1][j+2],arr[i+2][j+2]]] out[i][j]= self.maximum(checkArray) return(out)
largest-local-values-in-a-matrix
Largest Local Values in a Matrix
dhananjayaduttmishra
0
34
largest local values in a matrix
2,373
0.839
Easy
32,489
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2425971/Python-Accurate-and-Faster-Solution
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: localN = len(grid)-2 mat = [[0]*localN for _ in range(localN)] for ii in range(localN): for jj in range(localN): mat[ii][jj] = max([grid[i][j] for i in range(ii, ii+3) for j in range(jj, jj+3)]) return mat
largest-local-values-in-a-matrix
[Python] Accurate and Faster Solution
Buntynara
0
13
largest local values in a matrix
2,373
0.839
Easy
32,490
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2425956/O(n)-one-liner
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: return [[max([max([grid[mrow][mcol] for mcol in range(col - 1, col + 2)]) for mrow in range(row - 1, row + 2)]) for col in range(1, len(grid[0]) - 1)] for row in range(1, len(grid) - 1)]
largest-local-values-in-a-matrix
O(n) one-liner
ahmedyarub
0
30
largest local values in a matrix
2,373
0.839
Easy
32,491
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2425318/Commented-out-python-solution-100-fast
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: #make an empty 2d arrray to fill in later ret = [] for i in range(len(grid) - 2): ret.append([]) #for each matrix row in our return matrix... for i in range(len(ret)): #cut out the 3 corresponding rows from the input grid (think of this as moving down veritcally) s_grid = grid[i:i+3] j = 0 #while we still have space horizontally we want to move this inner matrix to the right while j+3 <= len(grid): #find the max number in this new 3x3 grid max_num = max([max(x[j:j+3]) for x in s_grid]) #append it to our return matrix at curent level (current i in the for loop) ret[i].append(max_num) #move inner matrix 1 to the right j += 1 #reset the position once we reach the right edge of the matrix j = 0 return ret
largest-local-values-in-a-matrix
Commented out python solution, 100% fast
igorkaluga
0
21
largest local values in a matrix
2,373
0.839
Easy
32,492
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2425173/List-comprehension-75-speed
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n1 = len(grid) - 1 return [[max(grid[i][j] for i in range(r - 1, r + 2) for j in range(c - 1, c + 2)) for c in range(1, n1)] for r in range(1, n1)]
largest-local-values-in-a-matrix
List comprehension, 75% speed
EvgenySH
0
14
largest local values in a matrix
2,373
0.839
Easy
32,493
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422487/Secret-Python-Answer-9-Lines-O(n2)
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) res = [[0 for i in range(n-2)] for j in range(n-2)] for i in range(1,n-1): for j in range(1,n-1): m = 0 for d in [(0,1),(0,-1),(-1,0),(1,-1),(-1,1),(1,0),(1,1),(-1,-1),(0,0)]: m = max(m , grid[i+d[0]][j+d[1]]) res[i-1][j-1] = m return res
largest-local-values-in-a-matrix
[Secret Python Answer🤫🐍👌😍] 9 Lines O(n^2)
xmky
0
33
largest local values in a matrix
2,373
0.839
Easy
32,494
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422458/Python3-Monotonic-Queue
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) res = [[0] * (n - 2) for _ in range(n - 2)] for i in range(n - 2): queue = collections.deque() num0 = max(grid[i][0], grid[i + 1][0], grid[i + 2][0]) num1 = max(grid[i][1], grid[i + 1][1], grid[i + 2][1]) if num0 > num1: queue.append((num0, 0)) queue.append((num1, 1)) for j in range(2, n): if queue[0][1] < j - 2: queue.popleft() num = max(grid[i][j], grid[i + 1][j], grid[i + 2][j]) while queue and num >= queue[-1][0]: queue.pop() queue.append((num, j)) res[i][j - 2] = queue[0][0] return res
largest-local-values-in-a-matrix
[Python3] Monotonic Queue
celestez
0
26
largest local values in a matrix
2,373
0.839
Easy
32,495
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422359/python3-straightforward-naive-way
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) dir8 = [(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)] output = [] # iterate over grid but not the stuff on the edges for i in range(1, n - 1): row = [] for j in range(1, n - 1): mx = grid[i][j] # initial max value is the value of the element we are on right now for dx, dy in dir8: mx = max(mx, grid[i + dx][j + dy]) # look at neighbors and set max if its bigger row.append(mx) output.append(row) return output
largest-local-values-in-a-matrix
python3 straightforward naive way
Pinfel
0
10
largest local values in a matrix
2,373
0.839
Easy
32,496
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422321/Python-3-Simple-solution
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ret = [[None] * (n - 2) for _ in range(n - 2)] for i in range(1, n-1): for j in range(1, n-1): ret[i - 1][j - 1] = max(grid[i-1][j-1], grid[i-1][j], grid[i-1][j+1], grid[i][j-1], grid[i][j], grid[i][j+1], grid[i+1][j-1], grid[i+1][j], grid[i+1][j+1]) return ret
largest-local-values-in-a-matrix
[Python 3] Simple solution
leet_aiml
0
34
largest local values in a matrix
2,373
0.839
Easy
32,497
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422318/Python-or-Brute-Force
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) m = len(grid[0]) ans = [[0] * (n-2) for i in range(n-2)] for p in range(n-2): for q in range(n-2): maxi = max(grid[p+1][q+1], grid[p+1 - 1][q+1], grid[p+1 + 1][q+1], grid[p+1][q+1 -1], grid[p+1][q+1 + 1],grid[p+1 - 1][q+1 -1], grid[p+1 + 1][q+1 + 1], grid[p+1 -1][q+1 +1], grid[p+1 + 1][q+1 - 1]) ans[p][q] = maxi return ans
largest-local-values-in-a-matrix
Python | Brute Force
LittleMonster23
0
17
largest local values in a matrix
2,373
0.839
Easy
32,498
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422293/Python-Simple-Python-Solution-Using-Brute-Force-or-100-Faster
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: result = [[0 for _ in range(len(grid)-2)] for _ in range(len(grid)-2)] def get_max_value(r,c): max_value = max( grid[r][c : c + 3] + grid[r + 1][ c : c + 3] + grid[r + 2][c : c + 3]) return max_value for row in range(len(grid)-2): for col in range(len(grid)-2): result[row][col] = get_max_value(row, col) return result
largest-local-values-in-a-matrix
[ Python ] ✅✅ Simple Python Solution Using Brute Force | 100 % Faster 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
59
largest local values in a matrix
2,373
0.839
Easy
32,499