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/search-suggestions-system/discuss/2168566/python-3-or-simple-two-pointer-solution
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() left, right = 0, len(products) - 1 res = [] for i, c in enumerate(searchWord): while left <= right and (len(products[left]) <= i or products[left][i] != c): left += 1 while left <= right and (len(products[right]) <= i or products[right][i] != c): right -= 1 res.append([products[left + j] for j in range(min(3, right - left + 1))]) return res
search-suggestions-system
python 3 | simple two pointer solution
dereky4
0
27
search suggestions system
1,268
0.665
Medium
18,900
https://leetcode.com/problems/search-suggestions-system/discuss/2156626/python-optimize-of-Brute-Fore-similar-to-trie
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() lookup = defaultdict(list) for prod in products: for i in range(1,len(prod)+1): lookup[prod[:i]].append(prod) res = [] for i in range(1, len(searchWord)+1): res.append(lookup[searchWord[:i]][:3]) return res # products.sort() # res = [] # for i in range(1,len(searchWord)+1): # match = [] # for product in products: # if product.startswith(searchWord[:i]): # match.append(product) # if len(match) == 3: # break # res.append(match) # return res
search-suggestions-system
python optimize of Brute Fore, similar to trie
hardernharder
0
51
search suggestions system
1,268
0.665
Medium
18,901
https://leetcode.com/problems/search-suggestions-system/discuss/2079025/Python3-solution-faster-than-79.04-and-consumes-less-memory-than-84.48-of-submissions
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: prducts = list(map(lambda x:x.lower(),products)) searchWord = searchWord.lower() realtime_keyword = '' found_products = products output= [] for letter in searchWord: realtime_keyword+=letter temp_list = [] for product in found_products: if product.startswith(realtime_keyword): temp_list.append(product) found_products = temp_list found_products.sort() output.append(found_products[:3]) return output
search-suggestions-system
Python3 solution faster than %79.04 and consumes less memory than %84.48 of submissions
aliie62
0
77
search suggestions system
1,268
0.665
Medium
18,902
https://leetcode.com/problems/search-suggestions-system/discuss/2017188/Python3-Easy
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() self.products = products self.searchWord = searchWord return self.findTheProducts() def findTheProducts(self): char_list = list(self.searchWord) curr_char = '' length = 0 res = list() for char in char_list: curr_char += char length += 1 current_res =[] for prod in self.products: if len(current_res) == 3: break if curr_char == prod[:length]: current_res.append(prod) else: pass res.append(current_res) return res
search-suggestions-system
Python3 Easy
MicroRay
0
67
search suggestions system
1,268
0.665
Medium
18,903
https://leetcode.com/problems/search-suggestions-system/discuss/1612917/Python3-Solution-with-using-two-pointers-and-sorting
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() begin = 0 end = len(products) - 1 max_returns_cnt = 3 res = [] for i in range(len(searchWord)): while begin <= end and (i > len(products[begin]) - 1 or searchWord[i] != products[begin][i]): begin += 1 while begin <= end and (i > len(products[end]) - 1 or searchWord[i] != products[end][i]): end -= 1 res.append(products[begin:min(begin + max_returns_cnt, end + 1)]) return res
search-suggestions-system
[Python3] Solution with using two pointers and sorting
maosipov11
0
228
search suggestions system
1,268
0.665
Medium
18,904
https://leetcode.com/problems/search-suggestions-system/discuss/1243439/python3-Trie-solution-for-reference.
class Solution: def suggestedProducts(self, products, searchWord: str): trie = {'#': []} limit = 3 # sort products so that the lexicograph is resumed. products.sort() # insert the products into the trie with ending as '#' # store in trie such that... ## each char -> c -> stores the words that has it in the sequence. def insertIntoTrie(t, word): for c in word: if c in t: t = t[c] t['#'].append(word) else: t[c] = {} t = t[c] t["#"] = [word] for p in products: insertIntoTrie(trie, p) o = [] # if search word initial char is not trie, no need to search further. if searchWord[0] not in trie: return [[] for _ in range(len(searchWord))] for x in range(1,len(searchWord)+1): tmp = trie for sw in searchWord[:x]: if sw not in tmp: ## To identify that we have reached the end of the trie search. This will happen in two cases. # char mismath in middle, search word and trie both have more to go. # trie has ended but search has more to go. ## if there are multiple search words, this solution will not work ( assigning [] to trie.) tmp['#'] = [] break else: tmp = tmp[sw] o.append(tmp['#'][:limit]) return o
search-suggestions-system
[python3] Trie solution for reference.
vadhri_venkat
0
79
search suggestions system
1,268
0.665
Medium
18,905
https://leetcode.com/problems/search-suggestions-system/discuss/1243172/Python-3-Trie-approach
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: trie = {} # build trie for product in products: node = trie for p in product: node = node.setdefault(p, {}) node['*'] = product # DFS traversing all prefix nodes def dfs(node): for x in node: if x == '*': tmp.append(node[x]) continue dfs(node[x]) ans = [[] for _ in range(len(searchWord))] node = trie for i, s in enumerate(searchWord): tmp = [] if s in node: node = node[s] dfs(node) # output first three lexicographicall minimum words ans[i] = sorted(tmp)[:3] else: break return ans
search-suggestions-system
[Python 3] Trie approach
chestnut890123
0
121
search suggestions system
1,268
0.665
Medium
18,906
https://leetcode.com/problems/search-suggestions-system/discuss/1189743/simple-of-simple
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: COUNT = 3 products = sorted(products) l = len(searchWord) result = [] for i in range(l): s = searchWord[:i+1] t = [] for p in products: if p.find(s) == 0: t.append(p) if len(t) == COUNT: break result.append(t) return result
search-suggestions-system
simple of simple
seunggabi
0
52
search suggestions system
1,268
0.665
Medium
18,907
https://leetcode.com/problems/search-suggestions-system/discuss/923918/Simple-Beginner-Friendly-Python-Solution
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: ans = [] n = len(products) now = products #iterate through length of searchWord for i in range(len(searchWord)): temp = [] #iterate through length of current list for j in range(len(now)): #check if there are enough characters if len(now[j])>= i and searchWord[:i+1] == now[j][:i+1]: temp.append(now[j]) #top 3 words hence sort temp.sort() if len(temp)>3: ans.append(temp[:3]) else: ans.append(temp) now = temp return ans
search-suggestions-system
Simple -Beginner Friendly Python Solution
SaSha59
0
138
search suggestions system
1,268
0.665
Medium
18,908
https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/2488667/LeetCode-The-Hard-Way-DP-with-Explanation
class Solution: def numWays(self, steps: int, arrLen: int) -> int: M = 10 ** 9 + 7 @lru_cache(None) def dfs(pos, steps): # if we walk outside the array or use all the steps # then return 0 if pos < 0 or pos > steps or pos > arrLen - 1: return 0 # if we use all the steps, return 1 only if pos is 0 if steps == 0: return pos == 0 return ( # move to the left dfs(pos - 1, steps - 1) + # stay at current position dfs(pos, steps - 1) + # move to the right dfs(pos + 1, steps - 1) ) % M return dfs(0, steps)
number-of-ways-to-stay-in-the-same-place-after-some-steps
[LeetCode The Hard Way] DP with Explanation
wingkwong
1
94
number of ways to stay in the same place after some steps
1,269
0.436
Hard
18,909
https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/2786758/Python-Memo-EASY-TO-UNDERSTAND
class Solution: def numWays(self, steps: int, arrLen: int) -> int: MOD = (10**9)+7 @cache def dfs(steps,index): if steps == 0 and index == 0: return 1 if steps == 0: return 0 goLeft = 0 goRight = 0 goStay = 0 if index > 0: goLeft = dfs(steps-1,index-1) if index < arrLen-1: goRight = dfs(steps-1,index+1) goStay = dfs(steps-1,index) return goLeft+goStay+goRight return dfs(steps,0) % MOD
number-of-ways-to-stay-in-the-same-place-after-some-steps
Python Memo EASY TO UNDERSTAND
tupsr
0
2
number of ways to stay in the same place after some steps
1,269
0.436
Hard
18,910
https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/2422581/Python-3-dp
class Solution: def numWays(self, steps: int, arrLen: int) -> int: mod=10**9+7 to_consider=min(arrLen,steps//2+1) dp=[1]+[0]*(to_consider-1) for i in range(steps): new_dp=[0]*to_consider for j in range(to_consider): new_dp[j]=(dp[j]+(dp[j+1] if j+1<to_consider else 0)+(dp[j-1] if j-1>=0 else 0))%mod dp=new_dp return dp[0]
number-of-ways-to-stay-in-the-same-place-after-some-steps
[Python 3] dp
gabhay
0
15
number of ways to stay in the same place after some steps
1,269
0.436
Hard
18,911
https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/437749/Python3-dynamic-programming-(98.45)-with-explanation
class Solution: def numWays(self, steps: int, arrLen: int) -> int: n = min(arrLen, steps//2+1) #reachable right end ways = [1] + [0]*(n-1) for step in range(steps): ways = [sum(ways[max(0,i-1):i+2]) % (10**9+7) for i in range(min(step+2,steps-step,n))] return ways[0]
number-of-ways-to-stay-in-the-same-place-after-some-steps
Python3 dynamic programming (98.45%) with explanation
ye15
0
86
number of ways to stay in the same place after some steps
1,269
0.436
Hard
18,912
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1767406/Python-3-solution-with-comments
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: # keep track of the "net score" of each row/col/diagonal # player A adds 1 to the "net score" of each row/col/diagonal they play in, # player B subtracts 1 # scores[0], scores[1] and scores[2] are for rows 0, 1 and 2 # scores[3], scores[4] and scores[5] are for cols 0, 1 and 2 # scores[6] and scores[7] are for the forward and backward diagonal scores = [0] * 8 for i, (row, col) in enumerate(moves): if i % 2 == 0: # if player A is playing x = 1 else: # if player B is playing x = -1 scores[row] += x scores[col + 3] += x if row == col: scores[6] += x if 2 - row == col: scores[7] += x for score in scores: if score == 3: return 'A' elif score == -3: return 'B' return 'Draw' if len(moves) == 9 else 'Pending'
find-winner-on-a-tic-tac-toe-game
Python 3 solution with comments
dereky4
15
871
find winner on a tic tac toe game
1,275
0.543
Easy
18,913
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/441452/Python3-memo-scores
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: score = [[0]*8 for _ in range(2)] for p, (i, j) in enumerate(moves): p %= 2 score[p][i] += 1 score[p][3+j] += 1 if i == j: score[p][6] += 1 if i+j == 2: score[p][7] += 1 if any(x == 3 for x in score[p]): return "AB"[p] return "Pending" if len(moves) < 9 else "Draw"
find-winner-on-a-tic-tac-toe-game
[Python3] memo scores
ye15
15
1,300
find winner on a tic tac toe game
1,275
0.543
Easy
18,914
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/441652/Python-3-(four-lines)-(beats-100)-(24-ms)-(With-Explanation)
class Solution: def tictactoe(self, M: List[List[int]]) -> str: L, P, [x,y], N = len(M), 1 - len(M) % 2, M[-1], [M[::2], M[1::2]] if all(p in N[P] for p in [[x,0],[x,1],[x,2]]) or all(p in N[P] for p in [[0,y],[1,y],[2,y]]): return ['A','B'][P] if all(p in N[P] for p in [[0,0],[1,1],[2,2]]) or all(p in N[P] for p in [[0,2],[1,1],[2,0]]): return ['A','B'][P] return ["Pending","Draw"][L == 9] - Junaid Mansuri - Chicago, IL
find-winner-on-a-tic-tac-toe-game
Python 3 (four lines) (beats 100%) (24 ms) (With Explanation)
junaidmansuri
3
1,000
find winner on a tic tac toe game
1,275
0.543
Easy
18,915
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1442163/Using-issubset()-98-speed
class Solution: wins = [{(0, 0), (0, 1), (0, 2)}, {(1, 0), (1, 1), (1, 2)}, {(2, 0), (2, 1), (2, 2)}, {(0, 0), (1, 0), (2, 0)}, {(0, 1), (1, 1), (2, 1)}, {(0, 2), (1, 2), (2, 2)}, {(0, 0), (1, 1), (2, 2)}, {(2, 0), (1, 1), (0, 2)}] def tictactoe(self, moves: List[List[int]]) -> str: a, b = set(), set() for i, (r, c) in enumerate(moves): if i % 2: b.add((r, c)) if any(win.issubset(b) for win in Solution.wins): return "B" else: a.add((r, c)) if any(win.issubset(a) for win in Solution.wins): return "A" return "Pending" if len(moves) < 9 else "Draw"
find-winner-on-a-tic-tac-toe-game
Using issubset(), 98% speed
EvgenySH
2
244
find winner on a tic tac toe game
1,275
0.543
Easy
18,916
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1947959/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: game = [['','',''],['','',''],['','','']] a = 0 for i,j in moves: if a%2 == 0: game[i][j] = 'A' a+=1 else: game[i][j] = 'B' a+=1 if game[0][0] == game[0][1] == game[0][2] and game[0][0]!='': return game[0][0] elif game[1][0] == game[1][1] == game[1][2] and game[1][0]!='': return game[1][0] elif game[2][0] == game[2][1] == game[2][2] and game[2][0]!='': return game[2][0] elif game[0][0] == game[1][0] == game[2][0] and game[0][0]!='': return game[0][0] elif game[0][1] == game[1][1] == game[2][1] and game[0][1]!='': return game[0][1] elif game[0][2] == game[1][2] == game[2][2] and game[0][2]!='': return game[0][2] elif game[0][0] == game[1][1] == game[2][2] and game[0][0]!='': return game[0][0] elif game[0][2] == game[1][1] == game[2][0] and game[0][2]!='': return game[0][2] else: for i in game: if '' in i: return "Pending" return "Draw"
find-winner-on-a-tic-tac-toe-game
Python (Simple Approach and Beginner-Friendly)
vishvavariya
1
172
find winner on a tic tac toe game
1,275
0.543
Easy
18,917
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1836738/7-lines-Python-Solution-oror-93-Faster-oror-Memory-less-than-60
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: wins= [ [[0,0],[1,1],[2,2]], [[0,2],[1,1],[2,0]], [[0,0],[1,0],[2,0]], [[0,1],[1,1],[2,1]], [[0,2],[1,2],[2,2]], [[0,0],[0,1],[0,2]], [[1,0],[1,1],[1,2]], [[2,0],[2,1],[2,2]] ] MA=[moves[i] for i in range(0,len(moves),2)] ; MB=[moves[i] for i in range(1,len(moves),2)] for win in wins: if all(item in MA for item in win): return 'A' if all(item in MB for item in win): return 'B' if len(moves)==9: return 'Draw' return 'Pending'
find-winner-on-a-tic-tac-toe-game
7-lines Python Solution || 93% Faster || Memory less than 60%
Taha-C
1
229
find winner on a tic tac toe game
1,275
0.543
Easy
18,918
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1264367/Generalize-approach-work-with-%22n%22-square-board
class Solution: player = { "A" : 1, "B" : 2, } def __get_player_code(self, player:str)->int: return self.player.get(player) def win_player(self, board : List[List[str]], player : str) -> bool: return self.__win_row_wise(board, player) or self.__win_column_wise(board, player) or self.__win_diagonal_wise(board, player) def __win_row_wise(self, board : List[List[str]], player : str) -> bool: n = len(board) player_code = self.__get_player_code(player) for i in range(n): if all([player_code== board[i][j] for j in range(n)]): return True return False def __win_column_wise(self, board : List[List[str]], player : str) -> bool: n = len(board) player_code = self.__get_player_code(player) for j in range(n): if all([player_code== board[i][j] for i in range(n)]): return True return False def __win_diagonal_wise(self, board : List[List[str]], player : str) -> bool: n = len(board) player_code = self.__get_player_code(player) if all([player_code== board[i][j] for i in range(n) for j in range(n) if i == j]): return True if all([player_code== board[i][j] for i in range(n) for j in range(n) if (i+j)==n-1]): return True return False def __create_board(self, board_size: int) -> List[List[str]]: return [[0 for i in range(board_size)] for j in range(board_size)] def tictactoe(self, moves: List[List[int]]) -> str: board_size = 3 board = self.__create_board(board_size) player_list = ["A","B"] index = 0 n = len(player_list) for i,j in moves: board[i][j] = self.__get_player_code(player_list[index]) index = (index+1)%n for player in player_list: if self.win_player(board, player): return player if any([0 == board[i][j] for i in range(board_size) for j in range(board_size)]): return "Pending" return "Draw"
find-winner-on-a-tic-tac-toe-game
Generalize approach work with "n" square board
Sanjaychandak95
1
218
find winner on a tic tac toe game
1,275
0.543
Easy
18,919
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1216138/Pyhton-or-Faster-than-89.19-or-Easy-Solution
class Solution(object): def tictactoe(self, moves): if (len(moves)<5): return "Pending" c1=0 c2=0 a=[[0 for i in range(3)]for j in range(3)] for i in range (len(moves)): for j in range (len(moves[0])-1): if i==0 or i%2==0: a[moves[i][j]][moves[i][j+1]]=1 else: a[moves[i][j]][moves[i][j+1]]=2 print(a) r=len(a) c=len(a[0]) for i in range (r-2): for j in range (c-2): if a[i][j]==a[i+1][j+1]==a[i+2][j+2]: if a[i][j]==1: c1+=1 elif a[i][j]==2: c2+=1 for i in range (r-2): for j in range (c-2): if a[i][j+2]==a[i+1][j+1]==a[i+2][j]: if a[i][j+2]==1: c1+=1 elif a[i][j+2]==2: c2+=1 for i in range(r): for j in range(c-2): if a[i][j]==a[i][j+1]==a[i][j+2]: if a[i][j]==1: c1+=1 elif a[i][j]==2: c2+=1 for i in range (r-2): for j in range (c): if a[i][j]==a[i+1][j]==a[i+2][j]: if a[i][j]==1: c1+=1 elif a[i][j]==2: c2+=1 if c1>0: return 'A' elif c2>0: return 'B' if(len(moves)==9): return "Draw" return "Pending"
find-winner-on-a-tic-tac-toe-game
Pyhton | Faster than 89.19% | Easy Solution
divyadharshini12
1
194
find winner on a tic tac toe game
1,275
0.543
Easy
18,920
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/717528/Python-3-brute-force-(easy-to-understand)
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: counter = 0 arr = [["" for i in range(3)] for j in range(3)] def helper(): diag = [ row[i] for i,row in enumerate(arr) ] other_diag = [ row[-i-1] for i,row in enumerate(arr) ] if diag.count("X") == 3: return "A" if diag.count("O") == 3: return "B" if other_diag.count("X") == 3: return "A" if other_diag.count("O") == 3: return "B" for x in arr: if x.count("X") == 3: return "A" if x.count("O") == 3: return "B" for i in range(3): col = [row[i] for row in arr] if col.count("X") == 3: return "A" if col.count("O") == 3: return "B" return None x = True for move in moves: counter += 1 if x: arr[move[0]][move[1]] = "X" else: arr[move[0]][move[1]] = "O" x = not x res = helper() if res is not None: return res if counter == 9: return "Draw" return "Pending"
find-winner-on-a-tic-tac-toe-game
Python 3 brute-force (easy to understand)
ermolushka2
1
132
find winner on a tic tac toe game
1,275
0.543
Easy
18,921
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2818822/Python-bitmanipulations
class Solution: def tictactoe(self, moves) -> str: # 1, 2, 4 # 8, 16, 32 # 64, 128, 256 a = 0 b = 0 flag = True counter = 0 def isWinner(value): for pattern in list([(1 + 2 + 4), (8 + 16 + 32), (64 + 128 + 256), (1 + 8 + 64), (2 + 16 + 128), (4 + 32 + 256), (1 + 16 + 256), (4 + 16 + 64)]): if pattern &amp; value == pattern: return True for x, y in moves: value = 1 << x * 3 + y if flag: a |= value if isWinner(a): return "A" else: b |= value if isWinner(b): return "B" flag = not flag counter += 1 return "Draw" if counter == 9 else "Pending"
find-winner-on-a-tic-tac-toe-game
Python, bitmanipulations
swepln
0
3
find winner on a tic tac toe game
1,275
0.543
Easy
18,922
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2805970/tic-tac-toe
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: grid = [ [None] * 3 for i in range(3)] for i in range(len(moves)): move = moves[i] if i % 2 == 0: grid[move[0]][move[1]] = 'X' if self.won(grid) == True: return 'A' else: grid[move[0]][move[1]] = '0' if self.won(grid) == True: print("final",grid) return 'B' print(grid) if self.won(grid) == 'Draw': return 'Draw' elif self.won(grid) == "Pending": return "Pending" def won(self,grid): if grid[0][0] == grid[1][1] == grid[2][2] and None not in [grid[0][0], grid[1][1], grid[2][2]]: return True elif grid[0][2] == grid[1][1] == grid[2][0] and None not in [grid[0][2],grid[1][1],grid[2][0]]: return True for i in range(3): if grid[i][0] == grid[i][1] == grid[i][2] and None not in grid[i]: return True for i in range(3): if grid[0][i] == grid[1][i] == grid[2][i] and None not in [grid[0][i], grid[1][i] ,grid[2][i]]: return True if None not in grid[0] and None not in grid[1] and None not in grid[2]: return 'Draw' else: return "Pending"
find-winner-on-a-tic-tac-toe-game
tic tac toe
user4363G
0
3
find winner on a tic tac toe game
1,275
0.543
Easy
18,923
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2794455/Beats-99.94-solutions
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: diagr,to_row,to_col,diag = 0,moves[-1][0],moves[-1][1],0 row,col,i = 0,0,len(moves)-1 while i >= 0: if moves[i][0] == to_row : row +=1 if moves[i][1] == to_col : col+=1 if moves[i][0] == moves[i][1] : diag+=1 if (moves[i][0] == 1 and moves[i][1] == 1) or (moves[i][0] == 0 and moves[i][1] == 2) or (moves[i][0] == 2 and moves[i][1] == 0): diagr +=1 i-=2 if (row == 3 or col == 3 or diag == 3 or diagr == 3): if len(moves)%2 == 0: return "B" else: return "A" return "Draw" if len(moves) == 9 else "Pending"
find-winner-on-a-tic-tac-toe-game
Beats 99.94% solutions
ishitakumardps
0
4
find winner on a tic tac toe game
1,275
0.543
Easy
18,924
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2769392/Find-Winner-on-a-Tic-Tac-Toe-Game-or-PYTHON
class Solution: def check(self, matrix: List[List[int]]) -> bool: # checking row wise if matrix[0][0]==matrix[0][1] and matrix[0][1]==matrix[0][2]: if matrix[0][0]!="": return True if matrix[1][0]==matrix[1][1] and matrix[1][1]==matrix[1][2]: if matrix[1][0]!="": return True if matrix[2][0]==matrix[2][1] and matrix[2][1]==matrix[2][2]: if matrix[2][0]!="": return True # checking column wise if matrix[0][0]==matrix[1][0] and matrix[1][0]==matrix[2][0]: if matrix[0][0]!="": return True if matrix[0][1]==matrix[1][1] and matrix[1][1]==matrix[2][1]: if matrix[0][1]!="": return True if matrix[0][2]==matrix[1][2] and matrix[1][2]==matrix[2][2]: if matrix[0][2]!="": return True # check 1 diagonal if matrix[0][0]==matrix[1][1] and matrix[1][1]==matrix[2][2]: if matrix[0][0]!="": return True # check 2 diagonal if matrix[0][2]==matrix[1][1] and matrix[1][1]==matrix[2][0]: if matrix[0][2]!="": return True return False def tictactoe(self, moves: List[List[int]]) -> str: matrix=[["","",""],["","",""],["","",""]] f="A" for t in range(0,len(moves)): if f=="A": i=moves[t][0] j=moves[t][1] matrix[i][j]="A" f="B" if self.check(matrix): return "A" else: i=moves[t][0] j=moves[t][1] matrix[i][j]="B" f="A" if self.check(matrix): return "B" for i in range(0,3): if "" in matrix[i]: return "Pending" return "Draw"
find-winner-on-a-tic-tac-toe-game
Find Winner on a Tic Tac Toe Game | PYTHON
saptarishimondal
0
12
find winner on a tic tac toe game
1,275
0.543
Easy
18,925
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2605258/An-Optimized-Solution-with-a-%22Scoring%22-System
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: if len(moves) < 5: # It's impossible to win before turn five return "Pending" # Keep track of players' row, column, and diagonal "scores" rowPts, colPts, diagPts = [0,0,0], [0,0,0], [0,0] point = 1 # "X" = 1, "O" = -1 for turn, (row, col) in enumerate(moves, start=1): scores = [] * 4 # Compile current scores for a winner check rowPts[row] += point # Every cell belongs to a row colPts[col] += point # Every cell belongs to a column scores.append(rowPts[row]) scores.append(colPts[col]) if row == col: # Cell is on first diagonal diagPts[0] += point scores.append(diagPts[0]) if row + col == 2: # Cell is on second diagonal diagPts[1] += point scores.append(diagPts[1]) if turn >= 5: # It's impossible to win before turn five for score in scores: if abs(score) == 3: # "X" needs 3 points to win # "O" needs -3 points to win return "A" if point == 1 else "B" point = -point return "Draw" if len(moves) == 9 else "Pending"
find-winner-on-a-tic-tac-toe-game
An Optimized Solution with a "Scoring" System
kcstar
0
22
find winner on a tic tac toe game
1,275
0.543
Easy
18,926
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2367231/Python-Modular-solution-sc-tc-%3A-O(n)-O(n)
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: row, col, diag, anti = [0] * 3, [0] * 3, 0, 0 for i in range(len(moves)): offset = 1 if i % 2 == 0 else -1 row[moves[i][0]] += offset col[moves[i][1]] += offset if moves[i][0] == moves[i][1]: diag += offset if moves[i][0] + moves[i][1] == 2: anti += offset if row[moves[i][0]] == 3 or col[moves[i][1]] == 3 or diag == 3 or anti == 3: return 'A' if row[moves[i][0]] == -3 or col[moves[i][1]] == -3 or diag == -3 or anti == -3: return 'B' return 'Pending' if len(moves) != 9 else 'Draw'
find-winner-on-a-tic-tac-toe-game
Python Modular solution sc, tc : O(n), O(n)
byusuf
0
59
find winner on a tic tac toe game
1,275
0.543
Easy
18,927
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/2324381/Straightforward-Python3-solution.-Faster-than-95
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: # There can't be a winner if neither player has made 3 moves yet if len(moves) < 5: return "Pending" # Build grid grid = [[0] * 3 for _ in range(3)] play = 1 # Player "A" = +1 , Player "B" = -1 for y, x in moves: grid[y][x] = play play = -play # If the sum is any row is 3 or -3, we have a winner #print("Checking rows") for row in grid: if (total := sum(row)) == 3: return "A" elif total == -3: return "B" diag_d, diag_u = 0, 0 col = [] # Collect info for diagonals and columns in the same loop for n in range(3): diag_d += grid[n][n] diag_u += grid[2-n][n] col.append(grid[0][n] + grid[1][n] + grid[2][n]) #print("Checking Diagonals") if diag_d == 3 or diag_u == 3: return "A" elif diag_d == -3 or diag_u == -3: return "B" #print(f"Checking columns {col=}") for c in col: if c == 3: return "A" elif c == -3: return "B" # If we had no winner, then we either have a Draw or are pending. return "Draw" if len(moves) == 9 else "Pending"
find-winner-on-a-tic-tac-toe-game
Straightforward Python3 solution. Faster than 95%
nigh_anxiety
0
66
find winner on a tic tac toe game
1,275
0.543
Easy
18,928
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1720153/Python3-easy-to-understand
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: if len(moves)<5: return "Pending" def helper(arr:list): arr = sorted(arr) for i in arr: if i[0] == 0 and i[1] == 0: if ([0,1] in arr and [0,2] in arr ) or \ ([1,1] in arr and [2,2] in arr ) or \ ([1,0] in arr and [2,0] in arr ) : return True elif i[0] == 0: if i[1] == 1: if ([1,1] in arr and [2,1] in arr ) : return True elif i[1] == 2: if ([1,2] in arr and [2,2] in arr ) or ([1,1] in arr and [2,0] in arr ) : return True elif i[0] == 1 and i[1] == 0: if ([1,1] in arr and [1,2] in arr ) : return True elif i[0] == 2 and i[1] == 0: if ([2,1] in arr and [2,2] in arr ) : return True return False a = helper([x for x in moves[::2]]) b = helper([x for x in moves[1::2]]) if a : return 'A' elif b: return 'B' else: if len(moves)>=9: return 'Draw' else: return 'Pending' return
find-winner-on-a-tic-tac-toe-game
Python3 easy to understand
jasonjfk
0
103
find winner on a tic tac toe game
1,275
0.543
Easy
18,929
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1477138/Python3-Score-counting-and-some-optimization-to-cut-the-search-time-by-half!-(24-ms)
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: turns = len(moves) if turns < 5: # There's no way winner can be determined return "Pending" rows, cols, tlbr, trbl = [0] * 3, [0] * 3, 0, 0 cand = "A" if turns % 2 == 1 else "B" # Player who moved last is probably the winner moves = moves[::-2] for row, col in moves: # Check for vertical and horizontal lines rows[row] += 1 cols[col] += 1 # Check for diagonal lines if row == col: tlbr += 1 if row + col == 2: trbl += 1 # Check if condition is estabilished... if any(abs(line) == 3 for line in (rows[row], cols[col], tlbr, trbl)): return cand # There's no winner return "Pending" if turns < 9 else "Draw"
find-winner-on-a-tic-tac-toe-game
[Python3] Score counting and some optimization to cut the search time by half! (24 ms)
park-csu
0
103
find winner on a tic tac toe game
1,275
0.543
Easy
18,930
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1424204/Python3-Detailed-Solution-Faster-Than-97.61-Memory-Less-Than-96.48
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: grid = [[".", ".", "."], [".", ".", "."], [".", ".", "."]] def check(grid): if grid[0][0] == grid[1][1] == grid[2][2] and grid[0][0] != '.': if grid[0][0] == 'x': return 'A' else: return 'B' elif grid[0][0] == grid[0][1] == grid[0][2] and grid[0][0] != '.': if grid[0][0] == 'x': return 'A' else: return 'B' elif grid[0][0] == grid[1][0] == grid[2][0] and grid[0][0] != '.': if grid[0][0] == 'x': return 'A' else: return 'B' elif grid[0][2] == grid[1][1] == grid[2][0] and grid[0][2] != '.': if grid[0][2] == 'x': return 'A' else: return 'B' elif grid[1][0] == grid[1][1] == grid[1][2] and grid[1][0] != '.': if grid[1][0] == 'x': return 'A' else: return 'B' elif grid[2][0] == grid[2][1] == grid[2][2] and grid[2][0] != '.': if grid[2][0] == 'x': return 'A' else: return 'B' elif grid[0][1] == grid[1][1] == grid[2][1] and grid[0][1] != '.': if grid[0][1] == 'x': return 'A' else: return 'B' elif grid[0][2] == grid[1][2] == grid[2][2] and grid[0][2] != '.': if grid[0][2] == 'x': return 'A' else: return 'B' return 'D' j = 0 for i in moves: x, y = i[0], i[1] if j % 2 == 0: grid[x][y] = 'x' else: grid[x][y] = 'o' j += 1 if check(grid) == 'A': return 'A' elif check(grid) == 'B': return 'B' if check(grid) == 'D' and j <= 8: return 'Pending' else: return 'Draw'
find-winner-on-a-tic-tac-toe-game
Python3 Detailed Solution Faster Than 97.61%, Memory Less Than 96.48%
Hejita
0
128
find winner on a tic tac toe game
1,275
0.543
Easy
18,931
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1316284/Python3-simple-verification-solution
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: grid=[[0]*3 for _ in range(3)] for i in range(len(moves)): x,y=moves[i] if i%2==0: grid[x][y]="A" else: grid[x][y]="B" def winner(ch): if grid[0][0]==grid[0][1]==grid[0][2]==ch or grid[1][0]==grid[1][1]==grid[1][2]==ch or grid[2][0]==grid[2][1]==grid[2][2]==ch: return True if grid[0][0]==grid[1][1]==grid[2][2]==ch or grid[0][2]==grid[1][1]==grid[2][0]==ch: return True if grid[0][0]==grid[1][0]==grid[2][0]==ch or grid[0][1]==grid[1][1]==grid[2][1]==ch or grid[0][2]==grid[1][2]==grid[2][2]==ch: return True return False if winner("A"): return "A" if winner("B"): return "B" if len(moves)==9: return "Draw" return "Pending"
find-winner-on-a-tic-tac-toe-game
Python3 simple verification solution
atm1504
0
177
find winner on a tic tac toe game
1,275
0.543
Easy
18,932
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/916789/Python3-easy-and-Fast-solution
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: grid = [[0] * 3 for i in range(3)] idx = 0 # fill the grid, 1 represents "X" (A's move) and 2 represents "O" (B's move) for r,c in moves: if idx % 2 == 0: grid[r][c] = 1 else: grid[r][c] = 2 idx += 1 # check rows and columns for i in range(3): if grid[i][0] == grid[i][1] and grid[i][1] == grid[i][2]: if grid[i][0] == 1: return "A" elif grid[i][0] == 2: return "B" if grid[0][i] == grid[1][i] and grid[1][i] == grid[2][i]: if grid[0][i] == 1: return "A" elif grid[0][i] == 2: return "B" # check diagonal if grid[0][0] == grid[1][1] and grid[1][1] == grid[2][2]: if grid[0][0] == 1: return "A" elif grid[0][0] == 2: return "B" if grid[0][2] == grid[1][1] and grid[1][1] == grid[2][0]: if grid[0][2] == 1: return "A" elif grid[0][2] == 2: return "B" if len(moves) == 9: return "Draw" else: return "Pending"
find-winner-on-a-tic-tac-toe-game
Python3 easy and Fast solution
marzi_ash
0
194
find winner on a tic tac toe game
1,275
0.543
Easy
18,933
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/819192/Intuitive-approach-by-checking-who-wins-and-then-%22Draw%22-or-%22Pending%22
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: r''' X X 0 0 X ''' def is_win(moves): # Check row, column, diagnol for i in range(3): if len(list(map(lambda t: t[1], filter(lambda t: t[0]==i, moves)))) == 3: return True if len(list(map(lambda t: t[0], filter(lambda t: t[1]==i, moves)))) == 3: return True if len(list(filter(lambda t: t[0] == t[1], moves))) == 3: return True if len(list(filter(lambda t: t[0] + t[1] == 2, moves))) == 3: return True # 0) Separate moves into a_moves &amp; b_moves a_moves, b_moves = [], [] for i, m in enumerate(moves): if i % 2 == 0: a_moves.append(m) else: b_moves.append(m) # 1) Condition check if is_win(a_moves): return "A" if is_win(b_moves): return "B" if len(a_moves) + len(b_moves) == 9: return "Draw" else: return "Pending"
find-winner-on-a-tic-tac-toe-game
Intuitive approach by checking who wins and then "Draw" or "Pending"
puremonkey2001
0
78
find winner on a tic tac toe game
1,275
0.543
Easy
18,934
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/660124/Python-Solution-based-on-Game-simulation-(-faster-than-72.84-)-Memory-Usage%3A-13.9-MB
class Solution: def vertical1(self, data, ch): if data[0][0]==ch and data[1][0]==ch and data[2][0]==ch: return True return False def vertical3(self, data, ch): if data[0][2]==ch and data[1][2]==ch and data[2][2]==ch: return True return False def vertical2(self, data, ch): if data[0][1]==ch and data[1][1]==ch and data[2][1]==ch: return True return False def horizontal1(self, data, ch): if data[0][0]==ch and data[0][1]==ch and data[0][2]==ch: return True return False def horizontal2(self, data, ch): if data[1][0]==ch and data[1][1]==ch and data[1][2]==ch: return True return False def horizontal3(self, data, ch): if data[2][0]==ch and data[2][1]==ch and data[2][2]==ch: return True return False def diagonal1(self, data, ch): if data[0][0]==ch and data[1][1]==ch and data[2][2]==ch: return True return False def diagonal2(self, data, ch): if data[0][2]==ch and data[1][1]==ch and data[2][0]==ch: return True return False def check(self, cordinate, data, ch): if cordinate[0]==0 and cordinate[1]==0: if self.vertical1(data, ch) or self.horizontal1(data, ch) or self.diagonal1(data,ch): return True elif cordinate[0]==0 and cordinate[1]==1: if self.vertical2(data, ch) or self.horizontal1(data, ch): return True elif cordinate[0]==0 and cordinate[1]==2: if self.vertical3(data, ch) or self.horizontal1(data, ch) or self.diagonal2(data,ch): return True elif cordinate[0]==1 and cordinate[1]==0: if self.vertical1(data, ch) or self.horizontal2(data, ch): return True elif cordinate[0]==1 and cordinate[1]==1: if self.vertical2(data, ch) or self.horizontal2(data, ch) or self.diagonal1(data,ch) or self.diagonal2(data,ch): return True elif cordinate[0]==1 and cordinate[1]==2: if self.vertical3(data, ch) or self.horizontal2(data, ch): return True elif cordinate[0]==2 and cordinate[1]==0: if self.vertical1(data, ch) or self.horizontal3(data, ch) or self.diagonal2(data,ch): return True elif cordinate[0]==2 and cordinate[1]==1: if self.vertical2(data, ch) or self.horizontal3(data, ch): return True elif cordinate[0]==2 and cordinate[1]==2: if self.vertical3(data, ch) or self.horizontal3(data, ch) or self.diagonal1(data,ch): return True else: return False def tictactoe(self, moves: List[List[int]]) -> str: data = [ ["*"] * 3 for i1 in range(3) ] flag = True for cordinate in moves: if flag==True: data[cordinate[0]][cordinate[1]] = 'X' flag = False if self.check(cordinate, data, 'X'): return 'A' else: data[cordinate[0]][cordinate[1]] = 'O' flag = True if self.check(cordinate, data, 'O'): return 'B' return 'Draw' if len(moves)==9 else "Pending"
find-winner-on-a-tic-tac-toe-game
Python Solution based on Game simulation ( faster than 72.84% ) Memory Usage: 13.9 MB
hasan08sust
0
85
find winner on a tic tac toe game
1,275
0.543
Easy
18,935
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/552910/Python3-solution-using-a-transpose
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: board = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] for i in range(len(moves)): if i%2 == 0: player = 'A' else: player = 'B' board[moves[i][0]][moves[i][1]] = player transpose = [list(x) for x in zip(*board)] for num in range(3): if ''.join(board[num]) == player*3 \ or ''.join(transpose[num]) == player*3 \ or board[0][0]+board[1][1]+board[2][2] == player*3 \ or board[0][2]+board[1][1]+board[2][0] == player*3: return player if '-' not in board[0] and '-' not in board[1] and '-' not in board[2]: return 'Draw' return 'Pending'
find-winner-on-a-tic-tac-toe-game
Python3 solution using a transpose
altareen
0
111
find winner on a tic tac toe game
1,275
0.543
Easy
18,936
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/441445/Python3-solution-faster-than-100-using-less-memory-than-100-(as-of-1st-Dec-2019-%3AD)
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: class Score: def __init__(self): self.rows = [0 for i in range(3)] self.cols = [0 for i in range(3)] self.diag = 0 self.adiag = 0 A = Score() B = Score() for i, (x,y) in enumerate(moves): player = B if (i % 2) else A player.rows[x] += 1 player.cols[y] += 1 if (x == y): player.diag += 1 if (x + y == 2): player.adiag += 1 if 3 in A.rows or 3 in A.cols or A.diag == 3 or A.adiag == 3: return "A" if 3 in B.rows or 3 in B.cols or B.diag == 3 or B.adiag == 3: return "B" if len(moves) == 9: return "Draw" else: return "Pending"
find-winner-on-a-tic-tac-toe-game
Python3 solution faster than 100%, using less memory than 100% (as of 1st Dec 2019 :D)
akasprzak
0
110
find winner on a tic tac toe game
1,275
0.543
Easy
18,937
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/551868/Math-%2B-Python-Using-2-variables-linear-algebra-to-solve-the-problem
class Solution: def numOfBurgers(self, tomatoSlices, cheeseSlices): # on the basis of the matrix solution ans = [0.5 * tomatoSlices - cheeseSlices, -0.5 * tomatoSlices + 2 * cheeseSlices] # using the constraints to see if solution satisfies it if 0 <= int(ans[0]) == ans[0] and 0 <= int(ans[1]) == ans[1]: return [int(ans[0]), int(ans[1])] else: return []
number-of-burgers-with-no-waste-of-ingredients
[Math + Python] Using 2 variables linear algebra to solve the problem
Suraj1127
3
203
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,938
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/441667/Python-3-(one-line)-(beats-100)-(24-ms)-(With-Explanation)
class Solution: def numOfBurgers(self, T: int, C: int) -> List[int]: return [[T//2 - C, 2*C - T//2],[]][T % 2 or T < 2*C or 4*C < T] - Junaid Mansuri - Chicago, IL
number-of-burgers-with-no-waste-of-ingredients
Python 3 (one line) (beats 100%) (24 ms) (With Explanation)
junaidmansuri
2
139
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,939
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/2326286/Python-easy-understanding-beats-100.
class Solution(object): def numOfBurgers(self, t, c): if t==c==0: return [0,0] four=(t-2*c)//2 # no of jumbo burgers by solving 4x+2y=t and x+y=c two=c-four #number of small burgers if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or if number of jumbo burgers is a decimal or number of burgers are negtive we return empty list return [] return [four,two]
number-of-burgers-with-no-waste-of-ingredients
Python easy understanding beats 100%.
babashankarsn
0
29
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,940
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/2120256/python-3-oror-simple-O(1)-math-solution
class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: if tomatoSlices % 2: return [] jumbo = tomatoSlices // 2 - cheeseSlices if jumbo < 0 or cheeseSlices < jumbo: return [] return [jumbo, cheeseSlices - jumbo]
number-of-burgers-with-no-waste-of-ingredients
python 3 || simple O(1) math solution
dereky4
0
44
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,941
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/2072905/Python3-oror-Greedy-oror-readable-code-with-comments
class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: if tomatoSlices%2: return [] x=tomatoSlices//2 diff=x-cheeseSlices if diff<0: return [] if x-(2*diff)<0: return [] return [diff,x-(2*diff)] # Logic is if tomatoslice is odd, not any combination possible return [] # x is total no. of smallburgers possible # diff is difference in no. of cheeseSlices,it also represent no. of jumboburgers # if diff<0 , means even combinations of smallburgers can't fullfill all the slices # so return [] # return [diff,x-(2*diff)]
number-of-burgers-with-no-waste-of-ingredients
Python3 || Greedy || readable code with comments
Aniket_liar07
0
49
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,942
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/1391208/Easy-Python-Solution-(Faster-than-99)
class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: eq1, eq2 = 0, 0 a = tomatoSlices//2 x = a - cheeseSlices y = (2*cheeseSlices) - a if x >= 0 and y >= 0: eq1 = (4*x) + (2*y) eq2 = x + y if eq1 == tomatoSlices and eq2 == cheeseSlices: return [x,y] else: return []
number-of-burgers-with-no-waste-of-ingredients
Easy Python Solution (Faster than 99%)
the_sky_high
0
111
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,943
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/1210878/python-sol
class Solution: def numOfBurgers(self, tomato: int, cheese: int) -> List[int]: if (tomato-2*cheese)%2!=0: return [] x=(tomato-2*cheese)//2 y=cheese-x if x>=0 and y>=0: return [x,y] return []
number-of-burgers-with-no-waste-of-ingredients
python sol
heisenbarg
0
48
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,944
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/1055764/Python-Solution
class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: if tomatoSlices == 0 and cheeseSlices ==0: return [0,0] if tomatoSlices <= cheeseSlices: return [] prod1 = 2*cheeseSlices ans1 = tomatoSlices - prod1 x = 0 if ans1 % 2 ==0: x = ans1 // 2 if x >=0 and cheeseSlices-x >=0: return [x,cheeseSlices-x] return []
number-of-burgers-with-no-waste-of-ingredients
Python Solution
SaSha59
0
71
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,945
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/699715/Python3-chicken-and-rabbit-problem-Number-of-Burgers-with-No-Waste-of-Ingredients
class Solution: def numOfBurgers(self, t: int, c: int) -> List[int]: jumbo = (t - 2*c) // 2 small = c - jumbo if jumbo >= 0 and small >= 0 and jumbo*4 + small*2 == t and jumbo + small == c: return [jumbo, small] return []
number-of-burgers-with-no-waste-of-ingredients
Python3 chicken and rabbit problem - Number of Burgers with No Waste of Ingredients
r0bertz
0
97
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,946
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/448090/O(log-M)-where-M-is-cheese-slice-num-Binary-Search-20-Line-Python-3
class Solution: # O(log N) def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int): if tomatoSlices < cheeseSlices * 2: return [] if tomatoSlices == 0 and cheeseSlices == 0: return [0, 0] l, r = 0, cheeseSlices while l <= r: middle = l + (r - l) // 2 numOfJumbo = cheeseSlices - middle currTomatoSlices = middle * 2 + numOfJumbo * 4 if currTomatoSlices > tomatoSlices: l = middle + 1 elif currTomatoSlices < tomatoSlices: r = middle - 1 else: return [numOfJumbo, middle] return []
number-of-burgers-with-no-waste-of-ingredients
O(log M) where M is cheese slice num- Binary Search 20 Line - Python 3
ilkercankaya
0
89
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,947
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/441460/Python3-Linear-algebra
class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: if tomatoSlices &amp; 1 or not (2*cheeseSlices <= tomatoSlices <= 4*cheeseSlices): return [] return [(tomatoSlices - 2*cheeseSlices)//2, (4*cheeseSlices - tomatoSlices)//2]
number-of-burgers-with-no-waste-of-ingredients
[Python3] Linear algebra
ye15
0
101
number of burgers with no waste of ingredients
1,276
0.506
Medium
18,948
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1736397/Python-Thought-process-for-the-DP-solution-with-very-simple-explanation-(with-images)
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: count=matrix.count(1) count=0 for r in range(len(matrix)): for c in range(len(matrix[0])): if matrix[r][c]==1: count+=1 if r==0 or c==0: continue old_val=matrix[r][c] matrix[r][c]=min(matrix[r-1][c-1], matrix[r][c-1],matrix[r-1][c]) + 1 if matrix[r][c]==1 else 0 count= count+ matrix[r][c]- old_val return count
count-square-submatrices-with-all-ones
Python 🐍 Thought process for the DP solution with very simple explanation (with images)
InjySarhan
4
354
count square submatrices with all ones
1,277
0.744
Medium
18,949
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1179327/Python3-simple-solution-beats-80-users
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: count = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 1 and (i != 0 and j != 0): matrix[i][j] = min(matrix[i-1][j-1], matrix[i-1][j], matrix[i][j-1])+1 count += sum(matrix[i]) return count
count-square-submatrices-with-all-ones
Python3 simple solution beats 80% users
EklavyaJoshi
4
169
count square submatrices with all ones
1,277
0.744
Medium
18,950
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1183726/Python3-oror-DP-oror-Simple-Code-oror-98-Faster-oror
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: m=len(matrix) n=len(matrix[0]) for i in range(1,m): for j in range(1,n): if matrix[i][j]: matrix[i][j]=min(matrix[i-1][j],matrix[i][j-1],matrix[i-1][j-1])+1 res=0 for p in range(m): res+=sum(matrix[p]) return res
count-square-submatrices-with-all-ones
Python3 || DP || Simple Code || 98% Faster ||
abhi9Rai
2
329
count square submatrices with all ones
1,277
0.744
Medium
18,951
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1149133/Python3-DP-or-Easy-to-understand
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: m,n=len(matrix),len(matrix[0]) dp=[[0]*n for _ in range(m)] ans=0 for i in range(m): for j in range(n): if i==0 or j==0: dp[i][j]=matrix[i][j] else: if matrix[i][j]: dp[i][j]=1+min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]) ans+=dp[i][j] return ans
count-square-submatrices-with-all-ones
[Python3] DP | Easy to understand
_vaishalijain
2
321
count square submatrices with all ones
1,277
0.744
Medium
18,952
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/441696/Python-3-(w-and-wo-DP)-(two-lines)
class Solution: def countSquares(self, G: List[List[int]]) -> int: M, N, t = len(G), len(G[0]), 0; H = [[0]*(N+1) for _ in range(M+1)] for i in range(M): c = 0 for j in range(N): c += G[i][j]; H[i+1][j+1] = H[i][j+1] + c for k in range(1, 1 + min(i,j)): if H[i+1][j+1] - H[i-k][j+1] - H[i+1][j-k] + H[i-k][j-k] == (k+1)**2: t += 1 else: break return t + sum(map(sum,G))
count-square-submatrices-with-all-ones
Python 3 (w/ and w/o DP) (two lines)
junaidmansuri
2
387
count square submatrices with all ones
1,277
0.744
Medium
18,953
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/441696/Python-3-(w-and-wo-DP)-(two-lines)
class Solution: def countSquares(self, G: List[List[int]]) -> int: for i,j in itertools.product(range(1,len(G)),range(1,len(G[0]))): G[i][j] = G[i][j] and 1 + min(G[i-1][j], G[i][j-1], G[i-1][j-1]) return sum(map(sum,G)) - Junaid Mansuri - Chicago, IL
count-square-submatrices-with-all-ones
Python 3 (w/ and w/o DP) (two lines)
junaidmansuri
2
387
count square submatrices with all ones
1,277
0.744
Medium
18,954
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/2519879/Py-or-Easy-solution-or-Best-Approch
class Solution: def countSquares(self, arr: List[List[int]]) -> int: n=len(arr) m=len(arr[0]) dp=[[0 for i in range(m)]for j in range(n)] for i in range(n): dp[i][0]=arr[i][0] for j in range(m): dp[0][j]=arr[0][j] for i in range(1,n): for j in range(1,m): if arr[i][j]==1: dp[i][j]= 1+min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1]) else: dp[i][j]=0 ans=0 for i in range(n): ans+=sum(dp[i]) return ans
count-square-submatrices-with-all-ones
Py | Easy solution | Best Approch 💯 ✅
adarshg04
1
64
count square submatrices with all ones
1,277
0.744
Medium
18,955
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/2059294/Python-or-DP
class Solution: def countSquares(self, mat: List[List[int]]) -> int: ans = [[0 for i in range(len(mat[0]))]for j in range(len(mat))] t = 0 for i in range(len(mat)): for j in range(len(mat[0])): if mat[i][j] == 1: if i==0 or j==0: ans[i][j] = 1 else: t2 = min(ans[i-1][j],ans[i][j-1],ans[i-1][j-1]) ans[i][j] = 1+t2 t += ans[i][j] return t
count-square-submatrices-with-all-ones
Python | DP
Shivamk09
1
198
count square submatrices with all ones
1,277
0.744
Medium
18,956
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1367928/Python-Clean-DP-or-94.76-faster
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: M, N = len(matrix), len(matrix[0]) count = sum(matrix[-1]) + sum(matrix[row][-1] for row in range(M-1)) for r in range(M-2, -1, -1): for c in range(N-2, -1, -1): if matrix[r][c] == 1: matrix[r][c] = 1 + min(matrix[r][c+1], matrix[r+1][c], matrix[r+1][c+1]) count += matrix[r][c] return count
count-square-submatrices-with-all-ones
[Python] Clean DP | 94.76% faster
soma28
1
185
count square submatrices with all ones
1,277
0.744
Medium
18,957
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/441557/Python3-DP-solution
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: ans = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if i > 0 and j > 0 and matrix[i][j]: matrix[i][j] = min(matrix[i-1][j], matrix[i-1][j-1], matrix[i][j-1]) + 1 ans += matrix[i][j] return ans
count-square-submatrices-with-all-ones
[Python3] DP solution
ye15
1
113
count square submatrices with all ones
1,277
0.744
Medium
18,958
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/441537/Python-easy-understand-explain
class Solution: def countSquares(self, matrix: List[List[int]], rc = None, cc = None) -> int: """ :type matrix: List[List[int]] :rtype: int """ # Main logic: # It just like board game "Gigamic Pylos" # We can use 4 index nearby to check a next round possible # Let's make an example: # ################################################# # # [side 1] [side 2] [side 3] # # # 0 1 1 1 0 1 1 1 # # # 0 1 1 0 1 1 0 1 1 # # # 1 1 1 1 => 1 1 1 1 => => 0 1 => 0 1 # # # 0 1 1 0 1 1 0 1 1 # # # 0 1 1 1 0 1 1 1 # # ################################################# # RC and CC: # In order not keep call len(), we can pass lenth by ourselves # * rc for row_count # * cc for col_count # Shortcut: # Though size are restricted in 300 # It still have big possible to run out of time # If we found that at a specific side size count < 4, # there is no possible for next or further round. # Which means we can stop here # First input setting if not rc: rc = len(matrix) cc = len(matrix[0]) return self.countSquares(matrix, rc, cc) \ + sum(sum(row) for row in matrix) # End point if rc == 1 or cc == 1: return 0 # Create place for side n and Search it next_matrix, case_in_this_side = [], 0 for r in range(rc-1): new_row = [matrix[r][c] &amp; matrix[r][c+1] &amp; matrix[r+1][c] &amp; matrix[r+1][c+1] for c in range(cc-1)] next_matrix.append(new_row) case_in_this_side += sum(new_row) # Recursive search # Make a little short cut here if case_in_this_side >= 4: return self.countSquares(next_matrix, rc-1, cc-1) + case_in_this_side else: return case_in_this_side
count-square-submatrices-with-all-ones
Python, easy understand, explain
Chumicat
1
368
count square submatrices with all ones
1,277
0.744
Medium
18,959
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/2779118/Python-(Simple-Dynamic-Programming)
class Solution: def countSquares(self, A): n, m = len(A), len(A[0]) dp = [[0 for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if i>0 and j>0: if A[i-1][j] == A[i][j-1] == A[i-1][j-1] == A[i][j] == 1: dp[i][j] = 1 + min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) else: dp[i][j] = A[i][j] else: dp[i][j] = A[i][j] return sum([sum(i) for i in dp])
count-square-submatrices-with-all-ones
Python (Simple Dynamic Programming)
rnotappl
0
9
count square submatrices with all ones
1,277
0.744
Medium
18,960
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/2639753/Python-Simple-Solution
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: #First row count=sum(matrix[0]) #First column for i in range(1,len(matrix)): count+=matrix[i][0] #Square for i in range(1,len(matrix)): for j in range(1,len(matrix[0])): #All ones are required for forming a Square if matrix[i][j] == 0: continue ''' [[0,1,1,1] ,[1,1,1,1] ,[0,1,1,1]] -> Eg i,j at (1,2) Earlier matrix[i][j]=1 matrix[i][j]=min(matrix[i-1][j],matrix[i][j-1],matrix[i-1][j-1])+1 We add + 1 because if earlier the size of square was 1 * 1. It can be now 2*2 and so on. min((0,2),(1,1),(0,1))+1=1+1=2 [[1,1] [1,2]] Now (1,2) =2 0 1 2 3 [0[0, 1, 1, 1], 1[1, 1, 2, 2], 2[0, 1, 2, 3]] these 1,2,3 are denoting the size of square. [1, 1, 1], [ 1, 2, 2], [ 1, 2, 3]] 3 denotes -> 1 sqaure of 3*3 1s ''' #Take minimum from top,before,top left matrix[i][j]=min(matrix[i-1][j],matrix[i][j-1],matrix[i-1][j-1])+1 #Increment count+=matrix[i][j] return count
count-square-submatrices-with-all-ones
Python Simple Solution
beingab329
0
16
count square submatrices with all ones
1,277
0.744
Medium
18,961
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1903122/One-pass-and-O(1)-space-DP-in-Python
class Solution: def countSquares(self, M: List[List[int]]) -> int: ans, m, n = 0, len(M), len(M[0]) from itertools import product for i, j in product(range(m), range(n)): if i > 0 and j > 0: if M[i - 1][j] and M[i][j - 1] and M[i - 1][j - 1] and M[i][j]: M[i][j] += min(M[i - 1][j], M[i][j - 1], M[i - 1][j - 1]) ans += M[i][j] return ans
count-square-submatrices-with-all-ones
One-pass and O(1)-space DP in Python
mousun224
0
193
count square submatrices with all ones
1,277
0.744
Medium
18,962
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1722718/Simple-python-easy-to-understand
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: def helper(i,j,r_mac,c_mac,mat,level=0): if i+level+1> r_mac or j+level+1>c_mac: return 0 sqr = True total = 0 for m in range(i,i+level+1): for n in range(j,j+level+1): if mat[m][n] == 0: sqr = False return 0 total += 1 total += helper(i,j,r_mac,c_mac,mat,level+1) return total _total = 0 _r = len(matrix) _c = len(matrix[0]) for _i in range(_r): for _j in range(_c): _total+=helper(_i,_j,_r,_c,matrix,0) return _total
count-square-submatrices-with-all-ones
Simple python easy to understand
jasonjfk
0
94
count square submatrices with all ones
1,277
0.744
Medium
18,963
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/841131/Easy-Better-than-99.5-Dp-solution
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: n = len(matrix) m = len(matrix[0]) if n<2 or m<2: return matrix.count(1) dp = [[0]*m for _ in range(n)] sum = 0 for i in range(n): if i==0: for j in range(m): dp[i][j] = matrix[i][j] sum+=dp[i][j] continue for j in range(1): dp[i][j] = matrix[i][j] sum+=dp[i][j] for i in range(1,n): for j in range(1,m): if matrix[i][j]==0: continue if matrix[i-1][j] and matrix[i-1][j-1] and matrix[i][j-1]: dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1 else: dp[i][j]=matrix[i][j] sum+=dp[i][j] return sum
count-square-submatrices-with-all-ones
Easy Better than 99.5% Dp solution
oossiiris
0
391
count square submatrices with all ones
1,277
0.744
Medium
18,964
https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/644948/Simple-Intuitive-Python-DP-Solution-O(n)-Time-and-Space
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: total = 0 dp = [[0] * len(row) for row in matrix] for i, row in enumerate(matrix): for j, num in enumerate(row): if not num: continue upper = 0 if i-1 >= 0: upper = dp[i-1][j] left = 0 if j-1 >= 0: left = dp[i][j-1] diag = 0 if i-1 >= 0 and j-1 >= 0: # Can this be made less redundant? diag = dp[i-1][j-1] dp[i][j] = min(upper, left, diag) + 1 total += dp[i][j] return total
count-square-submatrices-with-all-ones
Simple, Intuitive Python DP Solution - O(n) Time and Space
schedutron
0
147
count square submatrices with all ones
1,277
0.744
Medium
18,965
https://leetcode.com/problems/palindrome-partitioning-iii/discuss/2593400/Dynamic-Programming-oror-Recursion-oror-Memoization-oror-Easy-Intuition-oror-Python
class Solution: def palindromePartition(self, s: str, k: int) -> int: #This is the cost function def Cost(s): i,j,c=0,len(s)-1,0 while i<j: if s[i]!=s[j]:c+=1 j-=1 i+=1 return c dp={} # Recursion def A(s,k): # Memoization if (s,k) in dp: return dp[(s,k)] # if k==1 then we want the whole string there is no other way if k==1: return Cost(s) #intial value to max f=float('inf') #start checking whole string for x in range(1,len(s)+1): #check wheather if both the strings exist. if len(s[:x]) and len(s[x:]): #if exist we find the cost recursively assign min value f=min(f,Cost(s[:x])+A(s[x:],k-1)) #store the min value dp[(s,k)]=f return dp[(s,k)] return A(s,k) ```
palindrome-partitioning-iii
Dynamic Programming || Recursion || Memoization || Easy Intuition || Python
srikarsai550
2
70
palindrome partitioning iii
1,278
0.608
Hard
18,966
https://leetcode.com/problems/palindrome-partitioning-iii/discuss/2814529/Python3-Solution-or-DP
class Solution: def palindromePartition(self, S, K): N = len(S) dp = [[N] * (N + 1) for _ in range(K + 1)] dp[0][0] = 0 for i in range(2 * N - 1): c = 0 l = i // 2 r = l + (i &amp; 1) while 0 <= l and r < N: if S[l] != S[r]: c += 1 for i in range(K): dp[i + 1][r + 1] = min(dp[i + 1][r + 1], dp[i][l] + c) l -= 1 r += 1 return dp[-1][-1]
palindrome-partitioning-iii
✔ Python3 Solution | DP
satyam2001
0
5
palindrome partitioning iii
1,278
0.608
Hard
18,967
https://leetcode.com/problems/palindrome-partitioning-iii/discuss/2803724/Python3-or-Recursive-Dp-Approach
class Solution: def palindromePartition(self, s: str, k: int) -> int: n = len(s) def costToMakePalindrome(left,right): change = 0 while left<=right: if s[left]!=s[right]: change+=1 left+=1 right-=1 return change @cache def dp(ind,partition): if ind == n: if partition == 0: return 0 else: return math.inf if partition == 0: return math.inf res = math.inf for i in range(ind,n-partition+1): res = min(res,dp(i+1,partition - 1) + costToMakePalindrome(ind,i)) return res return dp(0,k)
palindrome-partitioning-iii
[Python3] | Recursive Dp Approach
swapnilsingh421
0
6
palindrome partitioning iii
1,278
0.608
Hard
18,968
https://leetcode.com/problems/palindrome-partitioning-iii/discuss/2333666/Python3-or-O(n2-*-k)-or-DP-or-pre-computing-cost-matrix
class Solution: def palindromePartition(self, s: str, k: int) -> int: n = len(s) def getChanges(i, j): ret = 0 while i < j: if s[i] != s[j]: ret += 1 i += 1 j -= 1 return ret cost = [[getChanges(i, j) for j in range(n)] for i in range(n)] @cache def res(l = 0, r = 0, k = k): if l == len(s) and r == len(s) and k == 0: return 0 elif r == len(s) or k <= 0: return math.inf else: return min(cost[l][r] + res(r + 1, r + 1, k - 1), res(l, r +1, k)) return res()
palindrome-partitioning-iii
Python3 | O(n^2 * k) | DP | pre-computing cost matrix
DheerajGadwala
0
27
palindrome partitioning iii
1,278
0.608
Hard
18,969
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1713663/Python-3-(20ms)-or-3-Solutions-or-Fastest-Iterative-and-One-Liners-or-Super-Easy
class Solution: def subtractProductAndSum(self, n: int) -> int: p,s=1,0 while n!=0: p*=(n%10) s+=(n%10) n//=10 return p-s
subtract-the-product-and-sum-of-digits-of-an-integer
Python 3 (20ms) | 3 Solutions | Fastest Iterative & One-Liners | Super Easy
MrShobhit
12
659
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,970
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1713663/Python-3-(20ms)-or-3-Solutions-or-Fastest-Iterative-and-One-Liners-or-Super-Easy
class Solution: def subtractProductAndSum(self, n: int) -> int: return prod(list(map(int, str(n))))-sum(list(map(int, str(n))))
subtract-the-product-and-sum-of-digits-of-an-integer
Python 3 (20ms) | 3 Solutions | Fastest Iterative & One-Liners | Super Easy
MrShobhit
12
659
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,971
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1713663/Python-3-(20ms)-or-3-Solutions-or-Fastest-Iterative-and-One-Liners-or-Super-Easy
class Solution: def subtractProductAndSum(self, n: int) -> int: arr = list(map(int, str(n))) return prod(arr)-sum(arr)
subtract-the-product-and-sum-of-digits-of-an-integer
Python 3 (20ms) | 3 Solutions | Fastest Iterative & One-Liners | Super Easy
MrShobhit
12
659
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,972
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1713663/Python-3-(20ms)-or-3-Solutions-or-Fastest-Iterative-and-One-Liners-or-Super-Easy
class Solution: def subtractProductAndSum(self, n: int) -> int: arr = list(map(int, str(n))) return reduce(operator.mul, arr) - sum(arr)
subtract-the-product-and-sum-of-digits-of-an-integer
Python 3 (20ms) | 3 Solutions | Fastest Iterative & One-Liners | Super Easy
MrShobhit
12
659
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,973
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2215978/Python3-simple-solution-one-pass-using-divMod
class Solution: def subtractProductAndSum(self, n: int) -> int: plus = 0 product = 1 n = str(n) for i in n: plus = plus + int(i) product = product * int(i) return product - plus
subtract-the-product-and-sum-of-digits-of-an-integer
📌 Python3 simple solution one pass using divMod
Dark_wolf_jss
6
143
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,974
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1752896/1281-Product-sum-of-an-int
class Solution(object): def subtractProductAndSum(self, n): sumOfInts = 0 productOfInts = 1 while(n>0): remainder1 = n % 10 sumOfInts += remainder1 productOfInts *= remainder1 n -= remainder1 n /= 10 return productOfInts - sumOfInts
subtract-the-product-and-sum-of-digits-of-an-integer
1281 Product - sum of an int
ankit61d
4
211
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,975
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1930463/Python-One-Liner!
class Solution: def subtractProductAndSum(self, n): def prod(arr): return reduce(lambda a,b: a * b, arr) x = [int(i) for i in str(n)] return prod(x) - sum(x)
subtract-the-product-and-sum-of-digits-of-an-integer
Python - One Liner!
domthedeveloper
3
234
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,976
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1930463/Python-One-Liner!
class Solution: def subtractProductAndSum(self, n): x = [int(i) for i in str(n)] return prod(x) - sum(x)
subtract-the-product-and-sum-of-digits-of-an-integer
Python - One Liner!
domthedeveloper
3
234
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,977
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1930463/Python-One-Liner!
class Solution: def subtractProductAndSum(self, n): return prod(x := [int(i) for i in str(n)]) - sum(x)
subtract-the-product-and-sum-of-digits-of-an-integer
Python - One Liner!
domthedeveloper
3
234
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,978
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1699640/Python3-oror-easy-to-understand-code-oror-faster-than-100-%2B-one-liner
class Solution: def subtractProductAndSum(self, n: int) -> int: a,b=1,0 for i in list(str(n)): a*=int(i) b+=int(i) return (a-b)
subtract-the-product-and-sum-of-digits-of-an-integer
✔ Python3 || easy to understand code || faster than 100% + one liner
Anilchouhan181
3
168
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,979
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1699640/Python3-oror-easy-to-understand-code-oror-faster-than-100-%2B-one-liner
class Solution: def subtractProductAndSum(self, n: int) -> int: return prod(list(map(int,str(n))))-sum(list(map(int,str(n))))
subtract-the-product-and-sum-of-digits-of-an-integer
✔ Python3 || easy to understand code || faster than 100% + one liner
Anilchouhan181
3
168
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,980
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1203246/Much-simple-and-readable.
class Solution: def subtractProductAndSum(self, n: int) -> int: mult,add=1,0 for i in str(n): mult*=int(i) add+=int(i) return mult-add
subtract-the-product-and-sum-of-digits-of-an-integer
Much simple and readable.
_jorjis
3
141
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,981
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/446430/Python-3-(one-line)-(beats-100)
class Solution: def subtractProductAndSum(self, n: int) -> int: s, p = 0, 1 for i in str(n): s += int(i); p *= int(i) return p - s
subtract-the-product-and-sum-of-digits-of-an-integer
Python 3 (one line) (beats 100%)
junaidmansuri
3
858
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,982
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2598758/Python-very-short-solution
class Solution: def subtractProductAndSum(self, n: int) -> int: p, s = 1, 0 while n: n, digit = divmod(n, 10) p, s = p * digit, s + digit return p - s
subtract-the-product-and-sum-of-digits-of-an-integer
Python very short solution
Mark_computer
1
114
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,983
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2574747/Python-easy-solution
class Solution: def subtractProductAndSum(self, n: int) -> int: pdt = 1 sm = 0 while(n>0): d = n%10 pdt *= d sm += d n //=10 return pdt-sm
subtract-the-product-and-sum-of-digits-of-an-integer
Python easy solution
Jack_Chang
1
65
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,984
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2471326/Python3-Easy-solution-with-type-casting
class Solution: def subtractProductAndSum(self, n: int) -> int: n = str(n) sum_n =0 product = 1 for i in n: i = int(i) product = product*i sum_n += i res = product - sum_n return res
subtract-the-product-and-sum-of-digits-of-an-integer
Python3 Easy solution with type casting
prakashpandit
1
14
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,985
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2231889/Easiest-Solution
class Solution: def subtractProductAndSum(self, n: int) -> int: arr = [] while n: arr.append(n%10) n = n // 10 sum = 0 prod = 1 for i in arr: sum += i prod *= i return prod-sum
subtract-the-product-and-sum-of-digits-of-an-integer
Easiest Solution
EbrahimMG
1
44
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,986
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2145222/Python3-or-O(log-n)-or-Easy-math-logic
class Solution: def subtractProductAndSum(self, n: int) -> int: product = 1 total = 0 while n: product*=(n%10) total+=(n%10) n//=10 return product-total
subtract-the-product-and-sum-of-digits-of-an-integer
Python3 | O(log n) | Easy math logic
theKshah
1
93
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,987
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2136059/Easy-and-simple-Python-Solution
class Solution: def subtractProductAndSum(self, n: int) -> int: a=[] sum=0 prdt=1 while(n!=0): a.append(n%10) n=n//10 for i in range(0,len(a)): sum=sum+a[i] prdt=prdt*a[i] return prdt-sum
subtract-the-product-and-sum-of-digits-of-an-integer
Easy and simple - Python Solution
pruthashouche
1
88
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,988
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2100593/Very-easy-python-solution-with-stepwise-explaination
class Solution: def subtractProductAndSum(self, n: int) -> int: prod = 1 #initializing prod with 1 sum1 = 0 # Initializing sum1 with 0 # Initializing temp with the number so that if we want to check the original number we can directly check the temp value temp = n while(n>0): #Looping till the number becomes 0 digit = n%10 # Extracting the last digit from the number # Adding that digit to sum, overall at last it will give the sum of all digits present in the number sum1+=digit # Multiplying that digit to prod, overall at last it will give the prod of all the digits in the number prod*=digit n=n//10 # in every loop we are eliminating the last digit of the number res = prod-sum1 # Now the result will be product - sum of all the number return res # Now we can return the result
subtract-the-product-and-sum-of-digits-of-an-integer
Very easy python solution with stepwise explaination
yashkumarjha
1
62
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,989
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2099164/PYTHON-or-Simple-python-solution
class Solution: def subtractProductAndSum(self, n: int) -> int: n = str(n) s = 0 product = 1 for i in n: s += int(i) product *= int(i) return product - s
subtract-the-product-and-sum-of-digits-of-an-integer
PYTHON | Simple python solution
shreeruparel
1
143
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,990
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/2009289/PYTHON-oror-WITHOUT-RECURSION-oror-BEGINNER-FRIENDLY-oror-EASY-UNDERSTANDING
class Solution: def subtractProductAndSum(self, n: int) -> int: p = 1 s = 0 n = str(n) for i in n: p = p * (int(i)) for i in n: s = s + (int(i)) return p - s ```
subtract-the-product-and-sum-of-digits-of-an-integer
PYTHON || WITHOUT RECURSION || BEGINNER FRIENDLY || EASY UNDERSTANDING
Airodragon
1
49
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,991
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1998770/Easy-Python-Solution-Without-Using-Strings-oror-Better-Runtime-and-Memory
class Solution: def subtractProductAndSum(self, n: int) -> int: num, pro, sum_ = 0, 1, 0 while n!=0: num, n = n%10, n//10 pro*=num sum_ +=num return pro-sum_
subtract-the-product-and-sum-of-digits-of-an-integer
Easy Python Solution Without Using Strings || Better Runtime and Memory
YungMoMoney
1
81
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,992
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1897912/Python-solution-with-generator-expression-(instead-of-list-comprehension)
class Solution: def subtractProductAndSum(self, n: int) -> int: generator_expression = (int(digit) for digit in str(n)) prod_result = 1 sum_result = 0 for digit in generator_expression: prod_result *= digit sum_result += digit return prod_result - sum_result
subtract-the-product-and-sum-of-digits-of-an-integer
Python solution with generator expression (instead of list comprehension)
dashaternovskaya
1
29
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,993
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1826511/Python3-solution-(-and-operators)-with-comments
class Solution: def subtractProductAndSum(self, n: int) -> int: suma = 0 # keeps track of the sum product = 1 # keeps track of the products while n != 0: numero = n%10 # gets a digit e.g. 4 out of 234. suma += numero # adds the digit e.g. 4 product *= numero # product times digit n -= numero # substracts the digit from the number this could be omited if // operator is used instead of /. n //=10 # divides n by 10 so it reduces the quantity of digits by one e.g from 234 to 23 return product - suma
subtract-the-product-and-sum-of-digits-of-an-integer
Python3 solution (% and // operators) with comments
nanicp2202
1
41
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,994
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1339738/Simple-Python-Solution-for-%22Subtract-the-Product-and-Sum-of-Digits-of-an-Integer%22
class Solution: def subtractProductAndSum(self, n: int) -> int: s = digit = 0 product = 1 while(n>0): digit = n%10 s = s + digit product = product * digit n = n//10 return product-s
subtract-the-product-and-sum-of-digits-of-an-integer
Simple Python Solution for "Subtract the Product and Sum of Digits of an Integer"
sakshikhandare2527
1
151
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,995
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/1129910/Python-easy-divmod-solution
class Solution: def subtractProductAndSum(self, n: int) -> int: total = 0 product = 1 while n: n, remainder = divmod(n, 10) total += remainder product *= remainder return product - total
subtract-the-product-and-sum-of-digits-of-an-integer
Python easy divmod solution
alexanco
1
219
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,996
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/999822/Python-o(n)-or-3-Methods-or-Efficient-solution
class Solution: def subtractProductAndSum(self, n: int) -> int: product = 1 sums = 0 while n: temp = n%10 n//=10 product*=temp sums+=temp return product-sums
subtract-the-product-and-sum-of-digits-of-an-integer
Python o(n) | 3 Methods | Efficient solution
hritik5102
1
131
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,997
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/999822/Python-o(n)-or-3-Methods-or-Efficient-solution
class Solution: def subtractProductAndSum(self, n: int) -> int: product=1 sums = 0 for i in str(n): product*=int(i) sums += int(i) return product-sums
subtract-the-product-and-sum-of-digits-of-an-integer
Python o(n) | 3 Methods | Efficient solution
hritik5102
1
131
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,998
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/discuss/489790/Python3-99.9-faster-16ms-Simple-and-straight-forward
class Solution: def subtractProductAndSum(self, n: int) -> int: produc_sum = 1 sum_digit = 0 while n != 0: t = n % 10 n = n // 10 produc_sum = produc_sum * t sum_digit += t return produc_sum - sum_digit
subtract-the-product-and-sum-of-digits-of-an-integer
Python3 99.9% faster 16ms - Simple and straight forward
Dmx2
1
169
subtract the product and sum of digits of an integer
1,281
0.867
Easy
18,999