problem_title
stringlengths
3
77
python_solutions
stringlengths
81
8.45k
post_href
stringlengths
64
213
upvotes
int64
0
1.2k
question
stringlengths
0
3.6k
post_title
stringlengths
2
100
views
int64
1
60.9k
slug
stringlengths
3
77
acceptance
float64
0.14
0.91
user
stringlengths
3
26
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
number
int64
1
2.48k
count array pairs divisible by k
class Solution: def coutPairs(self, nums: List[int], k: int) -> int: factors = [] for x in range(1, int(sqrt(k))+1): if k % x == 0: factors.append(x) ans = 0 freq = Counter() for x in nums: x = gcd(x, k) ans += freq[k//x] for ...
https://leetcode.com/problems/count-array-pairs-divisible-by-k/discuss/1784801/Python3-factors
6
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k. Example 1: Input: nums = [1,2,3,4,5], k = 2 Output: 7 Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are (0...
[Python3] factors
661
count-array-pairs-divisible-by-k
0.287
ye15
Hard
30,301
2,183
counting words with a given prefix
class Solution: def prefixCount(self, words: List[str], pref: str) -> int: return sum(word.find(pref) == 0 for word in words)
https://leetcode.com/problems/counting-words-with-a-given-prefix/discuss/1803163/Python-1-Liner-Solution
3
You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s. Example 1: Input: words = ["pay","attention","practice","attend"], pref = "at" Output: 2 Explanation: The 2 strings that cont...
Python 1 Liner Solution
210
counting-words-with-a-given-prefix
0.771
anCoderr
Easy
30,305
2,185
minimum number of steps to make two strings anagram ii
class Solution: def minSteps(self, s: str, t: str) -> int: fs, ft = Counter(s), Counter(t) return sum((fs-ft).values()) + sum((ft-fs).values())
https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/discuss/1802652/Python3-freq-table
6
You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Input: s = "leetcode", t = ...
[Python3] freq table
307
minimum-number-of-steps-to-make-two-strings-anagram-ii
0.719
ye15
Medium
30,354
2,186
minimum time to complete trips
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: r = min(time) * totalTrips + 1 # This is the worst case answer possible for any case. Could use big values like 10^15 as well but they might slow the time down for smaller cases. l = 0 ans = 0 def check_...
https://leetcode.com/problems/minimum-time-to-complete-trips/discuss/1802433/Python-Solution-oror-Detailed-Article-on-Binary-Search-on-Answer
12
You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the t...
✅ Python Solution || Detailed Article on Binary Search on Answer
694
minimum-time-to-complete-trips
0.32
anCoderr
Medium
30,378
2,187
minimum time to finish the race
class Solution: def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: tires.sort() newTires = [] minTime = [changeTime*(i-1) + tires[0][0]*i for i in range(numLaps+1)] minTime[0] = 0 maxi = 0 for f,r in tires: if not ne...
https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1803014/Python-DP-with-pre-treatment-to-reduce-time-complexity
3
You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, ...
[Python] DP with pre-treatment to reduce time complexity
226
minimum-time-to-finish-the-race
0.419
wssx349
Hard
30,404
2,188
most frequent number following key in an array
class Solution: def mostFrequent(self, nums, key): counts = {} for i in range(1,len(nums)): if nums[i-1]==key: if nums[i] not in counts: counts[nums[i]] = 1 else: counts[nums[i]] += 1 return max(counts, key=counts.get)
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
4
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: 0 <= i <= nums.length - 2, nums[...
Python - Multiple Solutions + One-Liners | Clean and Simple
214
most-frequent-number-following-key-in-an-array
0.605
domthedeveloper
Easy
30,408
2,190
sort the jumbled numbers
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: @cache def convert(i: int): res, pow10 = 0, 1 while i: res += pow10 * mapping[i % 10] i //= 10 pow10 *= 10 return res r...
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822244/Sorted-Lambda
8
You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for a...
Sorted Lambda
869
sort-the-jumbled-numbers
0.453
votrubac
Medium
30,436
2,191
all ancestors of a node in a directed acyclic graph
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: #Use Kahn's algorithm of toposort using a queue and bfs! graph = [[] for _ in range(n)] indegrees = [0] * n #Time: O(n^2) #Space: O(n^2 + n + n) -> O(n^2) #1st...
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2333862/Python3-or-Solved-using-Topo-Sort(Kahn-Algo)-with-Queue(BFS)
4
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list ...
Python3 | Solved using Topo Sort(Kahn Algo) with Queue(BFS)
169
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0.503
JOON1234
Medium
30,448
2,192
minimum number of moves to make palindrome
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: ans = 0 while len(s) > 2: lo = s.find(s[-1]) hi = s.rfind(s[0]) if lo < len(s)-hi-1: ans += lo s = s[:lo] + s[lo+1:-1] else: ans += ...
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2152484/Python3-peel-the-string
1
You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome. Example 1: Inp...
[Python3] peel the string
614
minimum-number-of-moves-to-make-palindrome
0.514
ye15
Hard
30,460
2,193
cells in a range on an excel sheet
class Solution: def cellsInRange(self, s: str) -> List[str]: return [chr(c)+str(r) for c in range(ord(s[0]), ord(s[3])+1) for r in range(int(s[1]), int(s[4])+1)]
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823607/Python3-1-line
7
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: <col> denotes the column number c of the cell. It is represented by alphabetical letters. For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on. <row> is the row number r of the cell. The rth row is represe...
[Python3] 1-line
368
cells-in-a-range-on-an-excel-sheet
0.856
ye15
Easy
30,466
2,194
append k integers with minimal sum
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: ans = k*(k+1)//2 prev = -inf for x in sorted(nums): if prev < x: if x <= k: k += 1 ans += k - x else: break prev = x ...
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823628/Python3-swap
10
You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum. Return the sum of the k integers appended to nums. Example 1: Input: nums = [1,4,25,10,25], k = 2 Output: 5 Explanation: The two unique positive inte...
[Python3] swap
495
append-k-integers-with-minimal-sum
0.25
ye15
Medium
30,497
2,195
create binary tree from descriptions
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: mp = {} seen = set() for p, c, left in descriptions: if p not in mp: mp[p] = TreeNode(p) if c not in mp: mp[c] = TreeNode(c) if left: mp[p].left = mp[c] ...
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823644/Python3-simulation
8
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, If isLefti == 1, then childi is the left child of parenti. If isLefti == 0, then childi is the right child of parenti. Construct...
[Python3] simulation
191
create-binary-tree-from-descriptions
0.722
ye15
Medium
30,515
2,196
replace non coprime numbers in array
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: stack = nums[:1] for j in range(1, len(nums)): cur = nums[j] while stack and math.gcd(stack[-1], cur) > 1: prev = stack.pop() cur = math.lcm(prev, cur)...
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1825538/Python-3-Stack-solution
2
You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime. If no such numbers are found, stop the process. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). Repeat this process as long as you keep finding two...
[Python 3] Stack solution
125
replace-non-coprime-numbers-in-array
0.387
chestnut890123
Hard
30,531
2,197
find all k distant indices in an array
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: ind_j = [] for ind, elem in enumerate(nums): if elem == key: ind_j.append(ind) res = [] for i in range(len(nums)): for j in ind_j: if...
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/2171271/Python-easy-to-understand-oror-Beginner-friendly
4
You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. Example 1: Input: nums = [3,4,9,1,3,9,5], key = 9, ...
✅Python easy to understand || Beginner friendly
147
find-all-k-distant-indices-in-an-array
0.646
Shivam_Raj_Sharma
Easy
30,538
2,200
count artifacts that can be extracted
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: # Time: O(max(artifacts, dig)) which is O(N^2) as every position in the grid can be in dig # Space: O(dig) which is O(N^2) result, dig_pos = 0, set(tuple(pos) for pos in dig) for pos in ar...
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844361/Python-elegant-short-and-simple-to-understand-with-explanations
6
There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried in the subgrid where: (r1i, c1i) is the coordi...
💯 Python elegant, short and simple to understand with explanations
352
count-artifacts-that-can-be-extracted
0.551
yangshun
Medium
30,559
2,201
maximize the topmost element after k moves
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: if len(nums) == 1: if k%2 != 0: return -1 return nums[0] if k == 0: return nums[0] if k == len(nums): return max(nums[:-1]) if k > len(nums):...
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844186/Python-3-Find-Maximum-of-first-k-1-elements-or-(k%2B1)th-element-or-Beats-100
9
You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: If the pile is not empty, remove the topmost element of the pile. If there are one or more removed elements, add any one of them back ...
[Python 3] Find Maximum of first k-1 elements or (k+1)th element | Beats 100%
369
maximize-the-topmost-element-after-k-moves
0.228
hari19041
Medium
30,568
2,202
minimum weighted subgraph with the required paths
class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: forward, backward = dict(), dict() for start, end, weight in edges: if start in forward: if end in forward[start]: forward[start][end] = mi...
https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1867689/Three-min-costs-to-every-node-97-speed
1
You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three di...
Three min costs to every node, 97% speed
144
minimum-weighted-subgraph-with-the-required-paths
0.357
EvgenySH
Hard
30,577
2,203
divide array into equal pairs
class Solution: def divideArray(self, nums: List[int]) -> bool: lena = len(nums) count = sum(num//2 for num in Counter(nums).values()) return (lena/2 == count)
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864079/Python-Solution-Using-Counter-oror-Beats-99-oror-O(n)
6
You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Each element belongs to exactly one pair. The elements present in a pair are equal. Return true if nums can be divided into n pairs, otherwise return false. Example 1: Input: nums = [3,2,3,2,2,2] Output: ...
Python Solution Using Counter || Beats 99% || O(n)
698
divide-array-into-equal-pairs
0.746
IvanTsukei
Easy
30,581
2,206
maximize number of subsequences in a string
class Solution: def maximumSubsequenceCount(self, string: str, pattern: str) -> int: text = pattern[0]+string text1 = string + pattern[1] cnt,cnt1 = 0,0 ans,ans1 = 0,0 for i in range(len(text)): if text[i] == pattern[0]: cnt+=1 ...
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/2501496/Python-Easy-Solution
0
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum...
Python Easy Solution
26
maximize-number-of-subsequences-in-a-string
0.328
Abhi_009
Medium
30,624
2,207
minimum operations to halve array sum
class Solution: def halveArray(self, nums: List[int]) -> int: s = sum(nums) goal = s / 2 res = 0 for i, num in enumerate(nums): nums[i] = -num heapq.heapify(nums) while s > goal: halfLargest = -heapq.heappop(nums) / 2 ...
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1984994/python-3-oror-priority-queue
2
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. Example 1: Input: n...
python 3 || priority queue
79
minimum-operations-to-halve-array-sum
0.452
dereky4
Medium
30,630
2,208
minimum white tiles after covering with carpets
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: @cache def fn(i, n): """Return min while tiles at k with n carpets left.""" if n < 0: return inf if i >= len(floor): return 0 if floor[i] == '1'...
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1874969/Python3-dp
2
You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: floor[i] = '0' denotes that the ith tile of the floor is colored black. On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white. You are also given numCarpets and carpetLen. You have numCarp...
[Python3] dp
51
minimum-white-tiles-after-covering-with-carpets
0.338
ye15
Hard
30,637
2,209
count hills and valleys in an array
class Solution: def countHillValley(self, nums: List[int]) -> int: #cnt: An integer to store total hills and valleys #left: Highest point of hill or lowest point of valley left of the current index cnt, left = 0, nums[0] for i in range(1, len(nums)-1): i...
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1866869/Python3-One-pass-oror-O(1)-space
3
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or va...
[Python3] One pass || O(1) space
82
count-hills-and-valleys-in-an-array
0.581
__PiYush__
Easy
30,644
2,210
count collisions on a road
class Solution: def countCollisions(self, directions: str) -> int: return sum(d!='S' for d in directions.lstrip('L').rstrip('R'))
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865694/One-liner-in-Python
65
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the righ...
One-liner in Python
1,200
count-collisions-on-a-road
0.419
LuckyBoy88
Medium
30,666
2,211
maximum points in an archery competition
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: # Initialization with round 1 (round 0 is skipped) dp = {(0, 0): (0, numArrows), (0, aliceArrows[1] + 1): (1, numArrows - (aliceArrows[1] + 1))} # Loop from round 2 for ...
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1866042/Python3-DP-100-with-Detailed-Explanation
1
Alice and Bob are opponents in an archery competition. The competition has set the following rules: Alice first shoots numArrows arrows and then Bob shoots numArrows arrows. The points are then calculated as follows: The target has integer scoring sections ranging from 0 to 11 inclusive. For each section of the target ...
[Python3] DP 100% with Detailed Explanation
68
maximum-points-in-an-archery-competition
0.489
hsjiang
Medium
30,682
2,212
find the difference of two arrays
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: set_1 = list_to_set(nums1) set_2 = list_to_set(nums2) return remove_same_elements(set_1, set_2) # Convert the lists into sets via helper method. def list_...
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2668224/Python-solution.-Clean-code-with-full-comments.-95.96-speed.
3
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1. Note that the integers in the lists may be returned in any...
Python solution. Clean code with full comments. 95.96% speed.
159
find-the-difference-of-two-arrays
0.693
375d
Easy
30,692
2,215
minimum deletions to make array beautiful
class Solution: def minDeletion(self, nums: List[int]) -> int: # Greedy ! # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0 # at the begining, we consider the num on the even index # when we delete a num, we need consider the num on the odd index ...
https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/discuss/1886918/Python-or-Greedy
10
You are given a 0-indexed integer array nums. The array nums is beautiful if: nums.length is even. nums[i] != nums[i + 1] for all i % 2 == 0. Note that an empty array is considered beautiful. You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted elemen...
Python | Greedy
397
minimum-deletions-to-make-array-beautiful
0.463
Mikey98
Medium
30,733
2,216
find palindrome with fixed length
class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]: # think the palindromes in half # e.g. len = 4 we only consider the first 2 digits # half: 10, 11, 12, 13, 14, ..., 19, 20, # full: 1001, 1111, 1221, 1331, ... # e.g. len = 5 we consid...
https://leetcode.com/problems/find-palindrome-with-fixed-length/discuss/1886956/Python-or-simple-and-straightforward
6
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zer...
Python | simple and straightforward
474
find-palindrome-with-fixed-length
0.343
Mikey98
Medium
30,750
2,217
maximum value of k coins from piles
class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: n, m = len(piles), 0 prefixSum = [] for i in range(n): temp = [0] for j in range(len(piles[i])): temp.append(temp[-1] + piles[i][j]) m += 1 pr...
https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/discuss/1889647/Python-Bottom-up-DP-solution
9
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to ...
[Python] Bottom-up DP solution
407
maximum-value-of-k-coins-from-piles
0.48
xil899
Hard
30,764
2,218
minimum bit flips to convert number
class Solution: def minBitFlips(self, s: int, g: int) -> int: count = 0 while s or g: if s%2 != g%2: count+=1 s, g = s//2, g//2 return count
https://leetcode.com/problems/minimum-bit-flips-to-convert-number/discuss/2775126/Python-Solution-without-XOR
4
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the...
Python Solution without XOR
134
minimum-bit-flips-to-convert-number
0.821
keioon
Easy
30,769
2,220
find triangular sum of an array
class Solution: def triangularSum(self, nums: List[int]) -> int: return sum(n * comb(len(nums) - 1, i) for i, n in enumerate(nums)) % 10
https://leetcode.com/problems/find-triangular-sum-of-an-array/discuss/1909302/Pascal-Triangle
28
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer a...
Pascal Triangle
3,800
find-triangular-sum-of-an-array
0.79
votrubac
Medium
30,798
2,221
number of ways to select buildings
class Solution: def numberOfWays(self, s: str) -> int: zeros = s.count('0') ones = len(s) - zeros zeroPrefix = onePrefix = res = 0 for c in s: if c == '0': res += onePrefix * (ones - onePrefix) zeroPrefix += 1 else: ...
https://leetcode.com/problems/number-of-ways-to-select-buildings/discuss/1979756/python-3-oror-short-and-simple-oror-O(n)O(1)
5
You are given a 0-indexed binary string s which represents the types of buildings along a street where: s[i] = '0' denotes that the ith building is an office and s[i] = '1' denotes that the ith building is a restaurant. As a city official, you would like to select 3 buildings for random inspection. However, to ensure v...
python 3 || short and simple || O(n)/O(1)
304
number-of-ways-to-select-buildings
0.512
dereky4
Medium
30,844
2,222
sum of scores of built strings
class Solution: def sumScores(self, s: str) -> int: mod = 119_218_851_371 hs = 0 vals = [0] for i, ch in enumerate(s): hs = (hs * 26 + ord(ch) - 97) % mod vals.append(hs) p26 = [1] for _ in range(len(s)): p26.append(p26[-1] * 26 % mo...
https://leetcode.com/problems/sum-of-scores-of-built-strings/discuss/2256814/Python3-rolling-hash-and-z-algorithm
1
You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc. The score of si is the length of the longes...
[Python3] rolling hash & z-algorithm
82
sum-of-scores-of-built-strings
0.37
ye15
Hard
30,852
2,223
minimum number of operations to convert time
class Solution: def convertTime(self, current: str, correct: str) -> int: current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes diff = target_time - current_time # Difference b/w c...
https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/discuss/1908786/Easy-Python-Solution-or-Convert-time-to-minutes
30
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. Yo...
⭐Easy Python Solution | Convert time to minutes
1,200
minimum-number-of-operations-to-convert-time
0.655
anCoderr
Easy
30,856
2,224
find players with zero or one losses
class Solution: def findWinners(self, matches: List[List[int]]) -> List[List[int]]: winners, losers, table = [], [], {} for winner, loser in matches: # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented. # map.get(key, 0) re...
https://leetcode.com/problems/find-players-with-zero-or-one-losses/discuss/1908760/Python-Solution-with-Hashmap
22
You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match. Return a list answer of size 2 where: answer[0] is a list of all players that have not lost any matches. answer[1] is a list of all players that have lost exactly one match. T...
⭐Python Solution with Hashmap
1,200
find-players-with-zero-or-one-losses
0.686
anCoderr
Medium
30,877
2,225
maximum candies allocated to k children
class Solution: def maximumCandies(self, candies, k): n = len(candies) left = 1 # the least number of candy in each stack we can give to each student is one right = max(candies) # the max number of candy in each stack that we can give to each student is the maximum number in the candies ar...
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1912213/Easy-To-Understand-Python-Solution-(Binary-Search)
2
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each chil...
Easy To Understand Python Solution (Binary Search)
87
maximum-candies-allocated-to-k-children
0.361
danielkua
Medium
30,899
2,226
largest number after digit swaps by parity
class Solution: def largestInteger(self, num: int): n = len(str(num)) arr = [int(i) for i in str(num)] odd, even = [], [] for i in arr: if i % 2 == 0: even.append(i) else: odd.append(i) odd.sort() even.sort() ...
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931017/Python-Solution-using-Sorting
17
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. Example 1: Input: num = 1234 Output: 3412 Explanation: Swap the digit 3 with the digit 1, this results in t...
Python Solution using Sorting
1,500
largest-number-after-digit-swaps-by-parity
0.605
anCoderr
Easy
30,913
2,231
minimize result by adding parentheses to expression
class Solution: def minimizeResult(self, expression: str) -> str: plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression] def evaluate(exps: str): return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*')) for l in range(plus_index...
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931004/Python-Solution-using-2-Pointers-Brute-Force
12
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthes...
Python Solution using 2 Pointers Brute Force
1,500
minimize-result-by-adding-parentheses-to-expression
0.651
anCoderr
Medium
30,930
2,232
maximum product after k increments
class Solution: def maximumProduct(self, nums: List[int], k: int) -> int: heap = nums.copy() heapify(heap) for i in range(k): t = heappop(heap) heappush(heap, t + 1) ans = 1 mod = 1000000007 for i in heap: ans = (ans*i) % mod ...
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1930986/Python-Solution-using-Min-Heap
2
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product befo...
➡️Python Solution using Min Heap
150
maximum-product-after-k-increments
0.413
anCoderr
Medium
30,947
2,233
maximum total beauty of the gardens
class Solution: def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int: flowers = sorted(min(target, x) for x in flowers) prefix = [0] ii = -1 for i in range(len(flowers)): if flowers[i] < target: ii = i if...
https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/discuss/2313576/Python3-2-pointer
1
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given...
[Python3] 2-pointer
61
maximum-total-beauty-of-the-gardens
0.283
ye15
Hard
30,958
2,234
add two integers
class Solution: def sum(self, num1: int, num2: int) -> int: return num1 + num2
https://leetcode.com/problems/add-two-integers/discuss/2670517/Solutions-in-Every-Language-*on-leetcode*-or-One-Liner
5
Given two integers num1 and num2, return the sum of the two integers. Example 1: Input: num1 = 12, num2 = 5 Output: 17 Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. Example 2: Input: num1 = -10, num2 = 4 Output: -6 Explanation: num1 + num2 = -6, so -6 is returned. Constraints:...
Solutions in Every Language *on leetcode* | One-Liner ✅
465
add-two-integers
0.894
qing306037
Easy
30,961
2,235
root equals sum of children
class Solution: def checkTree(self, root: Optional[TreeNode]) -> bool: return root.left.val+root.right.val == root.val
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2178260/Python-oneliner
5
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise. Example 1: Input: root = [10,4,6] Output: true Explanation: The values of the root, i...
Python oneliner
322
root-equals-sum-of-children
0.869
StikS32
Easy
30,983
2,236
find closest number to zero
class Solution: def findClosestNumber(self, nums: List[int]) -> int: m = 10 ** 6 for i in nums: x = abs(i-0) if x < m: m = x val = i elif x == m and val < i: val = i return val
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1959624/Python-dollarolution
2
Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value. Example 1: Input: nums = [-4,-2,1,4,8] Output: 1 Explanation: The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The distanc...
Python $olution
180
find-closest-number-to-zero
0.458
AakRay
Easy
30,998
2,239
number of ways to buy pens and pencils
class Solution: def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int: if total < cost1 and total < cost2: return 1 ways = 0 if cost1 > cost2: for i in range(0, (total // cost1)+1): rem = total - (i * cost1) ways += ...
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1962778/Python-easy-solution-faster-than-90
2
You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil. Return the number of distinct ways ...
Python easy solution faster than 90%
84
number-of-ways-to-buy-pens-and-pencils
0.57
alishak1999
Medium
31,026
2,240
maximum score of a node sequence
class Solution: def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int: connection = {} for source, target in edges: if source not in connection: connection[source] = [target] else: connection[source].append(target) if target not in conn...
https://leetcode.com/problems/maximum-score-of-a-node-sequence/discuss/1984916/Python3-O(orEor)-solution
2
There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A no...
Python3 O(|E|) solution
239
maximum-score-of-a-node-sequence
0.375
xxHRxx
Hard
31,037
2,242
calculate digit sum of a string
class Solution: def digitSum(self, s: str, k: int) -> str: while len(s) > k: set_3 = [s[i:i+k] for i in range(0, len(s), k)] s = '' for e in set_3: val = 0 for n in e: val += int(n) s += str(val) ...
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955460/Python3-elegant-pythonic-clean-and-easy-to-understand
10
You are given a string s consisting of digits and an integer k. A round can be completed if the length of s is greater than k. In one round, do the following: Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Not...
Python3 elegant pythonic clean and easy to understand
881
calculate-digit-sum-of-a-string
0.668
Tallicia
Easy
31,038
2,243
minimum rounds to complete all tasks
class Solution: def minimumRounds(self, tasks: List[int]) -> int: table, res = Counter(tasks), 0 # Counter to hold frequency of ith task and res stores the result. for count in table.values(): if count <= 1: return -1 # If count <= 1 then it cannot follow the condition hence return -1. ...
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955367/Well-Explained-Python-Solution
4
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. Example 1: Inp...
⭐ Well Explained Python Solution
184
minimum-rounds-to-complete-all-tasks
0.575
anCoderr
Medium
31,071
2,244
maximum trailing zeros in a cornered path
class Solution: def maxTrailingZeros(self, grid: List[List[int]]) -> int: ans = 0 m, n = len(grid), len(grid[0]) prefixH = [[[0] * 2 for _ in range(n + 1)] for __ in range(m)] prefixV = [[[0] * 2 for _ in range(n)] for __ in range(m + 1)] for i in range(m): for j ...
https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1955502/Python-Prefix-Sum-O(m-*-n)
7
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a pr...
[Python] Prefix Sum, O(m * n)
574
maximum-trailing-zeros-in-a-cornered-path
0.35
xil899
Medium
31,090
2,245
longest path with different adjacent characters
class Solution: def longestPath(self, par: List[int], s: str) -> int: dit = {} # store tree in dictionary for i in range(len(par)): if par[i] in dit: dit[par[i]].append(i) else: dit[par[i]] = [i] ans = 1 ...
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2494179/Python-oror-Faster-than-100-oror-Simple-DFS-oror-Easy-Explanation
10
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s o...
Python || Faster than 100% || Simple DFS || Easy Explanation
359
longest-path-with-different-adjacent-characters
0.453
Laxman_Singh_Saini
Hard
31,094
2,246
intersection of multiple arrays
class Solution: def intersection(self, nums: List[List[int]]) -> List[int]: res = set(nums[0]) for i in range(1, len(nums)): res &amp;= set(nums[i]) res = list(res) res.sort() return res
https://leetcode.com/problems/intersection-of-multiple-arrays/discuss/2428232/94.58-faster-using-set-and-and-operator-in-Python
6
Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order. Example 1: Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] Output: [3,4] Explanation: The only integers present in each of nums...
94.58% faster using set and & operator in Python
172
intersection-of-multiple-arrays
0.695
ankurbhambri
Easy
31,101
2,248
count lattice points inside a circle
class Solution: def countLatticePoints(self, circles: List[List[int]]) -> int: points = set() for x, y, r in circles: for dx in range(-r, r + 1, 1): temp = math.floor(math.sqrt(r ** 2 - dx ** 2)) for dy in range(-temp, temp + 1): points...
https://leetcode.com/problems/count-lattice-points-inside-a-circle/discuss/1977094/Python-Math-(Geometry)-and-Set-Solution-No-Brute-Force
1
Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle. Note: A lattice point is a point with integer coordinates. Points that lie on the circumferenc...
[Python] Math (Geometry) and Set Solution, No Brute Force
60
count-lattice-points-inside-a-circle
0.503
xil899
Medium
31,147
2,249
count number of rectangles containing each point
class Solution: def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]: mp = defaultdict(list) for l, h in rectangles: mp[h].append(l) for v in mp.values(): v.sort() ans = [] for x, y in points: cnt = 0 for yy in...
https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/discuss/1980349/Python3-binary-search
3
You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj). The ith rectangle has its bottom-left corner point at the coordinat...
[Python3] binary search
55
count-number-of-rectangles-containing-each-point
0.341
ye15
Medium
31,154
2,250
number of flowers in full bloom
class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: start, end, res = [], [], [] for i in flowers: start.append(i[0]) end.append(i[1]) start.sort() #bisect only works with sorted data end.sort() for p...
https://leetcode.com/problems/number-of-flowers-in-full-bloom/discuss/2757459/Binary-Search-with-Explanation-Fast-and-Easy-Solution
0
You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers. Return an integ...
Binary Search with Explanation - Fast and Easy Solution
2
number-of-flowers-in-full-bloom
0.519
user6770yv
Hard
31,158
2,251
count prefixes of a given string
class Solution: def countPrefixes(self, words: List[str], s: str) -> int: count=0 for i in words: if (s[:len(i)]==i): count+=1 return count
https://leetcode.com/problems/count-prefixes-of-a-given-string/discuss/2076295/Easy-python-solution
9
You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s. A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a st...
Easy python solution
336
count-prefixes-of-a-given-string
0.734
tusharkhanna575
Easy
31,166
2,255
minimum average difference
class Solution: def minimumAverageDifference(self, a: List[int]) -> int: l=0 r=sum(a) z=100001 y=0 n=len(a) for i in range(n-1): l+=a[i] r-=a[i] d=abs((l//(i+1))-(r//(n-i-1))) if d<z: z=...
https://leetcode.com/problems/minimum-average-difference/discuss/2098497/PYTHON-oror-EASY-oror-BEGINER-FRIENDLY
1
You are given a 0-indexed integer array nums of length n. The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. Return the index with the minimu...
✔️PYTHON || EASY || ✔️ BEGINER FRIENDLY
75
minimum-average-difference
0.359
karan_8082
Medium
31,199
2,256
count unguarded cells in the grid
class Solution: def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int: vis = [[0]*n for _ in range(m)] # i - rows, j - colums # sum(row.count('hit') for row in grid) for i,j in walls: vis[i][j] = 2 for i,j in guards: ...
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994806/Simple-python-code
1
You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively. A guard can see every cell in the four cardinal directions (nor...
Simple python code
37
count-unguarded-cells-in-the-grid
0.522
beast316
Medium
31,211
2,257
escape the spreading fire
class Solution: def maximumMinutes(self, grid: List[List[int]]) -> int: #region growing to assign each grass with the time that it will catch fire m, n = len(grid), len(grid[0]) start = [] for i in range(m): for j in range(n): if grid[i][j] == 1:...
https://leetcode.com/problems/escape-the-spreading-fire/discuss/2005513/Python3-BFS-%2B-DFS-%2B-Binary-Search-Solution
0
You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: 0 represents grass, 1 represents fire, 2 represents a wall that you and fire cannot pass through. You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the botto...
Python3 BFS + DFS + Binary Search Solution
44
escape-the-spreading-fire
0.347
xxHRxx
Hard
31,221
2,258
remove digit from number to maximize result
class Solution: def removeDigit(self, number: str, digit: str) -> str: # Initializing the last index as zero last_index = 0 #iterating each number to find the occurences, \ # and to find if the number is greater than the next element \ for num in range(1, ...
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2074599/Python-O(N)-solution-oror-Faster-than-99-submissions-oror-Detailed-explanation.
16
You are given a string number representing a positive integer and a character digit. Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in numbe...
🔥🔥🔥Python O(N) solution || Faster than 99% submissions || Detailed explanation.
1,400
remove-digit-from-number-to-maximize-result
0.47
litdatascience
Easy
31,224
2,259
minimum consecutive cards to pick up
class Solution: def minimumCardPickup(self, cards: List[int]) -> int: minPick = float('inf') seen = {} for i, n in enumerate(cards): if n in seen: if i - seen[n] + 1 < minPick: minPick = i - seen[n] + 1 seen[n] = i if minPic...
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996393/Python3-or-Beginner-friendly-explained-or
22
You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards,...
Python3 | Beginner-friendly explained |
919
minimum-consecutive-cards-to-pick-up
0.517
hanjo108
Medium
31,251
2,260
k divisible elements subarrays
class Solution: def countDistinct(self, nums: List[int], k: int, p: int) -> int: n = len(nums) sub_arrays = set() # generate all combinations of subarray for start in range(n): cnt = 0 temp = '' for i in range(start, n): ...
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996643/Python-Simple-Count-all-combinations
20
Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i]. A subarray is defin...
✅ Python - Simple Count all combinations
885
k-divisible-elements-subarrays
0.476
constantine786
Medium
31,275
2,261
total appeal of a string
class Solution: def appealSum(self, s: str) -> int: res, cur, prev = 0, 0, defaultdict(lambda: -1) for i, ch in enumerate(s): cur += i - prev[ch] prev[ch] = i res += cur return res
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996203/DP
245
The appeal of a string is the number of distinct characters found in the string. For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'. Given a string s, return the total appeal of all of its substrings. A substring is a contiguous sequence of characters within a string. Exam...
DP
10,100
total-appeal-of-a-string
0.583
votrubac
Hard
31,287
2,262
largest 3 same digit number in string
class Solution: def largestGoodInteger(self, n: str) -> str: return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else "" for i in range(2, len(n)))
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2017786/Compare-with-2-previous
51
You are given a string num representing a large integer. An integer is good if it meets the following conditions: It is a substring of num with length 3. It consists of only one unique digit. Return the maximum good integer as a string or an empty string "" if no such integer exists. Note: A substring is a contiguous s...
Compare with 2 previous
2,300
largest-3-same-digit-number-in-string
0.59
votrubac
Easy
31,303
2,264
count nodes equal to average of subtree
class Solution: def averageOfSubtree(self, root: Optional[TreeNode]) -> int: def fn(node): nonlocal ans if not node: return 0, 0 ls, ln = fn(node.left) rs, rn = fn(node.right) s = node.val + ls + rs n = 1 + ln + rn ...
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2017794/Python3-post-order-dfs
6
Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. Note: The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer. A subtree of root is a tree consisting of root and all of its d...
[Python3] post-order dfs
266
count-nodes-equal-to-average-of-subtree
0.856
ye15
Medium
31,327
2,265
count number of texts
class Solution: def countTexts(self, pressedKeys: str) -> int: MOD = 1_000_000_007 @cache def fn(n, k): """Return number of possible text of n repeated k times.""" if n < 0: return 0 if n == 0: return 1 ans = 0 for x in ...
https://leetcode.com/problems/count-number-of-texts/discuss/2017834/Python3-group-by-group
8
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. For example, to add the letter 's', Alice has to press '7' four times. Similarly...
[Python3] group-by-group
371
count-number-of-texts
0.473
ye15
Medium
31,339
2,266
check if there is a valid parentheses string path
class Solution: def hasValidPath(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) @lru_cache(maxsize=None) def hasValidPathInner(x, y, cnt): # cnt variable would act as a counter to track # the balance of parantheses sequence ...
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2018005/Python-Simple-MemoisationCaching
13
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given an m x...
✅ Python Simple Memoisation/Caching
405
check-if-there-is-a-valid-parentheses-string-path
0.38
constantine786
Hard
31,346
2,267
find the k beauty of a number
class Solution: """ Time: O(log10(n)*k) Memory: O(log10(n)) """ def divisorSubstrings(self, num: int, k: int) -> int: str_num = str(num) return sum( num % int(str_num[i - k:i]) == 0 for i in range(k, len(str_num) + 1) if int(str_num[i - k:i]) !=...
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2611592/Python-Elegant-and-Short-or-Sliding-window-or-O(log10(n))-time-or-O(1)-memory
3
The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions: It has a length of k. It is a divisor of num. Given integers num and k, return the k-beauty of num. Note: Leading zeros are allowed. 0 is not a divisor of any value. A substring i...
Python Elegant & Short | Sliding window | O(log10(n)) time | O(1) memory
211
find-the-k-beauty-of-a-number
0.567
Kyrylo-Ktl
Easy
31,355
2,269
number of ways to split array
class Solution: def waysToSplitArray(self, n: List[int]) -> int: n = list(accumulate(n)) return sum(n[i] >= n[-1] - n[i] for i in range(len(n) - 1))
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038567/Prefix-Sum
14
You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. There is at least one element to the right of i. That is, 0 <= i < n - 1. Return the number ...
Prefix Sum
1,100
number-of-ways-to-split-array
0.446
votrubac
Medium
31,385
2,270
maximum white tiles covered by a carpet
class Solution: def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int: tiles.sort() ans = ii = val = 0 for i in range(len(tiles)): hi = tiles[i][0] + carpetLen - 1 while ii < len(tiles) and tiles[ii][1] <= hi: val += tiles[ii][1]...
https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/discuss/2148636/Python3-greedy
1
You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white. You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere. Return the maximum number of white tiles that can be covered by the carpet. Exa...
[Python3] greedy
105
maximum-white-tiles-covered-by-a-carpet
0.327
ye15
Medium
31,402
2,271
substring with largest variance
class Solution: def largestVariance(self, s: str) -> int: ans = 0 seen = set(s) for x in ascii_lowercase: for y in ascii_lowercase: if x != y and x in seen and y in seen: vals = [] for ch in s: i...
https://leetcode.com/problems/substring-with-largest-variance/discuss/2148640/Python3-pairwise-prefix-sum
3
The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s. A ...
[Python3] pairwise prefix sum
620
substring-with-largest-variance
0.374
ye15
Hard
31,410
2,272
find resultant array after removing anagrams
class Solution: def removeAnagrams(self, w: List[str]) -> List[str]: return [next(g) for _, g in groupby(w, sorted)]
https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/discuss/2039752/Weird-Description
39
You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satis...
Weird Description
2,900
find-resultant-array-after-removing-anagrams
0.583
votrubac
Easy
31,414
2,273
maximum consecutive floors without special floors
class Solution: def maxConsecutive(self, bottom: int, top: int, special: list[int]) -> int: special.sort() res = special[0] - bottom for i in range(1, len(special)): res = max(res, special[i] - special[i - 1] - 1) return max(res, top - special[-1])
https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/discuss/2039754/Python-Simulation-Just-sort-the-array-special
7
Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only. You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the...
Python Simulation - Just sort the array special
326
maximum-consecutive-floors-without-special-floors
0.521
GigaMoksh
Medium
31,445
2,274
largest combination with bitwise and greater than zero
class Solution: def largestCombination(self, candidates: List[int]) -> int: return max(sum(n &amp; (1 << i) > 0 for n in candidates) for i in range(0, 24))
https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/discuss/2039717/Check-Each-Bit
55
The bitwise AND of an array nums is the bitwise AND of all integers in nums. For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candi...
Check Each Bit
3,600
largest-combination-with-bitwise-and-greater-than-zero
0.724
votrubac
Medium
31,457
2,275
percentage of letter in string
class Solution: def percentageLetter(self, s: str, letter: str) -> int: a = s.count(letter) return (a*100)//len(s)
https://leetcode.com/problems/percentage-of-letter-in-string/discuss/2061930/Simple-Python-Solution-or-Easy-to-Understand-or-Two-Liner-Solution-or-O(N)-Solution
2
Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent. Example 1: Input: s = "foobar", letter = "o" Output: 33 Explanation: The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we...
Simple Python Solution | Easy to Understand | Two Liner Solution | O(N) Solution
63
percentage-of-letter-in-string
0.741
AkashHooda
Easy
31,468
2,278
maximum bags with full capacity of rocks
class Solution: def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int: remaining = [0] * len(capacity) res = 0 for i in range(len(capacity)): remaining[i] = capacity[i] - rocks[i] remaining.sort() for i in rang...
https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/discuss/2062186/Python-Easy-Solution
1
You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags. Return the m...
Python Easy Solution
28
maximum-bags-with-full-capacity-of-rocks
0.626
MiKueen
Medium
31,492
2,279
minimum lines to represent a line chart
class Solution: def minimumLines(self, stockPrices: List[List[int]]) -> int: # key point: never use devision to judge whether 3 points are on a same line or not, use the multiplication instead !! n = len(stockPrices) stockPrices.sort(key = lambda x: (x[0], x[1])) if...
https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/discuss/2061893/Python-or-Easy-to-Understand
11
You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent point...
Python | Easy to Understand
548
minimum-lines-to-represent-a-line-chart
0.238
Mikey98
Medium
31,507
2,280
sum of total strength of wizards
class Solution: def totalStrength(self, strength: List[int]) -> int: strength = [0] + strength + [0] def calc_prefix_sum(array): if not array: return [] result = [array[0]] for el in array[1:]: result.append(array[-1]+el) return result ...
https://leetcode.com/problems/sum-of-total-strength-of-wizards/discuss/2373525/faster-than-98.90-or-easy-python-or-solution
2
As the ruler of a kingdom, you have an army of wizards at your command. You are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of...
faster than 98.90% | easy python | solution
1,800
sum-of-total-strength-of-wizards
0.279
vimla_kushwaha
Hard
31,516
2,281
check if number has equal digit count and digit value
class Solution: def digitCount(self, num: str) -> bool: counter=Counter(num) for i in range(len(num)): if counter[f'{i}'] != int(num[i]): return False return True
https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/discuss/2084112/Python-Easy-solution
3
You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false. Example 1: Input: num = "1210" Output: true Explanation: num[0] = '1'. The digit 0 occurs once in num. num[1] = '2'. The digi...
Python Easy solution
142
check-if-number-has-equal-digit-count-and-digit-value
0.735
constantine786
Easy
31,518
2,283
sender with largest word count
class Solution: def largestWordCount(self, messages: List[str], senders: List[str]) -> str: d={} l=[] for i in range(len(messages)): if senders[i] not in d: d[senders[i]]=len(messages[i].split()) else: d[senders[i]]+=len(messages[i].spl...
https://leetcode.com/problems/sender-with-largest-word-count/discuss/2084222/Easy-Python-Solution-With-Dictionary
7
You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note ...
Easy Python Solution With Dictionary
356
sender-with-largest-word-count
0.561
a_dityamishra
Medium
31,546
2,284
maximum total importance of roads
class Solution: def maximumImportance(self, n: int, roads: List[List[int]]) -> int: Arr = [0] * n # i-th city has Arr[i] roads for A,B in roads: Arr[A] += 1 # Each road increase the road count Arr[B] += 1 Arr.sort() # Cities with most road should receive the most sc...
https://leetcode.com/problems/maximum-total-importance-of-roads/discuss/2083990/Very-simple-Python-solution-O(nlog(n))
14
You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1. You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. You need to assign each city with an integer value from 1 to n...
Very simple Python solution O(nlog(n))
452
maximum-total-importance-of-roads
0.608
Eba472
Medium
31,580
2,285
rearrange characters to make target string
class Solution: def rearrangeCharacters(self, s: str, target: str) -> int: counter_s = Counter(s) return min(counter_s[c] // count for c,count in Counter(target).items())
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2085849/Python-Two-Liner-Beats-~95
14
You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. Example 1: Input: s = "ilovecodingonleetcode", target = "code" Output: 2 Explanatio...
Python Two Liner Beats ~95%
854
rearrange-characters-to-make-target-string
0.578
constantine786
Easy
31,592
2,287
apply discount to prices
class Solution: def discountPrices(self, sentence: str, discount: int) -> str: s = sentence.split() # convert to List to easily update m = discount / 100 for i,word in enumerate(s): if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format ...
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085723/Simple-Python-with-explanation
7
A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign. For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not. You are giv...
Simple Python with explanation
311
apply-discount-to-prices
0.274
Eba472
Medium
31,615
2,288
steps to make array non decreasing
class Solution: def totalSteps(self, nums: List[int]) -> int: n = len(nums) l = [i-1 for i in range(n)] r = [i+1 for i in range(n)] q = [] dist = dict() ans = 0 for i in range(1, n): if nums[i] < nums[i-1]: q.append(i) ...
https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2567529/BFS-with-updating-neighbours-or-O(n)-or-Python3
0
You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length. Return the number of steps performed until nums becomes a non-decreasing array. Example 1: Input: nums = [5,3,4,4,7,3,6,11,8,5,11] Output: 3 Explanation: The following are th...
BFS with updating neighbours | O(n) | Python3
67
steps-to-make-array-non-decreasing
0.214
DheerajGadwala
Medium
31,634
2,289
minimum obstacle removal to reach corner
class Solution: def minimumObstacles(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dist = [[inf]*n for _ in range(m)] dist[0][0] = 0 pq = [(0, 0, 0)] while pq: x, i, j = heappop(pq) if i == m-1 and j == n-1: return x ...
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2313936/Python3-Dijkstra's-algo
1
You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values: 0 represents an empty cell, 1 represents an obstacle that may be removed. You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left ...
[Python3] Dijkstra's algo
32
minimum-obstacle-removal-to-reach-corner
0.487
ye15
Hard
31,637
2,290
min max game
class Solution: def minMaxGame(self, nums: List[int]) -> int: l=nums while len(l)>1: is_min=True tmp=[] for i in range(0, len(l), 2): if is_min: tmp.append(min(l[i:i+2])) else: ...
https://leetcode.com/problems/min-max-game/discuss/2112349/Python-Easy-Approach
8
You are given a 0-indexed integer array nums whose length is a power of 2. Apply the following algorithm on nums: Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2. For every even index i where 0 <= i < n / 2, assign the value of newNums[i] ...
✅ Python Easy Approach
503
min-max-game
0.643
constantine786
Easy
31,641
2,293
partition array such that maximum difference is k
class Solution: def partitionArray(self, nums: List[int], k: int) -> int: nums.sort() ans = 1 # To keep track of starting element of each subsequence start = nums[0] for i in range(1, len(nums)): diff = nums[i] - start if diff > k: # If differen...
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2111923/Python-Easy-Solution-using-Sorting
19
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at...
Python Easy Solution using Sorting
877
partition-array-such-that-maximum-difference-is-k
0.726
MiKueen
Medium
31,669
2,294
replace elements in an array
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: replacements = {} for x, y in reversed(operations): replacements[x] = replacements.get(y, y) for idx, val in enumerate(nums): if val in replacements: ...
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112285/Python-Simple-Map-Approach
25
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1]. It is guaranteed that in the ith operation: operations[i][0] exists in nums. operations[i][1] does not exist in ...
✅ Python Simple Map Approach
1,300
replace-elements-in-an-array
0.576
constantine786
Medium
31,692
2,295
strong password checker ii
class Solution: def strongPasswordCheckerII(self, pwd: str) -> bool: return ( len(pwd) > 7 and max(len(list(p[1])) for p in groupby(pwd)) == 1 and reduce( lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0 ...
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139499/Nothing-Special
22
A password is said to be strong if it satisfies all the following criteria: It has at least 8 characters. It contains at least one lowercase letter. It contains at least one uppercase letter. It contains at least one digit. It contains at least one special character. The special characters are the characters in the fol...
Nothing Special
882
strong-password-checker-ii
0.567
votrubac
Easy
31,708
2,299
successful pairs of spells and potions
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() ans, n = [], len(potions) for spell in spells: val = success // spell if success % spell == 0: idx = bisect.bisect_left(potions,...
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139547/Python-3-or-Math-Binary-Search-or-Explanation
2
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. You are also given an integer success. A spell and potion pair is considered successful if the product of their...
Python 3 | Math, Binary Search | Explanation
89
successful-pairs-of-spells-and-potions
0.317
idontknoooo
Medium
31,719
2,300
match substring after replacement
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: s_maps = defaultdict(lambda : set()) for x,y in mappings: s_maps[x].add(y) # build a sequence of set for substring match # eg: sub=leet, mappings = {e: 3, t:7...
https://leetcode.com/problems/match-substring-after-replacement/discuss/2140652/Python-Precalculation-O(n*k)-without-TLE
7
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi. Each character in sub cannot be replaced more than once. Return true if it is poss...
✅ Python Precalculation O(n*k) without TLE
181
match-substring-after-replacement
0.393
constantine786
Hard
31,727
2,301
count subarrays with score less than k
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: sum, res, j = 0, 0, 0 for i, n in enumerate(nums): sum += n while sum * (i - j + 1) >= k: sum -= nums[j] j += 1 res += i - j + 1 return res
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2138778/Sliding-Window
126
The score of an array is defined as the product of its sum and its length. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75. Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k. A subarray is a contiguous seq...
Sliding Window
4,700
count-subarrays-with-score-less-than-k
0.522
votrubac
Hard
31,734
2,302
calculate amount paid in taxes
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ans = prev = 0 for hi, pct in brackets: hi = min(hi, income) ans += (hi - prev)*pct/100 prev = hi return ans
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141187/Python3-bracket-by-bracket
14
You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length). Tax is calculated as follows: The first ...
[Python3] bracket by bracket
535
calculate-amount-paid-in-taxes
0.634
ye15
Easy
31,740
2,303
minimum path cost in a grid
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: max_row, max_col = len(grid), len(grid[0]) dp = [[-1] * max_col for _ in range(max_row)] def recursion(row, col): if row == max_row - 1: # If last row then return nodes value ...
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141004/Python-Recursion-%2B-Memoization
13
You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note t...
Python Recursion + Memoization
501
minimum-path-cost-in-a-grid
0.656
anCoderr
Medium
31,761
2,304
fair distribution of cookies
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: l = [0]*k self.s = float('inf') def ser(l,i): if i>=len(cookies): self.s = min(self.s,max(l)) return if max(l)>=self.s: return ...
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141013/Python-optimized-solution-or-Backtracking-Implemented-or-O(KN)-Time-Complexity
5
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distr...
Python optimized solution | Backtracking Implemented | O(K^N) Time Complexity
852
fair-distribution-of-cookies
0.626
AkashHooda
Medium
31,780
2,305
naming a company
class Solution: def distinctNames(self, ideas: List[str]) -> int: names=defaultdict(set) res=0 #to store first letter as key and followed suffix as val for i in ideas: names[i[0]].add(i[1:]) #list of distinct first-letters availabl...
https://leetcode.com/problems/naming-a-company/discuss/2147565/Python-or-Faster-than-100-or-groupby-detailed-explanation
4
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Choose 2 distinct names from ideas, call them ideaA and ideaB. Swap the first letters of ideaA and ideaB with each other. If both of the new names are not...
Python | Faster than 100% | groupby detailed explanation
172
naming-a-company
0.344
anjalianupam23
Hard
31,793
2,306
greatest english letter in upper and lower case
class Solution: def greatestLetter(self, s: str) -> str: cnt = Counter(s) return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), "")
https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2168442/Counter
37
Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string. An English letter b is greater than another letter a if b appears after a in the English alpha...
Counter
2,500
greatest-english-letter-in-upper-and-lower-case
0.686
votrubac
Easy
31,796
2,309
sum of numbers with units digit k
class Solution: def minimumNumbers(self, num: int, k: int) -> int: if num == 0: return 0 if num < k: return -1 if num == k: return 1 ans = -1 i = 1 while i <= 10: if (num - i * k) % 1...
https://leetcode.com/problems/sum-of-numbers-with-units-digit-k/discuss/2168546/Python-oror-Easy-Approach-oror-beats-90.00-Both-Runtime-and-Memory-oror-Remainder
1
Given two integers num and k, consider a set of positive integers with the following properties: The units digit of each integer is k. The sum of the integers is num. Return the minimum possible size of such a set, or -1 if no such set exists. Note: The set can contain multiple instances of the same integer, and the su...
✅Python || Easy Approach || beats 90.00% Both Runtime & Memory || Remainder
43
sum-of-numbers-with-units-digit-k
0.255
chuhonghao01
Medium
31,845
2,310
longest binary subsequence less than or equal to k
class Solution: def longestSubsequence(self, s: str, k: int) -> int: n = len(s) ones = [] # Notice how I reversed the string, # because the binary representation is written from greatest value of 2**n for i, val in enumerate(s[::-1]): if val == '1': ones.appen...
https://leetcode.com/problems/longest-binary-subsequence-less-than-or-equal-to-k/discuss/2168527/PythonororGreedyororFastororEasy-to-undestandoror-With-explanations
5
You are given a binary string s and a positive integer k. Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. Note: The subsequence can contain leading zeroes. The empty string is considered to be equal to 0. A subsequence is a string that can be derived from another...
Python||Greedy||Fast||Easy to undestand|| With explanations
127
longest-binary-subsequence-less-than-or-equal-to-k
0.364
muctep_k
Medium
31,860
2,311
selling pieces of wood
class Solution: def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: dp = [[0]*(n+1) for _ in range(m+1)] for h, w, p in prices: dp[h][w] = p for i in range(1, m+1): for j in range(1, n+1): v = max(dp[k][j] + dp[i - k][j] for k in ran...
https://leetcode.com/problems/selling-pieces-of-wood/discuss/2194345/Python-bottom-up-DP-faster-than-99
1
You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars. To cut a piece of wood, you must make a...
Python bottom up DP faster than 99%
75
selling-pieces-of-wood
0.482
metaphysicalist
Hard
31,875
2,312
count asterisks
class Solution: """ Time: O(n) Memory: O(1) """ def countAsterisks(self, s: str) -> int: is_closed = True count = 0 for c in s: count += is_closed * c == '*' is_closed ^= c == '|' return count class Solution: """ Time: O(n) Memory: O(n) """ def countAsterisks(self, s: str) -> int: re...
https://leetcode.com/problems/count-asterisks/discuss/2484633/Python-Elegant-and-Short-or-Two-solutions-or-One-pass-One-line
3
You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth. Return the number of '*' in s, excluding the '*' between each pair of '|'. Note that each '|' will belong to exactly one pair. ...
Python Elegant & Short | Two solutions | One pass / One line
137
count-asterisks
0.825
Kyrylo-Ktl
Easy
31,877
2,315
count unreachable pairs of nodes in an undirected graph
class Solution: def countPairs(self, n: int, edges: List[List[int]]) -> int: def dfs(graph,node,visited): visited.add(node) self.c += 1 for child in graph[node]: if child not in visited: dfs(graph, child, visited) #buil...
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2199190/Simple-and-easy-to-understand-using-dfs-with-explanation-Python
8
You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. Return the number of pairs of different nodes that are unreachable from each other. ...
Simple and easy to understand using dfs with explanation [Python]
217
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0.386
ratre21
Medium
31,909
2,316
maximum xor after operations
class Solution: def maximumXOR(self, nums: List[int]) -> int: return reduce(lambda x,y: x|y, nums) class Solution: def maximumXOR(self, nums: List[int]) -> int: return reduce(or_, nums) class Solution: def maximumXOR(self, nums: List[int]) -> int: ans = 0 for n in nums: ...
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2366537/Python3-oror-1-line-bit-operations-w-explanation-oror-TM%3A-8887
5
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nu...
Python3 || 1 line, bit operations, w/ explanation || T/M: 88%/87%
88
maximum-xor-after-operations
0.786
warrenruud
Medium
31,922
2,317