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/top-k-frequent-words/discuss/2723437/Python-Counter-or-two-lines-or-99-Time-99-Memory | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
c = sorted(Counter(words).items(), key=lambda x: (-x[1],x[0]))
return [w for w, n in c[:k]] | top-k-frequent-words | Python Counter | two lines | 99% Time 99% Memory | AgentIvan | 1 | 31 | top k frequent words | 692 | 0.569 | Medium | 11,400 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723437/Python-Counter-or-two-lines-or-99-Time-99-Memory | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
c = Counter(words)
return sorted(Counter(words), key=lambda x: (-c[x],x))[:k] | top-k-frequent-words | Python Counter | two lines | 99% Time 99% Memory | AgentIvan | 1 | 31 | top k frequent words | 692 | 0.569 | Medium | 11,401 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2722312/Simple-Python-One-Liner-Solution | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
return list(dict(sorted(Counter(words).items(), key = lambda x : (-x[1], x[0]))).keys())[:k] | top-k-frequent-words | Simple Python One-Liner Solution | g_aswin | 1 | 17 | top k frequent words | 692 | 0.569 | Medium | 11,402 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2722295/Python-3-with-no-imported-libs | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
wordsdict = {}
for word in words:
if word not in wordsdict.keys():
wordsdict[word] = 1
else:
wordsdict[word] += 1
wordsdictsort = dict(sorted(wordsdict.items(), key=lambda item: item[1], reverse=True))
lexico = {}
for key, value in wordsdictsort.items():
if value not in lexico.keys():
lexico[value] = [key]
else:
lexico[value].append(key)
lexico[value].sort()
ans = []
for value in lexico.values():
ans.extend(value)
return ans[:k] | top-k-frequent-words | Python 3 with no imported libs | vegancyberpunk | 1 | 20 | top k frequent words | 692 | 0.569 | Medium | 11,403 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2720543/Python's-simplest-and-fastest-solution-or-96-Faster | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
# Sorting the List
words = sorted(words)
# Count the number of words using Counter
c = Counter(words)
# Return the k most common words
return [word for word, _ in c.most_common(k)] | top-k-frequent-words | ✔️ Python's simplest and fastest solution | 96% Faster 🔥 | pniraj657 | 1 | 89 | top k frequent words | 692 | 0.569 | Medium | 11,404 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2720294/Python-3-Lines-Solution-oror-Counter-or-Runtime-88 | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
words = sorted(words)
counts = Counter(words)
return [word for word, _ in counts.most_common(k)] | top-k-frequent-words | ✅ 🔥 Python 3 Lines Solution || Counter | Runtime 88% | jimunna150 | 1 | 69 | top k frequent words | 692 | 0.569 | Medium | 11,405 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2041668/6-line-python-solution-use-Heap-queue | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
dictionary = collections.Counter(words)
heap = []
for key, value in dictionary.items():
heap.append((-value,key))
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for i in range(k)] | top-k-frequent-words | 6-line python solution, use Heap queue | prejudice23 | 1 | 203 | top k frequent words | 692 | 0.569 | Medium | 11,406 |
https://leetcode.com/problems/top-k-frequent-words/discuss/1951113/Python3-oror-Beats-96-oror-Dict-and-Lambda-Sorting | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq = defaultdict(int)
for s in words: freq[s] -= 1
res = []
for s, f in sorted(freq.items(), key=lambda x: (x[1], x[0])):
k -= 1
res.append(s)
if not k: return res | top-k-frequent-words | Python3 || Beats 96% || Dict and Lambda Sorting | Dewang_Patil | 1 | 144 | top k frequent words | 692 | 0.569 | Medium | 11,407 |
https://leetcode.com/problems/top-k-frequent-words/discuss/1928621/Python3-Two-line-solution-with-comments-Heap-O(nlogk) | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
# Hash Table O(N) time
Freqs = Counter(words)
# Heap O(NlogK)
# create lambda function that can sort by -freq and word order
return heapq.nsmallest(k, Freqs, key=lambda word:(-Freqs[word], word)) | top-k-frequent-words | Python3 Two-line solution with comments Heap O(nlogk) | jlu56 | 1 | 199 | top k frequent words | 692 | 0.569 | Medium | 11,408 |
https://leetcode.com/problems/top-k-frequent-words/discuss/1479308/Python3-O(nlogn)-and-O(nlogk)-solutions | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counts = collections.Counter(words)
freq_arr = [[] for i in range(counts.most_common(1)[0][1] + 1)]
for key in counts:
freq_arr[counts[key]].append(key)
res = []
idx = len(freq_arr) - 1
while k > 0:
for s in sorted(freq_arr[idx]):
res.append(s)
k -= 1
if k == 0:
break
idx -= 1
return res
class CompareWrapper:
def __init__(self, word, freq):
self.word = word
self.freq = freq
def __lt__(self, other):
if self.freq == other.freq:
return self.word > other.word
return self.freq < other.freq
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counts = collections.Counter(words)
heap = []
for key, val in counts.items():
heapq.heappush(heap, CompareWrapper(key, val))
if len(heap) > k:
heapq.heappop(heap)
res = [""] * k
for i in range(k):
res[k - i - 1] = heapq.heappop(heap).word
return res | top-k-frequent-words | [Python3] O(nlogn) and O(nlogk) solutions | maosipov11 | 1 | 203 | top k frequent words | 692 | 0.569 | Medium | 11,409 |
https://leetcode.com/problems/top-k-frequent-words/discuss/1081288/5-Line-Python-Beating-99-Memory | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
seen = {}
for i in words:
if i in seen:seen[i] += 1
else:seen[i] = 0
return sorted(seen, key = lambda x: [-seen[x],x])[:k] | top-k-frequent-words | 5-Line Python Beating 99% Memory | Venezsia1573 | 1 | 134 | top k frequent words | 692 | 0.569 | Medium | 11,410 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2841213/Python-simple-heap-solution | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counter = Counter(words)
heap = []
for i in counter:
heapq.heappush(heap, (-counter[i], i))
result = []
for i in range(k):
freq, word = heapq.heappop(heap)
result.append(word)
return result | top-k-frequent-words | Python simple heap solution | Bread0307 | 0 | 3 | top k frequent words | 692 | 0.569 | Medium | 11,411 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2840054/Bucket-Sort-Python-Easy-To-Understand | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq = collections.Counter(words)
max_fr = max(freq.values())
buckets = [[] for _ in range(max_fr)]
ans = []
for word in freq:
count = freq[word]
buckets[count-1].append(word)
for bucket in range(len(buckets)-1,-1,-1):
buckets[bucket].sort()
for word in buckets[bucket]:
if k:
ans.append(word)
k-=1
if k == 0:
return ans | top-k-frequent-words | Bucket Sort Python Easy To Understand | taabish_khan22 | 0 | 2 | top k frequent words | 692 | 0.569 | Medium | 11,412 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2840053/Bucket-Sort-Python-Easy-To-Understand | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq = collections.Counter(words)
max_fr = max(freq.values())
buckets = [[] for _ in range(max_fr)]
ans = []
for word in freq:
count = freq[word]
buckets[count-1].append(word)
for bucket in range(len(buckets)-1,-1,-1):
buckets[bucket].sort()
for word in buckets[bucket]:
if k:
ans.append(word)
k-=1
if k == 0:
return ans | top-k-frequent-words | Bucket Sort Python Easy To Understand | taabish_khan22 | 0 | 1 | top k frequent words | 692 | 0.569 | Medium | 11,413 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2830622/Top-K-Frequent-Words-or-Python-Solution | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
words.sort()
freq = Counter(words).most_common()
result = []
counter = 1
for i,val in freq:
if counter <= k:
result.append(i)
counter += 1
return result | top-k-frequent-words | Top K Frequent Words | Python Solution | nishanrahman1994 | 0 | 4 | top k frequent words | 692 | 0.569 | Medium | 11,414 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2734372/Python-Solution | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
result = []
heap = []
frequency = defaultdict(int)
for word in words:
frequency[word] += 1
for key, value in frequency.items():
heapq.heappush(heap, (-value, key))
ordered = heapq.nsmallest(k, heap)
for _, key in ordered:
result.append(key)
return result | top-k-frequent-words | Python Solution | mansoorafzal | 0 | 28 | top k frequent words | 692 | 0.569 | Medium | 11,415 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2728922/One-liner-Python.-O(Nlog(K)) | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
return [v[0] for v in nsmallest(k, Counter(words).items(), key = lambda x: (-x[1], x[0]))] | top-k-frequent-words | One-liner Python. O(Nlog(K)) | nonchalant-enthusiast | 0 | 8 | top k frequent words | 692 | 0.569 | Medium | 11,416 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2728811/Naive-approach-for-Python | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
res = dict()
for w in words:
res[w] = res.setdefault(w, 0) + 1
res = [(v, k) for k, v in res.items()]
res.sort(key = lambda x: (-x[0], x[1]))
return [v[1] for v in res[:k]] | top-k-frequent-words | Naive approach for Python | nonchalant-enthusiast | 0 | 4 | top k frequent words | 692 | 0.569 | Medium | 11,417 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2728662/Python-priority-queue-O(n-%2B-klogn) | class Solution:
from heapq import heapify, heappop
def topKFrequent(self, words: List[str], k: int) -> List[str]:
# O(n + klogn)
dic = defaultdict(int)
for word in words: dic[word]+=1
# build max heap
pq = []
for s, c in dic.items():
pq.append((-c, s))
heapify(pq)
res = []
for _ in range(k):
res.append(heappop(pq)[1])
return res | top-k-frequent-words | Python priority queue O(n + klogn) | ESoapW | 0 | 6 | top k frequent words | 692 | 0.569 | Medium | 11,418 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2726271/Simple-python-solution-using-Counter-and-OrderedDict | class Solution:
from collections import Counter, OrderedDict
def topKFrequent(self, words: List[str], k: int) -> List[str]:
words.sort()
fmap = OrderedDict(Counter(words))
result = []
for word, freq in sorted(fmap.items(), key = lambda x : x[1], reverse = True):
if k == 0:
break
result.append(word)
k -=1
return result | top-k-frequent-words | Simple python solution using Counter and OrderedDict | johnny7p | 0 | 3 | top k frequent words | 692 | 0.569 | Medium | 11,419 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723650/Simple-python3-one-liner-(105ms60) | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
return [e[1] for e in sorted(((-v,w) for w,v in Counter(words).items()))[:k]] | top-k-frequent-words | Simple python3 one-liner (105ms/60%) | leetavenger | 0 | 8 | top k frequent words | 692 | 0.569 | Medium | 11,420 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723614/python-counter-faster-than-90-and-memory-less-than-94 | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counter = Counter(sorted(words))
return [word for word, _ in counter.most_common(k)] | top-k-frequent-words | python, counter, faster than 90% and memory less than 94% | m-s-dwh-bi | 0 | 10 | top k frequent words | 692 | 0.569 | Medium | 11,421 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723552/Top-K-words | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
##First use collections
counts = collections.Counter(words)
sorted_counts = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return [word[0] for word in sorted_counts[0:k]] | top-k-frequent-words | Top K words | user4028c | 0 | 7 | top k frequent words | 692 | 0.569 | Medium | 11,422 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723351/Python-(kinda-long) | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
wordDict = dict()
for word in words:
wordDict[word] = wordDict.get(word, 0) + 1
word_tuple_list = list(wordDict.items())
reverse_list = list()
count_dict = dict()
for word, count in word_tuple_list:
try:
count_dict[count].append(word)
count_dict[count].sort()
except:
count_dict[count] = [word]
count_list = list(count_dict.items())
count_list.sort(reverse = True)
ans_list = list()
for count, Word in count_list:
for word in Word:
ans_list.append(word)
k -= 1
if k == 0:
break
if k == 0:
break
return ans_list | top-k-frequent-words | Python (kinda long) | TommyV | 0 | 4 | top k frequent words | 692 | 0.569 | Medium | 11,423 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723258/Python3-Solution | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
d = Counter(words)
arr = []
for key, val in sorted(d.items(), key = lambda x:(-x[1], x[0])):
arr.append(key)
return arr[:k] | top-k-frequent-words | Python3 Solution | mediocre-coder | 0 | 9 | top k frequent words | 692 | 0.569 | Medium | 11,424 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723227/Daily-LeetCoding-Challenge-October-Day-19-in-Python3 | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
finalDict = {}
for word in words:
if word in finalDict.keys():
finalDict[word] +=1
else:
finalDict[word] = 1
finalList = []
cnt = 0
for key,val in sorted(finalDict.items(),key=lambda x:(-x[1],x[0])):
if cnt < k:
finalList.append(key)
cnt +=1
return finalList | top-k-frequent-words | Daily LeetCoding Challenge October, Day 19 in Python3 | exploringmlnai | 0 | 4 | top k frequent words | 692 | 0.569 | Medium | 11,425 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723208/Sorted-Dictionary-Simple-or-Python | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
words.sort()
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
word_freq={key:val for key, val in sorted(word_freq.items(), key=lambda item : item[1], reverse= True)}
ans = []
j = 0
for i in word_freq.keys():
ans.append(i)
j += 1
if j == k:
break
return ans | top-k-frequent-words | Sorted Dictionary Simple | Python | Abhi_-_- | 0 | 5 | top k frequent words | 692 | 0.569 | Medium | 11,426 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723149/Simple-Python-3-O(nlogk)-Time | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq=collections.defaultdict(int)
for word in words:
freq[word]+=1
h=[]
for word in freq:
heapq.heappush(h,(-freq[word],word))
res=[]
for _ in range(k):
res.append(heapq.heappop(h)[1])
return res | top-k-frequent-words | ✅ Simple Python 3 O(nlogk) Time | VIjayAnnepu | 0 | 6 | top k frequent words | 692 | 0.569 | Medium | 11,427 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723110/Python3!-1-Line-solution. | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
return [a[1] for a in sorted([(-value, key) for key,value in collections.Counter(words).items()])[:k]] | top-k-frequent-words | 😎Python3! 1 Line solution. | aminjun | 0 | 8 | top k frequent words | 692 | 0.569 | Medium | 11,428 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723087/SImple-python-solution | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
dico = defaultdict(int)
for word in words: dico[word]+=1
res = sorted(dico, key = lambda x: (-dico[x], x))
return res[:k] | top-k-frequent-words | SImple python solution | Jaykant | 0 | 4 | top k frequent words | 692 | 0.569 | Medium | 11,429 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723059/using-python-dictionaries-basic | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
p=dict(Counter(words))
a={v:[] for v in set(p.values())}
for i in p.keys():
a[p[i]].append(i)
for i in a.keys():
a[i].sort()
p=[]
for i in sorted(a.keys(),reverse=True):
p+=a[i]
return p[:k] | top-k-frequent-words | using python dictionaries basic | adithyalingisetty | 0 | 2 | top k frequent words | 692 | 0.569 | Medium | 11,430 |
https://leetcode.com/problems/top-k-frequent-words/discuss/2723022/Python-Hash-Map-Solution-with-Documentation | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
"""
Firstly, we use a Counter to count the frequency of each word within
words, assigning the outcome as count. Then, for each key, value pair
in count, a tuple of (value, key) is created, which is subsequently
sorted using a lambda of -x[0] (the frequency, sorted high to low), and
the lexographical order within the frequency. Finally, the k largest
values of words are returned.
:param words: the words to be considered. (List[str])
:param k: the number of words to be considered. (int)
:return outcome_list: the list containing the outcome. (List[str])
"""
words = ((value, key) for key, value in Counter(words).items())
words = sorted(words, key=lambda x: (-x[0], x[1]))
return [value for key, value in words[:k]] | top-k-frequent-words | Python - Hash Map - Solution with Documentation | dworoniuk1 | 0 | 10 | top k frequent words | 692 | 0.569 | Medium | 11,431 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1095502/Python3-simple-solution | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
s = bin(n).replace('0b','')
for i in range(len(s)-1):
if s[i] == s[i+1]:
return False
return True | binary-number-with-alternating-bits | Python3 simple solution | EklavyaJoshi | 2 | 54 | binary number with alternating bits | 693 | 0.613 | Easy | 11,432 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1555338/Python-Efficient-Solution-or-Faster-than-90 | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
while n > 1:
bit1 = n & 1
n >>= 1
bit2 = n & 1
if bit1 == bit2:
return False
return True | binary-number-with-alternating-bits | Python Efficient Solution | Faster than 90% | leet_satyam | 1 | 92 | binary number with alternating bits | 693 | 0.613 | Easy | 11,433 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1309579/Python-28ms-Bit-Manipulation | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
while n > 0:
if not 3 > (n & 3) > 0:
return False
n >>= 1
return True | binary-number-with-alternating-bits | Python, 28ms, Bit-Manipulation | MihailP | 1 | 78 | binary number with alternating bits | 693 | 0.613 | Easy | 11,434 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1305279/Easy-Python-Solution(94.75) | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
if(n<2):
return True
n=bin(n)[2:]
for i in range(1,len(n)):
if(n[i]==n[i-1]):
return False
return True | binary-number-with-alternating-bits | Easy Python Solution(94.75%) | Sneh17029 | 1 | 96 | binary number with alternating bits | 693 | 0.613 | Easy | 11,435 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/974151/Easiest-Solution | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
# To check whether it has alternating bits i.e if alternating then all bits becomes 1.
n = n ^ (n >> 1)
# To check if all bits are 1
return True if (n+1) & n == 0 else False | binary-number-with-alternating-bits | Easiest Solution | Aditya380 | 1 | 62 | binary number with alternating bits | 693 | 0.613 | Easy | 11,436 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/2685427/Simple-python-code-with-explanation | class Solution:
def hasAlternatingBits(self, n):
#convert the number to binary number using bin --> keyword
n = bin(n)
#if you use bin keyword first 2 letter will be 0b
#and followed by the binary number
#so to remove first to number using indexing
#sting contains binary number from 2nd index to end
n = n[2:]
#iterate over the binary number
for i in range(len(n)-1):
#if the current bit is equal to next bit
if n[i] == n[i+1]:
#then return False
return False
#after finishing the forloop
#if we not return false
#that means the adjacent bits have different values
return True | binary-number-with-alternating-bits | Simple python code with explanation | thomanani | 0 | 13 | binary number with alternating bits | 693 | 0.613 | Easy | 11,437 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/2053428/Python-simple-solution | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
j = '$'
for i in bin(n)[2:]:
if i == j:
return False
j = i
return True | binary-number-with-alternating-bits | Python simple solution | StikS32 | 0 | 43 | binary number with alternating bits | 693 | 0.613 | Easy | 11,438 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/2027182/Python-Simplest-Solution!-Right-Shift | class Solution:
def hasAlternatingBits(self, n):
lastBit = -1
while n:
bit = n & 1
if bit == lastBit:
return False
else:
lastBit = bit
n >>= 1
return True | binary-number-with-alternating-bits | Python - Simplest Solution! Right Shift | domthedeveloper | 0 | 81 | binary number with alternating bits | 693 | 0.613 | Easy | 11,439 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1998352/Beginner-friendly-solution-in-Python3 | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
nBinary = ""
while (n > 0):
temp = n % 2
nBinary += str(temp)
n = n // 2
for i in range(1, len(nBinary)):
if nBinary[i] == nBinary[i-1]:
return False
break
return True | binary-number-with-alternating-bits | Beginner-friendly solution in Python3 | huyanguyen3695 | 0 | 23 | binary number with alternating bits | 693 | 0.613 | Easy | 11,440 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1975386/4-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90 | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n=bin(n)[2:]
for i in range(len(n)-1):
if n[i]==n[i+1]: return False
return True | binary-number-with-alternating-bits | 4-Lines Python Solution || 50% Faster || Memory less than 90% | Taha-C | 0 | 36 | binary number with alternating bits | 693 | 0.613 | Easy | 11,441 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1975386/4-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90 | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n=bin(n)[2:]
return all([n[i+1]!=n[i] for i in range(len(n)-1)]) | binary-number-with-alternating-bits | 4-Lines Python Solution || 50% Faster || Memory less than 90% | Taha-C | 0 | 36 | binary number with alternating bits | 693 | 0.613 | Easy | 11,442 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1975386/4-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90 | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n=bin(n)[2:]
return not('11' in n or '00' in n) | binary-number-with-alternating-bits | 4-Lines Python Solution || 50% Faster || Memory less than 90% | Taha-C | 0 | 36 | binary number with alternating bits | 693 | 0.613 | Easy | 11,443 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1922935/Python-easy-solution-for-beginners-faster-than-85 | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
bin_n = bin(n)[2:]
check = bin_n[0]
for i in range(1, len(bin_n)):
if check == '0' and bin_n[i] == '1':
check = '1'
continue
elif check == '1' and bin_n[i] == '0':
check = '0'
continue
else:
return False
return True | binary-number-with-alternating-bits | Python easy solution for beginners, faster than 85% | alishak1999 | 0 | 29 | binary number with alternating bits | 693 | 0.613 | Easy | 11,444 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1847767/PYTHON-BIT-MASKING-with-explanation-(28ms) | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
#Use bit mask of 0b00000001
mask = 1;
#Find the starting condition
#I use == 1 throughout. == 0 would yield the same result
start = ( ( n & mask ) == 1 );
#bitshift n
n = n >> 1;
#Use the starting value as the previous value
prev = start;
#While n is greater than zero, we can keep bit shifting it right
while n > 0:
#Check to see if our mask matches 1
check = ( ( n & mask ) == 1 );
#We see if our current check matches the previous
#If they do, then we return false
#So if we have ....00 we would be comparing False == False
#And if we have ....11 we would be comparing True == True
if check == prev:
return False;
#Otherwise, bitshift n to the right to shrink the number
n = n >> 1;
#and update the previous to our current
prev = check;
#If we make it out of the while loop
#It means we have processed all of the numbers
#And they alternated
return True; | binary-number-with-alternating-bits | PYTHON BIT MASKING with explanation (28ms) | greg_savage | 0 | 29 | binary number with alternating bits | 693 | 0.613 | Easy | 11,445 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1570636/Python-faster-than-87-O(log4(n)) | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
x = 2 ** math.floor(math.log2(n))
while x > 0:
n -= x
x //= 4
return n == 0 | binary-number-with-alternating-bits | Python faster than 87% O(log4(n)) | dereky4 | 0 | 85 | binary number with alternating bits | 693 | 0.613 | Easy | 11,446 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1461053/Simple-Python-Solution | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
b = bin(n)
if ('00' in b) or ('11' in b):
return False
return True | binary-number-with-alternating-bits | Simple Python Solution | Annushams | 0 | 57 | binary number with alternating bits | 693 | 0.613 | Easy | 11,447 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1133484/simple-python-solution | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
b = bin(n)[2:]
if '00' in b or '11' in b:
return False
else:
return True | binary-number-with-alternating-bits | simple python solution | pheobhe | 0 | 22 | binary number with alternating bits | 693 | 0.613 | Easy | 11,448 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/718082/Python-Simple-Solution-using-Bit-Operators | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
last = n & 1
n = n>>1
while n>0:
curr = n & 1
if curr == last:return False
last = curr
n = n >> 1
return True | binary-number-with-alternating-bits | [Python] Simple Solution using Bit Operators | spongeb0b | 0 | 31 | binary number with alternating bits | 693 | 0.613 | Easy | 11,449 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/407651/Python-Simple-Logic-Beats-100-solutions | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
cnt = 0
n = bin(n)[2:]
for i in range(1, len(n)):
if n[i-1]==n[i]:
return False
return True | binary-number-with-alternating-bits | Python Simple Logic Beats 100% solutions | saffi | 0 | 86 | binary number with alternating bits | 693 | 0.613 | Easy | 11,450 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/381108/Three-Solutions-in-Python-3-(beats-~99) | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n = bin(n)+'0'
for i in range(2,len(n)-1,2):
if n[i:i+2] != '10': return False
return True
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n = bin(n)
for i in range(2,len(n)-1):
if n[i] == n[i+1]: return False
return True
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
return (lambda x: all([x[i] != x[i+1] for i in range(len(x)-1)]))(bin(n))
- Junaid Mansuri
(LeetCode ID)@hotmail.com | binary-number-with-alternating-bits | Three Solutions in Python 3 (beats ~99%) | junaidmansuri | 0 | 118 | binary number with alternating bits | 693 | 0.613 | Easy | 11,451 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/366091/Python3-two-simple-solutions | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
bits = bin(n)[2:] # remove the 0b prefix
previous = bits[0]
for b in bits[1:]:
if previous == b:
return False
previous = b
return True | binary-number-with-alternating-bits | Python3 two simple solutions | llanowarelves | 0 | 48 | binary number with alternating bits | 693 | 0.613 | Easy | 11,452 |
https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/366091/Python3-two-simple-solutions | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
while True:
previous_bit = n & 1
n >>= 1
if not n:
return True
current_bit = n & 1
if previous_bit == current_bit:
return False
previous_bit = current_bit | binary-number-with-alternating-bits | Python3 two simple solutions | llanowarelves | 0 | 48 | binary number with alternating bits | 693 | 0.613 | Easy | 11,453 |
https://leetcode.com/problems/max-area-of-island/discuss/1459194/python-Simple-and-intuitive-DFS-approach-!!! | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
maxArea = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1: # run dfs only when we find a land
maxArea = max(maxArea, self.dfs(grid, i, j))
return maxArea
def dfs(self, grid, i, j):
# conditions for out of bound and when we encounter water
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:
return 0
maxArea = 1
grid[i][j] = '#' # this will act as visited set
maxArea += self.dfs(grid, i+1, j)
maxArea += self.dfs(grid, i-1, j)
maxArea += self.dfs(grid, i, j+1)
maxArea += self.dfs(grid, i, j-1)
return maxArea | max-area-of-island | [python] Simple and intuitive DFS approach !!! | nandanabhishek | 15 | 1,400 | max area of island | 695 | 0.717 | Medium | 11,454 |
https://leetcode.com/problems/max-area-of-island/discuss/2284144/Python-or-Commented-or-Two-Solutions-or-Recursion-or-O(n-*-m) | # Set + Recursion Solution
# Time: O(n * m), Iterates through grid once.
# Space: O(n * m), Uses set to keep track of visited indices.
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0]) # Gets size of grid.
visited = set() # Set containing a tuple if indices visited in grid.
def isValidIndice(row: int, column: int) -> bool: # Chekcs if a row and column are in the grid.
if row < 0 or M <= row: return False # Checks for out of bounds row.
if column < 0 or N <= column: return False # Checks for out of bounds column.
return True # Returns True if all checks are passed.
def islandArea(row, column) -> int: # Gets the area of a 4-connected island on the grid.
if (row, column) in visited: return 0 # Checks if indices have been visited already.
if not isValidIndice(row, column): return 0 # Checks if the indice is in bounds.
if grid[row][column] == 0: return 0 # Checks if cell is water.
visited.add((row, column)) # Adds cell to visited set.
up, down = islandArea(row-1, column), islandArea(row+1, column) # Recursive call to cells above and below to get area.
left, right = islandArea(row, column-1), islandArea(row, column+1) # Recursive call to cells left and right to get area.
return 1 + up + down + left + right # returns the area of the island.
area, maxArea = 0, 0
for row in range(M): # Iterates through grid rows.
for column in range(N): # Iterates through grid columns.
area = islandArea(row, column) # Gets area of island if cell is 1.
maxArea = max(maxArea, area) # Sets max island area found.
return maxArea # Returns max island area found. | max-area-of-island | Python | Commented | Two Solutions | Recursion | O(n * m) | bensmith0 | 10 | 889 | max area of island | 695 | 0.717 | Medium | 11,455 |
https://leetcode.com/problems/max-area-of-island/discuss/2284144/Python-or-Commented-or-Two-Solutions-or-Recursion-or-O(n-*-m) | # Recursion Solution
# Time: O(n * m), Iterates through grid once.
# Space: O(1), Constant space used by mutating the input list to track visited cells.
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0]) # Gets size of grid.
def isValidIndice(row: int, column: int) -> bool: # Chekcs if a row and column are in the grid.
if row < 0 or M <= row: return False # Checks for out of bounds row.
if column < 0 or N <= column: return False # Checks for out of bounds column.
return True # Returns True if all checks are passed.
def islandArea(row, column) -> int: # Gets the area of a 4-connected island on the grid.
if not isValidIndice(row, column): return 0 # Checks if the indice is in bounds.
if grid[row][column] == 0: return 0 # Checks if cell is water or has been visited.
grid[row][column] = 0 # Sets cell value to 0 to indicate its been visited.
up, down = islandArea(row-1, column), islandArea(row+1, column) # Recursive call to cells above and below to get area.
left, right = islandArea(row, column-1), islandArea(row, column+1) # Recursive call to cells left and right to get area.
return 1 + up + down + left + right # returns the area of the island.
area, maxArea = 0, 0
for row in range(M): # Iterates through grid rows.
for column in range(N): # Iterates through grid columns.
area = islandArea(row, column) # Gets area of island if cell is 1.
maxArea = max(maxArea, area) # Sets max island area found.
return maxArea # Returns max island area found. | max-area-of-island | Python | Commented | Two Solutions | Recursion | O(n * m) | bensmith0 | 10 | 889 | max area of island | 695 | 0.717 | Medium | 11,456 |
https://leetcode.com/problems/max-area-of-island/discuss/2283657/Python3-oror-recursion-one-grid-w-explanation | class Solution: # The plan is to iterate through grid, a 2D array, and if we find
# a cell in grid has value 1, then we recognize this cell as the
# first cell on an unexplored island, start an area count (res) and
# mark this first cell as visited (with a -1) in grid.
# A cell in the grid is connected to the first cell if there is a path of 1s from
# the first cell to the this cell. We explore recursively in each connected
# cell to this cell looking for values of 1. If a connected cell is in the grid
# and its value is 1, we add it to the area for this island, mark it as visited,
# and keep exploring. If we get a 0 or -1, we consider that the base case
# for the recursion. Once the island is completely explored, we deteremine
# whether the area of this island is greater than the those explored before.
# We continue the iteration thoughout the grid to determine the the max.
def maxAreaOfIsland(self, grid: list[list[int]]) -> int:
ans, R, C = 0, range(len(grid)), range(len(grid[0])) # <-- initialize some stuff for maxAreaOfIsland
def explore(r: int, c: int)->int: # <-- The recursive function
grid[r][c], res, dr, dc = -1, 0, 1, 0 # <-- dr, dc = 1,0 sets the initial direction as south
for _ in range(4):
row, col = r+dr, c+dc
if row in R and col in C and grid[row][col] == 1:
res+= explore(row, col)
dr, dc = dc, -dr # <--- this transformation rotates the direction though the
# sequence south, west, north, east
return 1+res
for r in R: # <--- the iteration through the grid
for c in C:
if grid[r][c] >= 1:
ans = max(explore(r,c), ans)
return ans
# My thanks to fouad399 for catching an error in the original post | max-area-of-island | Python3 || recursion , one grid w/ explanation | warrenruud | 6 | 503 | max area of island | 695 | 0.717 | Medium | 11,457 |
https://leetcode.com/problems/max-area-of-island/discuss/2085836/Python3-using-DFS | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
rowLength = len(grid[0])
columnLength = len(grid)
visited = {}
def dfs(i,j):
if(i<0 or i>=columnLength or j<0 or j>=rowLength or grid[i][j] == 0 or (i,j) in visited):
return 0
visited[(i,j)] = True
left = dfs(i,j-1)
right = dfs(i,j+1)
top = dfs(i-1,j)
bottom = dfs(i+1,j)
return 1 + left + right + top + bottom
result = 0
for i in range(columnLength):
for j in range(rowLength):
result = max(result,dfs(i,j))
return result | max-area-of-island | 📌 Python3 using DFS | Dark_wolf_jss | 4 | 118 | max area of island | 695 | 0.717 | Medium | 11,458 |
https://leetcode.com/problems/max-area-of-island/discuss/1759860/Python-Simple-Python-Solution-Using-DFS-With-the-Help-of-Recursion | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
Row = len(grid)
Col = len(grid[0])
result = 0
def DFS(grid,r,c):
if r >= 0 and r < Row and c >= 0 and c < Col and grid[r][c]==1:
grid[r][c]=0
return 1 + DFS(grid,r-1,c) + DFS(grid,r+1,c) + DFS(grid,r,c-1) + DFS(grid,r,c+1)
return 0
for i in range(Row):
for j in range(Col):
if grid[i][j] == 1:
result = max(result, DFS(grid,i,j))
return result | max-area-of-island | [ Python ] ✅✅ Simple Python Solution Using DFS With the Help of Recursion ✌🔥🔥 | ASHOK_KUMAR_MEGHVANSHI | 3 | 97 | max area of island | 695 | 0.717 | Medium | 11,459 |
https://leetcode.com/problems/max-area-of-island/discuss/2513255/Efficient-Python-Solution-using-DFS-or-Faster-than-91.5-Solutions | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
ROWS = len(grid)
COLS = len(grid[0])
visit = set()
def dfs(r, c):
if (r < 0 or r == ROWS or c < 0 or c == COLS or grid[r][c] == 0 or (r, c) in visit ):
return 0
grid[r][c] = 0
visit.add((r, c))
return (1 + dfs(r + 1, c) +
dfs(r - 1, c) +
dfs(r, c + 1) +
dfs(r, c - 1))
area = 0
for r in range(ROWS):
for c in range(COLS):
area = max(area, dfs(r, c))
return area | max-area-of-island | Efficient Python Solution using DFS | Faster than 91.5% Solutions | nikhitamore | 2 | 163 | max area of island | 695 | 0.717 | Medium | 11,460 |
https://leetcode.com/problems/max-area-of-island/discuss/2470488/Python-Elegant-and-Short-or-In-place-or-DFS | class Solution:
"""
Time: O(n^2)
Memory: O(n^2)
"""
WATER = 0
LAND = 1
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
return max(self.island_area(i, j, grid) for i in range(n) for j in range(m))
@classmethod
def island_area(cls, row: int, col: int, grid: List[List[int]]) -> int:
if grid[row][col] != cls.LAND:
return 0
n, m = len(grid), len(grid[0])
grid[row][col] = cls.WATER
area = 1
if row > 0:
area += cls.island_area(row - 1, col, grid)
if row < n - 1:
area += cls.island_area(row + 1, col, grid)
if col > 0:
area += cls.island_area(row, col - 1, grid)
if col < m - 1:
area += cls.island_area(row, col + 1, grid)
return area | max-area-of-island | Python Elegant & Short | In-place | DFS | Kyrylo-Ktl | 2 | 97 | max area of island | 695 | 0.717 | Medium | 11,461 |
https://leetcode.com/problems/max-area-of-island/discuss/2270322/Python3-DFS-solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
rowLength = len(grid[0])
columnLength = len(grid)
visited = {}
def dfs(i,j):
if(i<0 or i>=columnLength or j<0 or j>=rowLength or grid[i][j] == 0 or (i,j) in visited):
return 0
visited[(i,j)] = True
left = dfs(i,j-1)
right = dfs(i,j+1)
top = dfs(i-1,j)
bottom = dfs(i+1,j)
return 1 + left + right + top + bottom
result = 0
for i in range(columnLength):
for j in range(rowLength):
result = max(result,dfs(i,j))
return result | max-area-of-island | 📌 Python3 DFS solution | Dark_wolf_jss | 2 | 36 | max area of island | 695 | 0.717 | Medium | 11,462 |
https://leetcode.com/problems/max-area-of-island/discuss/1811737/easy-Python-DFS-solution-beat-88.7-with-explanation | class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# set up a list to save all areas of different islands
areas = []
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
# for every time we do BFS, add the result of area in to areas list
areas.append(self.dfs(grid, i, j))
# if there is no element in areas, that means we do not have any islands, so return 0
return max(areas) if areas else 0
def dfs(self, grid, i, j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != 1:
return 0
# mark it as -1(or anything other than 1) to show that we have traversed it
grid[i][j] = -1
# because this is already a "land"(equals to 1), the area will be 1 plus other parts
area = 1 + self.dfs(grid, i - 1, j) + self.dfs(grid, i + 1, j) + self.dfs(grid, i, j - 1) + self.dfs(grid, i, j + 1)
return area
``` | max-area-of-island | easy Python DFS solution beat 88.7%, with explanation | siyu_ | 2 | 66 | max area of island | 695 | 0.717 | Medium | 11,463 |
https://leetcode.com/problems/max-area-of-island/discuss/2530359/Clean-Python3-or-BFS-or-greater-90-Time-and-Memory | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
neighbors = [(0, -1), (-1, 0), (0, 1), (1, 0)]
def bfs(st_row, st_col):
nonlocal rows, cols, neighbors, seen
area = 1
q = deque([(st_row, st_col)])
while q:
row, col = q.pop()
for r, c in neighbors:
if 0 <= row + r < rows and 0 <= col + c < cols and grid[row + r][col + c] == 1 and (row + r, col + c) not in seen:
area += 1
seen.add((row + r, col + c))
q.appendleft((row + r, col + c))
return area
rows, cols = len(grid), len(grid[0])
island, seen = 0, set()
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1 and (row, col) not in seen:
seen.add((row, col))
island = max(island, bfs(row, col))
return island | max-area-of-island | Clean Python3 | BFS | > 90% Time & Memory | ryangrayson | 1 | 61 | max area of island | 695 | 0.717 | Medium | 11,464 |
https://leetcode.com/problems/max-area-of-island/discuss/2508415/Python-or-DFS-or-Easy-to-understand | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_area=0
n=len(grid)
m=len(grid[0])
def validMove(row, col):
if row>=0 and row<n and col>=0 and col<m and grid[row][col]==1:
return True
return False
def findArea(r, c):
if r<0 and r>=n and c<0 and c>=m:
return 0
grid[r][c]='v'
area=1
rVector=[-1, 0, 1, 0]
cVector=[0, 1, 0, -1]
for i in range(4):
row=r+rVector[i]
col=c+cVector[i]
if validMove(row, col):
area+=findArea(row, col)
return area
for i in range(n):
for j in range(m):
if grid[i][j]==1:
area=findArea(i, j)
max_area=max(area, max_area)
return max_area | max-area-of-island | Python | DFS | Easy to understand | Siddharth_singh | 1 | 49 | max area of island | 695 | 0.717 | Medium | 11,465 |
https://leetcode.com/problems/max-area-of-island/discuss/2286937/Python-or-Optimised-DFS-solution-faster-than-89.58-or-Easy-understandable-solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
area = 0
rows = len(grid)
cols = len(grid[0])
def calculate_area(grid, r, c):
if 0 <= r < rows and 0 <= c < cols and grid[r][c] == 1:
temp_area = 1
grid[r][c] = 0
for x, y in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
temp_area += calculate_area(grid, r+x, y+c)
return temp_area
return 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
area = max(area, calculate_area(grid, i, j))
return area | max-area-of-island | Python | Optimised DFS solution, faster than 89.58% | Easy understandable solution | om06 | 1 | 91 | max area of island | 695 | 0.717 | Medium | 11,466 |
https://leetcode.com/problems/max-area-of-island/discuss/2286361/GoPython-O(N)-time-or-O(N)-space-Solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
visited = set()
moves = ((-1,0),(1,0),(0,-1),(0,1))
area = 0
for i,row in enumerate(grid):
for j,item in enumerate(row):
area = max(area,dfs(grid,visited,moves,i,j))
return area
def dfs(grid,visited,moves,r,c):
if (r < 0 or r >= len(grid) or
c < 0 or c >= len(grid[0]) or
not grid[r][c] or
(r,c) in visited):
return 0
area = 1
visited.add((r,c))
for move in moves:
row = r+move[0]
col = c+move[1]
area += dfs(grid,visited,moves,row,col)
return area | max-area-of-island | Go/Python O(N) time | O(N) space Solution | vtalantsev | 1 | 58 | max area of island | 695 | 0.717 | Medium | 11,467 |
https://leetcode.com/problems/max-area-of-island/discuss/2286361/GoPython-O(N)-time-or-O(N)-space-Solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
visited = set()
moves = ((-1,0),(1,0),(0,-1),(0,1))
area = 0
for i,row in enumerate(grid):
for j,item in enumerate(row):
stack = [(i,j)]
curr_area = 0
while stack:
r,c = stack.pop()
if (r < 0 or r >= len(grid) or
c < 0 or c >= len(grid[0]) or
not grid[r][c] or
(r,c) in visited):
continue
visited.add((r,c))
curr_area+=1
for move in moves:
row = r+move[0]
col = c+move[1]
stack.append((row,col))
area = max(area,curr_area)
return area | max-area-of-island | Go/Python O(N) time | O(N) space Solution | vtalantsev | 1 | 58 | max area of island | 695 | 0.717 | Medium | 11,468 |
https://leetcode.com/problems/max-area-of-island/discuss/2283597/python3-or-explained-or-BFS-or-easy-to-uderstand | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
self.visited = [[False for _ in range(m)] for _ in range(n)]
ans = 0
for i in range(n):
for j in range(m):
# if grid[i][j] == 1 -> area
if grid[i][j] == 1 and not self.visited[i][j]:
# BFS to count the max area
v = self.bfs(grid, n, m, i, j)
# updating the area
ans = max(ans, v)
return ans
# Normal BFS
def bfs(self, grid, n, m, i, j):
queue = [(i, j)]
area_counter = 0
self.visited[i][j] = True
while queue:
x, y = queue.pop(0)
area_counter += 1
for i, j in self.adjacent_area(grid, n, m, x, y):
queue.append((i, j))
return area_counter
def adjacent_area(self, grid, n, m, x, y):
lst = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
arr=[]
for i, j in lst:
if 0<=i<n and 0<=j<m and grid[i][j]==1 and not self.visited[i][j]:
self.visited[i][j]=True
arr.append((i, j))
return arr | max-area-of-island | python3 | explained | BFS | easy to uderstand | H-R-S | 1 | 147 | max area of island | 695 | 0.717 | Medium | 11,469 |
https://leetcode.com/problems/max-area-of-island/discuss/1981795/Python3-Runtime%3A-202ms-41.26-Memory%3A-16.7mb-46.11 | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
visited = [[False for row in rows]for rows in grid]
maxIsland = 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if visited[row][col]:
continue
count = self.maxAreaHelper(grid, row, col, visited)
maxIsland = max(maxIsland, count)
return maxIsland
def maxAreaHelper(self, grid, row, col, visited):
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[row]) or visited[row][col] or grid[row][col] == 0:
return 0
visited[row][col] = True
return (1
+ self.maxAreaHelper(grid, row - 1, col, visited)
+ self.maxAreaHelper(grid, row + 1, col, visited)
+ self.maxAreaHelper(grid, row, col - 1, visited)
+ self.maxAreaHelper(grid, row, col + 1, visited)
) | max-area-of-island | Python3 Runtime: 202ms 41.26% Memory: 16.7mb 46.11% | arshergon | 1 | 28 | max area of island | 695 | 0.717 | Medium | 11,470 |
https://leetcode.com/problems/max-area-of-island/discuss/1859214/Faster-99-early-stopping-python-solution-(Space-56) | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
max_island_size = 0
def follow_island(x, y):
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
grid[x][y] = 0
return 1 + follow_island(x-1, y) + follow_island(x+1, y) + follow_island(x, y-1) + follow_island(x, y+1)
else:
return 0
def solve(l, r, o, u):
if l > r or o > u:
return
nonlocal max_island_size
if (r-l+1)*(u-o+1) <= max_island_size:
return
if r - l > u - o:
mid = l + (r-l)//2
for i in range(o, u+1):
max_island_size = max(max_island_size, follow_island(i, mid))
solve(mid + 1, r, o, u)
solve(l, mid - 1, o, u)
else:
mid = o + (u-o)//2
for i in range(l, r+1):
max_island_size = max(max_island_size, follow_island(mid, i))
solve(l, r, mid + 1, u)
solve(l, r, o, mid - 1)
solve(0, n-1, 0, m-1)
return max_island_size | max-area-of-island | Faster 99% early stopping python solution (Space 56%) | Nitschi | 1 | 80 | max area of island | 695 | 0.717 | Medium | 11,471 |
https://leetcode.com/problems/max-area-of-island/discuss/1802236/python-dfs-easy-to-understand-with-explanation | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
a = []
r = len(grid)
c = len(grid[0])
res = []
ans = []
def dfs(x,y):
grid[x][y] = 0 #make it unvalid for use again
a.append((x,y))
dx = [-1, 0, 1, 0] #all possible x moves
dy = [0, 1, 0, -1] #all possible y moves without interfering with x
for i in range(4): #only 4 moves
x2 = x+dx[i] #makes new coordinates for x
y2 = y+dy[i] #makes new coordinates for y
if x2 >= 0 and y2 >= 0 and x2 < r and y2 < c and grid[x2][y2] == 1: #see if a island is near by and not out of bound
dfs(x2, y2) #do the process again
for x in range(r):
for y in range(c):
if grid[x][y] == 1: #find a point with 1
dfs(x,y)
res.append(len(a)) # append the anwser
if len(res) == 0:
return 0
else:
ans.append(res[0])
for i in range(len(res)-1):
ans.append(res[i+1]-res[i]) #make it into the format we want
ans.sort() #sorts it so the max is at the end
return ans[-1] | max-area-of-island | python dfs easy to understand with explanation | ggeeoorrggee | 1 | 99 | max area of island | 695 | 0.717 | Medium | 11,472 |
https://leetcode.com/problems/max-area-of-island/discuss/1793393/BFS-python | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
visited = set()
def bfs(i,j,grid,visited):
count = 1
visited.add((i,j))
q = deque()
q.append((i,j))
while q:
currr, currc = q.popleft()
for item in [(0,1),(1,0),(-1,0),(0,-1)]:
r, c = item
if -1< currr+r < len(grid) and -1 < currc+c < len(grid[0]) and grid[currr+r][currc+c] == 1 and (currr+r, currc+c) not in visited:
count += 1
visited.add((currr+r, currc+c))
q.append((currr+r, currc+c))
return count
mx = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1 and (i,j) not in visited:
mx = max(mx, bfs(i,j,grid,visited))
return mx | max-area-of-island | BFS python | fengqilong | 1 | 51 | max area of island | 695 | 0.717 | Medium | 11,473 |
https://leetcode.com/problems/max-area-of-island/discuss/1616497/python-solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
max_area = 0
visited = [[False for _ in range(col)] for _ in range(row)]
def dfs(r, c):
if 0 > r or r >= row or 0 > c or c >= col or grid[r][c] == 0 or visited[r][c]:
return 0
visited[r][c] = True
return (1 + dfs(r + 1, c) +
dfs(r - 1, c) +
dfs(r, c + 1) +
dfs(r, c - 1))
for i in range(row):
for j in range(col):
max_area = max(max_area, dfs(i, j))
return max_area | max-area-of-island | python solution | fatemebesharat766 | 1 | 119 | max area of island | 695 | 0.717 | Medium | 11,474 |
https://leetcode.com/problems/max-area-of-island/discuss/1460568/WEEB-DOES-PYTHON-BFS | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
queue, max_area = deque([]), 0
for x in range(row):
for y in range(col):
if grid[x][y] == 1:
queue.append((x,y))
max_area = max(max_area, self.bfs(grid, queue, row, col))
return max_area
def bfs(self, grid, queue, row, col):
area = 0
while queue:
x, y = queue.popleft()
if grid[x][y] == "X": continue
grid[x][y] = "X"
area+=1
for nx, ny in [[x+1,y], [x-1,y], [x,y+1], [x,y-1]]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny] == 1:
queue.append((nx,ny))
return area | max-area-of-island | WEEB DOES PYTHON BFS | Skywalker5423 | 1 | 136 | max area of island | 695 | 0.717 | Medium | 11,475 |
https://leetcode.com/problems/max-area-of-island/discuss/1451258/Python3-DFS-solution-or-faster-than-99.5 | class Solution:
def dfs(self, r,c,grids):
# if out of boundary or current position is equal to zero
if r < 0 or c < 0 or r >= len(grids) or c >= len(grids[0]) or grids[r][c] == 0:
return 0
grids[r][c] = 0 # Sink the island if it has been traversed (if current position is 1, mark it as 0)
return 1 + self.dfs(r+1,c,grids) + self.dfs(r-1,c,grids) + self.dfs(r,c+1,grids) + self.dfs(r,c-1,grids)
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
area = 0 # maximum area
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
curr_area = self.dfs(i, j, grid) # current area
area = max(curr_area, area)
return area | max-area-of-island | Python3 DFS solution | faster than 99.5% | Janetcxy | 1 | 71 | max area of island | 695 | 0.717 | Medium | 11,476 |
https://leetcode.com/problems/max-area-of-island/discuss/1296462/Python3-oror-dfs-oror-15-lines-of-code-oror-Simple-And-Self-Explanatory | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
def dfs(i,j):
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j]==0:
return 0
grid[i][j]=0
a=1+(dfs(i+1,j)+dfs(i,j+1)+dfs(i-1,j)+dfs(i,j-1))
return a
ans=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1:
ans=max(ans,dfs(i,j))
return ans | max-area-of-island | Python3 || dfs || 15 lines of code || Simple And Self Explanatory | bug_buster | 1 | 126 | max area of island | 695 | 0.717 | Medium | 11,477 |
https://leetcode.com/problems/max-area-of-island/discuss/897955/Python3-dfs | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0]) # dimension
def dfs(i, j):
"""Depth-first traverse the grid."""
if grid[i][j] == 1:
grid[i][j] = 0 # mark visited
return 1 + sum(dfs(ii, jj) for ii, jj in ((i-1, j), (i, j-1), (i, j+1), (i+1, j)) if 0 <= ii < m and 0 <= jj < n)
return 0
return max(dfs(i, j) for i in range(m) for j in range(n)) | max-area-of-island | [Python3] dfs | ye15 | 1 | 104 | max area of island | 695 | 0.717 | Medium | 11,478 |
https://leetcode.com/problems/max-area-of-island/discuss/897955/Python3-dfs | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0]) # dimensions
def fn(i, j):
"""Return island area."""
ans = 1
grid[i][j] = 0 # mark as visited
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj]: ans += fn(ii, jj)
return ans
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j]: ans = max(ans, fn(i, j))
return ans | max-area-of-island | [Python3] dfs | ye15 | 1 | 104 | max area of island | 695 | 0.717 | Medium | 11,479 |
https://leetcode.com/problems/max-area-of-island/discuss/897955/Python3-dfs | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for r in range(m):
for c in range(n):
if grid[r][c]:
val = 1
grid[r][c] = 0
stack = [(r, c)]
while stack:
i, j = stack.pop()
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj]:
val += 1
grid[ii][jj] = 0
stack.append((ii, jj))
ans = max(ans, val)
return ans | max-area-of-island | [Python3] dfs | ye15 | 1 | 104 | max area of island | 695 | 0.717 | Medium | 11,480 |
https://leetcode.com/problems/max-area-of-island/discuss/750599/Python-DFS-Readable-Faster-than-92 | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
area_of_all = []
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
area_of_all.append(self.dfs(grid, i, j, 0))
return max(area_of_all) if area_of_all else 0 # 0 if there's no island
def dfs(self, grid, i, j,res):
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] == 0:
return 0
grid[i][j] = 0
return (1+ self.dfs(grid, i+1, j, res)+\
self.dfs(grid, i-1, j, res)+\
self.dfs(grid, i, j+1, res) +\
self.dfs(grid, i, j-1, res)) | max-area-of-island | [Python] DFS Readable Faster than 92% | Prodyte | 1 | 80 | max area of island | 695 | 0.717 | Medium | 11,481 |
https://leetcode.com/problems/max-area-of-island/discuss/717057/Python-DFS-O(M*N) | class Solution:
# Time: O(m*n)
# Space: O(m*n)
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
res = max(res, self.dfs(i, j, grid))
return res
def dfs(self, i, j, grid):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or not grid[i][j]:
return 0
# Mark visited
grid[i][j] = 0
u = self.dfs(i + 1, j, grid)
d = self.dfs(i - 1, j, grid)
r = self.dfs(i, j + 1, grid)
l = self.dfs(i, j - 1, grid)
return u + d + r + l + 1 | max-area-of-island | Python DFS O(M*N) | whissely | 1 | 180 | max area of island | 695 | 0.717 | Medium | 11,482 |
https://leetcode.com/problems/max-area-of-island/discuss/395168/Solution-in-Python-3-(BFS-and-DFS)-(beats-~-90-and-82) | class Solution:
def maxAreaOfIsland(self, G: List[List[int]]) -> int:
M, N, m = len(G), len(G[0]), 0
def area(x,y):
p, t, a, G[x][y] = [[x,y]], [], 1, 0
while p:
for i,j in p:
for k,l in [[i-1,j],[i,j+1],[i+1,j],[i,j-1]]:
if k in [-1,M] or l in [-1,N] or G[k][l] == 0: continue
a, G[k][l], _ = a + 1, 0, t.append([k,l])
p, t = t, []
return a
for i,j in itertools.product(range(M),range(N)):
if G[i][j]: m = max(m,area(i,j))
return m | max-area-of-island | Solution in Python 3 (BFS and DFS) (beats ~ 90% and 82%) | junaidmansuri | 1 | 1,400 | max area of island | 695 | 0.717 | Medium | 11,483 |
https://leetcode.com/problems/max-area-of-island/discuss/395168/Solution-in-Python-3-(BFS-and-DFS)-(beats-~-90-and-82) | class Solution:
def maxAreaOfIsland(self, G: List[List[int]]) -> int:
M, N, m = len(G), len(G[0]), 0
def dfs_area(x,y):
if (x,y) in V: return
G[x][y], _ = 0, V.add((x,y))
for i,j in [[x-1,y],[x,y+1],[x+1,y],[x,y-1]]:
if not (i in [-1,M] or j in [-1,N] or G[i][j] == 0): dfs_area(i,j)
for i,j in itertools.product(range(M),range(N)):
if G[i][j]: V = set(); dfs_area(i,j); m = max(m,len(V))
return m
- Junaid Mansuri
(LeetCode ID)@hotmail.com | max-area-of-island | Solution in Python 3 (BFS and DFS) (beats ~ 90% and 82%) | junaidmansuri | 1 | 1,400 | max area of island | 695 | 0.717 | Medium | 11,484 |
https://leetcode.com/problems/max-area-of-island/discuss/305750/Python3-DFS-solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid or len(grid) == 0:
return 0
rows = len(grid)
cols = len(grid[0])
greed = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 0:
continue
greed = max(greed, dfs(grid, r, c))
return greed
def dfs(grid, r, c):
rows = len(grid)-1
cols = len(grid[0])-1
if r > rows or r < 0 or c > cols or c < 0 or grid[r][c] == 0:
return 0
grid[r][c] = 0
return 1 + dfs(grid, r+1, c) + dfs(grid, r-1, c) + dfs(grid, r, c+1) + dfs(grid, r, c-1) | max-area-of-island | Python3 DFS solution | nzelei | 1 | 142 | max area of island | 695 | 0.717 | Medium | 11,485 |
https://leetcode.com/problems/max-area-of-island/discuss/2838747/Python-DFS-Solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
DIR = [0, 1, 0, -1, 0]
def dfs(r, c):
if r < 0 or r == m or c < 0 or c == n or grid[r][c] == 0:
return 0
ans = 1
grid[r][c] = 0 # Mark this square as visited
for i in range(4):
ans += dfs(r + DIR[i], c + DIR[i + 1])
return ans
ans = 0
for r in range(m):
for c in range(n):
ans = max(ans, dfs(r, c))
return ans | max-area-of-island | Python DFS Solution | taoxinyyyun | 0 | 1 | max area of island | 695 | 0.717 | Medium | 11,486 |
https://leetcode.com/problems/max-area-of-island/discuss/2837475/dfs-in-python | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
res = 0
def dfs(row, col):
if 0<=row<m and 0<=col<n and grid[row][col] == 1:
grid[row][col] = 0
return dfs(row+1,col)+dfs(row-1,col)+dfs(row,col+1)+dfs(row,col-1)+1
else:
return 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
res = max(res,dfs(i, j))
return res | max-area-of-island | dfs in python | ychhhen | 0 | 1 | max area of island | 695 | 0.717 | Medium | 11,487 |
https://leetcode.com/problems/max-area-of-island/discuss/2822139/Python3-detailed-DFS-solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_area = [0]
def dfs(i, j):
def count_area(i, j) -> int:
# ensure in bounds and is land
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]): return 0
if grid[i][j] != 1: return 0
# remove piece of island
grid[i][j] = 0
area = 1
# visit rest of island
area += count_area(i+1, j)
area += count_area(i-1, j)
area += count_area(i, j+1)
area += count_area(i, j-1)
return area
# ensure in bounds and hasn't been visited
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]): return
if grid[i][j] == -1: return
# found water
if grid[i][j] == 0: grid[i][j] = -1
# count area of island
if grid[i][j] == 1: max_area[0] = max(max_area[0], count_area(i, j))
# visit rest of grid
dfs(i+1, j)
dfs(i-1, j)
dfs(i, j+1)
dfs(i, j-1)
dfs(0, 0)
return max_area[0] | max-area-of-island | Python3 - detailed DFS solution | rschevenin | 0 | 1 | max area of island | 695 | 0.717 | Medium | 11,488 |
https://leetcode.com/problems/max-area-of-island/discuss/2775203/Python-DFS-Solution-Faster-than-100.00 | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
maxArea = 0
area = [0]
def dfs(r, c, area):
grid[r][c] = 0
area[0] += 1
if r - 1 >= 0 and grid[r - 1][c] == 1: dfs(r - 1, c, area)
if r + 1 < rows and grid[r + 1][c] == 1: dfs(r + 1, c, area)
if c - 1 >= 0 and grid[r][c - 1] == 1: dfs(r, c - 1, area)
if c + 1 < cols and grid[r][c + 1] == 1: dfs(r, c + 1, area)
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
dfs(r, c, area)
maxArea = max(maxArea, area[0])
area[0] = 0
return maxArea | max-area-of-island | Python DFS Solution, Faster than 100.00% | skromez | 0 | 7 | max area of island | 695 | 0.717 | Medium | 11,489 |
https://leetcode.com/problems/max-area-of-island/discuss/2770105/Easy-Python-Solution-or-Matrix-or-Flood-Fill | class Solution(object):
def maxAreaOfIsland(self, grid):
def solve(r, c):
if r not in range(len(grid)):
return 0
if c not in range(len(grid[0])):
return 0
if grid[r][c] == 0:
return 0
if grid[r][c] == 2:
return 0
grid[r][c] = 2
return (1 + solve(r+1, c)+solve(r-1, c)+solve(r, c+1)+solve(r, c-1))
ans = set()
for r in range(len(grid)):
for c in range(len(grid[0])):
ans.add(solve(r, c))
return max(ans) | max-area-of-island | Easy Python Solution | Matrix | Flood Fill | atharva77 | 0 | 1 | max area of island | 695 | 0.717 | Medium | 11,490 |
https://leetcode.com/problems/max-area-of-island/discuss/2735086/Python-%2B-DFS-%2B-nonlocal-parameter | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
res = 0
island_size = 0
def dfs(grid, i, j, m, n):
nonlocal island_size
dirs = [[-1,0], [1,0], [0,1], [0,-1]]
if grid[i][j] == 1:
grid[i][j] = 2
island_size += 1
for dir1 in dirs:
if i+dir1[0]>=0 and i+dir1[0]<m and j+dir1[1]>=0 and j+dir1[1]<n:
if grid[i+dir1[0]][j+dir1[1]]== 1:
dfs(grid, i+dir1[0], j+dir1[1], m, n)
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
island_size = 0
dfs(grid, i, j, m, n)
res = max(res, island_size)
return res | max-area-of-island | Python + DFS + nonlocal parameter | Arana | 0 | 5 | max area of island | 695 | 0.717 | Medium | 11,491 |
https://leetcode.com/problems/max-area-of-island/discuss/2706684/Depth-First-Search-Python-Solution | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
maxArea = 0
for col in range(cols):
for row in range(rows):
area = 0
if grid[row][col]==1:
CalcArea = self.dfs(row,col,area,grid,rows,cols)
maxArea = max(maxArea,CalcArea)
return maxArea
def dfs(self,r,c,area,grid,rows,cols):
if grid[r][c]==1:
area+=1
grid[r][c]=0
if r>0:
area = self.dfs(r-1,c,area,grid,rows,cols)
if r+1<rows:
area = self.dfs(r+1,c,area,grid,rows,cols)
if c>0:
area = self.dfs(r,c-1,area,grid,rows,cols)
if c+1<cols:
area = self.dfs(r,c+1,area,grid,rows,cols)
return area | max-area-of-island | Depth First Search - Python Solution | ManitejaPadigela | 0 | 2 | max area of island | 695 | 0.717 | Medium | 11,492 |
https://leetcode.com/problems/max-area-of-island/discuss/2577012/Python-runtime-O(rc)-memory-O(1)-(98.87) | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_area = 0
row_len = len(grid)
col_len = len(grid[0])
for r in range(row_len):
for c in range(col_len):
if grid[r][c] == 1:
grid[r][c] = 0
cur_area = self.dfs(grid, r, c)
if max_area < cur_area:
max_area = cur_area
return max_area
def dfs(self, grid, r, c):
cur_area = 0
for x,y in [(0,1),(0,-1),(1,0),(-1,0)]:
if -1<r+x<len(grid) and -1<c+y<len(grid[0]) and grid[r+x][c+y] == 1:
grid[r+x][c+y] = 0
cur_area += self.dfs(grid, r+x, c+y)
return cur_area+1 | max-area-of-island | Python, runtime O(rc), memory O(1) (98.87%) | tsai00150 | 0 | 38 | max area of island | 695 | 0.717 | Medium | 11,493 |
https://leetcode.com/problems/max-area-of-island/discuss/2568612/DFS-solution-space-O(1) | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
# before start, we need to make sure if we can edit the graph, turn 1 to 0
# in here, I assume we can, we are using a dfs algorithm
# comparing current island size and max_area size
def dfs(r, c):
nonlocal curr_area
grid[r][c] = 0 # key element here is to turn a land into an ocean, which then will not be counted
for direction in ((-1,0),(1,0),(0,-1),(0,1)):
neighborR = r + direction[0]
neighborC = c + direction[1]
if 0 <= neighborR < maxR and 0 <= neighborC < maxC and grid[neighborR][neighborC] == 1:
curr_area += 1
dfs(neighborR, neighborC)
max_area = 0
if not grid:
return 0
maxR, maxC = len(grid), len(grid[0])
for r in range(maxR):
for c in range(maxC):
if grid[r][c] == 1:
curr_area = 1
dfs(r, c) # row, col, 1 as area
max_area = max(max_area, curr_area)
return max_area | max-area-of-island | DFS solution space O(1) | RayML | 0 | 36 | max area of island | 695 | 0.717 | Medium | 11,494 |
https://leetcode.com/problems/max-area-of-island/discuss/2458343/Python-iterative-dfs-oror-81 | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_area = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
a = self.dfs(i,j,grid)
max_area = max(max_area,a)
return max_area
def dfs(self,i,j,grid):
cur_len = 1
stack = [(i,j)]
grid[i][j] = 0
while stack:
x,y = stack.pop()
for direction in [(1,0),(0,1),(-1,0),(0,-1)]:
new_x, new_y = x + direction[0], y + direction[1]
if new_x >= 0 and new_x < len(grid) and new_y >= 0 and new_y < len(grid[0]) and grid[new_x][new_y] == 1:
cur_len += 1
grid[new_x][new_y] = 0
stack.append((new_x,new_y))
return cur_len | max-area-of-island | Python iterative dfs || 81 | aruj900 | 0 | 23 | max area of island | 695 | 0.717 | Medium | 11,495 |
https://leetcode.com/problems/max-area-of-island/discuss/2429030/Max-Area-of-Island-oror-Python3-oror-DFS | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
ans = 0
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
for i in range(0, len(grid)):
for j in range(0, len(grid[0])):
if(grid[i][j] == 1):
count = self.dfs(i, j, grid, dirs)
ans = max(ans, count)
return ans
def dfs(self, i, j, grid, dirs):
grid[i][j] = -1
count = 1
for dx, dy in dirs:
x = i + dx
y = j + dy
if(x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]) or grid[x][y] != 1):
continue
count += self.dfs(x, y, grid, dirs)
return count | max-area-of-island | Max Area of Island || Python3 || DFS | vanshika_2507 | 0 | 20 | max area of island | 695 | 0.717 | Medium | 11,496 |
https://leetcode.com/problems/max-area-of-island/discuss/2408752/Python3-Max-Area-of-Island-w-Explanation-92-Runtime | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_size = 0
#Helper - Given a pos (i,j) on the grid, this function will recursively search around it for other land
# - It marks all land it has seen by changing it from 1 to 2, preventing it being counted again
# - This also prevents the entire island from being detected again later
# - It keeps track of the size of the island it has been mapping with 'size'
def size_island(i, j, size):
if grid[i][j] == 1:
grid[i][j] = 2
size += 1
if i > 0:
size = max(size, size_island(i-1, j, size))
if i < len(grid) - 1:
size = max(size, size_island(i+1, j, size))
if j > 0:
size = max(size, size_island(i, j-1, size))
if j < len(grid[0]) - 1:
size = max(size, size_island(i, j+1, size))
return size
# Loop through the grid. When an island is found, use 'size_island' to get it's size and mark it with 2s
# to prevent rediscovery. If the size is higher than the highest seen so far, update the running maximum
for m in range(len(grid)):
for n in range(len(grid[0])):
if grid[m][n] == 1:
current_size = size_island(m, n, 0)
if current_size > max_size: max_size = current_size
return max_size | max-area-of-island | [Python3] Max Area of Island - w Explanation - 92% Runtime | connorthecrowe | 0 | 58 | max area of island | 695 | 0.717 | Medium | 11,497 |
https://leetcode.com/problems/max-area-of-island/discuss/2408730/C%2B%2BPython-best-optimal-solution-with-Good-results | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
maxArea = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
# run dfs only when we find a land
maxArea = max(maxArea, self.dfs(grid, i, j))
return maxArea
def dfs(self, grid, i, j):
# conditions for out of bound and when we encounter water
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:
return 0
maxArea = 1
grid[i][j] = '#'
# this will act as visited set
maxArea += self.dfs(grid, i+1, j)
maxArea += self.dfs(grid, i-1, j)
maxArea += self.dfs(grid, i, j+1)
maxArea += self.dfs(grid, i, j-1)
return maxArea | max-area-of-island | C++/Python best optimal solution with Good results | arpit3043 | 0 | 28 | max area of island | 695 | 0.717 | Medium | 11,498 |
https://leetcode.com/problems/max-area-of-island/discuss/2352862/Python3-or-Solved-using-BFS-%2B-Queue-%2B-HashSet | class Solution:
#Time-Complexity: O(m*n), in worst case, bfs while loop will run through each and every entry of grid if entire grid is land!
#Space-Complexity: O(m*n + m*n) -> O(m*n)
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
#dimension of the grid input: m * n
rows, cols = len(grid), len(grid[0])
#we can use tuple of row and column coordinates since the positions are fixed values!
visited = set()
#answer will be initialized to 0 and will be returned after nested for loop on line 33!
ans = 0
#define breath first search traversal helper function!
#this bfs will search for all adjacent lands from the starting land point or cell!
#i am going to structure my bfs so that in the end, it will return the area of the
#overall island that starts from cell (r,c)!
def bfs(r, c, grid):
nonlocal visited
#initialize empty queue!
q = collections.deque()
#we need to mark current cell we are about to bfs from as visited!
visited.add((r, c))
q.append([r, c])
area = 0
#as long as queue is not empty, we will continue doing bfs!
#for each element we pop from queue, increment the overall area of island by 1!
four_directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
while q:
#we first need to dequeue to process current position!
#cr= current row, cc = current column, rd = row dimension, cd = column dimensoin!
cr, cc = q.popleft()
area += 1
#process current element's contribution of area if we included in the island!
#check each of the four neighboring positions: in bounds, land cell, not visited!
for direction in four_directions:
row_change, col_change = direction
if(cr + row_change in range(rows) and
cc + col_change in range(cols) and
grid[cr+row_change][cc+col_change] == 1 and
(cr+row_change, cc+col_change) not in visited):
q.append([cr+row_change, cc+col_change])
visited.add((cr+row_change, cc+col_change))
else:
continue
#once we break out of this while loop, we processed all contiguous land cells!
#simply, return area of island!
return area
#go one cell at a time: first check it's a land cell, then check that it's not already
#previously visited by previous breath first search traversal iterations!
for i in range(rows):
for j in range(cols):
if(grid[i][j] == 1 and (i, j) not in visited):
ans = max(ans, bfs(i, j, grid))
return ans | max-area-of-island | Python3 | Solved using BFS + Queue + HashSet | JOON1234 | 0 | 27 | max area of island | 695 | 0.717 | Medium | 11,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.