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/move-zeroes/discuss/2831020/Super-simple-python-approach-with-minimal-lines-of-code | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
start = 0
second = 1
while second < len(nums):
if(nums[start] == 0 and nums[second] !=0):
nums[start], nums[second] = nums[second], nums[start]
start+=1
if(nums[start] != 0 ):
start +=1
second+=1 | move-zeroes | Super simple python approach with minimal lines of code | btulsi | 0 | 5 | move zeroes | 283 | 0.614 | Easy | 5,100 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/650942/Proof-of-Floyd's-cycle-detection-algorithm-Find-the-Duplicate-Number | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow = fast = ans = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
while ans != slow:
ans = nums[ans]
slow = nums[slow]
return ans | find-the-duplicate-number | Proof of Floyd's cycle detection algorithm - Find the Duplicate Number | r0bertz | 20 | 2,400 | find the duplicate number | 287 | 0.591 | Medium | 5,101 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/342853/Solution-in-Python-3-(-O(n)-speed-and-O(1)-memory-) | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
t, h = nums[0], nums[nums[0]]
while t != h: t, h = nums[t], nums[nums[h]]
t = 0
while t != h: t, h = nums[t], nums[h]
return t
- Junaid Mansuri
(LeetCode ID)@hotmail.com | find-the-duplicate-number | Solution in Python 3 ( O(n) speed and O(1) memory ) | junaidmansuri | 9 | 2,600 | find the duplicate number | 287 | 0.591 | Medium | 5,102 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2013321/Python-O(n)-Time-and-O(1)-Space-Optimal-Easy-to-Understand-Solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# Use concept of 142. Linked List Cycle II (find the node where linked list has cycle)
# start hopping from Node
slow, fast = 0, 0
# Cycle detection
# Let slow jumper and fast jumper meet somewhere in the cycle
while True:
# slow jumper hops 1 step, while fast jumper hops two steps forward.
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
# for locating start node of cycle
check = 0
while True:
# Locate the start node of cycle (i.e., the duplicate number)
slow = nums[slow]
check = nums[check]
if check == slow:
break
return check | find-the-duplicate-number | Python O(n) Time and O(1) Space Optimal Easy to Understand Solution ⭐ | samirpaul1 | 6 | 500 | find the duplicate number | 287 | 0.591 | Medium | 5,103 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1077997/Python-Floyd's-Cycle-Detecting-Algorithm-Easy-to-Understand | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow, fast = 0, 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow | find-the-duplicate-number | Python Floyd's Cycle Detecting Algorithm Easy to Understand | pikachuexeallen | 6 | 458 | find the duplicate number | 287 | 0.591 | Medium | 5,104 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1874359/Python-Solutions | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i] == nums[j]: return nums[i] | find-the-duplicate-number | ✅ Python Solutions | dhananjay79 | 4 | 212 | find the duplicate number | 287 | 0.591 | Medium | 5,105 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1874359/Python-Solutions | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
s = set()
for i in nums:
if i in s: return i
s.add(i) | find-the-duplicate-number | ✅ Python Solutions | dhananjay79 | 4 | 212 | find the duplicate number | 287 | 0.591 | Medium | 5,106 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1874359/Python-Solutions | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i in nums:
if nums[abs(i)] < 0: return abs(i)
nums[abs(i)] *= -1 | find-the-duplicate-number | ✅ Python Solutions | dhananjay79 | 4 | 212 | find the duplicate number | 287 | 0.591 | Medium | 5,107 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1874359/Python-Solutions | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow, fast = nums[nums[0]], nums[nums[nums[0]]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
start = nums[0]
while start != slow:
start = nums[start]
slow = nums[slow]
return start | find-the-duplicate-number | ✅ Python Solutions | dhananjay79 | 4 | 212 | find the duplicate number | 287 | 0.591 | Medium | 5,108 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2546656/Python-Easy-Approach-oror-O(n)-oror-Beginners-friendly | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i in range(len(nums)):
if nums[abs(nums[i])-1]>0:
nums[abs(nums[i])-1] = -nums[abs(nums[i])-1]
else:
return abs(nums[i]) | find-the-duplicate-number | [Python] Easy Approach || O(n) || Beginners friendly | iterator1114 | 2 | 303 | find the duplicate number | 287 | 0.591 | Medium | 5,109 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1433142/3-Way-of-solving-the-problem-with-Python-in-O(n)-Time | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
prevNums = set()
for n in nums:
if n in prevNums: return n
else: prevNums.add(n)
return float("inf") | find-the-duplicate-number | 3 Way of solving the problem with Python in O(n) Time | abrarjahin | 2 | 371 | find the duplicate number | 287 | 0.591 | Medium | 5,110 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1433142/3-Way-of-solving-the-problem-with-Python-in-O(n)-Time | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
#Time O(n) and extra space O(1)
# By Modifying the array - As value can be from 1-n, we can mark index to track them
for i in range(len(nums)):
index = (nums[i]%len(nums))-1 #As value from 1-n
nums[index]+=len(nums)
for i,v in enumerate(nums):
if v>2*len(nums):
return i+1
return float("inf") | find-the-duplicate-number | 3 Way of solving the problem with Python in O(n) Time | abrarjahin | 2 | 371 | find the duplicate number | 287 | 0.591 | Medium | 5,111 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1302366/PythonorSimpleorCounter | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
freq=Counter(nums)
for i in freq:
if freq[i]>1:
return i | find-the-duplicate-number | Python|Simple|Counter | atharva_shirode | 2 | 348 | find the duplicate number | 287 | 0.591 | Medium | 5,112 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2728909/simple-Set-solution-in-pyhton | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
setm = set()
for i in nums:
k = len(setm)
setm.add(i)
m = len(setm)
if m == k:
return i | find-the-duplicate-number | simple Set solution in pyhton | PrateekSikarwar | 1 | 34 | find the duplicate number | 287 | 0.591 | Medium | 5,113 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2383164/Binary-Search-Solution-O(nlogn)-time-or-O(1)-space-python3 | class Solution:
# O(nlogn) time,
# O(1) space,
# Approach: Binary search,
def findDuplicate(self, nums: List[int]) -> int:
n = len(nums)
def countNumbersLessOrEqualToNum(num:int) -> int:
count = 0
for number in nums:
if number <= num:
count +=1
return count
def findDuplicate(start, end):
mid = (start + end)//2
count = countNumbersLessOrEqualToNum(mid)
if count > mid and (mid == 1 or countNumbersLessOrEqualToNum(mid-1) == mid-1):
return mid
if start == end-1:
return end
if count > mid:
return findDuplicate(start, mid)
if count <= mid:
return findDuplicate(mid, end)
return findDuplicate(1, n) | find-the-duplicate-number | Binary Search Solution, O(nlogn) time | O(1) space, python3 | destifo | 1 | 56 | find the duplicate number | 287 | 0.591 | Medium | 5,114 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2315229/Python3-O(n)-time-O(1)-space | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i, _ in enumerate(nums):
while(i+1 != nums[i]):
n = nums[i]
tmp = nums[n-1]
if tmp == nums[i]:
return tmp
else:
nums[i], nums[n-1] = nums[n-1], nums[i]
i += 1
return -1 | find-the-duplicate-number | [Python3] O(n) time O(1) space | Yan_Yichun | 1 | 70 | find the duplicate number | 287 | 0.591 | Medium | 5,115 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1754451/Simple-Solution-Python3-or-Explained | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)- 1):
if nums[i] == nums[i + 1]:
return nums[i] | find-the-duplicate-number | Simple Solution Python3 | Explained | dporwal985 | 1 | 82 | find the duplicate number | 287 | 0.591 | Medium | 5,116 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/1748330/Easy-to-understand-O(N)-runtime | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i,j in enumerate(nums):
# If the current index value is negative, making it +ve
# To navigate to the index
if j < 0:
j *= -1
# The index is marked negative
nums[j-1] *= -1
# If we find the number; previously the number is marked negative
# Will now make it +ve
if nums[j-1] > 0:
return j # Return the number that causes do so | find-the-duplicate-number | Easy to understand [O(N) - runtime] | funnybacon | 1 | 107 | find the duplicate number | 287 | 0.591 | Medium | 5,117 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2813374/Python-Sol-with-Collections | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
from collections import Counter
k = Counter(nums)
for i,j in k.items():
if j > 1:
return i | find-the-duplicate-number | Python Sol with Collections | user5631IZ | 0 | 4 | find the duplicate number | 287 | 0.591 | Medium | 5,118 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2804316/Python-New-very-simple-cycle-detection-approach.-No-extra-space.-Code-commented. | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# Start iteration
i = 0
while i < len(nums):
currNr = nums[i]
# This number is in its right place. Increment i and continue.
if currNr == i + 1:
i = i + 1
else:
# We need to do a switch.
eleToSwitch = nums[currNr - 1]
# We have already seen this number, return it.
if eleToSwitch == currNr:
return eleToSwitch
# Put the current element nums[i]
# in its right position nums[i] - 1 and put the number
# nums[nums[i] - 1] in the position i.
nums[i], nums[currNr - 1] = eleToSwitch, currNr | find-the-duplicate-number | [Python] New very simple cycle-detection approach. No extra space. Code commented. | interviewprepsimpleguy | 0 | 7 | find the duplicate number | 287 | 0.591 | Medium | 5,119 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2778691/Easy-python-solution. | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
dic={}
for i in nums:
if i in dic:
dic[i]=dic[i]+1
else:
dic[i]=1
for i in dic:
if dic[i]>=2:
return i
return 0 | find-the-duplicate-number | Easy python solution. | zaeden9 | 0 | 7 | find the duplicate number | 287 | 0.591 | Medium | 5,120 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2761191/Python-3-Solution-or-1-line-or-Faster-than-94.57 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
return (sum(nums) - sum(set(nums))) // (len(nums) - len(set(nums))) | find-the-duplicate-number | Python 3 Solution | 1 line | Faster than 94.57% | mati44 | 0 | 3 | find the duplicate number | 287 | 0.591 | Medium | 5,121 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2742360/Two-line-colution-Python | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
c = Counter(nums)
return sorted(c, key=lambda x: (-c[x], x))[0] | find-the-duplicate-number | Two line colution Python | a3amaT | 0 | 13 | find the duplicate number | 287 | 0.591 | Medium | 5,122 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2732200/Python-oror-3-liner-oror-beginners-solution-oror-Easy | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i in range(len(nums)):
if nums[abs(nums[i])-1] < 0: return abs(nums[i])
else: nums[abs(nums[i])-1] = -nums[abs(nums[i])-1] | find-the-duplicate-number | Python || 3-liner || beginners solution || Easy | its_iterator | 0 | 6 | find the duplicate number | 287 | 0.591 | Medium | 5,123 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2719978/Concise-Python-and-Golang-Solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
cache = set()
for num in nums:
if num in cache:
return num
cache.add(num) | find-the-duplicate-number | Concise Python and Golang Solution | namashin | 0 | 2 | find the duplicate number | 287 | 0.591 | Medium | 5,124 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2716404/VERY-EASY-SOLUTION-WITH-PYTHON.ONLY-7-LINES.CHECK-IT-OUT | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)):
if i+1<len(nums):
if(nums[i]==nums[i+1]):
return nums[i] | find-the-duplicate-number | VERY EASY SOLUTION WITH PYTHON.ONLY 7 LINES.CHECK IT OUT | rajneeshkabdwal | 0 | 1 | find the duplicate number | 287 | 0.591 | Medium | 5,125 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2715784/easiest-for-understand!-1-line | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
return (sum(nums) - sum(set(nums))) // (len(nums) - len(set(nums))) | find-the-duplicate-number | easiest for understand! 1-line | neversleepsainou | 0 | 4 | find the duplicate number | 287 | 0.591 | Medium | 5,126 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2715687/Python-Two-approaches | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
#time complexity: O(n)
#space complexity: O(n)
dic={}
for i in range(len(nums)):
if nums[i] in dic:
return nums[i]
else:
dic[nums[i]]=i | find-the-duplicate-number | Python Two approaches | Godslyr10 | 0 | 4 | find the duplicate number | 287 | 0.591 | Medium | 5,127 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2715687/Python-Two-approaches | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow,fast=0,0
while True:
slow=nums[slow]
fast=nums[nums[fast]]
if slow == fast:
break
slow=0
while True:
slow=nums[slow]
fast=nums[fast]
if slow==fast:
return slow | find-the-duplicate-number | Python Two approaches | Godslyr10 | 0 | 4 | find the duplicate number | 287 | 0.591 | Medium | 5,128 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2707325/Easy-Python-solution-beats-99.99 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# Initiate a blank dictionary
num_dict = {}
for i in nums:
if i not in num_dict:
# Keep adding distinct numbers along with their count = 1 in the dictionary
num_dict[i] = 1
else:
# As soon as a repeated number is encountered in the dictionary, simply return that number
return i | find-the-duplicate-number | Easy Python solution beats 99.99% | code_snow | 0 | 7 | find the duplicate number | 287 | 0.591 | Medium | 5,129 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2688765/1-Line-python-solution-beat-99 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
return (sum(nums) - sum(set(nums))) // (len(nums) - len(set(nums))) | find-the-duplicate-number | 1 Line python solution beat 99% | wguo | 0 | 10 | find the duplicate number | 287 | 0.591 | Medium | 5,130 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2688230/Now-I-am-become-death | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
def linked(node, speed):
next_node = node
while True:
for i in range(speed):
next_node = nums[next_node]
yield next_node
slow = linked(0, 1)
fast = linked(0, 2)
while next(slow) != next(fast):
continue
fast = linked(0, 1)
while (result := next(slow)) != next(fast):
continue
return result | find-the-duplicate-number | Now I am become death | mshvern | 0 | 5 | find the duplicate number | 287 | 0.591 | Medium | 5,131 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2684667/Python-SolutionororUsing-Lists-and-Set | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
seenElements = set()
for n in nums:
if n in seenElements:
return n
seenElements.add(n) | find-the-duplicate-number | Python Solution||Using Lists and Set | PujalaChowdamma | 0 | 4 | find the duplicate number | 287 | 0.591 | Medium | 5,132 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2654481/PYTHON-easy-solution-oror | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
a = set(nums)
return (sum(nums)-sum(a)) // (len(nums)-len(a)) | find-the-duplicate-number | PYTHON easy solution || | sinjan_singh | 0 | 5 | find the duplicate number | 287 | 0.591 | Medium | 5,133 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2652790/Floyd's-Algorithm-Revised | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# each element represents a node
# the value of the node can represent an index
# since there's 1 duplicate, every other node
# will point to a node (no other node points to)
# the duplicate node will point to a node that has
# already been pointed to (creating cycle)
# use Floyd's Algorithm (fast and slow pointer)
# to find where the nodes intersect
# once you've found the intersection create another
# slow pointer and find where the new slow and original
# slow pointer intersect (where they intersect is the duplicate)
# time O(n) space O(1)
slow = fast = catch = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
while True:
slow = nums[slow]
catch = nums[catch]
if slow == catch:
return slow | find-the-duplicate-number | Floyd's Algorithm Revised | andrewnerdimo | 0 | 9 | find the duplicate number | 287 | 0.591 | Medium | 5,134 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2651202/Python-Easy-and-Explained | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)-1):
if (nums[i] == nums[i+1]):
return nums[i] | find-the-duplicate-number | Python Easy and Explained | kunallunia22 | 0 | 4 | find the duplicate number | 287 | 0.591 | Medium | 5,135 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2643791/Floy'd-Algorithm-(slow-and-fast-pointer) | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# each element represents a node
# the value of the node can represent an index
# since there's 1 duplicate, every other node
# will point to a node (no other node points to)
# the duplicate node will point to a node that has
# already been pointed to (creating cycle)
# use Floyd's Algorithm (fast and slow pointer)
# to find where the nodes intersect
# one you've found the intersection create another
# slow pointer and find where the new slow and original
# slow pointer intersect (where they intersect is the duplicate)
# time O(n) space O(1)
slow1 = slow2 = fast = 0
while True:
slow1 = nums[slow1]
fast = nums[nums[fast]]
if slow1 == fast:
break
while True:
slow1 = nums[slow1]
slow2 = nums[slow2]
if slow1 == slow2:
return slow1 | find-the-duplicate-number | Floy'd Algorithm (slow and fast pointer) | andrewnerdimo | 0 | 5 | find the duplicate number | 287 | 0.591 | Medium | 5,136 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2604605/python3 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# don't know why time limit exceeded for list but for set it worked
# please let me know in the comment section if you guys can clarify
l = set()
for x in nums:
if x in l: return x
l.add(x) | find-the-duplicate-number | python3 | priyam_jsx | 0 | 56 | find the duplicate number | 287 | 0.591 | Medium | 5,137 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2528752/Python-or-faster-than-77 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(1,len(nums)):
if nums[i]==nums[i-1]:
return nums[i]
return -1 | find-the-duplicate-number | Python | faster than 77% | moayaan1911 | 0 | 104 | find the duplicate number | 287 | 0.591 | Medium | 5,138 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2511941/simple-python-O(n)-time | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
d = defaultdict(int)
for i in nums:
d[i] += 1
for i in d:
if d[i] > 1:
return i | find-the-duplicate-number | simple python O(n) time | gasohel336 | 0 | 60 | find the duplicate number | 287 | 0.591 | Medium | 5,139 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2507536/Simple-python-code-with-explanation | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
thoma = {}
#store the keys of dictionary(thoma) in variable -->(k)
k = thoma.keys()
#iterate over the elements in array --> nums
for i in nums:
#if element not in k(keys of dictionary)
if i not in k:
#it means it is new element \
#assingn val 1 to that element
thoma[i] = 1
#if element is in k(keys of dictionary)
else:
#it is already occured
#so return that value
return i | find-the-duplicate-number | Simple python code with explanation | thomanani | 0 | 51 | find the duplicate number | 287 | 0.591 | Medium | 5,140 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2506207/Python3-solution-using-Counter-beats-98 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
temp = Counter(nums)
for i in temp:
if temp[i] > 1:
return i | find-the-duplicate-number | Python3 solution using Counter beats 98% | irapandey | 0 | 57 | find the duplicate number | 287 | 0.591 | Medium | 5,141 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2474136/Python-Binary-Search-Solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
start = 1
end = len(nums)
ans = float('inf')
def bs(start, end):
nonlocal ans
if start > end:
return -1
else:
mid = (start + end) // 2
cnt = 0
for i in range(len(nums)):
if nums[i] <= mid:
cnt += 1
if cnt > mid:
ans = mid
return bs(start, mid-1)
else:
return bs(mid+1, end)
bs(start, end)
return ans | find-the-duplicate-number | Python Binary Search Solution | DietCoke777 | 0 | 34 | find the duplicate number | 287 | 0.591 | Medium | 5,142 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2474122/Python-Binary-Search-solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
start = 1
end = len(nums)
ans = float('inf')
def bs(start, end):
nonlocal ans
if start > end:
return -1
else:
mid = (start + end) // 2
cnt = 0
for i in range(len(nums)):
if nums[i] <= mid:
cnt += 1
if cnt > mid:
ans = mid
return bs(start, mid-1)
else:
return bs(mid+1, end)
bs(start, end)
return ans | find-the-duplicate-number | Python Binary Search solution | DietCoke777 | 0 | 11 | find the duplicate number | 287 | 0.591 | Medium | 5,143 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2450142/Python3-two-Methods-O(n)-and-O(n-logn).-Dictionary-Map | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)-1):
l = bisect_left(nums,nums[i])
r = bisect_right(nums,nums[i])
if r-l >1:
return nums[i] | find-the-duplicate-number | Python3 two Methods O(n) and O(n logn). Dictionary Map | aditya_maskar | 0 | 36 | find the duplicate number | 287 | 0.591 | Medium | 5,144 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2428231/Find-the-duplicate-number-oror-Python3-oror-Cycle-detection | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
hare = nums[0]
tortoise = nums[0]
while(True):
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if(tortoise == hare):
# We found a cycle
break
# Find the starting point of cycle
tortoise = nums[0]
while(tortoise != hare):
tortoise = nums[tortoise]
hare = nums[hare]
return tortoise | find-the-duplicate-number | Find the duplicate number || Python3 || Cycle detection | vanshika_2507 | 0 | 35 | find the duplicate number | 287 | 0.591 | Medium | 5,145 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2426143/Python-O(n)-solution-linear-time-constant-space-and-no-modifications-to-array | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# Floyd Warshall Algorithm
slow, fast = 0, 0 # 0 is not a part of the cycle
while True:
slow = nums[slow] # equivalent to slow.next in linked list
fast = nums[nums[fast]] # equivalent to fast.next.next in linked list
if slow == fast:
break
slow2 = 0
# Currently, slow is at the intersection of the slow and fast pointers, which is
# always going to be the same distance from the start of the cycle as slow 2
while True:
slow = nums[slow] # equivalent to slow.next in linked list
slow2 = nums[slow2] # equivalent to slow2.next in linked list
if slow == slow2: # will always intersect at the start of the cycle
return slow | find-the-duplicate-number | Python O(n) solution linear time, constant space and no modifications to array | averule | 0 | 74 | find the duplicate number | 287 | 0.591 | Medium | 5,146 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2393672/Python-Solution-or-One-Liner-or-100-Faster-or-Frequency-Count-Based | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# get most frequent element
return collections.Counter(nums).most_common(1)[0][0] | find-the-duplicate-number | Python Solution | One Liner | 100% Faster | Frequency Count Based | Gautam_ProMax | 0 | 65 | find the duplicate number | 287 | 0.591 | Medium | 5,147 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2392875/Python | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums = sorted(nums)
for i in range(0, len(nums)-1, 1):
if nums[i+1] == nums[i]:
return nums[i]
else:
continue | find-the-duplicate-number | Python | vjgadre21 | 0 | 61 | find the duplicate number | 287 | 0.591 | Medium | 5,148 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2368912/Python-using-Counter-2-Lines | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
x = Counter(nums)
return(max(x, key=x.get)) | find-the-duplicate-number | Python using Counter 2 Lines | Yodawgz0 | 0 | 61 | find the duplicate number | 287 | 0.591 | Medium | 5,149 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2346451/Python-O(n)-time-O(1)-space-easy-solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int: # Time: O(n) and Space: O(1)
while nums[0] != nums[nums[0]]:
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]
return nums[0] | find-the-duplicate-number | Python O(n)-time O(1)-space easy solution | DanishKhanbx | 0 | 132 | find the duplicate number | 287 | 0.591 | Medium | 5,150 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2323407/Python-Solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
return nums[i]
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
ref= [0]*len(nums)
for n in nums:
if ref[n]:
return n
ref[n]=1 | find-the-duplicate-number | Python Solution | SakshiMore22 | 0 | 67 | find the duplicate number | 287 | 0.591 | Medium | 5,151 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2304694/Python-solution-with-descriptive-algorithm-walkthrough | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for num in nums:
if nums[abs(num)] < 0:
return abs(num)
nums[abs(num)] *= -1 | find-the-duplicate-number | Python solution with descriptive algorithm walkthrough | pawelborkar | 0 | 56 | find the duplicate number | 287 | 0.591 | Medium | 5,152 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2294368/Python-t-and-h-approach | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
t = h = nums[0]
while True:
t = nums[t]
h = nums[nums[h]]
if h==t:
break
t = nums[0]
while t!=h:
h = nums[h]
t = nums[t]
return h | find-the-duplicate-number | Python t & h approach | Brillianttyagi | 0 | 35 | find the duplicate number | 287 | 0.591 | Medium | 5,153 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2279705/Find-the-Duplicate-Numbers | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
count=collections.Counter(nums)``
for key,value in count.items():
if value>1:
return key | find-the-duplicate-number | Find the Duplicate Numbers | Faraz369 | 0 | 21 | find the duplicate number | 287 | 0.591 | Medium | 5,154 |
https://leetcode.com/problems/find-the-duplicate-number/discuss/2182225/2-Line-python-Solution | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
freq = Counter(nums)
return freq.most_common(1)[0][0] | find-the-duplicate-number | 2 Line python Solution | writemeom | 0 | 173 | find the duplicate number | 287 | 0.591 | Medium | 5,155 |
https://leetcode.com/problems/game-of-life/discuss/468108/Use-the-tens-digit-as-a-counter-Python-O(1)-Space-O(mn)-Time | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def is_neighbor(board, i, j):
return (0 <= i < len(board)) and (0 <= j < len(board[0])) and board[i][j] % 10 == 1
directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for i in range(len(board)):
for j in range(len(board[0])):
for d in directions:
board[i][j] += 10 if is_neighbor(board, i + d[0], j + d[1]) else 0 # if adj cell is neighbor, add 10
for i in range(len(board)):
for j in range(len(board[0])):
neighbors = board[i][j] // 10 # count of neighbors
is_live = board[i][j] % 10 == 1 # state is live or not
if is_live: # live(1)
if neighbors < 2: # Rule 1
board[i][j] = 0
elif neighbors > 3: # Rule 3
board[i][j] = 0
else: # Rule 2
board[i][j] = 1
else: # dead(0)
if neighbors == 3: # Rule 4
board[i][j] = 1
else:
board[i][j] = 0 | game-of-life | Use the tens digit as a counter, Python O(1) Space, O(mn) Time | Moooooon | 4 | 104 | game of life | 289 | 0.668 | Medium | 5,156 |
https://leetcode.com/problems/game-of-life/discuss/1722673/Python-3-O(mn)-time-O(1)-space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
# count number of live neighbours
live_neighbours = 0
for x in range(max(i-1, 0), min(i+2, m)):
for y in range(max(j-1, 0), min(j+2, n)):
if i == x and j == y:
continue
live_neighbours += board[x][y] % 2
# mark the cell if it needs to change states
if board[i][j] == 0:
if live_neighbours == 3:
board[i][j] = 2
elif live_neighbours < 2 or live_neighbours > 3:
board[i][j] = 3
# change all required states
for i in range(m):
for j in range(n):
if board[i][j] == 2:
board[i][j] = 1
elif board[i][j] == 3:
board[i][j] = 0 | game-of-life | Python 3, O(mn) time, O(1) space | dereky4 | 3 | 312 | game of life | 289 | 0.668 | Medium | 5,157 |
https://leetcode.com/problems/game-of-life/discuss/1822905/Python3-oror-Give-10-min-to-be-a-pro-coder | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
life = []
for i in range(len(board)):
col = []
for j in range(len(board[0])):
col.append(board[i][j])
life.append(col)
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 1:
if self.check(board,i,j) == True:
life[i][j] = 0
else:
if self.check(board,i,j) == True:
life[i][j] = 1
for i in range(len(life)):
for j in range(len(life[0])):
board[i][j] = life[i][j]
def check(self,board,i,j):
count = 0
if board[i][j]==1:
#diagonal top left to bottom right
if i !=0 and j !=0 :
if board[i-1][j-1] == 1:
count+=1
if i != len(board)-1 and j != len(board[0])-1:
if board[i+1][j+1] == 1:
count+=1
#diagonal top right to bottom left
if i!=0 and j != len(board[0])-1:
if board[i-1][j+1] ==1:
count+=1
if i!= len(board)-1 and j!=0:
if board[i+1][j-1] == 1:
count +=1
#top and bottom vertically
if i!=0 and board[i-1][j]==1:
count+=1
if i!= len(board)-1 and board[i+1][j]==1:
count +=1
#left and right horizontally
if j!=0 and board[i][j-1] ==1:
count+=1
if j!= len(board[0])-1 and board[i][j+1]==1:
count+=1
if count ==2 or count == 3:
return False
else:
return True
else:
if board[i][j]==0:
#diagonal top left to bottom right
if i !=0 and j !=0 :
if board[i-1][j-1] == 1:
count+=1
if i != len(board)-1 and j != len(board[0])-1:
if board[i+1][j+1] == 1:
count+=1
#diagonal top right to bottom left
if i!=0 and j != len(board[0])-1:
if board[i-1][j+1] ==1:
count+=1
if i!= len(board)-1 and j!= 0:
if board[i+1][j-1] ==1:
count +=1
#top and bottom vertically
if i!=0 and board[i-1][j]==1:
count+=1
if i!= len(board)-1 and board[i+1][j]==1:
count +=1
#left and right horizontally
if j!=0 and board[i][j-1] ==1:
count+=1
if j!= len(board[0])-1 and board[i][j+1]==1:
count+=1
if count == 3:
return True
else:
return False | game-of-life | Python3 || Give 10 min to be a pro coder | SV_Shriyansh | 2 | 86 | game of life | 289 | 0.668 | Medium | 5,158 |
https://leetcode.com/problems/game-of-life/discuss/2598106/Python-Easy | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# original new state
# 0 0 0
# 1 1 1
# 0 1 2
# 1 0 3
r = len(board) ; c = len(board[0])
for i in range(r):
for j in range(c):
live = 0
dirs = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
for d in dirs:
x = i + d[0] ; y = j + d[1]
if x>=0 and y>=0 and x<r and y<c and board[x][y] in [1, 3]:
live += 1
if board[i][j] == 0 and live == 3:
board[i][j] = 2
elif board[i][j] == 1 and live != 2 and live != 3:
board[i][j] = 3
for i in range(r):
for j in range(c):
if board[i][j] == 2:
board[i][j] = 1
elif board[i][j] == 3:
board[i][j] = 0 | game-of-life | Python - Easy | lokeshsenthilkumar | 1 | 58 | game of life | 289 | 0.668 | Medium | 5,159 |
https://leetcode.com/problems/game-of-life/discuss/2424762/game-of-Life-oror-Python3-oror-Arrays | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1]]
for i in range(0, len(board)):
for j in range(0, len(board[0])):
live_cells = self.count_live_cells(i, j, dirs, board)
if(board[i][j] == 1 and (live_cells < 2 or live_cells > 3)):
# Marking live cell now dead as -1
board[i][j] = -1
elif(board[i][j] == 0 and live_cells == 3):
# Marking dead cells now live as 2
board[i][j] = 2
# Updating all values
for i in range(0, len(board)):
for j in range(0, len(board[0])):
if(board[i][j] == -1):
board[i][j] = 0
elif(board[i][j] == 2):
board[i][j] = 1
return board
def count_live_cells(self, i, j, dirs, board):
# Get live neighbors for a cell from all 8 directions
live_cells = 0
for dx, dy in dirs:
x = i + dx
y = j + dy
# Taking abs(board[x][y]) since -1 indicates live cell which is now dead
if(x < 0 or y < 0 or x >= len(board) or y >= len(board[0]) or abs(board[x][y]) != 1):
continue
live_cells += 1
return live_cells | game-of-life | game of Life || Python3 || Arrays | vanshika_2507 | 1 | 40 | game of life | 289 | 0.668 | Medium | 5,160 |
https://leetcode.com/problems/game-of-life/discuss/1953459/My-most-efficient-in-place-python-code-that-beats-93-of-solutions. | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
for i in range(len(board)):
for j in range(len(board[0])):
check=0
try:
if j>0 and i>0 and (board[i-1][j-1]==1 or board[i-1][j-1]==3):
check+=1
except:
pass
try:
if i>0 and board[i-1][j]==1 or board[i-1][j]==3:
check+=1
except:
pass
try:
if i>0 and board[i-1][j+1]==1 or board[i-1][j+1]==3:
check+=1
except:
pass
try:
if j>0 and (board[i][j-1]==1 or board[i][j-1]==3):
check+=1
except:
pass
try:
if board[i][j+1]==1 or board[i][j+1]==3:
check+=1
except:
pass
try:
if j>0 and (board[i+1][j-1]==1 or board[i+1][j-1]==3):
check+=1
except:
pass
try:
if board[i+1][j]==1 or board[i+1][j]==3:
check+=1
except:
pass
try:
if board[i+1][j+1]==1 or board[i+1][j+1]==3:
check+=1
except:
pass
if board[i][j]==0:
if check==3:
board[i][j]=2
else:
board[i][j]=0
elif board[i][j]==1:
if check==2 or check==3:
board[i][j]=1
else:
board[i][j]=3
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==2:
board[i][j]=1
elif board[i][j]==3:
board[i][j]=0 | game-of-life | My most efficient in-place python code that beats 93% of solutions. | tkdhimanshusingh | 1 | 61 | game of life | 289 | 0.668 | Medium | 5,161 |
https://leetcode.com/problems/game-of-life/discuss/994050/Beats-97-in-speed-92-in-space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# New state indicators
# 0 -> 0: 2
# 0 -> 1: 3
# 1 -> 0: 4
# 1 -> 1: 5
m, n = len(board), len(board[0])
directions = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]]
for i in range(m):
for j in range(n):
count_ones = 0
for x_, y_ in directions:
x = i + x_
y = j + y_
if 0 <= x <= m - 1 and 0 <= y <= n - 1:
count_ones += board[x][y] in [1, 4, 5]
if board[i][j] == 1:
if count_ones in [2, 3]:
board[i][j] = 5
else:
board[i][j] = 4
elif board[i][j] == 0:
if count_ones == 3:
board[i][j] = 3
else:
board[i][j] = 2
# print(board)
for i in range(m):
for j in range(n):
board[i][j] = board[i][j] % 2 | game-of-life | Beats 97% in speed, 92% in space | leonine9 | 1 | 22 | game of life | 289 | 0.668 | Medium | 5,162 |
https://leetcode.com/problems/game-of-life/discuss/2834671/Python-solution | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row = len(board)
col = len(board[0])
change = []
for i in range(row):
for j in range(col):
nums = 0
neighbors = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
for dx, dy in neighbors:
x = i + dx
y = j + dy
if 0 <= x < row and 0 <= y < col:
nums += board[x][y]
if board[i][j] == 1 and (nums < 2 or nums > 3):
change.append((i, j, 0))
elif board[i][j] == 0 and nums == 3:
change.append((i, j, 1))
while change:
i, j, c = change.pop()
board[i][j] = c | game-of-life | Python solution | maomao1010 | 0 | 3 | game of life | 289 | 0.668 | Medium | 5,163 |
https://leetcode.com/problems/game-of-life/discuss/2778726/Python-oror-Hashmap | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
n, m = len(board), len(board[0])
adj = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (0,-1), (1,-1)]
graph = defaultdict(list)
for i in range(n):
for j in range(m):
for r,c in adj:
if not( 0 <= i+r < n and 0 <= j+c < m ): continue
graph[(i,j)].append((i+r,j+c))
state = defaultdict(int)
for i in range(n):
for j in range(m):
live = 0
for r,c in graph[(i,j)]:
live += board[r][c]
if live < 2: state[(i,j)] = 0
if 2 <= live <= 3 and board[i][j] == 1 : state[(i,j)] = 1
if live > 3 and board[i][j] == 1: state[(i,j)] = 0
if live == 3 and board[i][j] == 0: state[(i,j)] = 1
for i in range(n):
for j in range(m):
board[i][j] = state[(i,j)] | game-of-life | Python || Hashmap | morpheusdurden | 0 | 1 | game of life | 289 | 0.668 | Medium | 5,164 |
https://leetcode.com/problems/game-of-life/discuss/2774275/Python3-O(1)-Space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
DIRS = [[-1, -1], [-1, 0], [-1, 1], # top
[0, -1], [0, 1], # mid
[1, -1], [1, 0], [1, 1]] # bot
ROWS, COLS = len(board), len(board[0])
def get_live_neighbors(r, c):
total = 0
for dr, dc in DIRS:
i, j = r+dr, c+dc
if i < 0 or i == ROWS or j < 0 or j == COLS:
continue
if board[i][j] in [-1, 1]:
total += 1
return total
# update cells to new states
for r in range(ROWS):
for c in range(COLS):
num_live_neighbors = get_live_neighbors(r, c)
if board[r][c] == 1:
board[r][c] = 1 if 2 <= num_live_neighbors <= 3 else -1
else:
board[r][c] = 2 if num_live_neighbors == 3 else 0
# convert new states into correct format
for r in range(ROWS):
for c in range(COLS):
board[r][c] = 1 if board[r][c] > 0 else 0 | game-of-life | [Python3] O(1) Space | jonathanbrophy47 | 0 | 1 | game of life | 289 | 0.668 | Medium | 5,165 |
https://leetcode.com/problems/game-of-life/discuss/2754284/Python-3-Easiest-solution-with-explanation | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
prev_board = deepcopy(board)
m,n = len(board),len(board[0])
directions = [(1,0),(0,1),(-1,0),(0,-1),(1,-1),(-1,1),(1,1),(-1,-1)]
living_conditions = {(0,3),(1,2),(1,3)}
for x,row in enumerate(prev_board):
for y,cell in enumerate(row):
live_neighbours = 0
for dx,dy in directions:
newx,newy = x+dx,y+dy
if newx >= 0 and newx < m and newy >= 0 and newy < n and prev_board[newx][newy] == 1:
live_neighbours += 1
if (cell,live_neighbours) in living_conditions:
board[x][y] = 1
else:
board[x][y] = 0 | game-of-life | [Python 3] Easiest solution with explanation | shriyansnaik | 0 | 3 | game of life | 289 | 0.668 | Medium | 5,166 |
https://leetcode.com/problems/game-of-life/discuss/2704034/Python3-One-Pass-Four-Directions-No-extra-Space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
# go throught the board row by row
for rx in range(m):
for cx in range(n):
# get our current status
status = board[rx][cx]
# get the rest of the alive neighbours
# we only need to check to the right
# and below us as we already have done
# the ones left to uns and above us
alive = 0
for nrx, ncx in [(rx, cx+1), (rx+1, cx-1), (rx+1, cx), (rx+1, cx+1)]:
alive += self.check_and_update_neighbour(nrx, ncx, status, m, n, board)
# now check whether cell was alive
if status > 0:
# update the status
status = status + alive
# check whether it dies
if status < 3 or status > 4:
board[rx][cx] = 0
# else set it to alive
else:
board[rx][cx] = 1
# cell was dead and has exactly three neighbours
elif status <= 0 and status - alive == -3:
board[rx][cx] = 1
else:
board[rx][cx] = 0
def check_and_update_neighbour(self, rx, cx, current_cell, m, n, board):
# check if indices are out of bound
if rx < 0 or rx >= m or cx < 0 or cx >= n:
return 0
# check whether the cell is alive
if board[rx][cx] > 0:
# increase the counter of the alive neighbour
# cell if we come from an alive cell
if current_cell > 0:
board[rx][cx] += 1
# return 1 as we found an alive neighbour
return 1
else:
# decrease the counter of the dead neighbour
# cell if we come from an alive cell
if current_cell > 0:
board[rx][cx] -= 1
return 0 | game-of-life | [Python3] - One-Pass, Four Directions, No extra Space | Lucew | 0 | 7 | game of life | 289 | 0.668 | Medium | 5,167 |
https://leetcode.com/problems/game-of-life/discuss/2372417/Python3-or-set-store-(i-j)-to-be-changed | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m, n = len(board), len(board[0])
dirs = {(0,-1),(0,1),(-1,0),(1,0),(-1,-1),(-1,1),(1,-1),(1,1)}
def checkNeighbor(i, j):
sum_ones_nei = 0
for d_i, d_j in dirs:
nei_i, nei_j = i+d_i, j+d_j
if nei_i < 0 or nei_i >= m or nei_j < 0 or nei_j >= n:
continue
if board[nei_i][nei_j] == 1:
sum_ones_nei += 1
return sum_ones_nei
ones, zeros = set(), set()
for i in range(m):
for j in range(n):
sum_ones_nei = checkNeighbor(i, j)
if board[i][j] == 1:
if sum_ones_nei < 2 or sum_ones_nei > 3:
zeros.add((i, j))
else:
if sum_ones_nei == 3:
ones.add((i, j))
for i, j in ones:
board[i][j] = 1
for i, j in zeros:
board[i][j] = 0 | game-of-life | Python3 | set store (i, j) to be changed | Ploypaphat | 0 | 24 | game of life | 289 | 0.668 | Medium | 5,168 |
https://leetcode.com/problems/game-of-life/discuss/2290829/Python-Simple-Python-Solution | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def isValidNeighbour(x, y, board):
return x>=0 and x < len(board) and y>=0 and y< len(board[0])
dx = [0,1,1,1,0,-1,-1,-1]
dy = [1,1,0,-1,-1,-1,0,1]
for row in range(len(board)):
for col in range(len(board[0])):
count_live_neighbour = 0
for i in range(8):
cur_x = row + dx[i]
cur_y = col + dy[i]
if isValidNeighbour(cur_x, cur_y, board) and abs(board[cur_x][cur_y]) == 1:
count_live_neighbour+=1
if board[row][col] == 1 and (count_live_neighbour < 2 or count_live_neighbour > 3):
board[row][col] = -1
if board[row][col] == 0 and count_live_neighbour == 3:
board[row][col] = 2
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] >=1 :
board[row][col] = 1
else:
board[row][col] = 0 | game-of-life | [ Python ] ✅ Simple Python Solution ✅✅ | vaibhav0077 | 0 | 74 | game of life | 289 | 0.668 | Medium | 5,169 |
https://leetcode.com/problems/game-of-life/discuss/2173365/python-probably-readable | class Solution:
def get_environmental_info(self,coordinates,board):
x = coordinates[0]
y = coordinates[1]
environment = []
for i in range(-1,2):
for j in range(-1,2):
if i==j and i==0:
continue
new_x = x+j
new_y = y+i
if new_x<0:
continue
if new_y <0:
continue
try:
environment.append(board[new_y][new_x])
except:
pass
return sum(environment)
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
situation = []
m = len(board)
n = len(board[0])
for y in range(m):
for x in range(n):
coordinates = x,y
situation.append(self.get_environmental_info(coordinates,board))
count = 0
for y in range(m):
for x in range(n):
neighbours = situation[count]
if board[y][x] == 0:
#dead
if neighbours == 3:
board[y][x] = 1
else:
#alive
if neighbours == 2 or neighbours == 3:
pass
elif neighbours < 2 or neighbours > 3:
board[y][x] = 0
else:
pass
count += 1 | game-of-life | python probably readable | RionelKuster | 0 | 56 | game of life | 289 | 0.668 | Medium | 5,170 |
https://leetcode.com/problems/game-of-life/discuss/1944079/Python-O(1)-space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
R, C = len(board), len(board[0])
for i in range(R):
for j in range(C):
a = 0
# next-prev = decimal
# 00 = 0
# 01 = 1
# 10 = 2
# 11 = 3
for m in range(-1, 2):
for n in range(-1, 2):
if (m, n) == (0, 0):
continue
if not (0 <= (i+m) < R):
continue
if not (0 <= j+n < C):
continue
if board[i+m][j+n] in (1, 3):
a += 1
#print(f"{i=} {j=} {a=} {board[i][j]=}")
if board[i][j] == 0:
if a == 3:
board[i][j] = 2
else:
board[i][j] = 0
else:
if 2 <= a <= 3:
board[i][j] = 3
else:
board[i][j] = 1
#print(f"{board[i][j]=}")
for i in range(R):
for j in range(C):
if board[i][j] in (2, 3):
board[i][j] = 1
elif board[i][j] in (0, 1):
board[i][j] = 0 | game-of-life | [Python] O(1) space | Priyansh1210 | 0 | 33 | game of life | 289 | 0.668 | Medium | 5,171 |
https://leetcode.com/problems/game-of-life/discuss/1941087/Python-Solution-or-Faster-Than-95.48 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows = len(board)
cols = len(board[0])
sumBoard = []
sumBoard.insert(0, [0] * (cols+2))
for i in range(rows):
sumBoard.append([0] + board[i] + [0])
sumBoard.append([0] * (cols+2))
for row in range(0, rows):
for col in range(0, cols):
i = row + 1
j = col + 1
cellSum = sumBoard[i-1][j-1] + sumBoard[i-1][j] + sumBoard[i-1][j+1] + sumBoard[i][j-1] + sumBoard[i][j+1] + sumBoard[i+1][j-1] + sumBoard[i+1][j] + sumBoard[i+1][j+1]
if board[row][col] == 0 and cellSum == 3:
board[row][col] = 1
elif board[row][col] == 1:
if cellSum < 2:
board[row][col] = 0
elif cellSum > 3:
board[row][col] = 0
else:
board[row][col] = 1 | game-of-life | Python Solution | Faster Than 95.48% | harshnavingupta | 0 | 35 | game of life | 289 | 0.668 | Medium | 5,172 |
https://leetcode.com/problems/game-of-life/discuss/1941016/Time-%3A-O(m*n)-or-Space-%3A-O(1)-or-Simple-Solution | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# 1 -> 0 = -1 ( consider while neighbour counting one's)
# 0 -> 1 = -2 (don't consider while neighbour counting one's
for row in range(len(board)):
for column in range(len(board[0])):
neighbour_count = 0
val = board[row][column]
for r,c in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
if 0 <= row+r<len(board) and 0 <= column+c < len(board[0]):
new_row, new_column = row+r,column+c
if abs(board[new_row][new_column]) == 1:
neighbour_count += 1
if neighbour_count < 2 and abs(val) == 1:
board[row][column] = -1
elif neighbour_count > 3 and abs(val) == 1:
board[row][column] = -1
elif neighbour_count == 3 and abs(val) == 0:
board[row][column] = -2
# converting all -1 to 0
# converting all -2 to 1
for row in range(len(board)):
for column in range(len(board[0])):
if board[row][column] == -1:
board[row][column] = 0
elif board[row][column] == -2:
board[row][column] = 1 | game-of-life | Time : O(m*n) | Space : O(1) | Simple Solution | Call-Me-AJ | 0 | 20 | game of life | 289 | 0.668 | Medium | 5,173 |
https://leetcode.com/problems/game-of-life/discuss/1940806/python-O(n2)-Runtime%3A-faster-than-98.88-Memory-Usage%3A-less-than-93.42 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
width = len(board[0])
height = len(board)
temp = [[0 for x in range(width)] for y in range(height)]
for i in range(height):
for j in range(width):
counter = 0
if i - 1 >= 0 and board[i - 1][j] == 1:
counter += 1
if j - 1 >= 0 and board[i][j - 1] == 1:
counter += 1
if i+1 < height and board[i + 1][j] == 1:
counter += 1
if j+1 < width and board[i][j + 1] == 1:
counter += 1
if i - 1 >= 0 and j - 1 >= 0 and board[i - 1][j - 1] == 1:
counter += 1
if i+1 < height and j+1 < width and board[i + 1][j + 1] == 1:
counter += 1
if i - 1 >= 0 and j+1 < width and board[i - 1][j + 1] == 1:
counter += 1
if i+1 < height and j - 1 >= 0 and board[i + 1][j - 1] == 1:
counter += 1
if board[i][j] == 1:
if counter == 2 or counter == 3:
temp[i][j] = 1
if board[i][j] == 0:
if counter == 3:
temp[i][j] = 1
for i in range(height):
for j in range(width):
board[i][j] = temp[i][j] | game-of-life | python O(n^2) ✅ Runtime: faster than 98.88% Memory Usage: less than 93.42% | caneryikar | 0 | 15 | game of life | 289 | 0.668 | Medium | 5,174 |
https://leetcode.com/problems/game-of-life/discuss/1940461/Python-Count-the-neighbors-and-use-the-second-decimal-point-for-storing-in-the-cell. | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
NEIGHBORING_CELLS = (
(-1, -1),
(-1, 0),
(-1, +1),
(0, -1),
(0, +1),
(+1, -1),
(+1, 0),
(+1, +1)
)
def count_neighbors(board, row, col, h, w):
count = 0
for i, j in NEIGHBORING_CELLS:
new_row, new_col = row + i, col + j
if 0 <= new_row < h and 0 <= new_col < w:
if board[new_row][new_col] % 10 == 1:
count += 1
return count
h, w = len(board), len(board[0])
# Encode the number of neighbors in the cell Integer. There are only 8 posible neighbors,
# so using the second digit is possible.
for row in range(h):
for col in range(w):
board[row][col] += 10*count_neighbors(board, row, col, h, w)
# Check the neighbors count and act accordingly:
for row in range(h):
for col in range(w):
n_neighbors = board[row][col] // 10
is_alive = board[row][col] % 10 == 1
if is_alive:
if n_neighbors < 2:
board[row][col] = 0
elif 3 < n_neighbors:
board[row][col] = 0
else:
if n_neighbors == 3:
board[row][col] = 1
board[row][col] %= 10 | game-of-life | Python, Count the neighbors and use the second decimal point for storing in the cell. | sEzio | 0 | 18 | game of life | 289 | 0.668 | Medium | 5,175 |
https://leetcode.com/problems/game-of-life/discuss/1939825/Python-Over-Complicated-stuff-LOL-or-O(1)-space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# 11 => alive in initial, alive in next
# 10 => alive in initial, dead in next
# 0 => dead in both
# 13 => dead in initial, alive in next
nexxt = lambda x: int(x in [11,13])
initial = lambda x: int(x in [11,1,10])
m, n = len(board), len(board[0])
neighbors = [[-1,-1],[-1,1],[-1,0],[1,1],[1,-1],[1,0],[0,-1],[0,1]]
def countAlive(i,j,m,n):
alive = 0
for pos in neighbors:
x,y = i+pos[0], j+pos[1]
if x < 0 or y < 0 or x >= m or y >= n: continue
alive += initial(board[x][y])
return alive
for i in range(m):
for j in range(n):
alive = countAlive(i,j,m,n)
nextPlusInitialState = 0
if board[i][j] and alive < 2: nextPlusInitialState = 10
elif board[i][j] and alive < 4: nextPlusInitialState = 11
elif board[i][j] and alive > 3: nextPlusInitialState = 10
elif not board[i][j] and alive == 3: nextPlusInitialState = 13
board[i][j] = nextPlusInitialState
for i in range(m):
for j in range(n):
board[i][j] = nexxt(board[i][j]) | game-of-life | ✅ Python Over-Complicated stuff LOL | O(1) space | dhananjay79 | 0 | 42 | game of life | 289 | 0.668 | Medium | 5,176 |
https://leetcode.com/problems/game-of-life/discuss/1939418/Clean-Python-O(1)-space-modulo-arithmetic-for-state-change | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
nrows = len(board)
ncols = len(board[0])
# helper function to count alive neighbors
def countNeighbors(row,col):
ans = 0
for dRow, dCol in product([1,0,-1], [1,0,-1]):
neighRow = row + dRow
neighCol = col + dCol
if dRow == 0 and dCol == 0:
continue
if neighRow < 0 or neighRow > nrows-1:
continue
if neighCol < 0 or neighCol > ncols-1:
continue
ans += board[neighRow][neighCol] % 2 # ... % 2 is necessary to account that we store the new state in board
return ans
# calculate new state
for row, col in product(range(nrows),range(ncols)):
n = countNeighbors(row,col)
state = board[row][col] % 2
newState = state
if state:
if n < 2 or n > 3:
newState = 0
else:
if n == 3:
newState = 1
board[row][col] += 2*newState
# clean-up board
for row, col in product(range(nrows),range(ncols)):
board[row][col] //= 2 | game-of-life | Clean Python, O(1) space, modulo arithmetic for state change | boris17 | 0 | 27 | game of life | 289 | 0.668 | Medium | 5,177 |
https://leetcode.com/problems/game-of-life/discuss/1939342/Python3-code-beating-95-in-time-use-two-new-values-to-reflect-the-change-between-0-and-1 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
Use -1 to reflect change from 0 to 1 & use -2 to reflect change from 1 to 0.
Change from 0 to 0 and 1 to 1 do not need new flag as the value keeps the same.
-1: 0 -> 1
-2: 1 -> 0
"""
# 8 directions
directions = [
[-1, -1],
[0, -1],
[1, -1],
[-1, 0],
[1, 0],
[-1, 1],
[0, 1],
[1, 1]
]
m, n = len(board), len(board[0])
def calc(i, j):
count1 = 0
for di, dj in directions:
ii = i + di
jj = j + dj
if 0 <= ii < m and 0 <= jj < n:
# cells with value -2 are currently 1 (will be 0 in the next stage)
if board[ii][jj] in [1, -2]:
count1 += 1
if board[i][j] == 0:
if count1 == 3:
# flag the change from 0 to 1
board[i][j] = -1
else:
if count1 < 2 or count1 > 3:
# flag the change from 1 to 0
board[i][j] = -2
# encoding
for i in range(m):
for j in range(n):
calc(i, j)
# decoding
for i in range(m):
for j in range(n):
if board[i][j] < 0:
# change -1 to 1 and -2 to 0 to decode
board[i][j] += 2 | game-of-life | Python3 code beating 95% in time - use two new values to reflect the change between 0 & 1 | leonine9 | 0 | 10 | game of life | 289 | 0.668 | Medium | 5,178 |
https://leetcode.com/problems/game-of-life/discuss/1938882/BRANCHLESS-SOLUTION-(no-if-statements)-Python-O(1)-Space-O(m*n)-time | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
1 becoming a 0 will be temporary a 3.
0 becoming a 1 will be temporary a 2.
This is so that we can use modulo 2 to see if a cell was originally a 0 or a 1.
"""
n_r = len(board)
n_c = len(board[0])
for r in range(n_r):
for c in range(n_c):
# get the number of alive neigbors
nb_neighbors = 0
# up
nb_neighbors += (r > 0 and board[r - 1][c] % 2)
# left
nb_neighbors += (c > 0 and board[r][c - 1] % 2)
# down
nb_neighbors += (r < n_r - 1 and board[r + 1][c] % 2)
# right
nb_neighbors += (c < n_c - 1 and board[r][c + 1] % 2)
# top right
nb_neighbors += (r > 0 and c < n_c - 1 and board[r - 1][c + 1] % 2)
# bottom left
nb_neighbors += (r < n_r - 1 and c > 0 and board[r + 1][c - 1] % 2)
# left top
nb_neighbors += (r > 0 and c > 0 and board[r - 1][c - 1] % 2)
# right bottom
nb_neighbors += (r < n_r - 1 and c < n_c - 1 and board[r + 1][c + 1] % 2)
# decide what the new state of the cell will be
stays_alive = 1 * (board[r][c] and (nb_neighbors == 3 or nb_neighbors == 2))
gets_born = 2 * (not board[r][c] and nb_neighbors == 3)
dies = 3 * (board[r][c] and (nb_neighbors < 2 or nb_neighbors > 3))
board[r][c] = stays_alive + gets_born + dies
for r in range(n_r):
for c in range(n_c):
board[r][c] = 1 * (board[r][c] == 1 or board[r][c] == 2) | game-of-life | BRANCHLESS SOLUTION (no if statements), Python, O(1) Space, O(m*n) time | stevenhgs | 0 | 34 | game of life | 289 | 0.668 | Medium | 5,179 |
https://leetcode.com/problems/game-of-life/discuss/1938377/Python3-Solution | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
directions = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1), (0,1), (1,1)]
for i in range(len(board)):
for j in range(len(board[0])):
live = 0
for x, y in directions:
if ( i + x < len(board) and i + x >= 0 ) and ( j + y < len(board[0]) and j + y >=0 ) and abs(board[i + x][j + y]) == 1:
live += 1
if board[i][j] == 1 and (live < 2 or live > 3):
board[i][j] = -1
if board[i][j] == 0 and live == 3:
board[i][j] = 2
for i in range(len(board)):
for j in range(len(board[0])):
board[i][j] = 1 if(board[i][j] > 0) else 0
return board | game-of-life | Python3 Solution | nomanaasif9 | 0 | 62 | game of life | 289 | 0.668 | Medium | 5,180 |
https://leetcode.com/problems/game-of-life/discuss/1938097/Python3-oror-two-solutions%3A-hashset-and-in-place | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows = len(board)
columns = len(board[0])
def count_live_neighbours(x, y):
neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1), (-1, -1), (1, 1), (-1, 1), (1, -1)]
return sum(0<=x+i<rows and 0<=j+y<columns and board[x+i][y+j] for i, j in neighbors)
inverts = set()
for i in range(rows):
for j in range(columns):
cnt = count_live_neighbours(i, j)
if board[i][j]:
if not(cnt == 2 or cnt == 3):
if cnt < 2 or cnt > 3:
inverts.add((i,j))
else:
if cnt == 3:
inverts.add((i,j))
# invert the bits
for x,y in inverts:
board[x][y] ^= 1 | game-of-life | Python3 || two solutions: hashset and in-place | constantine786 | 0 | 34 | game of life | 289 | 0.668 | Medium | 5,181 |
https://leetcode.com/problems/game-of-life/discuss/1938097/Python3-oror-two-solutions%3A-hashset-and-in-place | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows = len(board)
columns = len(board[0])
def count_live_neighbours(x, y):
neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1), (-1, -1), (1, 1), (-1, 1), (1, -1)]
return sum(0<=x+i<rows and 0<=j+y<columns and board[x+i][y+j]>=1 for i, j in neighbors)
for i in range(rows):
for j in range(columns):
cnt = count_live_neighbours(i, j)
if board[i][j]:
if not(cnt == 2 or cnt == 3):
if cnt < 2 or cnt > 3:
board[i][j] = 2
else:
if cnt == 3:
board[i][j] = -2
for i in range(rows):
for j in range(columns):
if board[i][j] == -2:
board[i][j] = 1
elif board[i][j] == 2:
board[i][j] = 0 | game-of-life | Python3 || two solutions: hashset and in-place | constantine786 | 0 | 34 | game of life | 289 | 0.668 | Medium | 5,182 |
https://leetcode.com/problems/game-of-life/discuss/1938065/Python-Solution | class Solution:
def get(self, i, j, x=1):
if x == -1 and i - 1 >= 0 or x == 1 and self.h - 1 > i:
if self.w - 1 > j > 0:
return sum(self.arr[i + x][j + k] for k in [-1, 0, 1])
elif self.w - 1 > j >= 0:
return self.arr[i + x][j] + self.arr[i + x][j + 1]
elif self.w - 1 >= j > 0:
return self.arr[i + x][j - 1] + self.arr[i + x][j]
return self.arr[i + x][j]
return 0
def get_about(self, i, j):
if self.w - 1 > j > 0:
return self.arr[i][j - 1] + self.arr[i][j + 1]
elif self.w - 1 > j >= 0:
return self.arr[i][j + 1]
return self.arr[i][j - 1]
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.arr = copy.deepcopy(board)
self.h = len(board)
self.w = len(board[0])
for i in range(self.h):
for j in range(self.w):
total = self.get_about(i, j) + self.get(i, j, -1) + self.get(i, j)
board[i][j] = (0, 1)[self.arr[i][j] == 0 and total == 3 or self.arr[i][j] == 1 and 4 > total > 1] | game-of-life | Python Solution | hgalytoby | 0 | 48 | game of life | 289 | 0.668 | Medium | 5,183 |
https://leetcode.com/problems/game-of-life/discuss/1938000/Python-Simple-and-Easy-Solution-oror-O(m*n)-time-complexity | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows ,cols = len(board), len(board[0])
def countNei(r, c):
nei = 0
for i in range(r-1, r+2):
for j in range(c-1, c+2):
if ((i == r and j == c) or i < 0 or j < 0 or i == rows or j == cols):
continue
if board[i][j] in [1,3]:
nei += 1
return nei
for i in range(rows):
for j in range(cols):
nei = countNei(i, j)
if board[i][j] and nei in [2,3]:
board[i][j] = 3
elif nei == 3:
board[i][j] = 2
for i in range(rows):
for j in range(cols):
if board[i][j] == 1:
board[i][j] = 0
elif board[i][j] in [2,3]:
board[i][j] = 1 | game-of-life | Python - Simple & Easy Solution || O(m*n) time complexity | dayaniravi123 | 0 | 16 | game of life | 289 | 0.668 | Medium | 5,184 |
https://leetcode.com/problems/game-of-life/discuss/1937962/My-solution-(slow-though) | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def get_neighbours(board, row, col):
neighbours = []
if col < len(board[row])-1:
neighbours.append(board[row][col+1])
if col > 0:
neighbours.append(board[row][col-1])
if row < len(board) - 1:
neighbours.append(board[row + 1][col])
if row > 0:
neighbours.append(board[row-1][col])
if row > 0 and col > 0:
neighbours.append(board[row-1][col-1])
if row < len(board)-1 and col < len(board[row])-1:
neighbours.append(board[row+1][col+1])
if row > 0 and col < len(board[row])-1:
neighbours.append(board[row-1][col+1])
if row < len(board)-1 and col > 0:
neighbours.append(board[row+1][col+-1])
return neighbours
def get_new_state(item, neighbours):
state = 0
if item == 1:
if neighbours.count(1) < 2:
state = 0
if (neighbours.count(1) == 2) or (neighbours.count(1) == 3):
state = 1
if neighbours.count(1) > 3:
state = 0
if item == 0:
if neighbours.count(1) == 3:
state = 1
return state
new_board = [[0 for i in range(len(row))] for row in board]
for row in range(len(board)):
for col in range(len(board[row])):
neighbours = get_neighbours(board, row, col)
new_board[row][col] = get_new_state(board[row][col], neighbours)
for row in range(len(board)):
for col in range(len(board[row])):
board[row][col] = new_board[row][col] | game-of-life | My solution (slow though) | SharvariGC | 0 | 9 | game of life | 289 | 0.668 | Medium | 5,185 |
https://leetcode.com/problems/game-of-life/discuss/1937943/First-timer-it-is-not-much-but-it-is-honest-work | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
board_copy = copy.deepcopy(board)
for i, row in enumerate(board_copy):
for j, value in enumerate(row):
live_neighs = self.liveNeighbourCount(board_copy, i, j, m, n)
# condition 1 or 3
if value == 1 and (live_neighs < 2 or live_neighs > 3):
value = 0
# condition 4
elif value == 0 and live_neighs == 3:
value = 1
board[i][j] = value
def liveNeighbourCount(self, board, i, j, m, n):
rows = [-1, 0, 1]
columns = [-1, 0, 1]
count = 0
for row in rows:
for column in columns:
x = i + row
y = j + column
if (-1 < x < m) and (-1 < y < n):
count += board[x][y]
return count - board[i][j] | game-of-life | First timer, it is not much but it is honest work | Maxsis | 0 | 11 | game of life | 289 | 0.668 | Medium | 5,186 |
https://leetcode.com/problems/game-of-life/discuss/1937890/Python3-Javascript%3A-An-Average-Solution-O(mn)-Time-and-Space | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
neighbors = {}
for i in range(-1, m + 1):
for j in range(-1, n + 1):
neighbors[(i, j)] = 0
for i in range(m):
for j in range(n):
neighbors[(i - 1, j)] += board[i][j]
neighbors[(i - 1, j - 1)] += board[i][j]
neighbors[(i - 1, j + 1)] += board[i][j]
neighbors[(i, j - 1)] += board[i][j]
neighbors[(i + 1, j)] += board[i][j]
neighbors[(i + 1, j - 1)] += board[i][j]
neighbors[(i + 1, j + 1)] += board[i][j]
neighbors[(i, j + 1)] += board[i][j]
for i in range(m):
for j in range(n):
if board[i][j] == 1:
if neighbors[(i, j)] < 2:
board[i][j] = 0
elif neighbors[(i, j)] > 3:
board[i][j] = 0
else:
board[i][j] = 1
if board[i][j] == 0:
board[i][j] = 1 if neighbors[(i, j)] == 3 else 0 | game-of-life | Python3, Javascript: An Average Solution, O(mn) Time and Space | bpfaust | 0 | 17 | game of life | 289 | 0.668 | Medium | 5,187 |
https://leetcode.com/problems/game-of-life/discuss/1937869/python3-order(m*n) | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
cb = [x.copy() for x in board]
dir = []
for i in [-1,0,1]:
for j in [-1,0,1]:
if not (i == 0 and j == 0):
dir.append([i, j])
def getValue(i, j):
cnt = 0
for x in dir:
r, c = i + x[0] , j + x[1]
if 0 <= r < len(cb) and 0 <= c < len(cb[0]):
cnt += cb[r][c]
#-- die, if count is < 2
if cnt < 2:
return 0
#-- die if alive, if count > 3 or keep alive
if cb[i][j] == 1:
if 2 <= cnt <= 3:
return 1
return 0
#-- alive, if count == 3
if cnt == 3:
return 1
return cb[i][j]
for i in range(len(cb)):
for j in range(len(cb[0])):
board[i][j] = getValue(i, j) | game-of-life | python3 order(m*n) | user2613C | 0 | 7 | game of life | 289 | 0.668 | Medium | 5,188 |
https://leetcode.com/problems/game-of-life/discuss/1864969/python-or-Beats-99.63-for-Time-or-Not-a-concise | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m,n = len(board),len(board[0])
def dfs(r,c):
current = board[r][c]
res = 0
rc_list = [(r-1,c-1),(r,c-1),(r+1,c-1),(r-1,c),(r+1,c),(r-1,c+1),(r,c+1),(r+1,c+1)]
for dr,dc in rc_list:
if dr in range(m) and dc in range(n):
if board[dr][dc] == 2:
res += 0
elif board[dr][dc] == 3:
res += 1
else:
res += board[dr][dc]
if current == 0:
if res == 3:
board[r][c] = 2
elif current == 1:
if res > 3 or res < 2:
board[r][c] = 3
for row in range(m):
for col in range(n):
dfs(row,col)
for row in range(m):
for col in range(n):
if board[row][col] == 2:
board[row][col] = 1
elif board[row][col] == 3:
board[row][col] = 0 | game-of-life | python | Beats 99.63% for Time | Not a concise | iamskd03 | 0 | 47 | game of life | 289 | 0.668 | Medium | 5,189 |
https://leetcode.com/problems/game-of-life/discuss/1857159/All-aproachor-M*N-greater-1-spaceor-Python3-or-Game-Of-life | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows = len(board)
cols = len(board[0])
neighbors = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]
copy_board = [[board[row][col] for col in range(cols)] for row in range(rows)]
for row in range(rows):
for col in range(cols):
live_neighbors = 0
for neighbor in neighbors:
r = row + neighbor[0]
c = col + neighbor[1]
if (r < rows and r >= 0) and ( c< cols and c >= 0) and copy_board[r][c] == 1:
live_neighbors += 1
if copy_board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
board[row][col] = 0
if copy_board[row][col] == 0 and live_neighbors == 3:
board[row][col] = 1 | game-of-life | All aproach| M*N --> 1 space| Python3 | Game Of life | Adee_19 | 0 | 29 | game of life | 289 | 0.668 | Medium | 5,190 |
https://leetcode.com/problems/game-of-life/discuss/1857159/All-aproachor-M*N-greater-1-spaceor-Python3-or-Game-Of-life | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows = len(board)
cols = len(board[0])
neighbors = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]
for row in range(rows):
for col in range(cols):
live_neighbors = 0
for neighbor in neighbors:
r = row + neighbor[0]
c = col + neighbor[1]
if (r < rows and r >= 0) and ( c< cols and c >= 0) and abs(board[r][c]) == 1:
live_neighbors += 1
if board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
board[row][col] = -1
if board[row][col] == 0 and live_neighbors == 3:
board[row][col] = 3
for row in range(rows):
for col in range(cols):
if board[row][col] > 0:
board[row][col] = 1
else:
board[row][col] = 0 | game-of-life | All aproach| M*N --> 1 space| Python3 | Game Of life | Adee_19 | 0 | 29 | game of life | 289 | 0.668 | Medium | 5,191 |
https://leetcode.com/problems/game-of-life/discuss/1737171/Python3-In-place-solution-with-comments | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
for i in range(len(board)):
for j in range(len(board[i])):
l_cnt = 0
# if we can look at up
if i > 0:
if abs(board[i - 1][j]) == 1:
l_cnt += 1
# if we can look at up-left
if j > 0:
if abs(board[i - 1][j - 1]) == 1:
l_cnt += 1
# if we can look at up-right
if j < len(board[0]) - 1:
if abs(board[i - 1][j + 1]) == 1:
l_cnt += 1
# if we can look at left
if j > 0:
if abs(board[i][j - 1]) == 1:
l_cnt += 1
# if we can look at right
if j < len(board[0]) - 1:
if abs(board[i][j + 1]) == 1:
l_cnt += 1
#if we can look at down
if i < len(board) - 1:
if abs(board[i + 1][j]) == 1:
l_cnt += 1
# if we can look at down-left
if j > 0:
if abs(board[i + 1][j - 1]) == 1:
l_cnt += 1
# if we can look at down-right
if j < len(board[0]) - 1:
if abs(board[i + 1][j + 1]) == 1:
l_cnt += 1
if board[i][j] == 1:
if l_cnt < 2:
board[i][j] = -1
elif l_cnt > 3:
board[i][j] = -1
#else stay a live
else:
if l_cnt == 3:
board[i][j] = 2
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == -1:
board[i][j] = 0
elif board[i][j] == 2:
board[i][j] = 1 | game-of-life | [Python3] In-place solution with comments | maosipov11 | 0 | 118 | game of life | 289 | 0.668 | Medium | 5,192 |
https://leetcode.com/problems/game-of-life/discuss/1683279/Python3-Runtime-around-50ms | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
w, h = len(board[0]), len(board)
lives = []
deads = []
for i in range(h):
for j in range(w):
neighborCount = 0
for k in range(-1,2,1):
for l in range(-1,2,1):
if (k == 0 and l == 0) or not 0 <= i+k < h or not 0 <= j+l < w:
continue
if board[i+k][j+l] == 1:
neighborCount += 1
if neighborCount == 3:
lives.append([i, j])
elif neighborCount != 2 and board[i][j] == 1:
deads.append([i, j])
for d in deads:
board[d[0]][d[1]] = 0
for l in lives:
board[l[0]][l[1]] = 1 | game-of-life | Python3 - Runtime around 50ms | elainefaith0314 | 0 | 94 | game of life | 289 | 0.668 | Medium | 5,193 |
https://leetcode.com/problems/game-of-life/discuss/1606252/Python-sol-faster-than-94-less-mem-than-70-(iter-sol) | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
changes = []
rows = len(board)
cols = len(board[0])
for i in range(rows):
for j in range(cols):
ones = 0
if i - 1 >= 0:
if board[i - 1][j] == 1:
ones += 1
if j - 1 >= 0:
if board[i - 1][j - 1] == 1:
ones += 1
if j + 1 < cols:
if board[i - 1][j + 1] == 1:
ones += 1
if i + 1 < rows:
if board[i + 1][j] == 1:
ones += 1
if j - 1 >= 0:
if board[i + 1][j - 1] == 1:
ones += 1
if j + 1 < cols :
if board[i + 1][j + 1] == 1:
ones += 1
if j - 1 >= 0:
if board[i][j - 1] == 1:
ones += 1
if j + 1 < cols:
if board[i][j + 1] == 1:
ones += 1
if board[i][j] == 1:
if ones < 2 :
changes.append([i,j])
if ones > 3:
changes.append([i,j])
else:
if ones == 3:
changes.append([i,j])
for k in changes:
if board[k[0]][k[1]] == 1:
board[k[0]][k[1]] = 0
else:
board[k[0]][k[1]] = 1 | game-of-life | Python sol faster than 94% , less mem than 70% (iter sol) | elayan | 0 | 138 | game of life | 289 | 0.668 | Medium | 5,194 |
https://leetcode.com/problems/game-of-life/discuss/1420477/Python3-Simple-readable-solution-with-comments.-No-fancy-algo-used. | class Solution:
# Check if a cell is inside the given environment
def withinBoundry(self, m: int, n: int, row: int, col: int) -> bool:
return (0 <= row < m) and (0 <= col < n)
# Find number of live neighbors in all 8 directions of the current cell
def scanNeighbors(self, board: List[List[int]], m: int, n: int, row: int, col: int) -> int:
num_neighbors = 0
# 8 direction
directions = [(row-1, col-1), (row, col-1), (row+1, col-1),
(row-1, col), (row+1, col),
(row-1, col+1), (row, col+1), (row+1, col+1)]
# From all neighbors, calc no. of alive neighbors
for dir in directions:
if self.withinBoundry(m,n,dir[0],dir[1]):
num_neighbors = num_neighbors + board[dir[0]][dir[1]]
return num_neighbors
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# Init
m = len(board)
n = len(board[0])
neighbors = [[0 for _ in range(n)] for _ in range(m)]
# Find neighbors for all cells
for row in range(m):
for col in range(n):
neighbors[row][col] = self.scanNeighbors(board, m, n, row, col)
# Simulate
for row in range(m):
for col in range(n):
if board[row][col] == 1 and neighbors[row][col] < 2: # Condition 1:
board[row][col] = 0
elif board[row][col] == 1 and (2 <= neighbors[row][col] <= 3): # Condition 2
board[row][col] = 1
elif board[row][col] == 1 and neighbors[row][col] > 3: # Condition 3
board[row][col] = 0
elif board[row][col] == 0 and neighbors[row][col] == 3: # Condition 4
board[row][col] = 1
else:
pass
return | game-of-life | [Python3] Simple readable solution with comments. No fancy algo used. | ssshukla26 | 0 | 98 | game of life | 289 | 0.668 | Medium | 5,195 |
https://leetcode.com/problems/game-of-life/discuss/1410055/Python-O(3n)-Memory-Solution | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
m, n = len(board), len(board[0])
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
current = [[0] * (n + 2), [0] * (n + 2), [0] + board[0] + [0]]
board.append([0] * n)
for i in range(m):
current[0], current[1] = current[1], current[2]
current[2] = [0] + board[i + 1] + [0]
for j in range(n):
count = 0
for d_i, d_j in dirs:
new_i, new_j = d_i + 1, d_j + j + 1
count += current[new_i][new_j]
if board[i][j] == 1:
board[i][j] = int(2 <= count <= 3)
elif count == 3:
board[i][j] = 1
board.pop() | game-of-life | Python O(3n) Memory Solution | yiseboge | 0 | 138 | game of life | 289 | 0.668 | Medium | 5,196 |
https://leetcode.com/problems/game-of-life/discuss/1347991/Python3-Modify-In-Place | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
for i in range(len(board)):
for j in range(len(board[0])):
countOfOnes = 0
for x, y in [(-1, 1), (-1, 0), (-1, -1), (0, 1), (0, -1), (1, 1), (1, 0), (1, -1)]:
nx, ny = i + x, j + y
if nx < 0 or nx >= len(board) or ny < 0 or ny >= len(board[0]):
continue
if board[nx][ny] == 1 or board[nx][ny] == 3:
countOfOnes += 1
# 3 for new 0 (1 changing to 0), 4 for new 1 (0 changing to 1)
if board[i][j] == 1:
if countOfOnes < 2 or countOfOnes > 3:
board[i][j] = 3
elif board[i][j] == 0 and countOfOnes == 3:
board[i][j] = 4
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 3:
board[i][j] = 0
elif board[i][j] == 4:
board[i][j] = 1 | game-of-life | Python3 Modify In Place | zhanz1 | 0 | 76 | game of life | 289 | 0.668 | Medium | 5,197 |
https://leetcode.com/problems/game-of-life/discuss/1306686/Python-easy-solution-77.24-faster | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
r = len(board)
c = len(board[0])
dr = [-1,+1,0,0,-1,-1,+1,+1]
dc = [0,0,-1,+1,-1,+1,+1,-1]
for i in range(r):
rr = 0
cc = 0
for j in range(c):
if board[i][j]==0:
count = 0
for k in range(8):
rr = i + dr[k]
cc = j + dc[k]
if 0<=rr<r and 0<=cc<c and (board[rr][cc]==1 or board[rr][cc]=='D'):
count+=1
if count==3:
board[i][j] = 'A'
elif board[i][j]==1:
count = 0
for k in range(8):
rr = i + dr[k]
cc = j + dc[k]
if 0<=rr<r and 0<=cc<c and (board[rr][cc]==1 or board[rr][cc]=='D'):
count+=1
if count<=1 or count>=4:
board[i][j] = 'D'
for i in range(r):
for j in range(c):
if board[i][j]=='A':
board[i][j] = 1
elif board[i][j]=='D':
board[i][j] = 0 | game-of-life | Python easy solution, 77.24% faster | Vrushali20 | 0 | 82 | game of life | 289 | 0.668 | Medium | 5,198 |
https://leetcode.com/problems/game-of-life/discuss/1235795/Python-easy-understanding-faster-than-90 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board) # get number of rows
n = len(board[0]) # get number of columns
for i in range(m):
for j in range(n):
s_lives = self.get_surround_live(board,i,j,m,n) # get surrounding lives for a given box
if board[i][j] == 1: # if current box is alive
if s_lives < 2: # if less than 2 surrounding live die, so switch to 2(instead of 0)
board[i][j] = 2
elif s_lives == 2 or s_lives == 3:
continue # if surrounding lives is 2or 3, continues to live so do nothing
else:
board[i][j] = 2 #else die as more population so switch to 2(instead of 0)
elif board[i][j] == 0: # if current box is dead
if s_lives == 3:
board[i][j] = 3 #if surrounding lives is 3, then bring to life 3(instead of 1)
for i in range(m):
for j in range(n):
if board[i][j] == 2: # change all 2 to 0 as dead
board[i][j] = 0
elif board[i][j] == 3: # change all 3 to 1 as alive
board[i][j] = 1
def get_surround_live(self, board, i, j, m, n):
lives_count = 0
for k in [i-1, i, i+1]:
for l in [j-1,j,j+1]:
if (k >= 0 and k <= m-1) and (l >= 0 and l <= n-1):
if k ==i and l == j:
continue
if board[k][l] in [1, 2]:
lives_count += 1
return lives_count | game-of-life | Python easy understanding faster than 90% | NagaVenkatesh | 0 | 198 | game of life | 289 | 0.668 | Medium | 5,199 |
Subsets and Splits