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/univalued-binary-tree/discuss/1373585/1-line-recursion-in-Python
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: return all(c.val == root.val and self.isUnivalTree(c) for c in (root.left, root.right) if c)
univalued-binary-tree
1-line recursion in Python
mousun224
0
60
univalued binary tree
965
0.693
Easy
15,600
https://leetcode.com/problems/univalued-binary-tree/discuss/1070218/Elegant-Python-DFS-and-Recursion-Solutions
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: if not root: return val = root.val self.flag = True def dfs(node): if node: if node.val != val: self.flag = False return else: dfs(node.left) dfs(node.right) dfs(root) return self.flag
univalued-binary-tree
Elegant Python DFS & Recursion Solutions
111989
0
57
univalued binary tree
965
0.693
Easy
15,601
https://leetcode.com/problems/univalued-binary-tree/discuss/1070218/Elegant-Python-DFS-and-Recursion-Solutions
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: if not root: return def isValidTree(node, val = root.val): if not node: return True if node.val != val: return False return isValidTree(node.left, val) and isValidTree(node.right, val) return isValidTree(root)
univalued-binary-tree
Elegant Python DFS & Recursion Solutions
111989
0
57
univalued binary tree
965
0.693
Easy
15,602
https://leetcode.com/problems/univalued-binary-tree/discuss/1011884/BFS-iterative
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: queue = [root] while len(queue) > 0: current = queue.pop(0) if current.val != root.val: return False if current.left: queue.append(current.left) if current.right: queue.append(current.right) return True
univalued-binary-tree
BFS iterative
borodayev
0
29
univalued binary tree
965
0.693
Easy
15,603
https://leetcode.com/problems/univalued-binary-tree/discuss/621076/Python-3.-Univalued-Binary-Tree.-Very-Easy.-beats-95
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: # Traverse through the tree, store and use set. res = [] def traverse(root): if not root: return None traverse(root.left) res.append(root.val) traverse(root.right) traverse(root) if len(list(set(res))) == 1: return 1 else:return 0
univalued-binary-tree
[Python 3]. Univalued Binary Tree. Very-Easy. beats 95%
tilak_
0
38
univalued binary tree
965
0.693
Easy
15,604
https://leetcode.com/problems/univalued-binary-tree/discuss/600507/DFS-Python.-3
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: if root is None: return root c = self.dfs(root, None) return c def dfs(self, root, prev): if root: if prev is not None and root.val != prev: return False else: prev = root.val return self.dfs(root.left, prev) and self.dfs(root.right, prev) else: return True
univalued-binary-tree
DFS Python. 3
yadavalli
0
34
univalued binary tree
965
0.693
Easy
15,605
https://leetcode.com/problems/univalued-binary-tree/discuss/521907/Python-or-98-Faster-or-100-less-memory
class Solution: def Util(self, node, value): if not node: return True if node.val != value: return False return self.Util(node.left, value) and self.Util(node.right, value) def isUnivalTree(self, root: TreeNode) -> bool: return self.Util(root, root.val)
univalued-binary-tree
Python | 98% Faster | 100% less memory
Adeel_Syed
0
55
univalued binary tree
965
0.693
Easy
15,606
https://leetcode.com/problems/univalued-binary-tree/discuss/472005/Why-this-code-gives-wrong-answer
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: if root is None: return True self.cons=root.val def dfs(node): if node: if node.val!=self.cons: return False dfs(node.left) dfs(node.right) dfs(root) return True
univalued-binary-tree
Why this code gives wrong answer?
Golnoush123
0
32
univalued binary tree
965
0.693
Easy
15,607
https://leetcode.com/problems/vowel-spellchecker/discuss/1121773/Python-One-Case-At-A-Time
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: # Convert words and vowels to sets for O(1) lookup times words = set(wordlist) vowels = set('aeiouAEIOU') # Create two maps. # One for case insensitive word to all words that match "key" -> ["Key", "kEy", "KEY"] # The other for vowel insensitive words "k*t*" -> ["Kite", "kato", "KUTA"] case_insensitive = collections.defaultdict(list) vowel_insensitive = collections.defaultdict(list) for word in wordlist: case_insensitive[word.lower()].append(word) key = ''.join(char.lower() if char not in vowels else '*' for char in word) vowel_insensitive[key].append(word) res = [] for word in queries: # Case 1: When query exactly matches a word if word in words: res.append(word) continue # Case 2: When query matches a word up to capitalization low = word.lower() if low in case_insensitive: res.append(case_insensitive[low][0]) continue # Case 3: When query matches a word up to vowel errors key = ''.join(char.lower() if char not in vowels else '*' for char in word) if key in vowel_insensitive: res.append(vowel_insensitive[key][0]) continue res.append('') return res
vowel-spellchecker
[Python] One Case At A Time
rowe1227
5
288
vowel spellchecker
966
0.514
Medium
15,608
https://leetcode.com/problems/vowel-spellchecker/discuss/981316/Python3-3-hash-tables
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: orig = set(wordlist) # original words O(1) lookup case = {} # diff in case vowel = {} # diff in vowel for word in wordlist: key = word.lower() case.setdefault(key, []).append(word) for c in "aeiou": key = key.replace(c, "*") vowel.setdefault(key, []).append(word) ans = [] for word in queries: if word in orig: ans.append(word) else: key = word.lower() if key in case: ans.append(case[key][0]) else: for c in "aeiou": key = key.replace(c, "*") if key in vowel: ans.append(vowel[key][0]) else: ans.append("") return ans
vowel-spellchecker
[Python3] 3 hash tables
ye15
1
142
vowel spellchecker
966
0.514
Medium
15,609
https://leetcode.com/problems/vowel-spellchecker/discuss/838793/Python-3-or-Hash-Table-%2B-Wild-card-or-Explanations
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: low_origin, wild_origin = collections.defaultdict(str), collections.defaultdict(str) s = set(wordlist) def to_wild(word): return ''.join(['*' if c in 'aeiou' else c for c in word]) for word in wordlist: low = word.lower() if low not in low_origin: low_origin[low] = word wild = to_wild(low) if wild not in wild_origin: wild_origin[wild] = word ans = [] for query in queries: low = query.lower() wild = to_wild(low) if query in s: ans.append(query) elif low in low_origin: ans.append(low_origin[low]) elif wild in wild_origin: ans.append(wild_origin[wild]) else: ans.append('') return ans
vowel-spellchecker
Python 3 | Hash Table + Wild card | Explanations
idontknoooo
1
193
vowel spellchecker
966
0.514
Medium
15,610
https://leetcode.com/problems/vowel-spellchecker/discuss/2814626/Python3-Readable-and-Commented-Hashmap-Solution
class Solution: # a static vowel set so we don't initialize it with every quer vowel_set = set(('a', 'e', 'i', 'o', 'u')) def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: # keep a set of all variations in their original form for fast lookup wordset = set(wordlist) # put all the words into the wordlist (lowercase) and lowercase without vowels # we will use these dicts to check for the capitalization errors and vowel errors # which are both cas insensitive (so lower both) # # also we only keep the first occurencce to match the precedence rules worddict = dict() wrddct = dict() for idx, word in enumerate(wordlist): lowered = word.lower() devoweled = self.devowel(lowered) if lowered not in worddict: worddict[lowered] = word if devoweled not in wrddct: wrddct[devoweled] = word # go through each of the queries and check the rules result = [] for query in queries: # check if it is in the original wordlist # append the word and continue with the next query if query in wordset: result.append(query) continue # check if the word only has capitalization error # append the corrected one and continue with the next query lowered = query.lower() if lowered in worddict: result.append(worddict[lowered]) continue # check if the word has vowel errors, append it to the result # and go to the next query devoweled = self.devowel(lowered) if devoweled in wrddct: result.append(wrddct[devoweled]) continue # no case matched (all quard clauses have been passed) result.append("") return result def devowel(self, word): # replace vowels with unused placeholder return "".join(char if char not in self.vowel_set else "_" for char in word)
vowel-spellchecker
[Python3] - Readable and Commented Hashmap Solution
Lucew
0
1
vowel spellchecker
966
0.514
Medium
15,611
https://leetcode.com/problems/vowel-spellchecker/discuss/1925880/PYTHON-SOL-oror-SIMPLE-oror-EASY-CODE-oror-HASHTABLE-oror
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: n = len(wordlist) d = {} sd = {} vd = {} cd = {} for i in range(n): d[wordlist[i]] = i s = wordlist[i].lower() if s not in sd:sd[s] = i m = len(wordlist[i]) tmp = [] emp = "" for j in range(m): if wordlist[i][j] in 'aeiouAEIOU': tmp.append(j) else:emp+=wordlist[i][j].lower() cd[i] = emp vd[i] = tmp ans = [] for word in queries: word_lower = word.lower() if word in d: ans.append(word) continue elif word_lower in sd: ans.append(wordlist[sd[word_lower]]) continue else: vow_word = [] con_word = "" m = len(word) for i in range(m): if word[i] in 'aeiouAEIOU' : vow_word.append(i) else: con_word += word[i].lower() if vow_word == []: ans.append("") continue flag = False for i in range(n): vow_tmp = vd[i] con_tmp = cd[i] if vow_tmp == vow_word and con_tmp == con_word: ans.append(wordlist[i]) flag = True break if flag == True:continue ans.append("") return ans
vowel-spellchecker
PYTHON SOL || SIMPLE || EASY CODE || HASHTABLE ||
reaper_27
0
63
vowel spellchecker
966
0.514
Medium
15,612
https://leetcode.com/problems/vowel-spellchecker/discuss/1420676/Dictionary-of-words-100-speed
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: set_words = set(wordlist) dict_words = dict() for w in wordlist: w_lower = w.lower() w_key = (w_lower.replace("a", "_").replace("e", "_") .replace("i", "_").replace("o", "_").replace("u", "_")) if w_key in dict_words: for w_lower_, _ in dict_words[w_key]: if w_lower == w_lower_: break else: dict_words[w_key].append((w_lower, w)) else: dict_words[w_key] = [(w_lower, w)] ans = [""] * len(queries) for i, q in enumerate(queries): if q in set_words: ans[i] = q continue q_lower = q.lower() q_key = (q_lower.replace("a", "_").replace("e", "_") .replace("i", "_").replace("o", "_").replace("u", "_")) if q_key in dict_words: for w_lower_, first_word in dict_words[q_key]: if q_lower == w_lower_: ans[i] = first_word break else: ans[i] = dict_words[q_key][0][1] return ans
vowel-spellchecker
Dictionary of words, 100% speed
EvgenySH
0
89
vowel spellchecker
966
0.514
Medium
15,613
https://leetcode.com/problems/vowel-spellchecker/discuss/1132749/Easy-python-solution!
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: l=len(queries) lk=len(wordlist) l1=[] lw=[] l3=['a','e','i','o','u'] l4=[] for e in range(lk): l6=len(wordlist[e]) s9="" for c in range(l6): if(wordlist[e][c].lower() not in l3): s9=s9+wordlist[e][c].lower() else: s9=s9+'@' l4.append(s9) for k in wordlist: lw.append(k.lower()) for i in range(l): if(queries[i] in wordlist): l1.append(queries[i]) elif(queries[i].lower() in lw): for t in range(lk): if(queries[i].lower()==lw[t]): l1.append(wordlist[t]) break else: s19="" l2=len(queries[i]) for g in range(l2): if(queries[i][g].lower() not in l3): s19=s19+queries[i][g].lower() else: s19=s19+'@' for t1 in range(lk): if(s19==l4[t1]): l1.append(wordlist[t1]) break else: l1.append("") return l1
vowel-spellchecker
Easy python solution!
Rajashekar_Booreddy
0
146
vowel spellchecker
966
0.514
Medium
15,614
https://leetcode.com/problems/vowel-spellchecker/discuss/1122370/Python-hash-map-easy-to-understand
class Solution: vowels = ["a", "e", "i", "o", "u"] def make_key(self, word): key = "" for index in range(len(word)): if word[index].lower() not in self.vowels: key += str(index) + word[index].lower() return key def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: words_data = {} words = {} result = [] for word in wordlist: key = self.make_key(word) if key not in words_data: words_data[key] = [word] else: words_data[key].append(word) words[word] = 1 for query in queries: if words.get(query): result.append(query) continue key = self.make_key(query) if not words_data.get(key): result.append("") else: for word in words_data[key]: if query.lower() == word.lower(): result.append(word) break else: result.append(words_data[key][0]) return result
vowel-spellchecker
Python hash map easy to understand
dlog
0
66
vowel spellchecker
966
0.514
Medium
15,615
https://leetcode.com/problems/vowel-spellchecker/discuss/715753/Python3-use-a-set-and-a-dict-Vowel-Spellchecker
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: def replaceVowel(s): return re.sub(r'[aeiou]', '_', s.lower()) d = {} s = set() for w in wordlist: s.add(w) if (low := w.lower()) not in d: d[w.lower()] = w if (repl := replaceVowel(w)) not in d: d[repl] = w ans = [] for q in queries: r = '' if q in s: r = q elif (low := q.lower()) in d: r = d[low] elif (repl := replaceVowel(q)) in d: r = d[repl] ans.append(r) return ans
vowel-spellchecker
Python3 use a set and a dict - Vowel Spellchecker
r0bertz
0
132
vowel spellchecker
966
0.514
Medium
15,616
https://leetcode.com/problems/vowel-spellchecker/discuss/527434/Python3-simple-solution
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: original_hash, lowercase_hash, ignore_vowel_hash = {}, {}, {} for index, word in enumerate(wordlist): original_hash[word] = index lowercase_word = word.lower() if lowercase_word not in lowercase_hash: lowercase_hash[lowercase_word] = index trans_vowel_word = self.trans_vowel(lowercase_word) if trans_vowel_word not in ignore_vowel_hash: ignore_vowel_hash[trans_vowel_word] = index check_result = [] for query in queries: if query in original_hash: check_result.append(query) elif query.lower() in lowercase_hash: check_result.append(wordlist[lowercase_hash[query.lower()]]) else: trans = self.trans_vowel(query.lower()) if trans in ignore_vowel_hash: check_result.append(wordlist[ignore_vowel_hash[trans]]) else: check_result.append("") return check_result @classmethod def trans_vowel(cls, word): list_word = list(word) for i, c in enumerate(word): if c in ('a', 'e', 'i', 'o', 'u'): list_word[i] = 0 return str(list_word)
vowel-spellchecker
Python3 simple solution
tjucoder
0
216
vowel spellchecker
966
0.514
Medium
15,617
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521416/44ms-PYTHON-91-Faster-93-Memory-Efficient-Solution-MULTIPLE-APPROACHES
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: graph = defaultdict(list) for i in range(0, 10): if i-k >= 0: graph[i].append(i-k) if i +k < 10: graph[i].append(i+k) start = [i for i in graph if i!= 0] for j in range(n-1): new = set() for i in start: last = i%10 for k in graph[last]: new.add(i*10 + k) start = new return list(start)
numbers-with-same-consecutive-differences
🔥44ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES 🔥
anuvabtest
5
421
numbers with same consecutive differences
967
0.571
Medium
15,618
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521416/44ms-PYTHON-91-Faster-93-Memory-Efficient-Solution-MULTIPLE-APPROACHES
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: numset = [1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(n - 1): res = [] for num in numset: cur = num % 10 if cur + k <= 9: res.append(num * 10 + cur + k) if k != 0 and cur - k >= 0: res.append(num * 10 + cur - k) numset = res return res
numbers-with-same-consecutive-differences
🔥44ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES 🔥
anuvabtest
5
421
numbers with same consecutive differences
967
0.571
Medium
15,619
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521416/44ms-PYTHON-91-Faster-93-Memory-Efficient-Solution-MULTIPLE-APPROACHES
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: res = [] stack = deque((1, num) for num in range(1, 10)) while stack: curr_pos, curr_num = stack.pop() if curr_pos == n: res.append(curr_num) else: last_digit = curr_num % 10 next_pos = curr_pos + 1 candidates = (last_digit + k, last_digit - k) if k else (last_digit,) for digit in candidates: if digit in range(10): stack.append((next_pos, curr_num * 10 + digit)) return res
numbers-with-same-consecutive-differences
🔥44ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES 🔥
anuvabtest
5
421
numbers with same consecutive differences
967
0.571
Medium
15,620
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2524256/Python-Elegant-and-Short-or-DFS-%2B-BFS
class Solution: """ Time: O(2^n) Memory: O(2^n) """ def numsSameConsecDiff(self, n: int, k: int) -> List[int]: nums = list(range(1, 10)) for i in range(1, n): nums = [num * 10 + d for num in nums for d in {num % 10 + k, num % 10 - k} if 0 <= d <= 9] return nums
numbers-with-same-consecutive-differences
Python Elegant & Short | DFS + BFS
Kyrylo-Ktl
2
48
numbers with same consecutive differences
967
0.571
Medium
15,621
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2526418/Python-backtracking
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def bt(d, num, i): num = num * 10 + d if i == n: result.append(num) return if d + k < 10: bt(d + k, num, i + 1) if k > 0 and d - k >= 0: bt(d - k, num, i + 1) result = [] for d in range(1, 10): bt(d, 0, 1) return result
numbers-with-same-consecutive-differences
Python, backtracking
blue_sky5
1
12
numbers with same consecutive differences
967
0.571
Medium
15,622
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522025/python3-or-easy-understanding-or-explained-with-comments-or-DFS
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: self.ans = {} for i in range(1, 10): self.dfs(i, str(i), n, k) # dfs for numbers starting from i return self.ans.keys() def dfs(self, num, s, n, k): # dfs if len(s) > n: return if len(s) == n: self.ans[int(s)]=1; return; # if len(number) == n then store that number for v in self.adj(num, k): s += str(v) self.dfs(v, s, n, k) s = s[:-1] def adj(self, num, k): # to get the next number lst = [] if num+k <= 9: lst.append(num+k) if num-k >= 0: lst.append(num-k) return lst
numbers-with-same-consecutive-differences
python3 | easy-understanding | explained with comments | DFS
H-R-S
1
28
numbers with same consecutive differences
967
0.571
Medium
15,623
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521368/Clean-Python-Backtracking-solution
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: res = [] def backtrack(tempRes): nonlocal res if len(tempRes) == n: s = [str(i) for i in tempRes] res.append("".join(s)) return for i in range(10): # situation of more than 1 digit and the diff is not k if len(tempRes) != 0 and abs(i - tempRes[-1]) != k: continue if i == 0 and len(tempRes) == 0: continue tempRes.append(i) backtrack(tempRes) tempRes.pop() backtrack([]) return res
numbers-with-same-consecutive-differences
Clean Python Backtracking solution
RayML
1
108
numbers with same consecutive differences
967
0.571
Medium
15,624
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1752951/Python-3-DFS-Super-Simple-Code-beats-99-Time-and-98-Space-(Hours-of-Optimization).
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: l=[] def dfs(i,n1): j=i%10 if(n1==n): l.append(i) return q1=j+k q2=j-k i=i*10 if(q1<10 and q2>=0 and k!=0 ): dfs(i+q1,n1+1) dfs(i+q2,n1+1) elif(q1<10 ): dfs(i+q1,n1+1) elif(q2>=0 ): dfs(i+q2,n1+1) for x in range(1,10): if(x+k<10 or x-k>=0): dfs(x,1) return l
numbers-with-same-consecutive-differences
[Python 3] DFS Super Simple Code beats 99% Time and 98% Space (Hours of Optimization).
vedank98
1
100
numbers with same consecutive differences
967
0.571
Medium
15,625
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/798467/Consecutive-Differences-or-Python3-or-100-time-or-explained
class Solution: def __init__(self): self.vals = { 0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [1, 2, 3, 4, 5, 6, 7, 8, 9], 2: [1, 2, 3, 4, 5, 6, 7, 8, 9], 3: [1, 2, 3, 4, 5, 6, 7, 8, 9], 4: [1, 2, 3, 4, 5, 6, 7, 8, 9], 5: [1, 2, 3, 4, 5, 6, 7, 8, 9], 6: [1, 2, 3, 6, 7, 8, 9], 7: [1, 2, 7, 8, 9], 8: [1, 8, 9], 9: [1, 9] } def numsSameConsecDiff(self, N: int, K: int): if N == 1: return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] cur_array = [str(i) for i in self.vals[K]] for i in range(N-1): cur_length = len(cur_array) new_array = set() for j in range(cur_length): cur_num = int(cur_array[j][-1]) if cur_num - K >= 0: new_array.add(cur_array[j] + str(cur_num-K)) if cur_num + K < 10: new_array.add(cur_array[j] + str(cur_num+K)) cur_array = list(new_array) return cur_array
numbers-with-same-consecutive-differences
Consecutive Differences | Python3 | 100% time | explained
Matthias_Pilz
1
177
numbers with same consecutive differences
967
0.571
Medium
15,626
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2640843/Python-O(2N)-O(2N)
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: queue = collections.deque([(i, 1) for i in range(1, 10)]) result = [] while queue: current, length = queue.popleft() if length == n: result.append(current) continue last = current % 10 if k == 0: queue.append((current * 10 + last, length + 1)) continue if 0 <= last - k <= 9: queue.append((current * 10 + (last - k), length + 1)) if 0 <= last + k <= 9: queue.append((current * 10 + (last + k), length + 1)) return result
numbers-with-same-consecutive-differences
Python - O(2^N), O(2^N)
Teecha13
0
1
numbers with same consecutive differences
967
0.571
Medium
15,627
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2535437/Python-Solution-using-recursion
class Solution: def dfs(self,curNum,digLeft,k,ans): if digLeft==0: ans.append(curNum) return lastDig = curNum%10 if lastDig+k<=9: self.dfs(curNum*10+lastDig+k,digLeft-1,k,ans) if lastDig-k>=0 and k!=0: self.dfs(curNum*10+lastDig-k,digLeft-1,k,ans) def numsSameConsecDiff(self, n: int, k: int) -> List[int]: ans = [] if n==1: return [0,1,2,3,4,5,6,7,8,9] for i in range(1,10): self.dfs(i,n-1,k,ans) return ans
numbers-with-same-consecutive-differences
Python Solution [using recursion]
miyachan
0
10
numbers with same consecutive differences
967
0.571
Medium
15,628
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2534537/Python-Easy-solution
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: # Find what is accepted first digit accepted_digits = [] for digit in range(1, 10): if digit - k >= 0 or digit + k <= 9: accepted_digits.append(str(digit)) # Get the rest of digits 1, ... , n for i in range(1, n): next_digits = accepted_digits accepted_digits = [] for j, accepted_digit in enumerate(next_digits): for possible_digit in range(0, 10): if abs(possible_digit - int(accepted_digit[-1])) == k: accepted_digits.append(accepted_digit + str(possible_digit)) return accepted_digits
numbers-with-same-consecutive-differences
[Python] Easy solution
stefan_ivi
0
18
numbers with same consecutive differences
967
0.571
Medium
15,629
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2530664/python-dfs-quite-straight-forward
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def list2num(l) : # for example, [ 1, 8, 1 ] --> 181 s=0 for j in range(len(l)) : s += l[j] * 10**(len(l)-j-1) return s def dfs(i,nums) : nums.append(i) # dfs stop if condition filled if len(nums)==n : result.append( list2num(nums) ) return if 0<=i-k : dfs(i-k,nums) nums.pop() if k!=0 and i+k<=9 : # k!=0 ==>to avoid duplicate dfs(i+k,nums) nums.pop() result = [] for i in range(1,10) : dfs(i,[]) return result
numbers-with-same-consecutive-differences
python dfs quite straight-forward
3upt
0
6
numbers with same consecutive differences
967
0.571
Medium
15,630
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2526070/GolangPython-O(n2)-time-or-O(n2)-space
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: output = [] for i in range(1,10): dfs(i,i,1,n,k,output) return output def dfs(number,last_digit,lenght,n,k,output): if last_digit < 0 or last_digit > 9: return if lenght == n: output.append(number) return dfs(number*10+last_digit-k,last_digit-k,lenght+1,n,k,output) if k != 0: dfs(number*10+last_digit+k,last_digit+k,lenght+1,n,k,output)
numbers-with-same-consecutive-differences
Golang/Python O(n^2) time | O(n^2) space
vtalantsev
0
4
numbers with same consecutive differences
967
0.571
Medium
15,631
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2526064/Simplest-and-easy-to-understand-Python-recursive-solution
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: solution = [] def rf(current): if len(current) == n: solution.append(int(current)) return last = int(current[-1]) if k == 0: rf(current + str(last)) else: if last - k >= 0: rf(current + str(last-k)) if last + k <= 9: rf(current + str(last+k)) for num in range(1, 10): rf(str(num)) return solution
numbers-with-same-consecutive-differences
Simplest and easy to understand Python recursive solution
zebra-f
0
9
numbers with same consecutive differences
967
0.571
Medium
15,632
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2525908/Python-solution-or-Backtracking
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: """backtracking""" def dfs(num, curDigit): if len(num) == n: if int(num) in res: return res.append(int(num)) return if curDigit >= 10 or curDigit < 0: return return dfs(num + str(curDigit), curDigit + k) or dfs(num + str(curDigit), curDigit - k) res = [] for firstDigit in range(1, 10): dfs('', firstDigit) return res
numbers-with-same-consecutive-differences
Python solution | Backtracking
MushroomRice
0
5
numbers with same consecutive differences
967
0.571
Medium
15,633
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2525246/Python-solution-oror-Easy-approach-oror-65ms-runtime
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: if n==1: return range(10) q=range(1, 10) for i in range(n-1): tmp=[] for i in q: for d in set([i%10+k, i%10-k]): if 0<=d<10: tmp.append(i*10+d) q=tmp return q
numbers-with-same-consecutive-differences
Python solution || Easy approach || 65ms runtime
sowmyamalla111
0
8
numbers with same consecutive differences
967
0.571
Medium
15,634
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2524532/Backtracking-in-Python-3
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def bt(cur: int, i: int = 1): if i == n: yield cur else: u = cur % 10 cur *= 10 if u + k <= 9: yield from bt(cur + u + k, i + 1) if k > 0 and u - k >= 0: yield from bt(cur + u - k, i + 1) def main(): for m in range(1, 10): yield from bt(m) return list(main())
numbers-with-same-consecutive-differences
Backtracking in Python 3
mousun224
0
16
numbers with same consecutive differences
967
0.571
Medium
15,635
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2523868/Python-Easy-readable-DFS
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: result = [] # make a depth first search and make the beginning number # while leaving out zero for digit in range(1,10): dfs(digit, digit, 1, n, k, result) return result def dfs(number, last_digit, number_length, target_length, target_diff, result): # check whether our current length is target length if number_length == target_length: result.append(number) return # make two possible two cases diffed = last_digit-target_diff added = last_digit+target_diff if diffed >= 0: dfs(number*10+diffed, diffed, number_length+1, target_length, target_diff, result) if added <= 9 and target_diff: dfs(number*10+added, added, number_length+1, target_length, target_diff, result) return
numbers-with-same-consecutive-differences
[Python] - Easy readable DFS
Lucew
0
3
numbers with same consecutive differences
967
0.571
Medium
15,636
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2523849/Python-solution!!
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: ans = [] def countDigit(number): return len(str(number)) def helper(num,n,k): if countDigit(num) == n: ans.append(int(num)) return for j in range(10): last_digit = num % 10 if abs(j-last_digit) == k: helper(num*10+j, n ,k) for i in range(1,10): helper(i,n,k) return ans
numbers-with-same-consecutive-differences
Python solution!!
Namangarg98
0
13
numbers with same consecutive differences
967
0.571
Medium
15,637
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2523569/Backtracking
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def fsol(t): vrange = range(1, 10) if t==0 else set([digits[t-1] + v for v in [-k, k] if digits[t-1] + v>=0 and digits[t-1] + v<=9]) for i in vrange: digits[t] = i if t==n-1: ans.append(int("".join([str(vv) for vv in digits]))) else: fsol(t+1) digits[t] = -1 pass digits = [-1] * n ans = [] fsol(0) return ans
numbers-with-same-consecutive-differences
Backtracking
dntai
0
3
numbers with same consecutive differences
967
0.571
Medium
15,638
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2523399/Python3-BFS
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: if n == 1: return [*range(1,10)] res = [] for num in self.numsSameConsecDiff(n-1,k): for digit in {num%10+k, num%10-k}: if 0 <= digit < 10: res.append(10*num+digit) return res
numbers-with-same-consecutive-differences
[Python3] BFS
ruosengao
0
4
numbers with same consecutive differences
967
0.571
Medium
15,639
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2523094/Python-oror-DFS-oror-Simple
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: ans = [] def getNumbers(size, x, num): if size == 0: ans.append(num) return if x + k < 10: getNumbers(size - 1, x + k, (num * 10) + (x + k)) if k != 0 and x - k >= 0: getNumbers(size - 1, x - k, (num * 10) + (x - k)) for i in range(1, 10): getNumbers(n - 1, i, i) return ans
numbers-with-same-consecutive-differences
Python || DFS || Simple ✅
wilspi
0
19
numbers with same consecutive differences
967
0.571
Medium
15,640
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522708/Python-recursive-EASY-SOLUTION-DFS
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: self.out = set() def recurse(curr_num, count): if count==0: self.out.add(int(curr_num)) return last_val = int(curr_num[-1]) if last_val+k>=10 and last_val-k<0: return if last_val+k<10: recurse(curr_num+str(last_val+k), count-1) if last_val-k>=0: recurse(curr_num+str(last_val-k), count-1) for i in range(1, 10): recurse(str(i),n-1) return self.out
numbers-with-same-consecutive-differences
Python recursive EASY SOLUTION DFS
shubham3
0
4
numbers with same consecutive differences
967
0.571
Medium
15,641
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522688/Python-recursive-easy-enderstand
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: res = [] def helper(curr): if len(curr) == n: res.append(int(curr)) return if int(curr[-1]) + k < 10: helper(curr + str(int(curr[-1]) + k)) if int(curr[-1]) - k >= 0 and k != 0: helper(curr + str(int(curr[-1]) - k)) for i in range(1, 10): helper(str(i)) return res
numbers-with-same-consecutive-differences
Python recursive easy-enderstand
Kennyyhhu
0
7
numbers with same consecutive differences
967
0.571
Medium
15,642
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522501/Python-simple-and-clear-or-96-faster-or-Recursive
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: #goes an iteration deeper as long as we haven't reached n length and adding or subtracting k does not go out of bounds def buildNum (n, k, digitloc, digit, number, sol): if digitloc == n: return sol.append(number) if number % 10 + k < 10: buildNum(n,k,digitloc + 1, digit + k, (number*10) + digit + k, sol) if number % 10 - k >= 0 and digit + k != digit - k: buildNum(n,k,digitloc + 1, digit - k, (number*10) + digit - k, sol) return sol sol = [] #loop through starting integer for recursion for i in range(1,10): if i + k <= 9 or i - k >= 0: buildNum(n,k,1,i,i,sol) return sol
numbers-with-same-consecutive-differences
Python simple and clear | 96% faster | Recursive
yuvalsaf
0
11
numbers with same consecutive differences
967
0.571
Medium
15,643
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522476/Easy-Recursive-solution.
class Solution: def listtoNumber(self,con): st='' for i in con: st+=str(i) return int(st) def numsSameConsecDiff(self, n: int, k: int) -> List[int]: res = [] con = [0] * n def fun(ind,con): if ind==n: nos=self.listtoNumber(con) res.append(nos) return for i in range(10): if ind==0 and i==0:continue con[ind]=i if ind==0: fun(ind+1,con) elif abs(con[ind]-con[ind-1])==k: fun(ind+1,con) con[ind]=0 fun(0,con) return res
numbers-with-same-consecutive-differences
Easy Recursive solution.
Mohit_Hadiyal16
0
6
numbers with same consecutive differences
967
0.571
Medium
15,644
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522289/Python-or-Neat-and-Clean-Code-or-Using-DFS
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: res = [] if n == 1: res.append(0) def dfs(num,n): if n == 0: res.append(num) return lastDigit = num % 10 if lastDigit >= k: dfs(num * 10 + lastDigit - k, n-1) if k > 0 and lastDigit + k < 10: dfs(num * 10 + lastDigit + k, n-1) for i in range(1, 10): dfs(i, n-1) return res
numbers-with-same-consecutive-differences
Python | Neat and Clean Code | Using DFS
__Asrar
0
8
numbers with same consecutive differences
967
0.571
Medium
15,645
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2522016/python
class Solution: res = set() def numsSameConsecDiff(self, n: int, k: int) -> List[int]: self.res = set() def createNum(num): #termination case if len(num)>n: return #acceptance case + termination if len(num)==n: self.res.add(num) return else: #creation: only numbers will be accpted that their difference is k with the last charcter num for i in range(10): if (abs(int(num[-1])-i) == k): num+=str(i) createNum(num) num = num[:-1] for i in range(1,10): createNum(str(i)) #since results are string here we will convert them to int ans = list(map(int,self.res)) return ans
numbers-with-same-consecutive-differences
python
rojanrookhosh
0
7
numbers with same consecutive differences
967
0.571
Medium
15,646
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521941/Python-Solution-or-Brute-Force-or-Optimized
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: # Brute Force # ans=[] # for i in range(10**(n-1), 10**(n)): # s=str(i) # flag=True # for j in range(1, len(s)): # if abs(int(s[j])-int(s[j-1]))!=k: # flag=False # break # if flag: # ans.append(i) # return ans # Optimised ans=[] def helper(num): if len(num)==n: ans.append(int(num)) return for i in range(10): if abs(i-int(num[-1]))==k: helper(num+str(i)) return for i in range(1, 10): helper(str(i)) return ans
numbers-with-same-consecutive-differences
Python Solution | Brute Force | Optimized
Siddharth_singh
0
17
numbers with same consecutive differences
967
0.571
Medium
15,647
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521832/Python3-Solution-or-BFS
class Solution: def numsSameConsecDiff(self, n, k): q = collections.deque(list(range(1, 10))) for i in range(1, n): m = len(q) for j in range(m): val = q.popleft() mod = val % 10 if mod + k <= 9: q.append(val * 10 + mod + k) if k and mod - k >= 0: q.append(val * 10 + mod - k) return q
numbers-with-same-consecutive-differences
✔ Python3 Solution | BFS
satyam2001
0
11
numbers with same consecutive differences
967
0.571
Medium
15,648
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521458/Easy-python-solution-using-recursion
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def func(i,n,k,lst,s): if i<0 or i>=10: return lst if n==0: if s not in lst: lst.append(s) return lst lst=func(i-k,n-1,k,lst,s+str(i-k)) lst=func(i+k,n-1,k,lst,s+str(i+k)) return lst lst=[] for i in range(1,10): prev=i lst=func(prev,n-1,k,lst,str(i)) return lst
numbers-with-same-consecutive-differences
Easy python solution using recursion
shubham_1307
0
23
numbers with same consecutive differences
967
0.571
Medium
15,649
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521404/Python-or-Backtracking
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: allNumbers = []; currentNumber = [] def backtrack(currentDigit: int, numberOfDigits: int = 1): if numberOfDigits == n: allNumbers.append(int("".join(currentNumber))) else: for i in set([currentDigit - k, currentDigit + k]): # set handles the case k = 0 if 0 <= i <= 9: currentNumber.append(str(i)) backtrack(i, numberOfDigits + 1) currentNumber.pop() for i in range(1, 10): currentNumber.append(str(i)) backtrack(i) currentNumber.pop() return allNumbers
numbers-with-same-consecutive-differences
Python | Backtracking
sr_vrd
0
17
numbers with same consecutive differences
967
0.571
Medium
15,650
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1966069/Python-easy-to-read-and-understand-or-recursion
class Solution: def dfs(self, num, n, k): if n == 0: #print(num) self.ans.append(int(num)) return else: digit = num[-1] if int(digit) - k >= 0: self.dfs(num+str(int(digit)-k), n-1, k) if int(digit) + k < 10: self.dfs(num+str(int(digit)+k), n-1, k) def numsSameConsecDiff(self, n: int, k: int) -> List[int]: if k == 0: return [int(str(i) * n) for i in range(1, 10)] self.ans = [] for i in range(1, 10): self.dfs(str(i), n-1, k) return self.ans
numbers-with-same-consecutive-differences
Python easy to read and understand | recursion
sanial2001
0
41
numbers with same consecutive differences
967
0.571
Medium
15,651
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1925944/PYTHON-SOL-oror-EASY-oror-RECURSION-%2B-MEMOIZATION-oror-FAST-oror-WELL-COMMENTED-CODE-oror
class Solution: def recursion(self, cur , size , n , diff ): # if we have already made cur don't repeat if cur in self.dp : return # mark cur as visited self.dp[cur] = True # base case if size == n: self.ans.append(int(cur)) return # when size is 0 we need to add item . if size == 0: for i in range(1,10): self.recursion(cur + str(i) , size + 1, n ,diff) # we can add next val either by adding diff to last element # or by substracting diff to last element else: if int(cur[-1]) + diff < 10: self.recursion(cur + str(int(cur[-1]) + diff), size+1 , n ,diff) if int(cur[-1]) - diff >= 0: self.recursion(cur + str(int(cur[-1]) - diff), size+1 , n ,diff) def numsSameConsecDiff(self, n: int, k: int) -> List[int]: # length of digit = n # diff between digits = k # n = 3 , k = 7 ans = [181,292,707,818,929] self.dp = {} self.ans = [] self.recursion("",0,n,k) return self.ans
numbers-with-same-consecutive-differences
PYTHON SOL || EASY || RECURSION + MEMOIZATION || FAST || WELL COMMENTED CODE ||
reaper_27
0
48
numbers with same consecutive differences
967
0.571
Medium
15,652
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1841947/python-simple-dfs-solution
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: stack = [] for i in range(1, 10): stack.append((str(i), 1)) res = set() while stack: num, length = stack.pop() if length == n: res.add(num) s = int(num[-1]) if length < n: if s + k < 10: stack.append((num + str(s+k), length + 1)) if s - k >= 0: stack.append(((num + str(s-k), length + 1))) return [int(x) for x in res]
numbers-with-same-consecutive-differences
python simple dfs solution
byuns9334
0
39
numbers with same consecutive differences
967
0.571
Medium
15,653
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1737155/easy-using-backtracking-python3
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: self.ans = [] def solve(com): if(len(com) == n): self.ans.append(int(com)) return for i in range(10): if(not com and i == 0): continue if(not com or abs(int(com[-1])-int(i)) == k): solve(com+str(i)) solve("") return self.ans
numbers-with-same-consecutive-differences
easy using backtracking python3
jagdishpawar8105
0
33
numbers with same consecutive differences
967
0.571
Medium
15,654
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1307934/Python-3-BFS-using-yields
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: poss_entries = self.get_valid_entries_two_digits(k) for _ in range(n-2): poss_entries = self.get_valid_entries(poss_entries, k) return list(map(int, poss_entries)) def get_valid_entries_two_digits(self, k): for poss_entry in map(str, range(10, 100)): if abs(int(poss_entry[0]) - int(poss_entry[1])) == k: yield poss_entry def get_valid_entries(self, poss_entries, k): for poss_entry in poss_entries: last_digit = int(poss_entry[-1]) if last_digit + k < 10: yield poss_entry + str(last_digit+k) if last_digit - k >= 0 and k != 0: yield poss_entry + str(last_digit-k)
numbers-with-same-consecutive-differences
Python 3 BFS using yields
gamestopcantstop
0
60
numbers with same consecutive differences
967
0.571
Medium
15,655
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/1191960/simple-bfs
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: queue=[] for i in range(1,10): queue.append(str(i)) vis=set(queue) count=0 ans=[] while(queue): print(queue) if count<n: l=len(queue) for _ in range(0,l): q=queue.pop(0) if len(q)==n: ans.append(q) continue vis.add(q) p=q[-1] if int(p)+k<=9 and q+str(int(p)+k) not in vis: queue.append(q+str(int(p)+k)) vis.add(q+str(int(p)+k)) if int(p)-k>=0 and q+str(int(p)-k) not in vis: queue.append(q+str(int(p)-k)) vis.add(q+str(int(p)-k)) count+=1 return ans
numbers-with-same-consecutive-differences
simple bfs
heisenbarg
0
29
numbers with same consecutive differences
967
0.571
Medium
15,656
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/842073/python3-or-dfs
class Solution: def __init__(self): self.nums = [] def Util(self, N, K, cur): if len(cur) > N: return [] if len(cur) == N: return [cur] lis1 = [] lis2 = [] if int(cur[-1]) - K >= 0 and cur[0] != '0': lis1 = self.Util(N, K, cur + str(int(cur[-1]) - K)) if int(cur[-1]) + K < 10 and cur[0] != '0': lis2 = self.Util(N, K, cur + str(int(cur[-1]) + K)) return lis1 + lis2 def numsSameConsecDiff(self, N: int, K: int) -> List[int]: fin = [] for i in range(10): lis = self.Util(N, K, str(i)) fin.extend(lis) return list(set(fin))
numbers-with-same-consecutive-differences
python3 | dfs
_YASH_
0
28
numbers with same consecutive differences
967
0.571
Medium
15,657
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/798955/Python3-backtracking-and-dp
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def fn(i, x): """Populate ans via a stack.""" stack.append(x) if i == n-1: ans.append(int("".join(map(str, stack)))) else: if x + k < 10: fn(i+1, x+k) if k and 0 <= x - k: fn(i+1, x-k) stack.pop() ans, stack = [], [] for x in range(1, 10): fn(0, x) return ans
numbers-with-same-consecutive-differences
[Python3] backtracking & dp
ye15
0
42
numbers with same consecutive differences
967
0.571
Medium
15,658
https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/798955/Python3-backtracking-and-dp
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def fn(i, x): """Return numbers with same consecutive differences.""" if i == n-1: return [str(x)] ans = [] if x+k < 10: ans += [str(x) + xx for xx in fn(i+1, x+k)] if k and 0 <= x-k: ans += [str(x) + xx for xx in fn(i+1, x-k)] return ans return sum((fn(0, x) for x in range(1, 10)), [])
numbers-with-same-consecutive-differences
[Python3] backtracking & dp
ye15
0
42
numbers with same consecutive differences
967
0.571
Medium
15,659
https://leetcode.com/problems/binary-tree-cameras/discuss/2160386/Python-Making-a-Hard-Problem-Easy!-Postorder-Traversal-with-Explanation
class Solution: def minCameraCover(self, root: TreeNode) -> int: # set the value of camera nodes to 1 # set the value of monitored parent nodes to 2 def dfs(node: Optional[TreeNode]) -> int: if not node: return 0 res = dfs(node.left)+dfs(node.right) # find out if current node is a root node / next node in line to be monitored curr = min(node.left.val if node.left else float('inf'), node.right.val if node.right else float('inf')) if curr == 0: # at least one child node requires monitoring, this node must have a camera node.val = 1 res += 1 elif curr == 1: # at least one child node is a camera, this node is already monitored node.val = 2 # if curr == float('inf'), the current node is a leaf node; let the parent node monitor this node # if curr == 2, all child nodes are being monitored; treat the current node as a leaf node return res # ensure that root node is monitored, otherwise, add a camera onto root node return dfs(root)+(root.val == 0)
binary-tree-cameras
[Python] Making a Hard Problem Easy! Postorder Traversal with Explanation
zayne-siew
50
2,100
binary tree cameras
968
0.468
Hard
15,660
https://leetcode.com/problems/binary-tree-cameras/discuss/2160618/Python-Easy-Postorder-with-explanation
class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: def postorder(node): if not node: return (0, math.inf) l_count, l_state = postorder(node.left) r_count, r_state = postorder(node.right) state = min(l_state, r_state) total_cameras = l_count + r_count if state==0: # children are not monitored return (total_cameras + 1, 1) # install camera in current node if state==1: # one of the children is monitored and has camera return (total_cameras, 2) # set current node state as monitored but no camera return (total_cameras, 0) # set current node as unmonitored # adding dummy parent for the root for handling cases where root need a camera dummy=TreeNode(-1, root) return postorder(dummy)[0]
binary-tree-cameras
✅ Python Easy Postorder with explanation
constantine786
18
551
binary tree cameras
968
0.468
Hard
15,661
https://leetcode.com/problems/binary-tree-cameras/discuss/2160278/PYTHON-oror-EXPLAINED-oror
class Solution: res = 0 def minCameraCover(self, root: TreeNode) -> int: def dfs(node: TreeNode) -> int: if not node: return 0 val = dfs(node.left) + dfs(node.right) if val == 0: return 3 if val < 3: return 0 self.res += 1 return 1 return self.res + 1 if dfs(root) > 2 else self.res
binary-tree-cameras
✔️ PYTHON || EXPLAINED || ;]
karan_8082
8
479
binary tree cameras
968
0.468
Hard
15,662
https://leetcode.com/problems/binary-tree-cameras/discuss/2160423/Python3-DFS-solution
class Solution(object): def minCameraCover(self, root): result = [0] # 0 indicates that it doesn't need cam which might be a leaf node or a parent node which is already covered # < 3 indicates that it has already covered # >= 3 indicates that it needs a cam def getResult(root): if not root: return 0 needsCam = getResult(root.left) + getResult(root.right) if needsCam == 0: return 3 if needsCam < 3: return 0 result[0]+=1 return 1 return result[0] + 1 if getResult(root) >= 3 else result[0]
binary-tree-cameras
📌 Python3 DFS solution
Dark_wolf_jss
5
31
binary tree cameras
968
0.468
Hard
15,663
https://leetcode.com/problems/binary-tree-cameras/discuss/2163005/Python-Recursion-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: hasCamera = False isMonitored = False return self.helper(root, hasCamera, isMonitored) # Hypothesis -> Will always return the minimum Cameras required def helper(self, root, hasCamera, isMonitored) -> int: # if no node, then no camera needed if root is None: return 0 # ************************** BASE CASES ************************************************* if hasCamera: # CASE - 1 return 1 + self.helper(root=root.left, hasCamera=False, isMonitored=True) + self.helper(root=root.right, hasCamera=False, isMonitored=True) # no camera is present at node, which means node is monitored somehow if isMonitored: # CASE - 2 # No camera at node, but child have camera, so we need cameras from left and right childWithCam = self.helper(root.left, hasCamera=False, isMonitored=False) + \ self.helper(root.right, hasCamera=False, isMonitored=False) childWithNoCam = 1 + self.helper(root.left, hasCamera=False, isMonitored=True) + self.helper( root.right, hasCamera=False, isMonitored=True) # REMEMBER, THIS IS NOT THE FINAL ANSWER, IT IS JUST A BASE CASE return min(childWithCam, childWithNoCam) # REMEMBER, THIS IS TRICKY, # DONT ADD, THIS BASE CASE FOR MEMOIZATION, BEFORE OTHER POSSIBLE BASE CASES # BECAUSE, THEY HAVE THEIR OWN RECURSIVE CALLS AND THEIR OWN OPERATIONS TO PERFORM if root.val != 0: return root.val # ************************************* INDUCTION **************************************** # Now, all the cases, when adding camera at out will # Try, adding camera at node or root rootHasCam = 1 + self.helper(root.left, hasCamera=False, isMonitored=True) + \ self.helper(root.right, hasCamera=False, isMonitored=True) # Now, we have two cases, either add camera to left or right node leftHasCam = float("inf") if root.left is not None: leftHasCam = self.helper(root.left, hasCamera=True, isMonitored=False) + \ self.helper(root.right, hasCamera=False, isMonitored=False) rightHasCam = float("inf") if root.right is not None: rightHasCam = self.helper(root.left, hasCamera=False, isMonitored=False) + \ self.helper(root.right, hasCamera=True, isMonitored=False) # Now, we want minimum of all the cases # REMEMBER: - THIS MINIMUM IS THE FINAL ANSWER REQUIRED, SO MEMOIZE THIS root.val = min(rootHasCam, leftHasCam, rightHasCam) return root.val
binary-tree-cameras
Python Recursion + Memoization + DP + Greedy
zippysphinx
1
94
binary tree cameras
968
0.468
Hard
15,664
https://leetcode.com/problems/binary-tree-cameras/discuss/2163005/Python-Recursion-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: def solve(node): # Keep track, of all the cases # CASE-1 = ans[0] means, all nodes below i,e subtrees of left and right are monitored, not the current node # CASE-2 = ans[1] means, all, the nodes below are monitored and current node is monitored, # but current node doesnt have the camera # CASE-3 = ans[2] means, all, the nodes below are monitored and current node is monitored, # because current node has the camera # BASE CASE # if node is null, that means # CASE-1: Not possible as current is null and there will be no left and right also # CASE-2: Not possible as current and left and right doesnt exist # Case-3: Adding camera to watch current node which is null, So, we can place the camera at null # but what is the use of adding camera at null, so we will ignore this case, and to ignore this # we will add "infinity" here, as later min will automaticlly ignore this case if node is None: return 0, 0, float('inf') # Now, getting case results for left and right L = solve(node.left) R = solve(node.right) # Now, To get minimum, we will add up cases # CASE-1: Means all nodes left and right are monitored but not the node # So, to cover this case, the child node left and right must me in CASE-2 # So, we will take the values of CASE-2 from LEFT AND RIGHT dp0 = L[1] + R[1] # To cover CASE-2 without placing a camera here, the children of this node must be in CASE-1 or # CASE-3, and at least one of those children must be in CASE-3. dp1 = min(L[2] + min(R[1:]), R[2] + min(L[1:])) # To cover the CASE-3 when placing a camera here, the children can be in any CASE. dp2 = 1 + min(L) + min(R) return dp0, dp1, dp2 # Now, Solve for Every Node, but ignore the case in which current node is not monitored return min(solve(root)[1:])
binary-tree-cameras
Python Recursion + Memoization + DP + Greedy
zippysphinx
1
94
binary tree cameras
968
0.468
Hard
15,665
https://leetcode.com/problems/binary-tree-cameras/discuss/2163005/Python-Recursion-%2B-Memoization-%2B-DP-%2B-Greedy
class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: self.minimumCameras = 0 # Again, Distinguish with cases # 1 = node is not monitored # 2 = node is monitored, but no camera # 3 = has camera def dfs(root): # Null node, is always not monitored, so consider it monitored # no need of adding camera there at null if root is None: return 2 # Get Status of left and right getLeft = dfs(root.left) getRight = dfs(root.right) # If any of the child node is not monitored, we will add camera # 1 means node not monitored, below it means left or right is not monitored if getLeft == 1 or getRight == 1: # we will add the camera to parent or root self.minimumCameras += 1 # Now the camera is added, So return 3 for parent node or root return 3 # if any of the child node is monitored and has camera, # the current node is monitored, no need of camera # 3 Means node has camera, below it means left or right already has camera elif getLeft == 3 or getRight == 3: # 2 Means node is monitored, but has no camera # returning 2 for root as child has camera, so no need of camera here and parent or root is monitored return 2 else: # Else, case means not monitored by any child, means child is not even monitored or have camera return 1 # If root node is not monitored, means child node is also not monitored and has no camera # So, we will add camera at root if dfs(root) == 1: self.minimumCameras += 1 return self.minimumCameras
binary-tree-cameras
Python Recursion + Memoization + DP + Greedy
zippysphinx
1
94
binary tree cameras
968
0.468
Hard
15,666
https://leetcode.com/problems/binary-tree-cameras/discuss/2163895/Python3-or-O(n)-or-Greedy-Approach
class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: def dfs(root): if not root: return "covered" l = dfs(root.left) r = dfs(root.right) if l=="needed" or r=="needed": self.camera+=1 return "camera" if l=="camera" or r=="camera": return "covered" return "needed" self.camera = 0 return self.camera+1 if dfs(root) == "needed" else self.camera
binary-tree-cameras
Python3 | O(n) | Greedy Approach
theKshah
0
7
binary tree cameras
968
0.468
Hard
15,667
https://leetcode.com/problems/binary-tree-cameras/discuss/2161454/Postorder-DFS-oror-Fastest-OptimalSolution-oror-TC-%3A-O(N)-oror-SC-%3A-O(1)
class Solution: def __init__(self): self.minCameras = 0 def cameras(self,root, minCameras): if root == None: return "ok" left = self.cameras(root.left, minCameras) right = self.cameras(root.right, minCameras) if left == "want" or right == "want": self.minCameras += 1 return "provide" elif left == "provide" or right == "provide": return "ok" else: return "want" def minCameraCover(self, root: Optional[TreeNode]) -> int: if self.cameras(root, self.minCameras) == "want": self.minCameras += 1 return self.minCameras
binary-tree-cameras
Postorder DFS || Fastest OptimalSolution || TC :- O(N) || SC :- O(1)
Vaibhav7860
0
21
binary tree cameras
968
0.468
Hard
15,668
https://leetcode.com/problems/binary-tree-cameras/discuss/1464031/Python-memoization-rec-easy-to-understand-with-comments
class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: memo = {} # dict for storing dp states # we need three variables, node , parent denoting if parent is covered or not, # and done denoting whether current node is covered or not def rec(node, done, par): # base case if node is None: return 0 key = (id(node), done, par) # dp key if key in memo: return memo[key] # if parent is covered if par: # adding camera here, so for next calls, parent is covered, and childs are also covered a = 1 + rec(node.left, True, True) + rec(node.right, True, True) d = 0 if done: # if current node is covered, then for next calls their parent is covered but # not themselves d = rec(node.left, False, True) + rec(node.right, False, True) memo[key] = min(a, d) return memo[key] ans = a # Now, if parent is covered but not current node, so we have to decide whether we # want to cover it from its left child or right child if node.left: # if left child is there, then we are covering it from left child and passing **par** value as true # for right child ans = min(ans, rec(node.left, False, False) + rec(node.right, False, True)) if node.right: # if right child is there, then we are covering it from right child and passing **par** value as true # for leftt child ans = min(ans, rec(node.right, False, False) + rec(node.left, False, True)) # storing in memo memo[key] = ans else: # if parent is not covered, then we have only one way which is to add # camera to current node memo[key] = 1 + rec(node.left, True, True) + rec(node.right, True, True) return memo[key] # root is not covered but it has no parent, so we have to pass par value as true to avoid unneccessary # covering of root's parents return rec(root, False, True)
binary-tree-cameras
Python memoization rec easy to understand -- with comments
ashish_chiks
0
83
binary tree cameras
968
0.468
Hard
15,669
https://leetcode.com/problems/binary-tree-cameras/discuss/1428731/Python3-Postorder-DFS
class Solution: def __init__(self): self.cameras = 0 def traversal(self, node): if node == None: return (False, False) l_camera, l_need_vision = self.traversal(node.left) r_camera, r_need_vision = self.traversal(node.right) if (not l_camera and not l_need_vision) and (not r_camera and not r_need_vision): return (False, True) if (not l_camera and l_need_vision) or (not r_camera and r_need_vision): self.cameras += 1 return (True, False) if (l_camera and not l_need_vision) or (r_camera and not r_need_vision): return (False, False) def minCameraCover(self, root: TreeNode) -> int: camera, need_vision = self.traversal(root) if not camera and need_vision: self.cameras += 1 return self.cameras
binary-tree-cameras
[Python3] Postorder DFS
maosipov11
0
73
binary tree cameras
968
0.468
Hard
15,670
https://leetcode.com/problems/binary-tree-cameras/discuss/1214372/Python3-greedy-tri-color-encoding
class Solution: def minCameraCover(self, root: TreeNode) -> int: def fn(node): """Return color-coding of a node. 0 - not covered 1 - covered w/o camera 2 - covered w/ camera """ nonlocal ans if not node: return 1 left, right = fn(node.left), fn(node.right) if left == 0 or right == 0: ans += 1 return 2 # add a camera if left == 2 or right == 2: return 1 return 0 ans = 0 return int(fn(root) == 0) + ans
binary-tree-cameras
[Python3] greedy - tri-color encoding
ye15
0
53
binary tree cameras
968
0.468
Hard
15,671
https://leetcode.com/problems/binary-tree-cameras/discuss/1212014/python3-post-order-traversal-solution-for-reference
class Solution: def minCameraCover(self, root: TreeNode) -> int: # Post order traversal to make sure we transit left, right and root so that camera's can be assigned in the right order. def postorder(root, parent): if not root: return 0 L = postorder(root.left, root) R = postorder(root.right, root) # check if something is a tail node. tail_node = (not root.left and not root.right) # Camera coverage is there if either a camera exists or if a camera cover node # however, if we discovered coverage to children or camera with children, # we dont want to assign camera too root but to its parent. # Only case need covering in the root node. left_camera = (not root.left) or (root.left and root.left.val >= 1) right_camera = (not root.right) or (root.right and root.right.val >= 1) iscovered = left_camera and right_camera # check if either children is not having coverage == 0 # usecase : root has left chld covered by its children but on right side its not covered the the root needs to have a camera. either_zero = False if root.left and root.left.val == 0: either_zero = True if root.right and root.right.val == 0: either_zero = True if not parent and (root.val == 2 or root.val == 0): return L + R + (1 if (either_zero or not root.val) else 0) elif not tail_node and not iscovered: root.val = 1 # if root needs camera, then propagate coverate to its parent and children. if parent: parent.val = 2 if parent.val == 0 else parent.val if root.left: root.left.val = 2 if root.left.val == 0 else root.left.val if root.right: root.right.val = 2 if root.right.val == 0 else root.right.val L += 1 return L + R mc = postorder(root, None) return mc
binary-tree-cameras
[python3] post order traversal solution for reference
vadhri_venkat
0
59
binary tree cameras
968
0.468
Hard
15,672
https://leetcode.com/problems/pancake-sorting/discuss/2844744/Kind-of-a-simulation-solution
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: if arr == sorted(arr): return [] flips = [] end = len(arr) - 1 # find the max flip all the numbers from the first position to the max position # ==> from 0 to max_position = k # ==> if max not at the end : flip again until the max is at the end of the array # ==> from 0 to max_position = k # end = end - 1 # repeat previous steps while end > 0: max_num = max(arr[:end+1]) index_num = arr.index(max_num) if index_num != end: k = index_num + 1 arr = arr[0:k][::-1] + arr[k:] flips.append(k) arr = arr[:end+1][::-1] + arr[end+1:] flips.append(end+1) else: k = end arr = arr[0:k][::-1] + arr[k:] flips.append(k) end -= 1 return flips
pancake-sorting
Kind of a simulation solution
khaled_achech
0
1
pancake sorting
969
0.7
Medium
15,673
https://leetcode.com/problems/pancake-sorting/discuss/2516256/Very-simple-Python3-solution-beats-most-submissions
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: #helper function to flip the numbers in the array def flip(i, j): while i < j: arr[i], arr[j] = arr[j], arr[i] j -= 1 i += 1 #sort from 0 to i def sort(i): #base case where all the numbers are sorted, thus no more recursive calls if i < 0: return [] ret = [] #find the biggest number, which always will be the len(arr), or i + 1 idx = arr.index(i + 1) # if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number if idx == i: return sort(i - 1) #we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result ret.append(idx + 1) flip(0, idx) #we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well) ret.append(i + 1) flip(0, i) #sort the next biggest number by setting a new boundary i - 1 return ret + sort(i - 1) return sort(len(arr) - 1)
pancake-sorting
✔️ Very simple Python3 solution beats most submissions
Kagoot
0
20
pancake sorting
969
0.7
Medium
15,674
https://leetcode.com/problems/pancake-sorting/discuss/2393939/Python-Easy-Recursive-thorough-explanation
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: #helper function to flip the numbers in the array def flip(i, j): while i < j: arr[i], arr[j] = arr[j], arr[i] j -= 1 i += 1 #sort from 0 to i def sort(i): #base case where all the numbers are sorted, thus no more recursive calls if i < 0: return [] ret = [] #find the biggest number, which always will be the len(arr), or i + 1 idx = arr.index(i + 1) # if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number if idx == i: return sort(i - 1) #we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result ret.append(idx + 1) flip(0, idx) #we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well) ret.append(i + 1) flip(0, i) #sort the next biggest number by setting a new boundary i - 1 return ret + sort(i - 1) return sort(len(arr) - 1)
pancake-sorting
Python Easy Recursive, thorough explanation
gypark23
0
37
pancake sorting
969
0.7
Medium
15,675
https://leetcode.com/problems/pancake-sorting/discuss/1933155/PYTHON-SOL-oror-GREEDY-oror-TWO-POINTER-oror-WELL-EXPLAINED-oror-SIMPLE-oror
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: n = len(arr) issorted = True for i in range(1,n): if arr[i] < arr[i-1] : issorted = False break if issorted == True : return [] flips = [] for i in range(n): if len(flips) > 10 * n : return [-1] maxx = 0 for j in range(n-i): if arr[j] > arr[maxx] : maxx = j if maxx != 0 : flips.append(maxx+1) low = 0 high = maxx while low < high: arr[low],arr[high] = arr[high],arr[low] high -= 1 low += 1 low = 0 high = n - i - 1 while low < high : arr[low] , arr[high] = arr[high] , arr[low] low += 1 high -= 1 flips.append(n-i) return flips
pancake-sorting
PYTHON SOL || GREEDY || TWO POINTER || WELL EXPLAINED || SIMPLE ||
reaper_27
0
118
pancake sorting
969
0.7
Medium
15,676
https://leetcode.com/problems/pancake-sorting/discuss/1795022/Easily-understandable-Python-solution
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: i=0 n=len(arr) kArr=[] sorted = 0 while i<n: if not self.checkSorted(arr): k=self.getMaxIndex(arr[:n-sorted]) if k != 0: kArr.append(k+1) arr = self.pancakeSwap(arr, k) arr = self.pancakeSwap(arr, n-1-sorted) kArr.append(n-sorted) sorted+=1 else: return kArr def checkSorted(self, arr): arr1 = arr[:] arr1.sort() print(arr1==arr) return arr1 == arr def getMaxIndex(self, arr): m = arr.index(max(arr)) print(m) return m def pancakeSwap(self, arr, k): print(arr[:k+1][::-1] + arr[k+1:]) return arr[:k+1][::-1] + arr[k+1:]
pancake-sorting
Easily understandable Python solution
wadhwahitesh
0
42
pancake sorting
969
0.7
Medium
15,677
https://leetcode.com/problems/pancake-sorting/discuss/1380943/Python-or-Shifting-max-to-first-then-flipping-the-whole-array
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: n=len(arr) ans=[] for i in range(n): maxi=self.findmax(arr,n-i) ans.append(maxi+1) self.reverse(arr,maxi+1) self.reverse(arr,n-i) ans.append(n-i) return ans def findmax(self,arr,indx): return arr.index(max(arr[:indx])) def reverse(self,arr,indx): i=0 j=indx-1 while i<=j: temp=arr[i] arr[i]=arr[j] arr[j]=temp i+=1 j-=1
pancake-sorting
Python | Shifting max to first then flipping the whole array
swapnilsingh421
0
51
pancake sorting
969
0.7
Medium
15,678
https://leetcode.com/problems/pancake-sorting/discuss/1343748/Python-3-hack-or-O(n)-T-or-O(n)-S
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: a = arr.copy() end = len(a) cur_max = len(a) to_index = [0]*(len(a)+1) for i, num in enumerate(a): to_index[num] = i result = [] while end > 1: i = to_index[cur_max] if i+1 < end: result.append(end) i = end-1-i result.append(i+1) if i > 1: result.append(i) if i > 2: result.append(i-1) if i > 1: result.append(i) result.append(end) to_index[a[end-1]] = to_index[cur_max] a[to_index[cur_max]] = a[end-1] end -= 1 cur_max -= 1 return result
pancake-sorting
Python 3 hack | O(n) T | O(n) S
CiFFiRO
0
48
pancake sorting
969
0.7
Medium
15,679
https://leetcode.com/problems/pancake-sorting/discuss/1290819/Python3-solution-94-faster
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: result, temp, arr_len=[], 0, len(arr) while True: if arr_len-temp==1: break curr_max=max(arr[:arr_len-temp]) curr_index=arr.index(curr_max) if curr_index==arr_len-temp-1: temp+=1 continue if curr_index==0: arr[:arr_len-temp]=arr[arr_len-temp-1::-1] result.append(arr_len-temp) else: arr[:curr_index+1]=arr[curr_index::-1] arr[:arr_len-temp]=arr[arr_len-temp-1::-1] result.append(curr_index+1) result.append(arr_len-temp) temp+=1 return result
pancake-sorting
Python3 solution, 94% faster
alter_mage
0
75
pancake sorting
969
0.7
Medium
15,680
https://leetcode.com/problems/pancake-sorting/discuss/981053/Python3-greedy-O(N2)
class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: ans = [] for x in range(len(arr), 0, -1): i = arr.index(x) if i+1 != x: if i: ans.append(i+1) ans.append(x) arr[:i+1] = arr[:i+1][::-1] arr[:x] = arr[:x][::-1] return ans
pancake-sorting
[Python3] greedy O(N^2)
ye15
0
64
pancake sorting
969
0.7
Medium
15,681
https://leetcode.com/problems/pancake-sorting/discuss/817919/Python-easy-solution
class Solution: def pancakeSort(self, A: List[int]) -> List[int]: ans=[] for i in range(len(A),1,-1): temp=A.index(max(A[:i])) if temp==i-1: continue else: A=A[temp::-1]+A[temp+1:] ans.append(temp+1) A=A[i-1::-1]+A[i:] ans.append(i) return ans
pancake-sorting
Python easy solution
RedHeadphone
0
120
pancake sorting
969
0.7
Medium
15,682
https://leetcode.com/problems/pancake-sorting/discuss/642983/Intuitive-approach-by-sorting-from-the-end-of-array-(similar-to-select-sort)
class Solution: def pancakeSort(self, A: List[int]) -> List[int]: sort_k_list = [] ''' sorting k used for pancake flip ''' for i in range(len(A), 0, -1): v = A[i-1] if v != i: # Start pancake sorting # 0) Look for value as `v` vi = A.index(i) # 1) Performing pancake flip twice to move value `v` into # destined position `i` if vi >= 1: sort_k_list.append(vi+1) # 1.1 Move value `v` to first position A[:vi+1] = A[:vi+1][::-1] sort_k_list.append(i) # 1.2 Move value `v` from first position to target position `i` A[:i] = A[:i][::-1] else: # value `v` is already at first position # so swap it to the destined position sort_k_list.append(i) A[:i] = A[:i][::-1] return sort_k_list
pancake-sorting
Intuitive approach by sorting from the end of array (similar to select sort)
puremonkey2001
0
47
pancake sorting
969
0.7
Medium
15,683
https://leetcode.com/problems/powerful-integers/discuss/1184254/Python3-brute-force
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: bx = int(log(bound)/log(x)) if x > 1 else 0 by = int(log(bound)/log(y)) if y > 1 else 0 ans = set() for i in range(bx+1): for j in range(by+1): if x**i + y**j <= bound: ans.add(x**i + y**j) return ans
powerful-integers
[Python3] brute force
ye15
2
45
powerful integers
970
0.436
Medium
15,684
https://leetcode.com/problems/powerful-integers/discuss/795396/Python-Solution%3A-faster-than-100-less-memory-than-64
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: if x == 1 and y == 1: if bound >= 2: return [2] else: return [] ans = [] if x == 1 or y == 1: num = max(x, y) exponent = 0 while num**exponent < bound: ans.append(num**exponent+1) exponent += 1 if num**exponent == bound: ans.append(num**exponent) return set(ans) i, j = 0, 0 while True: ans.append(x**i+y**j) j += 1 if x**i+y**j > bound: j = 0 i += 1 if x**i+y**j > bound: return set(ans)
powerful-integers
Python Solution: faster than 100%, less memory than 64%
amateurpirate
1
102
powerful integers
970
0.436
Medium
15,685
https://leetcode.com/problems/powerful-integers/discuss/2129143/python-3-oror-simple-generator-solution
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: if bound == 0: return [] def get(v): yield 1 if v == 1: return vi = v while vi <= bound: yield vi vi *= v return list({xi + yi for xi in get(x) for yi in get(y) if xi + yi <= bound})
powerful-integers
python 3 || simple generator solution
dereky4
0
30
powerful integers
970
0.436
Medium
15,686
https://leetcode.com/problems/powerful-integers/discuss/1933201/PYTHON-SOL-oror-SIMPLE-oror-LOOPS-oror-EXPLAINED-WELL-oror
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: d = {} a = 1 while a < bound: b = 1 while True: if a + b <= bound: d[a+b] = True b*=y if y == 1: break else: break a *= x if x == 1: break ans = [] for i in d : ans.append(i) return ans
powerful-integers
PYTHON SOL || SIMPLE || LOOPS || EXPLAINED WELL ||
reaper_27
0
51
powerful integers
970
0.436
Medium
15,687
https://leetcode.com/problems/powerful-integers/discuss/1837625/Python-easy-to-read-and-understand-or-math
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: xset, yset = set(), set() for i in range(20): if x**i < bound: xset.add(x**i) for i in range(20): if y**i < bound: yset.add(y**i) ans = set() for i in xset: for j in yset: if i+j <= bound: ans.add(i+j) return list(ans)
powerful-integers
Python easy to read and understand | math
sanial2001
0
30
powerful integers
970
0.436
Medium
15,688
https://leetcode.com/problems/powerful-integers/discuss/1489078/Python-super-simple-solution
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: res = set() powerx = [1] powery = [1] a, b = x, y if x > 1: while x < bound: powerx.append(x) x = x*a if y > 1: while y < bound: powery.append(y) y = y*b for i in range(len(powerx)): for j in range(len(powery)): if powerx[i] + powery[j] <= bound: res.add(powerx[i] + powery[j]) return list(set(res))
powerful-integers
Python super simple solution
byuns9334
0
81
powerful integers
970
0.436
Medium
15,689
https://leetcode.com/problems/powerful-integers/discuss/1184072/Super-Easy-python-solution-Weird-observation
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: if bound <=1: return [] ans=set() for i in range(101): xpow=x**i if xpow > bound: break for j in range(101): s= xpow + y**j if s <= bound: ans.add(s) else: break return ans
powerful-integers
Super Easy python solution, Weird observation
hasham
0
35
powerful integers
970
0.436
Medium
15,690
https://leetcode.com/problems/powerful-integers/discuss/1183895/python-simplest-chillbro
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: s=[] i=0;j=0 while x**(i+1)<=bound: if x==1: break i+=1 while y**(j+1)<=bound: if y==1: break j+=1 for ii in range(i+1): for jj in range(j+1): if x**(ii) + y**(jj) <= bound: s.append((x**(ii) + y**(jj))) s=set(s) s=list(s) return(s)
powerful-integers
python simplest #chillbro
Khacker
0
31
powerful integers
970
0.436
Medium
15,691
https://leetcode.com/problems/powerful-integers/discuss/1183895/python-simplest-chillbro
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: a = bound if x == 1 else int(log(bound, x)) b = bound if y == 1 else int(log(bound, y)) powerful_integers = set([]) for i in range(a + 1): for j in range(b + 1): value = x**i + y**j if value <= bound: powerful_integers.add(value) if y == 1: break if x == 1: break return list(powerful_integers)
powerful-integers
python simplest #chillbro
Khacker
0
31
powerful integers
970
0.436
Medium
15,692
https://leetcode.com/problems/powerful-integers/discuss/1183843/PythonPython3-Solution-with-exaplanation-and-easy-understanding
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: x_bound, y_bound = 0, 0 # assign two variable and set it to zero resLis = set() # to store the values computed if x == 1: # if x is 1 then reinitialize x_bound to 1 x_bound = 1 else: #else take the log value of the given bound here the base value is x x_bound = int(log(bound,x)) if y == 1: # if y is 1 then reinitialize y_bound to 1 y_bound = 1 else: #else take the log value of the given bound here the base value is y y_bound = int(log(bound,y)) print(x_bound,y_bound) #to visualize i have printed the value for i in range(x_bound + 1): #run the loop till x_bound value for j in range(y_bound + 1): #run the loop till y_bound value val = x**i + y**j # compute the value as per given in the problem statement and store it in a variable if val <= bound: #if the val is less than or equal to the bound add it to the set(appending in the set) resLis.add(val) print(resLis) # just printed the resLis to visualize return resLis
powerful-integers
Python/Python3 Solution with exaplanation and easy understanding
prasanthksp1009
0
60
powerful integers
970
0.436
Medium
15,693
https://leetcode.com/problems/powerful-integers/discuss/1183843/PythonPython3-Solution-with-exaplanation-and-easy-understanding
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: x_bound, y_bound = 0, 0 # assign two variable and set it to zero resLis = [] # to store the values computed if x == 1: # if x is 1 then reinitialize x_bound to 1 x_bound = 1 else: #else take the log value of the given bound here the base value is x x_bound = int(log(bound,x)) if y == 1: # if y is 1 then reinitialize y_bound to 1 y_bound = 1 else: #else take the log value of the given bound here the base value is y y_bound = int(log(bound,y)) print(x_bound,y_bound) #to visualize i have printed the value for i in range(x_bound + 1): #run the loop till x_bound value for j in range(y_bound + 1): #run the loop till y_bound value val = x**i + y**j # comput the value as per given in the problem statement and store it in a variable if val <= bound and val not in resLis: #if the val is less than or equal to the bound and the computed val should not be in the list then append it to the list resLis.append(val) print(resLis) return resLis
powerful-integers
Python/Python3 Solution with exaplanation and easy understanding
prasanthksp1009
0
60
powerful integers
970
0.436
Medium
15,694
https://leetcode.com/problems/powerful-integers/discuss/246276/Python.-Good-solution.-Both-speed-and-memory
class Solution: def powerfulIntegers(self, x, y, bound): answer = [] cnt1 = 0 cnt2 = 0 while x**(cnt1+1) <= bound: if x == 1: break cnt1 += 1 while y**(cnt2+1) <= bound: if y == 1: break cnt2 += 1 for i in range(cnt1+1): for j in range(cnt2+1): if x**(i) +y**(j) <= bound: answer.append((x**(i) +y**(j))) answer = set(answer) answer = list(answer) return (answer) x = 1 y = 2 bound = 100 Solution().powerfulIntegers(x,y, bound)
powerful-integers
Python. Good solution. Both speed and memory
ali95
0
228
powerful integers
970
0.436
Medium
15,695
https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/1343381/Elegant-Python-Iterative-and-Recursive-Preorder-Traversals
class Solution: def __init__(self): self.flipped_nodes = [] self.index = 0 def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]: queue = deque([root]) while queue: node = queue.pop() if not node: continue if node.val != voyage[self.index]: return [-1] self.index += 1 if node.left and node.left.val != voyage[self.index]: self.flipped_nodes.append(node.val) node.left, node.right = node.right, node.left queue.append(node.right), queue.append(node.left) return self.flipped_nodes
flip-binary-tree-to-match-preorder-traversal
Elegant Python Iterative & Recursive Preorder Traversals
soma28
0
75
flip binary tree to match preorder traversal
971
0.499
Medium
15,696
https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/1343381/Elegant-Python-Iterative-and-Recursive-Preorder-Traversals
class Solution: def __init__(self): self.flipped_nodes = [] self.index = 0 self.flag = False def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]: def preorder(node = root): if not node: return if node.val != voyage[self.index]: self.flag = True return self.index += 1 if node.left and node.left.val != voyage[self.index]: self.flipped_nodes.append(node.val) node.left, node.right = node.right, node.left preorder(node.left), preorder(node.right) preorder() return self.flipped_nodes if not self.flag else [-1]
flip-binary-tree-to-match-preorder-traversal
Elegant Python Iterative & Recursive Preorder Traversals
soma28
0
75
flip binary tree to match preorder traversal
971
0.499
Medium
15,697
https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/1132472/Python-3-Iterative-DFS
class Solution: def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]: stack, res = [root], [] for i in range(len(voyage) - 1): node = stack.pop() if node.val != voyage[i]: return [-1] if node.left and node.right and node.right.val == voyage[i + 1]: res.append(node.val) stack.extend([node.left, node.right]) else: stack.extend(child for child in [node.right, node.left] if child) return res
flip-binary-tree-to-match-preorder-traversal
[Python 3] Iterative DFS
mcolen
0
76
flip binary tree to match preorder traversal
971
0.499
Medium
15,698
https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/982172/Python3-recursive-dfs
class Solution: def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]: def fn(node, i): """Return if tree can be flipped to match traversal &amp; size.""" if not node: return True, 0 if node.right and node.right.val == voyage[i+1]: if node.left: ans.append(node.val) node.left, node.right = node.right, node.left ltf, lx = fn(node.left, i+1) rtf, rx = fn(node.right, i+1+lx) return node.val == voyage[i] and ltf and rtf, 1 + lx + rx ans = [] return ans if fn(root, 0)[0] else [-1]
flip-binary-tree-to-match-preorder-traversal
[Python3] recursive dfs
ye15
-1
92
flip binary tree to match preorder traversal
971
0.499
Medium
15,699