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/goat-latin/discuss/1723113/Python-67.79-Faster-98.21-Less-Memory-32ms
class Solution: def toGoatLatin(self, sentence: str) -> str: #vars output = '' goatword = '' vowles = list(['a', 'e', 'i', 'o', 'u']) #enumerate and iterate for idx, word in enumerate(sentence.split(' ')): goatword = '' if word[0:1].lower() in vowles: goatword = word+'ma' elif word[0:1].lower() not in vowles: goatword = word[1:len(word)]+word[0:1]+'ma' #add extra a based on word position goatword = goatword + 'a'*(idx+1) + ' ' #update output word output = output + goatword return(output.rstrip())
goat-latin
Python 67.79 Faster, 98.21% Less Memory, 32ms
ovidaure
-1
78
goat latin
824
0.678
Easy
13,400
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2074946/Python-3-or-Three-Methods-(Binary-Search-CounterHashmap-Math)-or-Explanation
class Solution: def numFriendRequests(self, ages: List[int]) -> int: ages.sort() # sort the `ages` ans = 0 n = len(ages) for idx, age in enumerate(ages): # for each age lb = age # lower bound ub = (age - 7) * 2 # upper bound i = bisect.bisect_left(ages, lb) # binary search lower bound j = bisect.bisect_left(ages, ub) # binary search upper bound if j - i <= 0: continue ans += j - i # count number of potential friends if lb <= age < ub: # ignore itself ans -= 1 return ans
friends-of-appropriate-ages
Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation
idontknoooo
5
416
friends of appropriate ages
825
0.464
Medium
13,401
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2074946/Python-3-or-Three-Methods-(Binary-Search-CounterHashmap-Math)-or-Explanation
class Solution(object): def numFriendRequests(self, ages): count = [0] * 121 # counter: count frequency of each age for age in ages: count[age] += 1 ans = 0 for ageA, countA in enumerate(count): # nested loop, pretty straightforward for ageB, countB in enumerate(count): if ageA * 0.5 + 7 >= ageB: continue if ageA < ageB: continue if ageA < 100 < ageB: continue ans += countA * countB if ageA == ageB: ans -= countA return ans
friends-of-appropriate-ages
Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation
idontknoooo
5
416
friends of appropriate ages
825
0.464
Medium
13,402
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2074946/Python-3-or-Three-Methods-(Binary-Search-CounterHashmap-Math)-or-Explanation
class Solution: def numFriendRequests(self, ages): count = [0] * 121 # counter: count frequency of each age for age in ages: count[age] += 1 prefix = [0] * 121 # prefix-sum: prefix sum of frequency, we will use this for range subtraction for i in range(1, 121): prefix[i] = prefix[i-1] + count[i] nums = [i for i in range(121)] # a dummy age list, which will be used in binary search ans = 0 for age, cnt in enumerate(count): if not cnt: continue lb = age # lower bound ub = (age - 7) * 2 # upper bound i = bisect.bisect_left(nums, lb) # binary search on lower bound, O(log(121)) j = bisect.bisect_left(nums, ub) # binary search on upper bound, O(log(121)) if j - i <= 0: continue total = prefix[j-1] - prefix[i-1] # range subtraction - how many ages in total can be considered as friend, including current age itself if lb <= age < ub: # considering itself, e.g. [17, 17, 17] # total -= cnt # minus itself # total = (cnt - 1) * cnt + total * cnt # make friends with other at same age `(cnt-1) * cnt`; with other at different age `total * cnt` total = cnt * (total - 1) # a cleaner presentation of above two lines ans += total return ans
friends-of-appropriate-ages
Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation
idontknoooo
5
416
friends of appropriate ages
825
0.464
Medium
13,403
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2505228/Python-Time%3A-O(max(N-120))-Space-O(1)-Prefixsum-and-Numbersort-Solution
class Solution: def numFriendRequests(self, ages: List[int]) -> int: # make a number sort sort_ages = [0]*120 # sort the ages for age in ages: sort_ages[age-1] += 1 # make prefix sum for age in range(2,121): sort_ages[age-1] = sort_ages[age-1] + sort_ages[age-2] # make a sliding window through the array result = 0 for age in ages: # these ages fall out due to the first restriction # 14//2 + 7 = 14 -> 14 <= 14 -> falls out if age <= 14: continue # calculate the index of persons we don't want dox = age//2 + 7 # this is the amount of persons younger than ourselves # but older than age//2 + 7 result += sort_ages[age-2] - sort_ages[dox-1] # this is the amount of persons the same age as us but # without ourselves as we don't send a request to ourself result += (sort_ages[age-1] - sort_ages[age-2]) - 1 return result
friends-of-appropriate-ages
[Python] - Time: O(max(N, 120)) - Space O(1) - Prefixsum and Numbersort Solution
Lucew
1
95
friends of appropriate ages
825
0.464
Medium
13,404
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/1847580/python-3-oror-two-solutions
class Solution: def numFriendRequests(self, ages: List[int]) -> int: deque = collections.deque() ages.sort(reverse=True) res = 0 curSame = 0 for i, age in enumerate(ages): if i and age >= 15 and age == ages[i-1]: curSame += 1 else: curSame = 0 while deque and age <= deque[0]: deque.popleft() res += len(deque) + curSame deque.append(0.5*age + 7) return res
friends-of-appropriate-ages
python 3 || two solutions
dereky4
1
140
friends of appropriate ages
825
0.464
Medium
13,405
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/1847580/python-3-oror-two-solutions
class Solution: def numFriendRequests(self, ages: List[int]) -> int: prefixSum = collections.Counter(ages) for i in range(2, 121): prefixSum[i] += prefixSum[i-1] res = 0 for age in ages: left = int(0.5*age + 7) if age > left: res += prefixSum[age] - prefixSum[left] - 1 return res
friends-of-appropriate-ages
python 3 || two solutions
dereky4
1
140
friends of appropriate ages
825
0.464
Medium
13,406
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/1646281/Python-Easy-Solution-or-Best-Approach
class Solution: def numFriendRequests(self, ages: List[int]) -> int: count = 0 ages = Counter(ages) for x in ages: xCount = ages[x] for y in ages: if not (y <= 0.5*x+7 or y > x): yCount = ages[y] if x != y: count += xCount*yCount else: count += xCount*(xCount-1) return count
friends-of-appropriate-ages
Python Easy Solution | Best Approach ✔
leet_satyam
1
220
friends of appropriate ages
825
0.464
Medium
13,407
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/934783/Python3-two-approaches
class Solution: def numFriendRequests(self, ages: List[int]) -> int: ages.sort() ans = lo = hi = 0 for x in ages: while hi < len(ages) and x == ages[hi]: hi += 1 while lo+1 < hi and ages[lo] <= x//2 + 7: lo += 1 ans += hi - lo - 1 return ans
friends-of-appropriate-ages
[Python3] two approaches
ye15
1
89
friends of appropriate ages
825
0.464
Medium
13,408
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/934783/Python3-two-approaches
class Solution: def numFriendRequests(self, ages: List[int]) -> int: freq = {} for x in ages: freq[x] = 1 + freq.get(x, 0) ans = 0 for x in freq: for y in freq: if 0.5*x + 7 < y <= x: ans += freq[x] * freq[y] if x == y: ans -= freq[x] return ans
friends-of-appropriate-ages
[Python3] two approaches
ye15
1
89
friends of appropriate ages
825
0.464
Medium
13,409
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/1785489/Python-Binary-Search
class Solution: def numFriendRequests(self, ages: List[int]) -> int: if len(ages) == 1: return 0 self.counts = collections.defaultdict(int) def binary_search(ages, idx): start, end = 0, idx-1 result = -1 while start <= end: mid = start + (end - start) // 2 if 0.5 * ages[idx] + 7 >= ages[mid]: start = mid+1 else: end = mid-1 result = mid if result != -1: return (idx - result) + self.counts[ages[idx]] return 0 ages.sort() requests = 0 for i in range(len(ages)): requests += binary_search(ages, i) self.counts[ages[i]] += 1 return requests
friends-of-appropriate-ages
Python - Binary Search
shubhamadep007
0
170
friends of appropriate ages
825
0.464
Medium
13,410
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/527552/Python3-simple-solution
class Solution: def numFriendRequests(self, ages: List[int]) -> int: requests = 0 ages_le = [0 for _ in range(121)] for age in ages: ages_le[age] += 1 for index in range(1, 121): ages_le[index] += ages_le[index-1] for age in ages: age_lower_bound = int(age//2) + 8 age_upper_bound = age too_young = 0 if age_lower_bound > age_upper_bound: continue if age_lower_bound < 0: continue elif age_lower_bound > 0: too_young = ages_le[age_lower_bound-1] requests += ages_le[age_upper_bound] - 1 - too_young return requests
friends-of-appropriate-ages
Python3 simple solution
tjucoder
0
98
friends of appropriate ages
825
0.464
Medium
13,411
https://leetcode.com/problems/most-profit-assigning-work/discuss/2603913/Python3-or-Solved-Using-Binary-Search-W-Sorting-O((n%2Bm)*logn)-Runtime-Solution!
class Solution: #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn) #Space-Complexity: O(n) def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: #Approach: First of all, linearly traverse each and every corresponding index #position of first two input arrays: difficulty and profit to group each #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array #by increasing difficulty of the job! Then, for each worker, perform binary #search and consistently update the max profit the current worker can work and #earn! Add this value to answer variable, which is cumulative for all workers! #this will be the result returned at the end! arr = [] for i in range(len(difficulty)): arr.append([difficulty[i], profit[i]]) #sort by difficulty! arr.sort(key = lambda x: x[0]) #then, I need to update the maximum profit up to each and every item! maximum = float(-inf) for j in range(len(arr)): maximum = max(maximum, arr[j][1]) arr[j][1] = maximum ans = 0 #iterate through each and every worker! for w in worker: bestProfit = 0 #define search space to perform binary search! L, R = 0, len(arr) - 1 #as long as search space has at least one element to consider or one job, #continue iterations of binary search! while L <= R: mid = (L + R) // 2 mid_e = arr[mid] #check if current job has difficulty that is manageable! if(mid_e[0] <= w): bestProfit = max(bestProfit, mid_e[1]) #we still need to search right and try higher difficulty #jobs that might yield higher profit! L = mid + 1 continue else: R = mid - 1 continue #once we break from while loop and end binary search, we should have #found bestProfit for current worker performing task that is manageable! ans += bestProfit return ans
most-profit-assigning-work
Python3 | Solved Using Binary Search W/ Sorting O((n+m)*logn) Runtime Solution!
JOON1234
2
134
most profit assigning work
826
0.446
Medium
13,412
https://leetcode.com/problems/most-profit-assigning-work/discuss/1409945/Simple-Python-O(nlogn%2Bmlogm)-sort%2Bgreedy-solution
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: # sort difficulty and profit together as a tuple difficulty, profit = zip(*sorted(zip(difficulty, profit))) ret = max_profit = idx = 0 for ability in sorted(worker): # if ability is smaller than the smallest difficulty # it's smaller than all difficulties if ability < difficulty[0]: continue # try to find a larger profit than the current one # this while loop will be run for at most len(difficulty) times # as idx is not reset at the end while idx < len(difficulty) and ability >= difficulty[idx]: max_profit = max(max_profit, profit[idx]) idx += 1 # increment total profit ret += max_profit return ret
most-profit-assigning-work
Simple Python O(nlogn+mlogm) sort+greedy solution
Charlesl0129
1
170
most profit assigning work
826
0.446
Medium
13,413
https://leetcode.com/problems/most-profit-assigning-work/discuss/934864/Python3-two-approaches
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: mp = {} mx = 0 for x, y in sorted(zip(difficulty, profit)): mp[x] = max(mp.get(x, 0), mx := max(mx, y)) arr = list(mp.keys()) # ordered since 3.6 ans = 0 for x in worker: i = bisect_right(arr, x) - 1 if 0 <= i < len(arr): ans += mp[arr[i]] return ans
most-profit-assigning-work
[Python3] two approaches
ye15
1
91
most profit assigning work
826
0.446
Medium
13,414
https://leetcode.com/problems/most-profit-assigning-work/discuss/934864/Python3-two-approaches
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: job = sorted(zip(difficulty, profit)) ans = i = mx = 0 for w in sorted(worker): while i < len(job) and job[i][0] <= w: mx = max(mx, job[i][1]) i += 1 ans += mx return ans
most-profit-assigning-work
[Python3] two approaches
ye15
1
91
most profit assigning work
826
0.446
Medium
13,415
https://leetcode.com/problems/most-profit-assigning-work/discuss/2835053/Binary-search-and-precalculate-max-profit
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: res = 0 for i in range(len(worker)): max_p = 0 for j in range(len(difficulty)): if difficulty[j] <= worker[i]: max_p = max(max_p, profit[j]) res += max_p return res
most-profit-assigning-work
Binary search and precalculate max profit
michaelniki
0
2
most profit assigning work
826
0.446
Medium
13,416
https://leetcode.com/problems/most-profit-assigning-work/discuss/2835053/Binary-search-and-precalculate-max-profit
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: res = 0 hashmap_profit = defaultdict(int) for i in range(len(difficulty)): hashmap_profit[difficulty[i]] = max(hashmap_profit[difficulty[i]], profit[i]) difficulty.sort() prev = 0 for i in range(len(difficulty)): hashmap_profit[difficulty[i]] = max(hashmap_profit[difficulty[i]], prev) prev = hashmap_profit[difficulty[i]] for i in range(len(worker)): if worker[i] < difficulty[0]: continue left, right = 0, len(difficulty) - 1 while left < right: mid = left + (right - left + 1) // 2 if worker[i] >= difficulty[mid]: left = mid else: right = mid - 1 res += hashmap_profit[difficulty[left]] return res
most-profit-assigning-work
Binary search and precalculate max profit
michaelniki
0
2
most profit assigning work
826
0.446
Medium
13,417
https://leetcode.com/problems/most-profit-assigning-work/discuss/2779564/Python-Binary-Search
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: jobs = list(zip(difficulty, profit)) jobs.append((0,0)) jobs.sort(key=lambda j: [j[0], j[1]]) maxPay = 0 for i, job in enumerate(jobs): jobDiff, jobProfit = job maxPay = max(maxPay, jobProfit) jobs[i] = (jobDiff, maxPay) res = 0 for workerAbility in worker: workerJobIndex = bisect.bisect_right(jobs, (workerAbility, float('inf'))) - 1 res += jobs[workerJobIndex][1] return res
most-profit-assigning-work
Python - Binary Search
GavSwe
0
8
most profit assigning work
826
0.446
Medium
13,418
https://leetcode.com/problems/most-profit-assigning-work/discuss/2761062/Pythonoror-Binary-Search-Solution-Easy-to-understand
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: """ idea: - zip difficulty and profit - sort by difficulty - iterate through each worker's ability (worker) - find the greatest difficulty using binary search , returning the high (bisect right) - max_profit += profit_of_worker[index found with binary search] """ diff_prof = [list(i) for i in zip(difficulty, profit)] diff_prof.sort(key = lambda x: x[0]) # need to make profit be the max up to i prev = diff_prof[0][1] for i in range(len(diff_prof)): diff_prof[i][1] = max(diff_prof[i][1], prev) prev = diff_prof[i][1] max_profit = 0 for ability in worker: index = self.binary_search(diff_prof, ability) if index >= 0 and index < len(diff_prof): max_profit += diff_prof[index][1] return max_profit def binary_search(self, diff_prof: List, ability: int) -> int: lo, hi = 0 , len(diff_prof) - 1 index = -1 while lo <= hi: mid = (lo + (hi - lo)//2) #mid = (hi + lo) // 2 if diff_prof[mid][0] <= ability: # save index of what a worker can do up to index = mid lo = mid + 1 else: hi = mid - 1 return index
most-profit-assigning-work
Python|| Binary Search Solution Easy to understand
avgpersonlargetoes
0
17
most profit assigning work
826
0.446
Medium
13,419
https://leetcode.com/problems/most-profit-assigning-work/discuss/2733966/Binary-search
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: """ Greedy --> pair up each worker with job of largest profit that can be done brute force -> pair up profit and difficulty arrays, sort by profit, then for each worker, find the largest doable job. Time complexity is O(n*m) optimization. Pair up difficulty with profit in array, then sort through array. Create a new array with entries being difficulty and maximum profit that can be achieved with a difficulty level >= difficulty. Then for each worker difficulty level, binary search for the largest difficulty level <= it. time complexity is O((n + m)logn) """ n, m = len(difficulty), len(worker) arr1 = [(difficulty[i], p) for i, p in enumerate(profit)] arr1.sort() arr2 = [] currProfit = -float('inf') for diff, prof in arr1: currProfit = max(currProfit, prof) arr2.append((diff, currProfit)) def binsearchKey(arr, key): low, high = 0, len(arr) - 1 temp = -1 while low <= high: mid = (low + (high - low) // 2) if arr[mid][0] <= key: temp = mid low = mid + 1 else: high = mid - 1 return temp ans = 0 for wdif in worker: key = binsearchKey(arr2, wdif) if key == -1: continue ans += arr2[key][1] return ans
most-profit-assigning-work
Binary search
berkeley_upe
0
11
most profit assigning work
826
0.446
Medium
13,420
https://leetcode.com/problems/most-profit-assigning-work/discuss/2023243/Python-O(n)-hashtable-solution
class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: d = defaultdict(int) for k,v in zip(difficulty,profit): d[k] = max(d[k],v) bucket = [0 for _ in range(max(worker)+1)] val = 0 for i in range(len(bucket)): if i in d: val = max(val,d[i]) bucket[i] = val return sum([bucket[w] for w in worker])
most-profit-assigning-work
Python O(n) hashtable solution
yusianglin11010
0
59
most profit assigning work
826
0.446
Medium
13,421
https://leetcode.com/problems/making-a-large-island/discuss/1340782/Python-Clean-DFS
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: N = len(grid) DIRECTIONS = [(-1, 0), (0, -1), (0, 1), (1, 0)] address = {} def dfs(row, column, island_id): queue = deque([(row, column, island_id)]) visited.add((row, column)) area = 1 while queue: row, column, island_id = queue.pop() address[(row, column)] = island_id for direction in DIRECTIONS: r, c = row + direction[0], column + direction[1] if r in range(N) and c in range(N) and grid[r][c] == 1 and (r, c) not in visited: queue.append((r, c, island_id)) visited.add((r, c)) area += 1 return area visited = set() area = {} island_id = 0 for row in range(N): for column in range(N): if grid[row][column] == 1 and (row, column) not in visited: area[island_id] = dfs(row, column, island_id) island_id += 1 if len(address.keys()) == N**2: return N**2 largest_area = 1 for row in range(N): for column in range(N): if grid[row][column] == 1: continue neighbours = set() large_area = 1 for direction in DIRECTIONS: r, c = row + direction[0], column + direction[1] if r in range(N) and c in range(N) and grid[r][c] == 1 and address[(r, c)] not in neighbours: neighbours.add(address[(r, c)]) large_area += area[address[(r, c)]] largest_area = max(largest_area, large_area) return largest_area
making-a-large-island
[Python] Clean DFS
soma28
4
1,000
making a large island
827
0.447
Hard
13,422
https://leetcode.com/problems/making-a-large-island/discuss/1310016/Python3-union-find
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: n = len(grid) v = 2 freq = defaultdict(int) for r in range(n): for c in range(n): if grid[r][c] == 1: stack = [(r, c)] grid[r][c] = v while stack: i, j = stack.pop() freq[v] += 1 for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < n and 0 <= jj < n and grid[ii][jj] == 1: stack.append((ii, jj)) grid[ii][jj] = v v += 1 ans = max(freq.values(), default=0) for i in range(n): for j in range(n): if grid[i][j] == 0: cand = 1 seen = set() for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < n and 0 <= jj < n and grid[ii][jj] and grid[ii][jj] not in seen: seen.add(grid[ii][jj]) cand += freq[grid[ii][jj]] ans = max(ans, cand) return ans
making-a-large-island
[Python3] union-find
ye15
4
371
making a large island
827
0.447
Hard
13,423
https://leetcode.com/problems/making-a-large-island/discuss/1377243/python-3-solution-oror-clean-oror-80-fast-oror-dfs
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: directions=[[1,0],[-1,0],[0,1],[0,-1]] def getislandsize(grid,i,j,islandID): if i <0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j]!=1: return 0 grid[i][j]=islandID left=getislandsize(grid,i,j-1,islandID) right=getislandsize(grid,i,j+1,islandID) top=getislandsize(grid,i-1,j,islandID) bottom=getislandsize(grid,i+1,j,islandID) return left+right+top+bottom+1 if grid ==0 or len(grid)== 0: return 0 else: maxx=0 islandID=2 m=len(grid) n=len(grid[0]) mapp={} for i in range(0,m): for j in range (0,n): if grid[i][j]==1: size=getislandsize(grid,i,j,islandID) maxx=max(maxx,size) mapp[islandID]=size islandID+=1 for i in range(0,m): for j in range (0,n): if grid[i][j]==0: sett=set() for direction in directions: x=direction[0]+i y=direction[1]+j if x>-1 and y>-1 and x<m and y<n and grid[x][y]!=0: sett.add(grid[x][y]) summ=1 for num in sett: value=mapp[num] summ+=value maxx=max(maxx,summ) return maxx
making-a-large-island
python 3 solution || clean || 80 % fast || dfs
minato_namikaze
2
301
making a large island
827
0.447
Hard
13,424
https://leetcode.com/problems/making-a-large-island/discuss/1376002/Python-simple-python-dfs-with-value-markers
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: gsize = [0, 0] # Size of each group, index start from 2 cur = 2 def dfs(i, j, cur): if i < 0 or j < 0 or i == len(grid) or j == len(grid[0]) or grid[i][j] != 1: return gsize[cur] += 1 grid[i][j] = cur for di, dj in [(-1, 0), (0, -1), (1, 0), (0, 1)]: dfs(i + di, j + dj, cur) todo = [] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: todo.append((i, j)) elif grid[i][j] == 1: gsize.append(0) dfs(i, j, cur) cur += 1 # Move to the next group if not todo: return gsize[2] # Edge case: no zero in grid ans = 0 for i, j in todo: visited = set() cur = 1 for di, dj in [(-1, 0), (0, -1), (1, 0), (0, 1)]: if 0 <= i + di < len(grid) and 0 <= j + dj < len(grid[0]) and \ grid[i + di][j + dj] not in visited: cur += gsize[grid[i + di][j + dj]] visited.add(grid[i + di][j + dj]) ans = max(ans, cur) return ans
making-a-large-island
[Python] simple python dfs with value markers
cyshih
2
437
making a large island
827
0.447
Hard
13,425
https://leetcode.com/problems/making-a-large-island/discuss/995707/python-dfs-solution
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: # inside dfs, update the area of the current island and # update the boundary cell to include this island as adjacent def _dfs(i, j): visited.add((i,j)) areas[id] += 1 for dx, dy in [(-1, 0), (0, 1), (1, 0), (0, -1)]: x, y = i + dx, j + dy if 0 <= x < m and 0 <= y < n: if not grid[x][y]: boundaries[(x,y)].add(id) elif (x, y) not in visited: _dfs(x, y) m, n = len(grid), len(grid[0]) visited = set() boundaries = defaultdict(set) id, areas = 0, [0] * (m * n) for i in range(m): for j in range(n): if grid[i][j] == 1 and (i, j) not in visited: _dfs(i, j) id += 1 if max(areas) == m * n: return m * n res = 0 for p in boundaries: res = max(res, sum(areas[_] for _ in boundaries[p])) return res + 1
making-a-large-island
python dfs solution
ChiCeline
1
386
making a large island
827
0.447
Hard
13,426
https://leetcode.com/problems/making-a-large-island/discuss/919336/Python3-DFS-(easy-to-understand)
class Solution: def __init__(self): self.res = 0 self.island_id = 2 def largestIsland(self, grid: List[List[int]]) -> int: ans = 0 def dfs(i, j): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == 1 and (i, j) not in seen: seen.add((i, j)) self.res += 1 grid[i][j] = self.island_id dfs(i-1, j) dfs(i, j-1) dfs(i+1, j) dfs(i, j+1) zeros = 0 d = {} seen = set() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] and (i, j) not in seen: dfs(i, j) d[self.island_id] = self.res self.island_id += 1 self.res = 0 for i in range(len(grid)): for j in range(len(grid[0])): if not grid[i][j]: zeros += 1 cur = 0 cur_seen = set() for move in [(0, -1), (0, 1), (1, 0), (-1, 0)]: next_i, next_j = i + move[0], j + move[1] if 0 <= next_i < len(grid) and 0 <= next_j < len(grid[0]) and grid[next_i][next_j] not in cur_seen and grid[next_i][next_j] > 0: cur_seen.add(grid[next_i][next_j]) cur += d[grid[next_i][next_j]] ans = max(ans, cur + 1) # if no zeros then just multiply H*W if zeros == 0: return len(grid) ** 2 return ans
making-a-large-island
Python3 DFS (easy to understand)
ermolushka2
1
205
making a large island
827
0.447
Hard
13,427
https://leetcode.com/problems/making-a-large-island/discuss/2812348/Python-check-boundaries-of-islands.
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: n = len(grid) directions = [-1, 0, 1, 0, -1] islands = list() visited = [[False for _ in range(n)] for _ in range(n)] def helper(i, j): visited[i][j] = True island = [(i, j)] q = [(i, j)] while q: x, y = q.pop(0) for k in range(4): next_x, next_y = x + directions[k], y + directions[k + 1] if 0 <= next_x < n and 0 <= next_y < n and not visited[next_x][next_y] and grid[next_x][next_y] == 1: visited[next_x][next_y] = True q.append((next_x, next_y)) island.append((next_x, next_y)) islands.append(island[:]) return for i in range(n): for j in range(n): if not visited[i][j] and grid[i][j] == 1: helper(i, j) N = len(islands) if N == 0: return 1 sizes = [len(x) for x in islands] boundaies = [set() for _ in range(N)] boundaies = dict() for i in range(N): visited = set() for x, y in islands[i]: for k in range(4): next_x, next_y = x + directions[k], y + directions[k + 1] if 0 <= next_x < n and 0 <= next_y < n and grid[next_x][next_y] == 0 and (next_x, next_y) not in visited: boundaies[(next_x, next_y)] = boundaies.get((next_x, next_y), 0) + sizes[i] visited.add((next_x, next_y)) if not boundaies: return n ** 2 ans = min(max(sizes) + 1, n ** 2) return max(ans, max(boundaies.values()) + 1)
making-a-large-island
Python, check boundaries of islands.
yiming999
0
2
making a large island
827
0.447
Hard
13,428
https://leetcode.com/problems/making-a-large-island/discuss/2480366/python-3-or-dfs-or-O(n2)O(n2)
class Solution: DIRECTIONS = (-1, 0), (1, 0), (0, -1), (0, 1) def neighbours(self, i, j): return ((i + di, j + dj) for di, dj in Solution.DIRECTIONS if 0 <= i + di < self.n and 0 <= j + dj < self.n) def largestIsland(self, grid: List[List[int]]) -> int: self.n = len(grid) area = collections.Counter() def dfs(i, j, groupNumber): if grid[i][j] != 1: return grid[i][j] = groupNumber area[groupNumber] += 1 for ni, nj in self.neighbours(i, j): dfs(ni, nj, groupNumber) groupNumber = 2 for i, row in enumerate(grid): for j, cell in enumerate(row): if cell != 1: continue dfs(i, j, groupNumber) groupNumber += 1 if not area: return 1 res = max(area.values()) for i, row in enumerate(grid): for j, cell in enumerate(row): if cell: continue neighbourGroups = {grid[ni][nj] for ni, nj in self.neighbours(i, j)} res = max(res, 1 + sum(area[group] for group in neighbourGroups)) return res
making-a-large-island
python 3 | dfs | O(n^2)/O(n^2)
dereky4
0
51
making a large island
827
0.447
Hard
13,429
https://leetcode.com/problems/making-a-large-island/discuss/2442710/Making-a-large-island-oror-Python3-oror-DFS
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: # map to strore index of component along with number of nodes in that component map = {} index = 1 for i in range(0, len(grid)): for j in range(0, len(grid[0])): if(grid[i][j] == 1): index += 1 count = self.dfs(i, j, index, grid) map[index] = count # Handling edge case where grid has only water if(len(map) == 0): return 1 ans = 1 water_found = False for i in range(0, len(grid)): for j in range(0, len(grid[0])): if(grid[i][j] == 0): water_found = True neighbor_components = set() size = 1 for nx, ny in ((i+1, j), (i, j+1), (i-1, j), (i, j-1)): if(nx >= 0 and ny >= 0 and nx < len(grid) and ny < len(grid[0]) and grid[nx][ny] > 1): neighbor_components.add(grid[nx][ny]) # Add size of distinct components near water for comp in neighbor_components: size += map[comp] ans = max(ans, size) # Edge Case: If no water then whole grid is one large component if not water_found: return len(grid) * len(grid[0]) return ans # DFS on land def dfs(self, i, j, index, grid): grid[i][j] = index count = 1 for nx, ny in ((i+1, j), (i, j+1), (i-1, j), (i, j-1)): if(nx < 0 or ny < 0 or nx >= len(grid) or ny >= len(grid[0]) or grid[nx][ny] != 1): continue count += self.dfs(nx, ny, index, grid) return count
making-a-large-island
Making a large island || Python3 || DFS
vanshika_2507
0
36
making a large island
827
0.447
Hard
13,430
https://leetcode.com/problems/making-a-large-island/discuss/2103318/Python-oror-DFS-oror-Beats-90%2B
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: n = len(grid) stack = [] tag, area_dict = 2, {} for i in range(n): for j in range(n): if grid[i][j] == 1: area = 0 stack.append((i, j)) grid[i][j] = tag while stack: x, y = stack.pop() area += 1 for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: xx, yy = x + dx, y + dy if 0 <= xx < n and 0 <= yy < n and grid[xx][yy] == 1: stack.append((xx, yy)) grid[xx][yy] = tag area_dict[tag] = area tag += 1 if not area_dict: # if no island return 1 max_area = max(area_dict.values()) # if no ocean for i in range(n): for j in range(n): if grid[i][j] == 0: area = 1 islands = set() for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]: ii, jj = i + di, j + dj if 0 <= ii < n and 0 <= jj < n and grid[ii][jj] != 0: islands.add(grid[ii][jj]) for island in islands: area += area_dict[island] max_area = max(max_area, area) return max_area
making-a-large-island
Python || DFS || Beats 90%+
Tequila-Sunrise
0
64
making a large island
827
0.447
Hard
13,431
https://leetcode.com/problems/making-a-large-island/discuss/2063690/Python-easy-to-read-and-understand-or-graph
class Solution: def dfs(self, grid, row, col): if row < 0 or col < 0 or row == len(grid) or col == len(grid[0]) or grid[row][col] != 1: return 0 grid[row][col] = 2 x1 = self.dfs(grid, row-1, col) x2 = self.dfs(grid, row, col-1) x3 = self.dfs(grid, row+1, col) x4 = self.dfs(grid, row, col+1) return 1 + x1 + x2 + x3 + x4 def largestIsland(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ans = 0 for i in range(m): for j in range(n): if grid[i][j] == 0: grid[i][j] = 1 ans = max(ans, self.dfs(grid, i, j)) grid[i][j] = 0 for k in range(m): for l in range(n): if grid[k][l] == 2: grid[k][l] = 1 return ans if ans > 0 else n*n
making-a-large-island
Python easy to read and understand | graph
sanial2001
0
85
making a large island
827
0.447
Hard
13,432
https://leetcode.com/problems/making-a-large-island/discuss/2063690/Python-easy-to-read-and-understand-or-graph
class Solution: def dfs(self, grid, row, col, Id): if row < 0 or col < 0 or row == len(grid) or col == len(grid[0]) or grid[row][col] != 1: return 0 grid[row][col] = Id t = self.dfs(grid, row-1, col, Id) l = self.dfs(grid, row, col-1, Id) d = self.dfs(grid, row+1, col, Id) r = self.dfs(grid, row, col+1, Id) return 1+t+l+d+r def largestIsland(self, matrix: List[List[int]]) -> int: m, n = len(matrix), len(matrix[0]) hashmap = {} Id = 2 for i in range(m): for j in range(n): if matrix[i][j] == 1: hashmap[Id] = self.dfs(matrix, i, j, Id) Id += 1 ans = 0 for i in range(m): for j in range(n): if matrix[i][j] == 0: t, l, d, r = 0, 0, 0, 0 unique = set() if i > 0 and matrix[i-1][j] in hashmap and matrix[i-1][j] not in unique: t = hashmap[matrix[i-1][j]] unique.add(matrix[i-1][j]) if j > 0 and matrix[i][j-1] in hashmap and matrix[i][j-1] not in unique: l = hashmap[matrix[i][j-1]] unique.add(matrix[i][j-1]) if i < m-1 and matrix[i+1][j] in hashmap and matrix[i+1][j] not in unique: d = hashmap[matrix[i+1][j]] unique.add(matrix[i+1][j]) if j < n-1 and matrix[i][j+1] in hashmap and matrix[i][j+1] not in unique: r = hashmap[matrix[i][j+1]] unique.add(matrix[i][j+1]) ans = max(ans, 1+t+l+d+r) return ans if ans > 0 else m*n
making-a-large-island
Python easy to read and understand | graph
sanial2001
0
85
making a large island
827
0.447
Hard
13,433
https://leetcode.com/problems/making-a-large-island/discuss/1939285/Python-DFS-readable-solution-O(n2)
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: islands = {} position_mapping = {} island_id = 0 largest_island = [1] for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x] == 1 and (y,x) not in position_mapping: islands[island_id] = 0 explore_islands(y, x, grid, islands, position_mapping, island_id) largest_island[0] = max(largest_island[0], islands[island_id]) island_id += 1 for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x] == 0: connect_surrounding(y, x, grid, islands, position_mapping, largest_island) return largest_island[0] def explore_islands(y, x, grid, islands, position_mapping, island_id): if 0 <= y < len(grid) and 0 <= x < len(grid[0]) and grid[y][x] == 1 and (y,x) not in position_mapping: position_mapping[(y,x)] = island_id islands[island_id] += 1 for next_y, next_x in [(y +1, x),(y, x + 1),(y - 1, x),(y, x - 1)]: explore_islands(next_y, next_x, grid, islands, position_mapping, island_id) def connect_surrounding(y, x, grid, islands, position_mapping, largest_island): island_seen = set() size_accumulated = 0 for next_y, next_x in [(y +1, x),(y, x + 1),(y - 1, x),(y, x - 1)]: if (next_y, next_x) in position_mapping: island_id = position_mapping[(next_y, next_x)] if island_id in island_seen: continue island_seen.add(island_id) size_accumulated += islands[island_id] largest_island[0] = max(largest_island[0], size_accumulated +1)
making-a-large-island
Python DFS readable solution O(n^2)
user1267LD
0
81
making a large island
827
0.447
Hard
13,434
https://leetcode.com/problems/making-a-large-island/discuss/1746947/Python-O(N)-solution
class Solution: def __init__(self): self.directions = [(-1,0),(0,1),(1,0),(0,-1)] def largestIsland(self, grid: List[List[int]]) -> int: self.grid = grid self.rows, self.cols = len(self.grid), len(self.grid[0]) self.visited, self.islands, self.zeros = set(), [], set() for i in range(self.rows): for j in range(self.cols): if (i,j) in self.visited: continue cell = self.grid[i][j] if cell == 0: self.zeros.add((i,j)) continue curr_island = self.map_island(i,j) self.islands.append(curr_island) self.visited.add((i,j)) self.islands_hash = {} for i, island in enumerate(self.islands): island_size = len(island) for cell in island: self.islands_hash[cell] = [i,island_size] if len(self.zeros) <= 0: return self.rows*self.cols max_joined_island = 0 for i, j in self.zeros: joined_island_size = 0 pot_islands = set() for dir in self.directions: new_i,new_j = i+dir[0], j+dir[1] if 0 <= new_i < self.rows and 0 <= new_j < self.cols: if (new_i,new_j) in self.islands_hash and self.islands_hash[new_i,new_j][0] not in pot_islands: pot_islands.add(self.islands_hash[new_i,new_j][0]) joined_island_size += self.islands_hash[new_i,new_j][1] joined_island_size += 1 max_joined_island = max(max_joined_island,joined_island_size) return max_joined_island def map_island(self,i,j): stack = [] stack.append((i,j)) island = set() while stack: curr_i,curr_j = stack.pop() if (curr_i,curr_j) in self.visited: continue self.visited.add((curr_i,curr_j)) island.add((curr_i,curr_j)) for dir in self.directions: new_i,new_j = curr_i+dir[0], curr_j+dir[1] if 0 <= new_i < self.rows and 0 <= new_j < self.cols: curr_cell = self.grid[new_i][new_j] if curr_cell == 1: stack.append((new_i,new_j)) if curr_cell == 0: self.zeros.add((new_i,new_j)) return island
making-a-large-island
Python O(N) solution
dotaneli
0
110
making a large island
827
0.447
Hard
13,435
https://leetcode.com/problems/making-a-large-island/discuss/1618228/Python-Solution
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: island_map = [[0]*len(grid) for _ in range(len(grid))] #Colour coding the islands def dfs(row,col,curr): if island_map[col][row] == 0 and grid[col][row]==1: island_map[col][row] = curr island_area[curr]+=1 for d_row,d_col in [[1,0],[0,1],[-1,0],[0,-1]]: if len(grid)>row+d_row>=0 and len(grid)>col+d_col>=0: dfs(row+d_row,col+d_col,curr) return else: return #Making the islands curr = 0 #Colour island_area = {} #Storing the area of the islands for row in range(len(grid)): for col in range(len(grid)): if island_map[col][row] == 0 and grid[col][row]==1: curr+=1 island_area[curr] = 0 dfs(row,col,curr) areas = [] #Finding the neighbours and adding the areas for row in range(len(grid)): for col in range(len(grid)): if grid[col][row]==0: neighbours = set() for d_row,d_col in [[1,0],[0,1],[-1,0],[0,-1]]: if len(grid)>row+d_row>=0 and len(grid)>col+d_col>=0: neighbours.add(island_map[col+d_col][row+d_row]) area = 1 for neighbour in neighbours: if neighbour!=0: area+=island_area[neighbour] areas.append(area) #Adding the areas of the islands to the list for island,area in island_area.items(): areas.append(min(area+1,len(grid)**2)) return max(areas)
making-a-large-island
Python Solution
user7387N
0
89
making a large island
827
0.447
Hard
13,436
https://leetcode.com/problems/making-a-large-island/discuss/1612945/Help-with-Py3-code
class Solution: def largestIsland(self, grid) -> int: def search(i,j,color): nonlocal m,n,d if i<0 or j<0 or i>=m or j>=n or grid[i][j]!=1: return grid[i][j] = color d[color] += 1 search(i-1,j,color) search(i+1,j,color) search(i,j-1,color) search(i,j+1,color) color = 1 if not grid: return 0 m, n = len(grid), len(grid[0]) d = collections.defaultdict(list) d[0] = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: color += 1 d[color] = 0 search(i,j,color) island = 0 for i in range(m): for j in range(n): if grid[i][j]==0: count = 0 joint = collections.defaultdict(list) for s,t in ([max(i-1,0),j],[min(i+1,m-1),j],[i,max(0,j-1)],[i,min(j+1,n-1)]): joint[ grid[s][t] ]= d[grid[s][t]] for i,value in joint.items(): count += value island = max(island,count+1) return island
making-a-large-island
Help with Py3 code
ys258
0
41
making a large island
827
0.447
Hard
13,437
https://leetcode.com/problems/making-a-large-island/discuss/1560934/Well-commented-clean-python3-DFS-O(M*N)-Beats-time-83.04-space-75.5
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: # If there is nothing in the grid then return zero if not grid: return 0 # Mark every conntected island with a unique number, starting from 2 island_num = 2 # Nested recursive function that checks for connected Island def dfs(grid, r, c): nonlocal island_num sum_ = 0 if r >= 0 and c >= 0 and r < len(grid) and c < len(grid[0]) and grid[r][c] == 1: grid[r][c] = island_num sum_ += 1 # These calls visit all directions (N,S,E,W) to find the connected grid 1 entries and sum them all sum_ += dfs(grid, r+1, c) sum_ += dfs(grid, r-1, c) sum_ += dfs(grid, r, c+1) sum_ += dfs(grid, r, c-1) return sum_ area_d = {} ##### MAIN CODE EXECUTION STARTS HERE ###### # Visited every cell entry and then dfs it for connected island. # dfs will return the size of the island (aka area) for the particulared grid entry (r,c) # Store that area in a dictionary where the key is unique island_num, then increment the island_num # for next grid search for r, row in enumerate(grid): for c, cell in enumerate(row): if cell == 1: sum_ = dfs(grid, r, c) area_d[island_num] = sum_ island_num += 1 # So far we only know the number of island and their respective size in the given grid. # Below is the code where we find the single grid entry, which when converted to 1, yields largest area # Here we check area is equal to the number of grid entries then return the area because the given # grid is all land if len(list(area_d.keys())) == 1 and area_d[list(area_d.keys())[0]] == len(grid)**2: return len(grid)**2 # Since the description says (An island is a 4-directionally connected group of 1s). # It means we have to check North, South, East, West of zero grid entry to see if anything island is present # East West North South directions = [[0,1], [0,-1], [-1,0], [1,0]] N = len(grid) largest_area = 0 tmp_area = 0 # Lets go through every grid entry again for r, row in enumerate(grid): for c, cell in enumerate(row): # Now we are looking for zero entries only if grid[r][c] == 0: tmp_area = 0 # This is important to avoid wrong area calculation visited_island = [] # Visited all direction to see if land is present, if yes, sum the area for dir_ in directions: r_ = r + dir_[0] c_ = c + dir_[1] if r_ >= 0 and r_ < N and c_ >= 0 and c_ < N: # Since the island_num are assigned, now we check > 1 for land mass and make sure we # haven't visited this island before if grid[r_][c_] > 1 and grid[r_][c_] not in visited_island: # Put unique island number in the visited_island list visited_island.append(grid[r_][c_]) # increase the tmp_area by area of the island found in the respective direction tmp_area += area_d[grid[r_][c_]] # Finally, maintain the largest area found. 1 is added to tmp_area because we are converting zero to 1 largest_area = max(largest_area, tmp_area+1) return largest_area
making-a-large-island
Well commented, clean python3, DFS, O(M*N), Beats time 83.04%, space 75.5%
hiqbal
0
93
making a large island
827
0.447
Hard
13,438
https://leetcode.com/problems/making-a-large-island/discuss/1242056/Python-DFS-with-a-clean-implementation
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: rowcount = colcount = len(grid) areas = {} maxsize = 0 #Index is used to mark discovered cells. Starts from 2 to avoid collision with already existing values 0 and 1. index = 2 #Simple generator to make it easy to iterate over neighbors def neighbors(row, col): for newrow, newcol in ((row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)): if 0 <= newrow < rowcount and 0 <= newcol < colcount: yield newrow, newcol #BFS implementation to mark the whole island def bfs(r, c): nonlocal index queue = deque() queue.append((r, c)) #Mark the first cell grid[r][c] = index localcount = 0 while queue: row, col = queue.popleft() #increment local count to keep track of island area localcount += 1 for newrow, newcol in neighbors(row, col): if grid[newrow][newcol] == 1: #mark each cell with the current value of the index to differentiate this island from others grid[newrow][newcol] = index queue.append((newrow, newcol)) #we've traversed the whole island, save the area in a map areas[index] = localcount index += 1 for row in range(rowcount): for col in range(colcount): if grid[row][col] == 0: #Localsize starts at 1 because once we flip 0, it will add to the total area localsize = 1 seen = set( ) for newrow, newcol in neighbors(row, col): #Check all neighbors to determine if there are any islands. As we check, we add them to the set to not count them twice. #if cell is 1, it means this is an island we haven't seen yet. So let's calculate it's area first if grid[newrow][newcol] == 1: bfs(newrow, newcol) #Slight trick here: It can't be 1 anymore so we can directly look up the value as long as it's an island (not 0) if grid[newrow][newcol] != 0 and grid[newrow][newcol] not in seen: localsize += areas[grid[newrow][newcol]] seen.add(grid[newrow][newcol]) maxsize = max(maxsize, localsize) #Covers the corner case: If the grid is all 1, we would skip the loops above. I think this is more elegant than keeping a flag. return maxsize if maxsize > 0 else rowcount * colcount
making-a-large-island
Python, DFS with a clean implementation
swissified
0
208
making a large island
827
0.447
Hard
13,439
https://leetcode.com/problems/making-a-large-island/discuss/1165633/Python-O(N2)-Explore-beaches
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: n = len(grid) shifts = [(-1, 0), (1, 0), (0, 1), (0, -1)] islands = {0: [0, set()]} # island_id: [area, beach]. 0 to represent ocean def move(x, y): for dx, dy in shifts: if (0 <= x + dx < n) and (0 <= y + dy < n): yield x + dx, y + dy def explore(x, y, island_id, beach): if grid[x][y] != 1: if grid[x][y] == 0: # found an ocean around the island beach.add((x, y)) return 0 grid[x][y] = island_id area = 1 for xn, yn in move(x, y): area += explore(xn, yn, island_id, beach) return area def explore_beach(x, y): included_islands = set() area = 1 for xn, yn in move(x, y): island_id = grid[xn][yn] if island_id not in included_islands: area += islands[island_id][0] included_islands.add(island_id) return area # get island original area and beach around it for x in range(n): for y in range(n): if grid[x][y] == 1: island_id = len(islands) + 1 # 0: ocean, 1: unvisited islands beach = set() area = explore(x, y, island_id, beach) islands[island_id] = [area, beach] # extend each island by exploring their beaches max_extend_area = 1 # if no island for island_id, (area, beach) in islands.items(): max_extend_area = max(max_extend_area, area) # if no beach or ocean for x, y in beach: extend_area = explore_beach(x, y) max_extend_area = max(extend_area, max_extend_area) return max_extend_area
making-a-large-island
[Python] O(N^2) Explore beaches
louis925
0
106
making a large island
827
0.447
Hard
13,440
https://leetcode.com/problems/making-a-large-island/discuss/643108/Python3-O(N2)-Time-O(1)-Extra-Space-100-fast-100-memory
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: mark = 2 islands = [] n = len(grid) def mark_it(x, y): # marks island and returns square of that island grid[x][y] = mark s = 1 for xn in (x - 1, x + 1): if 0 <= xn < n and grid[xn][y] == 1: s += mark_it(xn, y) for yn in (y - 1, y + 1): if 0 <= yn < n and grid[x][yn] == 1: s += mark_it(x, yn) return s for i in range(n): for j in range(n): if grid[i][j] == 1: islands.append(mark_it(i, j)) mark += 1 if not islands: return 1 ret = max(islands) def check_it(x, y): # returns sum of adjacent islands to zero cell adj = [] for xn in (x - 1, x + 1): if 0 <= xn < n and grid[xn][y] != 0: adj.append(grid[xn][y] - 2) for yn in (y - 1, y + 1): if 0 <= yn < n and grid[x][yn] != 0: adj.append(grid[x][yn] - 2) if not adj: return 0 return sum([islands[a] for a in set(adj)]) for i in range(n): for j in range(n): if grid[i][j] == 0: ret = max(ret, 1 + check_it(i, j)) return ret
making-a-large-island
[Python3] O(N^2) Time; O(1) Extra Space; 100% fast; 100% memory
timetoai
0
176
making a large island
827
0.447
Hard
13,441
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process
class Solution: def uniqueLetterString(self, s: str) -> int: r=0 for i in range(len(s)): for j in range(i, len(s)): ss=s[i:j+1] unique=sum([ 1 for (i,v) in Counter(ss).items() if v == 1 ]) r+=unique return r
count-unique-characters-of-all-substrings-of-a-given-string
Python O(n) with intuition / step-by-step thought process
alskdjfhg123
6
354
count unique characters of all substrings of a given string
828
0.517
Hard
13,442
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process
class Solution: def uniqueLetterString(self, s: str) -> int: def does_char_appear_once(sub, t): num=0 for c in sub: if c==t: num+=1 return num==1 r=0 for c in string.ascii_uppercase: for i in range(len(s)): for j in range(i, len(s)): if does_char_appear_once(s[i:j+1], c): r+=1 return r
count-unique-characters-of-all-substrings-of-a-given-string
Python O(n) with intuition / step-by-step thought process
alskdjfhg123
6
354
count unique characters of all substrings of a given string
828
0.517
Hard
13,443
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process
class Solution: def uniqueLetterString(self, s): indices=defaultdict(list) for i in range(len(s)): indices[s[i]].append(i) r=0 for k,v in indices.items(): for i in range(len(v)): if i==0: prev=-1 else: prev=v[i-1] if i==len(v)-1: nxt=len(s) else: nxt=v[i+1] r+=nxt-prev-1 return r
count-unique-characters-of-all-substrings-of-a-given-string
Python O(n) with intuition / step-by-step thought process
alskdjfhg123
6
354
count unique characters of all substrings of a given string
828
0.517
Hard
13,444
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process
class Solution: def uniqueLetterString(self, s): indices=defaultdict(list) for i in range(len(s)): indices[s[i]].append(i) r=0 for k,v in indices.items(): for i in range(len(v)): curr=v[i] if i==0: prev=-1 else: prev=v[i-1] if i==len(v)-1: nxt=len(s) else: nxt=v[i+1] r+=(curr-prev)*(nxt-curr) return r
count-unique-characters-of-all-substrings-of-a-given-string
Python O(n) with intuition / step-by-step thought process
alskdjfhg123
6
354
count unique characters of all substrings of a given string
828
0.517
Hard
13,445
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/1377763/Python3-greedy
class Solution: def uniqueLetterString(self, s: str) -> int: locs = [[-1] for _ in range(26)] for i, x in enumerate(s): locs[ord(x)-65].append(i) ans = 0 for i in range(26): locs[i].append(len(s)) for k in range(1, len(locs[i])-1): ans += (locs[i][k] - locs[i][k-1]) * (locs[i][k+1] - locs[i][k]) return ans
count-unique-characters-of-all-substrings-of-a-given-string
[Python3] greedy
ye15
3
644
count unique characters of all substrings of a given string
828
0.517
Hard
13,446
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2564451/Python-simple-O(n)
class Solution: def uniqueLetterString(self, s: str) -> int: prev = [-1] * len(s) nex = [len(s)] * len(s) index = {} for i, c in enumerate(s): if c in index: prev[i] = index[c] index[c] = i index = {} for i in range(len(s) - 1, -1, -1): if s[i] in index: nex[i] = index[s[i]] index[s[i]] = i res = 0 for i, c in enumerate(s): res += (nex[i] - i) * (i - prev[i]) return res
count-unique-characters-of-all-substrings-of-a-given-string
Python simple O(n)
shubhamnishad25
1
106
count unique characters of all substrings of a given string
828
0.517
Hard
13,447
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/750028/Two-approaches-in-Python-(One-is-AC-and-the-other-is-TLE)
class Solution: def uniqueLetterString(self, s: str) -> int: mem, res, mod = [[-1] for _ in range(26)], 0, 1000000007 # ord('A') = 65 for i in range(len(s)): l = mem[ord(s[i]) - 65] l.append(i) if len(l) > 2: res = (res + (l[-1] - l[-2]) * (l[-2] - l[-3])) % mod for v in mem: if len(v) > 1: res = (res + (len(s) - v[-1]) * (v[-1] - v[-2])) % mod return res # logically correct but TLE def uniqueLetterString1(self, s: str) -> int: res, mod, mem = 0, 1000000007, defaultdict(int) for window in range(1, len(s) + 1): mem[s[window-1]] += 1 copy = mem.copy() res += list(copy.values()).count(1) for i in range(window, len(s)): copy[s[i-window]] -= 1 copy[s[i]] += 1 res += list(copy.values()).count(1) if res > mod: res %= mod return res
count-unique-characters-of-all-substrings-of-a-given-string
Two approaches in Python (One is AC and the other is TLE)
samparly
1
408
count unique characters of all substrings of a given string
828
0.517
Hard
13,448
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2774192/7-Line-Python-DP-O(N)-Time-O(1)-Space
class Solution: def uniqueLetterString(self, s: str) -> int: pre, ans, last_i, second_last_i = 0, 0, [-1] * 26, [-1] * 26 for i in range(len(s)): order = ord(s[i]) - ord('A') pre += i - last_i[order] - (last_i[order] - second_last_i[order]) ans += pre second_last_i[order], last_i[order] = last_i[order], i return ans
count-unique-characters-of-all-substrings-of-a-given-string
7 Line Python / DP / O(N) Time / O(1) Space
GregHuang
0
7
count unique characters of all substrings of a given string
828
0.517
Hard
13,449
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2757889/Python-Solution
class Solution: def uniqueLetterString(self, s: str) -> int: # default value from left is -1 and default value from the right is length of array # the difference is right minus left pointer LENGTH = len(s) left_map: dict[str, int] = {} left: list[int] = [] right_map: dict[str, int] = {} right: list[int] = [] for i in range(LENGTH): #print(i, LENGTH-i-1) l = i r = LENGTH-i-1 # --LEFT PROCESSING-- char = s[l] to_append = left_map[char] if char in left_map else -1 left.append(l-to_append) left_map[char] = l # --RIGHT PROCESSING-- char = s[r] to_append = right_map[char] if char in right_map else LENGTH right.append(to_append-r) right_map[char] = r right.reverse() #print(left) #print(right) result = 0 for i in range(LENGTH): result += (left[i]*right[i]) print(result) return result
count-unique-characters-of-all-substrings-of-a-given-string
Python Solution
ugookoh
0
8
count unique characters of all substrings of a given string
828
0.517
Hard
13,450
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2631577/Very-short-one-pass-O(n)-solution-in-Python-easy-to-understand
class Solution: def uniqueLetterString(self, s: str) -> int: last = {} ans = 0 step_sum = 0 for i, c in enumerate(s): if c not in last: last[c] = [-1, i] else: step_sum -= (last[c][1] - last[c][0]) last[c] = [last[c][1], i] step_sum += last[c][1] - last[c][0] ans += step_sum return ans
count-unique-characters-of-all-substrings-of-a-given-string
Very short one-pass O(n) solution in Python, easy to understand
metaphysicalist
0
36
count unique characters of all substrings of a given string
828
0.517
Hard
13,451
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2602956/Python-3-or-simple-solution-or-O(n)O(1)
class Solution: def uniqueLetterString(self, s: str) -> int: prev = collections.defaultdict(lambda: (-1, -1)) res = 0 for i, c in enumerate(s): prev2, prev1 = prev[c] res += (prev1 - prev2) * (i - prev1) prev[c] = prev1, i n = len(s) for prev2, prev1 in prev.values(): res += (prev1 - prev2) * (n - prev1) return res
count-unique-characters-of-all-substrings-of-a-given-string
Python 3 | simple solution | O(n)/O(1)
dereky4
0
99
count unique characters of all substrings of a given string
828
0.517
Hard
13,452
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2315652/Python-Idea-explain-Very-simple-solution
class Solution: def uniqueLetterString(self, s: str) -> int: ## RC ## ## APPROACH: SUBARRAY ## ## LOGIC ## ## 1. Translate this prob to sub-prob => what is the max len of subarray where s[i] is unique ? ## 2. Particular character s[i] is unique can be found checking the next and previous occurrence ## 3. Once the prev and next length are found, calcualte the substring combinations count # EX: LEETCODE # next = [8, 2, 7, 8, 8, 8, 8, 8] # prev = [-1, -1, 1, -1, -1, -1, -1, 2] def get_next_occur(s): hashmap = dict() arr = [len(s)] * len(s) for i, ch in enumerate(s): if ch in hashmap: arr[hashmap[ch]] = i del hashmap[ch] hashmap[ch] = i return arr # find the next ocuurance of ch in s next = get_next_occur(s) # find the prev ocuurance of ch in s prev = get_next_occur(s[::-1])[::-1] prev = [ len(s) - p -1 for p in prev ] # print(next, prev) return sum([ (next[i] - i) * (i - prev[i]) for i in range(len(s)) ])
count-unique-characters-of-all-substrings-of-a-given-string
[Python] Idea explain, Very simple solution,
101leetcode
0
303
count unique characters of all substrings of a given string
828
0.517
Hard
13,453
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2270505/Shortest-Python-Solution-you'll-see.-O(26n)
class Solution: def uniqueLetterString(self, s: str) -> int: prev,curr = defaultdict(int),defaultdict(int) ans = 0 for i,x in enumerate(s): curr[x] = i - prev[x] + 1 ans += sum(curr.values()) prev[x] = i + 1 return ans
count-unique-characters-of-all-substrings-of-a-given-string
Shortest Python Solution you'll see. O(26n)
pradhyumnjain10
0
181
count unique characters of all substrings of a given string
828
0.517
Hard
13,454
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/1832382/Dynamic-Programming-Solution-(time-limit-exceeded-)
class Solution: def uniqueLetterString(self, s: str) -> int: res = 0 n = len(s) # dp_keys stores all keys in a substring dp_keys = [[set() for _ in range(n)] for _ in range(n)] # dp_unqs stores all unique characters in a substring dp_unqs = [[set() for _ in range(n)] for _ in range(n)] # dp_count stores the number of unique characters in a substring dp_count = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): dp_keys[i][i] = set(s[i]) dp_unqs[i][i] = set(s[i]) dp_count[i][i] = 1 res += 1 for end_i in range(n): for start_i in range(end_i - 1, -1, -1): if s[start_i] not in dp_keys[start_i + 1][end_i]: tmp = copy.deepcopy(dp_keys[start_i + 1][end_i]) tmp.add(s[start_i]) dp_keys[start_i][end_i] = tmp tmp = copy.deepcopy(dp_unqs[start_i + 1][end_i]) tmp.add(s[start_i]) dp_unqs[start_i][end_i] = tmp dp_count[start_i][end_i] = dp_count[start_i + 1][end_i] + 1 res += dp_count[start_i][end_i] else: dp_keys[start_i][end_i] = dp_keys[start_i + 1][end_i] if s[start_i] in dp_unqs[start_i + 1][end_i]: tmp = copy.deepcopy(dp_unqs[start_i + 1][end_i]) tmp.remove(s[start_i]) dp_unqs[start_i][end_i] = tmp dp_count[start_i][end_i] = dp_count[start_i + 1][end_i] - 1 res += dp_count[start_i][end_i] else: dp_unqs[start_i][end_i] = dp_unqs[start_i + 1][end_i] dp_count[start_i][end_i] = dp_count[start_i + 1][end_i] res += dp_count[start_i][end_i] return res
count-unique-characters-of-all-substrings-of-a-given-string
Dynamic Programming Solution (time limit exceeded )
Mujojo
0
365
count unique characters of all substrings of a given string
828
0.517
Hard
13,455
https://leetcode.com/problems/consecutive-numbers-sum/discuss/1466133/8-lines-Python3-code
class Solution: def consecutiveNumbersSum(self, n: int) -> int: csum=0 result=0 for i in range(1,n+1): csum+=i-1 if csum>=n: break if (n-csum)%i==0: result+=1 return result
consecutive-numbers-sum
8 lines Python3 code
tongho
6
705
consecutive numbers sum
829
0.415
Hard
13,456
https://leetcode.com/problems/consecutive-numbers-sum/discuss/2150748/PYTHON-oror-EXPLAINED-oror
class Solution: def consecutiveNumbersSum(self, n: int) -> int: i=1 res=0 k=int((n*2)**0.5) while i<=k: if i%2: if n%i==0: res+=1 elif (n-(i//2))%i==0: res+=1 i+=1 return res
consecutive-numbers-sum
✔️ PYTHON || EXPLAINED || ;]
karan_8082
5
328
consecutive numbers sum
829
0.415
Hard
13,457
https://leetcode.com/problems/consecutive-numbers-sum/discuss/994601/Python3-6-lines-O(sqrt(n))-solution-with-simple-math
class Solution: def consecutiveNumbersSum(self, N: int) -> int: ''' let a be the starting number and k be the number of terms a + (a + 1) + ... (a + k - 1) = N (2a + k - 1) * k / 2 = N Since (k + 2a - 1) * k = 2N, k < sqrt(2N) On the other hand, the above equation can be turned into ak + k(k-1)/2 k(k-1)/2 is basically the sum of 1 to k-1. If we iterate all the way up to sqrt(2N), we could do the sum along the way. As long as (N - sum) can be devided by k, that's one count. ''' sum_term = 0 count = 0 for i in range(int((2 * N) ** 0.5)): sum_term += i if (N - sum_term) % (i + 1) == 0: count += 1 return count
consecutive-numbers-sum
Python3 6 lines O(sqrt(n)) solution with simple math
haozhu233
3
516
consecutive numbers sum
829
0.415
Hard
13,458
https://leetcode.com/problems/consecutive-numbers-sum/discuss/1603568/Python-simple-and-easy-no-SQRT-no-complex-math
class Solution: def consecutiveNumbersSum(self, n: int) -> int: count = 0 i = 1 while (n > 0): n -= i if n%i == 0: count += 1 i += 1 return count
consecutive-numbers-sum
Python simple & easy no SQRT, no complex math
ranasaani
2
477
consecutive numbers sum
829
0.415
Hard
13,459
https://leetcode.com/problems/consecutive-numbers-sum/discuss/1136982/Logical-Sliding-window-approach-or-Python-3-or-Linear
class Solution: def consecutiveNumbersSum(self, n: int) -> int: start = 1 end = 1 curr = 0 res = 0 while end <= n: curr += end while curr >= n: if curr == n: res += 1 curr -= start start += 1 end += 1 return res
consecutive-numbers-sum
Logical Sliding window approach | Python 3 | Linear
abhyasa
2
461
consecutive numbers sum
829
0.415
Hard
13,460
https://leetcode.com/problems/consecutive-numbers-sum/discuss/2353539/Python-Quick-maths-(slightly-different-from-other-solns)
class Solution: def consecutiveNumbersSum(self, n: int) -> int: count = 0 k = floor(math.sqrt(2*n)) for i in range(1,k+1): if (2*n)%i==0 and (2*n/i+i)%2!=0: count +=1 return count
consecutive-numbers-sum
[Python] Quick maths (slightly different from other solns)
In_Ctrl
1
99
consecutive numbers sum
829
0.415
Hard
13,461
https://leetcode.com/problems/consecutive-numbers-sum/discuss/2835487/Math-solution
class Solution: def consecutiveNumbersSum(self, n: int) -> int: i = 2 count = 1 while True: start = n // i - ((i - 1) // 2) if start < 1: break if (start* 2 + i - 1) * i // 2 == n: count += 1 i += 1 return count
consecutive-numbers-sum
Math solution
yukiyukiyeahyeah
0
1
consecutive numbers sum
829
0.415
Hard
13,462
https://leetcode.com/problems/consecutive-numbers-sum/discuss/1924171/Python-3Math-Method
class Solution: def consecutiveNumbersSum(self, n: int) -> int: m = 1 count = 0 while m*(m-1)/2 < n: a = float(n / m - (m - 1) / 2) m += 1 if a.is_integer(): count += 1 return count
consecutive-numbers-sum
[Python 3]Math Method
kkimm
0
127
consecutive numbers sum
829
0.415
Hard
13,463
https://leetcode.com/problems/consecutive-numbers-sum/discuss/1505191/Python3-enumeration
class Solution: def consecutiveNumbersSum(self, n: int) -> int: ans = 0 for x in range(1, int(sqrt(2*n))+1): if (n - x*(x+1)//2) % x == 0: ans += 1 return ans
consecutive-numbers-sum
[Python3] enumeration
ye15
0
189
consecutive numbers sum
829
0.415
Hard
13,464
https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22
class Solution(object): def largeGroupPositions(self, s): s += " " streak, char, out = 0, s[0], [] for i,c in enumerate(s): if c != char: if streak >= 3: out.append([i-streak, i-1]) streak, char = 0, s[i] streak += 1 return out
positions-of-large-groups
Python - simple and elegant - multiple solutions - "Streak"
domthedeveloper
1
83
positions of large groups
830
0.518
Easy
13,465
https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22
class Solution(object): def largeGroupPositions(self, s): s += " " start, char, out = 0, s[0], [] for i,c in enumerate(s): if c != char: if i-start >= 3: out.append([start, i-1]) start, char = i, s[i] return out
positions-of-large-groups
Python - simple and elegant - multiple solutions - "Streak"
domthedeveloper
1
83
positions of large groups
830
0.518
Easy
13,466
https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22
class Solution(object): def largeGroupPositions(self, s): streak, out = 0, [] for i in range(len(s)): streak += 1 if i == len(s)-1 or s[i] != s[i+1]: if streak >= 3: out.append([i-streak+1, i]) streak = 0 return out
positions-of-large-groups
Python - simple and elegant - multiple solutions - "Streak"
domthedeveloper
1
83
positions of large groups
830
0.518
Easy
13,467
https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22
class Solution(object): def largeGroupPositions(self, s): start, out = 0, [] for i in range(len(s)): if i == len(s)-1 or s[i] != s[i+1]: if i-start+1 >= 3: out.append([start, i]) start = i+1 return out
positions-of-large-groups
Python - simple and elegant - multiple solutions - "Streak"
domthedeveloper
1
83
positions of large groups
830
0.518
Easy
13,468
https://leetcode.com/problems/positions-of-large-groups/discuss/1620405/Python-3-faster-than-99
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: start = 0 cur = s[0] res = [] for i, c in enumerate(s[1:] + ' ', start=1): if c != cur: if i - start >= 3: res.append([start, i-1]) start = i cur = c return res
positions-of-large-groups
Python 3 faster than 99%
dereky4
1
146
positions of large groups
830
0.518
Easy
13,469
https://leetcode.com/problems/positions-of-large-groups/discuss/1353412/python-3-solution-easy-to-understand
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: lst=[] n=len(s) if s=="": return [] i=0 while(i<n): start=i end=i for j in range(i+1,n): if s[j]==s[i]: end=end+1 else: break if ((end-start)+1)>=3: lst.append([start,end]) i=end+1 return lst
positions-of-large-groups
python 3 solution easy to understand
minato_namikaze
1
71
positions of large groups
830
0.518
Easy
13,470
https://leetcode.com/problems/positions-of-large-groups/discuss/1016683/Easy-and-Clear-Solution-Python-3
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: i,j,n=0,1,len(s) tab,aux=[],[] while j<n: if s[i]==s[j]: aux,j=[i,j],j+1 elif aux: if aux[1]-aux[0]>=2: tab.append(aux) i,j,aux=j,j+1,[] else: i,j=j,j+1 if aux: if aux[1]-aux[0]>=2: tab.append(aux) return tab
positions-of-large-groups
Easy & Clear Solution Python 3
moazmar
1
190
positions of large groups
830
0.518
Easy
13,471
https://leetcode.com/problems/positions-of-large-groups/discuss/453124/Beats-97-in-run-time-and-100-in-memory.
class Solution: def largeGroupPositions(self, S: str) -> List[List[int]]: """ """ out = [] i =0 while i < (len(S) -1):#iteration for non repeating elements j = i while j < (len(S) -1) and S[j] == S[j+1]: #iteration for repeating elements j += 1 if (j - i + 1) >= 3: #Checking condition for length 3 or more. out.append([i,j]) i = j i+=1 return out
positions-of-large-groups
Beats 97% in run time and 100% in memory.
sudhirkumarshahu80
1
203
positions of large groups
830
0.518
Easy
13,472
https://leetcode.com/problems/positions-of-large-groups/discuss/2690091/Python3-Readable-and-easy-Solution
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: # make two pointers to start and end start = 0 result = [] # the end pointer will be the index for idx, char in enumerate(s): # check whether it is different to previous char if char != s[start]: # check whether our group was large if idx - start >= 3: result.append([start, idx-1]) # reset our start pointer start = idx # take care of large groups at the end if len(s) - start >= 3: result.append([start, len(s)-1]) return result
positions-of-large-groups
[Python3] - Readable and easy Solution
Lucew
0
9
positions of large groups
830
0.518
Easy
13,473
https://leetcode.com/problems/positions-of-large-groups/discuss/2547912/Two-pointer-approach
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: l, r = 0, 1 res = [] while r < len(s): if s[l] == s[r]: r += 1 else: if r - l >= 3: res.append([l, r - 1]) l = r r += 1 if r - l >= 3: res.append([l, r - 1]) return res
positions-of-large-groups
Two pointer approach
ankurbhambri
0
18
positions of large groups
830
0.518
Easy
13,474
https://leetcode.com/problems/positions-of-large-groups/discuss/2421730/Python-Two-Pointer-Solution
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: start = 0 res = [] for end in range(len(s)): if end == len(s) -1 and s[start] == s[end] and end - start + 1>=3: ## For test cases like "aaa" or "a" res.append([start, end]) ##Regular Two pointer solution elif s[start] != s[end]: l = end - start if l >= 3: res.append([start,end-1]) start = end return res
positions-of-large-groups
Python Two Pointer Solution
theReal007
0
25
positions of large groups
830
0.518
Easy
13,475
https://leetcode.com/problems/positions-of-large-groups/discuss/2380674/Python3-Easy
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: i=0 c=1 prev="" l=len(s) ans=[] while i<l: if s[i]==prev: c+=1 if (i==l-1) &amp; (c>=3): ans.append([i+1-c,i]) else: if c>=3: ans.append([i-c,i-1]) c=1 prev=s[i] i+=1 return ans
positions-of-large-groups
[Python3] Easy
sunakshi132
0
37
positions of large groups
830
0.518
Easy
13,476
https://leetcode.com/problems/positions-of-large-groups/discuss/1988451/Python-Easy-Solution-or-Faster-87-submits
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: tmp = '' index = 0 res = [] for i in range(len(s)) : if s[i] != tmp : if i - index >= 3 : res.append([index, i-1]) tmp = s[i] index = i if i - index >= 2 : res.append([index, i]) return res
positions-of-large-groups
[ Python ] Easy Solution | Faster 87% submits
crazypuppy
0
71
positions of large groups
830
0.518
Easy
13,477
https://leetcode.com/problems/positions-of-large-groups/discuss/1979271/Python-easy-to-read-and-understand
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: i, j = 0, 1 n = len(s) res = [] while i < n and j < n: if s[i] == s[j]: j += 1 else: if j-i >= 3: res.append([i, j-1]) i = j if j-i >= 3: res.append([i, j-1]) return res
positions-of-large-groups
Python easy to read and understand
sanial2001
0
47
positions of large groups
830
0.518
Easy
13,478
https://leetcode.com/problems/positions-of-large-groups/discuss/1851820/PYTHON-SIMPLE-ONE-pointer-solution-step-by-step-(36ms)
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: #Sentinel at the end s = s + '!'; #Then find the length LENGTH = len ( s ); #Make a list for the solution soln = [ ]; #Initialize the previous as the first character at zeroth index prev = s[ 0 ]; prevIndex = 0; #Pointer will be at the first index pointer = 1; #Streak default is one streak = 1; #While we have a vald index while pointer < LENGTH: #Look at the character using the pointer current = s[ pointer ]; #If we match, we proceed if current == prev: #By increasing our streak #And increasing the pointer, streak += 1; pointer += 1; continue; #If we have a mismatch and a streak of 3 or higher elif current != prev and streak >= 3 : #We append the indices to the solution soln.append( [ prevIndex, pointer - 1 ] ); #Each time we don't have a match #We reset the streak to one #Update previous and its index #And increment the pointer streak = 1; prev = current; prevIndex = pointer; pointer += 1; #Return the soln return soln ;
positions-of-large-groups
PYTHON SIMPLE ONE pointer solution step-by-step (36ms)
greg_savage
0
65
positions of large groups
830
0.518
Easy
13,479
https://leetcode.com/problems/positions-of-large-groups/discuss/1337702/Python3-dollarolution
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: x = s[0] a, y, v = 0, 1, [] for i in range(1,len(s)): if s[i] == x: y += 1 if y > 2: b = i else: if y > 2: v.append([a,b]) a, y, x = i, 1, s[i] if y > 2: v.append([a,b]) return v
positions-of-large-groups
Python3 $olution
AakRay
0
75
positions of large groups
830
0.518
Easy
13,480
https://leetcode.com/problems/positions-of-large-groups/discuss/1255602/Simple-and-Easy-or-or-Python-oror-830.-Positions-of-Large-Groups
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: res=[] count=1 for i in range(1,len(s)): if s[i]==s[i-1]: count+=1 else: if count >= 3: res.append([i-count,i-1]) count=1 if count >= 3: res.append([len(s)-count,len(s)-1]) return res
positions-of-large-groups
Simple and Easy | | Python || 830. Positions of Large Groups
jaipoo
0
83
positions of large groups
830
0.518
Easy
13,481
https://leetcode.com/problems/positions-of-large-groups/discuss/1219155/Python3-simple-solution-using-list-beats-90-users
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: res = [] x = 0 for i in range(len(s)): if i == len(s) - 1 or s[i] != s[i+1]: if i-x+1 >= 3: res.append([x, i]) x = i+1 return res
positions-of-large-groups
Python3 simple solution using list beats 90% users
EklavyaJoshi
0
47
positions of large groups
830
0.518
Easy
13,482
https://leetcode.com/problems/positions-of-large-groups/discuss/458518/Python3-super-simple-solution-using-a-for()-loop
class Solution: def largeGroupPositions(self, S: str) -> List[List[int]]: stack,res = [],[] for i in range(len(S)): if not stack or stack[-1][1] == S[i]: stack.append((i, S[i])) if i != len(S) - 1: continue if len(stack) >= 3: res.append([stack[0][0],stack[-1][0]]) stack = [(i, S[i])] return res
positions-of-large-groups
Python3 super simple solution using a for() loop
jb07
0
55
positions of large groups
830
0.518
Easy
13,483
https://leetcode.com/problems/masking-personal-information/discuss/1868652/3-Lines-Python-Solution-oror-98-Faster-oror-Memory-less-than-87
class Solution: def maskPII(self, s: str) -> str: if '@' in s: return f'{s[0].lower()}*****{s[s.index("@")-1].lower()+"".join([x.lower() for x in s[s.index("@"):]])}' s=''.join([x for x in s if x not in '()- +']) return ('' if len(s)<=10 else '+'+'*'*(len(s)-10)+'-')+f'***-***-{s[-4:]}'
masking-personal-information
3-Lines Python Solution || 98% Faster || Memory less than 87%
Taha-C
1
94
masking personal information
831
0.47
Medium
13,484
https://leetcode.com/problems/masking-personal-information/discuss/1868652/3-Lines-Python-Solution-oror-98-Faster-oror-Memory-less-than-87
class Solution: def maskPII(self, s: str) -> str: if '@' in s: user,domain=s.split('@') return f'{user[0].lower()}{"*"*5}{user[-1].lower()}@{domain.lower()}' s=''.join([x for x in s if x.isdigit()]) ; n=0 return f'+{"*"*(n-10)}-***-***-{s[-4:]}' if n>10 else f'***-***-{s[-4:]}'
masking-personal-information
3-Lines Python Solution || 98% Faster || Memory less than 87%
Taha-C
1
94
masking personal information
831
0.47
Medium
13,485
https://leetcode.com/problems/masking-personal-information/discuss/2762680/Python3-oror-Split-and-Filter-oror-Easy
class Solution: def maskPII(self, s: str) -> str: if '@' in s: s = s.lower() name, rest = s.split('@') name = name[0] + '*****' + name[-1] return name + '@' + rest else: num = ''.join([n for n in s if n in '1234567890']) if len(num) == 10: return "***-***-" + num[-4:] elif len(num) == 11: return "+*-***-***-" + num[-4:] elif len(num) == 12: return "+**-***-***-" + num[-4:] else: return "+***-***-***-" + num[-4:]
masking-personal-information
Python3 || Split & Filter || Easy
joshua_mur
0
17
masking personal information
831
0.47
Medium
13,486
https://leetcode.com/problems/masking-personal-information/discuss/1426661/Python-3-or-f-string-or-Explanation-(This-should-be-an-EASY-question)
class Solution: def maskPII(self, s: str) -> str: if '@' in s: user, domain = s.split('@') return f'{user[0].lower()}{"*"*5}{user[-1].lower()}@{domain.lower()}' else: s = ''.join([c for c in s if c.isdigit()]) n = len(s) return f'+{"*"*(n-10)}-***-***-{s[-4:]}' if n != 10 else f'***-***-{s[-4:]}'
masking-personal-information
Python 3 | f-string | Explanation (This should be an EASY question)
idontknoooo
0
79
masking personal information
831
0.47
Medium
13,487
https://leetcode.com/problems/masking-personal-information/discuss/937240/Python3-straightforward-soln
class Solution: def maskPII(self, S: str) -> str: if "@" in S: # email address name, domain = S.lower().split("@") return f"{name[0]}*****{name[-1]}@{domain}" else: # phone number d = "".join(c for c in S if c.isdigit()) ans = f"***-***-{d[-4:]}" return ans if len(d) == 10 else f"+{'*'*(len(d)-10)}-" + ans
masking-personal-information
[Python3] straightforward soln
ye15
0
69
masking personal information
831
0.47
Medium
13,488
https://leetcode.com/problems/flipping-an-image/discuss/1363051/PYTHON-VERY-VERY-EASY-SOLN.-3-solutions-explained-O(n).-With-or-without-inbuilt-functions.
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: """ Simple &amp; striaghtforward without using inbuilt functions. In actual the run time is very less as we are iterating only n/2 time for each image list. Time complexity : O(n * n/2) == O(n^2) Space complexity : O(1) """ for im in image: #Iterate through each im list in the image list. i, j = 0, len(im)-1 #Maintain two pointers one at start and one at end. while i <= j: #Iterate while first pointer is less than or equal to second pointer. im[i], im[j] = im[j]^1, im[i]^1 #swap element at both pointer &amp; complement them at the same time. i +=1 #increment first pointer to move forward j -=1 #decrement second pointer to move backward return image # return same list """ Using inbuilt functions """ # for im in range(len(image)): # image[im] = list(map(lambda a : abs(a-1), reversed(image[im]))) # return image """ One liner """ return [[i^1 for i in im[::-1]] for im in image]
flipping-an-image
[PYTHON] VERY VERY EASY SOLN. 3 solutions explained O(n). With or without inbuilt functions.
er1shivam
10
663
flipping an image
832
0.805
Easy
13,489
https://leetcode.com/problems/flipping-an-image/discuss/1780606/Python3-Solution-or-Easy-to-understand
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: for i in range(len(image)): image[i] = image[i][::-1] for j in range(len(image[i])): if image[i][j] == 0: image[i][j] = 1 else: image[i][j] = 0 return image
flipping-an-image
Python3 Solution | Easy to understand
Coding_Tan3
7
313
flipping an image
832
0.805
Easy
13,490
https://leetcode.com/problems/flipping-an-image/discuss/1225285/32ms-Python-(with-comments)
class Solution(object): def flipAndInvertImage(self, image): """ :type image: List[List[int]] :rtype: List[List[int]] """ #create a variable to store the result result = [] #create a variable for storing the number of elements in each sublist as we need it later, saving some computation time, by declaring it as a constant length = len(image[0]) #looping through each pixel in the images list for pixel in image: #mapping each element in the pixel with xor of 1, ^1, because it returns the opposite of 0,1! #We also reverse the list by slicing temp = map(operator.xor,pixel,[1]*length)[::-1] #Add each sublist in the desired formate in the result list result.append(temp) return result
flipping-an-image
32ms, Python (with comments)
Akshar-code
3
290
flipping an image
832
0.805
Easy
13,491
https://leetcode.com/problems/flipping-an-image/discuss/1287794/Python3-96-time-one-liner-with-list-comprehension-explained
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: return [[0 if n else 1 for n in i] for i in [item[::-1] for item in image]]
flipping-an-image
Python3, 96% time, one liner, with list comprehension, explained
albezx0
2
123
flipping an image
832
0.805
Easy
13,492
https://leetcode.com/problems/flipping-an-image/discuss/2558075/EASY-PYTHON3-SOLUTION
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: result = [] for i in range(len(image)): for j in range(len(image[i])): if image[i][j] == 1: image[i][j] = 0 else:image[i][j] = 1 result.append(image[i][::-1]) return result
flipping-an-image
✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔
rajukommula
1
102
flipping an image
832
0.805
Easy
13,493
https://leetcode.com/problems/flipping-an-image/discuss/2410950/Simple-python-code-with-explanation
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: #iterate over the list of list--> image for i in range(len(image)): #reverse every list in image list using reverse keyword image[i].reverse() #iterate over the each list in the image list for j in range(len(image[i])): #if the element in the list is 1 if image[i][j] == 1: #change it to 0 image[i][j] = 0 else: #if not change it to 1 image[i][j] = 1 #after changing just return image return image
flipping-an-image
Simple python code with explanation
thomanani
1
32
flipping an image
832
0.805
Easy
13,494
https://leetcode.com/problems/flipping-an-image/discuss/2205721/Python3-O(rc)-oror-O(1)-Runtime%3A-54ms-89.52-Memory%3A-13.8mb-64.60
class Solution: # O(r,c) || O(1) # Runtime: 54ms 89.52% Memory: 13.8mb 64.60% def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: def reverse(image): for row in range(len(image)): image[row] = image[row][::-1] reverse(image) for row in range(len(image)): for col in range(len(image[row])): if image[row][col] == 1: image[row][col] = 0 else: image[row][col] = 1 return image
flipping-an-image
Python3 O(r,c) || O(1) # Runtime: 54ms 89.52% Memory: 13.8mb 64.60%
arshergon
1
47
flipping an image
832
0.805
Easy
13,495
https://leetcode.com/problems/flipping-an-image/discuss/2009557/Python-3-Solution-Two-Pointers-fast
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: # Flipping Horizontally for k in range(len(image)): i, j = 0, len(image[k]) - 1 while i < j: image[k][i], image[k][j] = image[k][j], image[k][i] i += 1 j -= 1 # Inverting for k in range(len(image)): for i in range(len(image[k])): if image[k][i]: image[k][i] = 0 else: image[k][i] = 1 return image
flipping-an-image
Python 3 Solution, Two Pointers, fast
AprDev2011
1
58
flipping an image
832
0.805
Easy
13,496
https://leetcode.com/problems/flipping-an-image/discuss/1950486/Easy-Beginner-Solution-With-Slicing
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: final = [] cols = len(image[0]) for i in range(len(image)): c = image[i][::-1] for j in range(len(image)): if c[j] == 1: c[j] = 0 else: c[j] = 1 final.append(c[j]) final = [final[i:i + cols] for i in range(0, len(final), cols)] return final
flipping-an-image
Easy Beginner Solution With Slicing
itsmeparag14
1
23
flipping an image
832
0.805
Easy
13,497
https://leetcode.com/problems/flipping-an-image/discuss/1386440/Python-One-Liner-Fast
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: return [[1-val for val in row[::-1]] for row in image]
flipping-an-image
Python One Liner Fast
peatear-anthony
1
75
flipping an image
832
0.805
Easy
13,498
https://leetcode.com/problems/flipping-an-image/discuss/1154296/Python-Easy-To-Understand-Solution
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: for i in range(0, len(image)): image[i].reverse() for j in range(0, len(image[0])): if image[i][j] == 0: image[i][j] = 1 else: image[i][j] = 0 return image
flipping-an-image
Python Easy To Understand Solution
saurabhkhurpe
1
152
flipping an image
832
0.805
Easy
13,499