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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
elimination game | class Solution:
def lastRemaining(self, n: int) -> int:
if n == 1: return 1
if n&1: n -= 1
return n + 2 - 2*self.lastRemaining(n//2) | https://leetcode.com/problems/elimination-game/discuss/824126/Python3-3-line-O(logN) | 5 | You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:
Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
Repeat the previous step again, but this time from right to left... | [Python3] 3-line O(logN) | 588 | elimination-game | 0.465 | ye15 | Medium | 6,739 | 390 |
perfect rectangle | class Solution:
def isRectangleCover(self, rectangles: List[List[int]]) -> bool:
area = 0
corners = set()
a = lambda: (Y-y) * (X-x)
for x, y, X, Y in rectangles:
area += a()
corners ^= {(x,y), (x,Y), (X,y), (X,Y)}
if len(corners) != ... | https://leetcode.com/problems/perfect-rectangle/discuss/968076/Python-Fast-and-clear-solution-with-explanation | 40 | Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
Return true if all the rectangles together form an exact cover of a rectangular region.
Example 1:
Input: rectangles = [[... | [Python] Fast and clear solution with explanation | 1,200 | perfect-rectangle | 0.325 | modusV | Hard | 6,748 | 391 |
is subsequence | class Solution(object):
def isSubsequence(self, s, t):
# Base case
if not s:
return True
i = 0
# Traverse elements of t string
for j in t:
# If this index matches to the index of s string, increment i pointer...
if j == s[i]:
... | https://leetcode.com/problems/is-subsequence/discuss/2473010/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Two-Pointers-Approach) | 16 | Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence o... | Very Easy || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Two-Pointers Approach) | 998 | is-subsequence | 0.49 | PratikSen07 | Easy | 6,752 | 392 |
utf 8 validation | class Solution:
def validUtf8(self, data: List[int]) -> bool:
n = len(data)
l = [2**i for i in range(7, -1, -1)]
def isXByteSeq(pos, X):
f = data[pos]
rem = data[pos+1:pos+X]
ret = (f&l[X]) == 0
for i in range(X):
r... | https://leetcode.com/problems/utf-8-validation/discuss/2568848/Python3-or-DP-or-Memoization-or-Neat-Solution-or-O(n) | 4 | Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
For a 1-byte character, the first bit is a 0, followed by its Unicode ... | Python3 | DP | Memoization | Neat Solution | O(n) | 497 | utf-8-validation | 0.452 | DheerajGadwala | Medium | 6,807 | 393 |
decode string | class Solution:
def decodeString(self, s: str) -> str:
res,num = "",0
st = []
for c in s:
if c.isdigit():
num = num*10+int(c)
elif c=="[":
st.append(res)
st.append(num)
res=""
num=0
elif c=="]":
pnum = s... | https://leetcode.com/problems/decode-string/discuss/1400105/98-faster-oror-With-and-without-Stack-oror-Cleane-and-Concise | 27 | Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, s... | 🐍 98% faster || With and without Stack || Cleane & Concise 📌📌 | 2,700 | decode-string | 0.576 | abhi9Rai | Medium | 6,831 | 394 |
longest substring with at least k repeating characters | class Solution:
def rec(self, s, k):
c = Counter(s)
if pattern := "|".join(filter(lambda x: c[x] < k, c)):
if arr := list(filter(lambda x: len(x) >= k, re.split(pattern, s))):
return max(map(lambda x: self.rec(x, k), arr))
return 0
... | https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1721267/Faster-than-97.6.-Recursion | 3 | Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
if no such substring exists, return 0.
Example 1:
Input: s = "aaabb", k = 3
Output: 3
Explanation: The longest substring is "aaa", as 'a' is rep... | Faster than 97.6%. Recursion | 244 | longest-substring-with-at-least-k-repeating-characters | 0.448 | mygurbanov | Medium | 6,877 | 395 |
rotate function | class Solution:
def maxRotateFunction(self, A: List[int]) -> int:
s, n = sum(A), len(A)
cur_sum = sum([i*j for i, j in enumerate(A)])
ans = cur_sum
for i in range(n): ans = max(ans, cur_sum := cur_sum + s-A[n-1-i]*n)
return ans | https://leetcode.com/problems/rotate-function/discuss/857056/Python-3-(Py3.8)-or-Math-O(n)-or-Explanation | 6 | You are given an integer array nums of length n.
Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
Return the maximum value of F(0), F(1), ..., F(n-1).
The test cases are ge... | Python 3 (Py3.8) | Math, O(n) | Explanation | 588 | rotate-function | 0.404 | idontknoooo | Medium | 6,894 | 396 |
integer replacement | class Solution:
def integerReplacement(self, n: int) -> int:
cnt = 0
while n != 1:
if n%2 == 0:
n//=2
elif n%4 == 1 or n == 3:
n -= 1
else:
n += 1
cnt += 1
return cnt | https://leetcode.com/problems/integer-replacement/discuss/663134/Two-solution-in-Python | 4 | Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: n = 7
Ou... | Two solution in Python | 351 | integer-replacement | 0.352 | realslimshady | Medium | 6,902 | 397 |
random pick index | class Solution:
def __init__(self, nums: List[int]):
# Reservoir Sampling (which can handle the linked list with unknown size), time complexity O(n) (init: O(1), pick: O(n)), space complextiy O(1)
self.nums = nums
def pick(self, target: int) -> int:
# https://docs.python.org/3/library/... | https://leetcode.com/problems/random-pick-index/discuss/1671979/Python-3-Reservoir-Sampling-O(n)-Time-and-O(1)-Space | 6 | Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Implement the Solution class:
Solution(int[] nums) Initializes the object with the array nums.
int pick(int target) Picks a random index i from n... | Python 3 Reservoir Sampling, O(n) Time & O(1) Space | 453 | random-pick-index | 0.628 | xil899 | Medium | 6,922 | 398 |
evaluate division | class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = {}
for (u, v), w in zip(equations, values):
graph.setdefault(u, []).append((v, 1/w))
graph.setdefault(v, []).append((u, w))
def ... | https://leetcode.com/problems/evaluate-division/discuss/827506/Python3-dfs-and-union-find | 8 | You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.
You are also given some queries, where queries[j] = [Cj, Dj] represents the jth que... | [Python3] dfs & union-find | 489 | evaluate-division | 0.596 | ye15 | Medium | 6,938 | 399 |
nth digit | class Solution:
def findNthDigit(self, n: int) -> int:
digit = base = 1 # starting from 1 digit
while n > 9*base*digit: # upper limit of d digits
n -= 9*base*digit
digit += 1
base *= 10
q, r = divmod(n-1, digit)
return int(str(base + q)[r]) | https://leetcode.com/problems/nth-digit/discuss/828924/Python3-O(logN)-solution | 25 | Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].
Example 1:
Input: n = 3
Output: 3
Example 2:
Input: n = 11
Output: 0
Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
Constrai... | [Python3] O(logN) solution | 2,100 | nth-digit | 0.341 | ye15 | Medium | 6,971 | 400 |
binary watch | class Solution:
def readBinaryWatch(self, n: int) -> List[str]:
return [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') == n] | https://leetcode.com/problems/binary-watch/discuss/371775/Solution-in-Python-3-(beats-~98)-(one-line) | 10 | A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
For example, the below binary watch reads "4:51".
Given an integer turnedOn which represents the number of LEDs th... | Solution in Python 3 (beats ~98%) (one line) | 1,600 | binary-watch | 0.517 | junaidmansuri | Easy | 6,979 | 401 |
remove k digits | class Solution:
def removeKdigits(self, num: str, k: int) -> str:
st = list()
for n in num:
while st and k and st[-1] > n:
st.pop()
k -= 1
if st or n is not '0': # prevent leading zeros
st.append(n)
... | https://leetcode.com/problems/remove-k-digits/discuss/1779520/Python3-MONOTONIC-STACK-(oo)-Explained | 121 | Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Inpu... | ✔️ [Python3] MONOTONIC STACK (o^^o)♪, Explained | 7,900 | remove-k-digits | 0.305 | artod | Medium | 6,998 | 402 |
frog jump | class Solution(object):
def canCross(self, stones):
n = len(stones)
stoneSet = set(stones)
visited = set()
def goFurther(value,units):
if (value+units not in stoneSet) or ((value,units) in visited):
return False
if value+units == stones[n-1]:
... | https://leetcode.com/problems/frog-jump/discuss/418003/11-line-DFS-solution | 20 | A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones positions (in units) in sorted ascending order, determine if the frog can cross the river by landing... | 11 line DFS solution | 2,700 | frog-jump | 0.432 | nirajmotiani | Hard | 7,025 | 403 |
sum of left leaves | class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# does this node have a left child which is a leaf?
if root.left and not root.left.left and not root.left.right:
# gotcha
return root.left.val + self.sumOfLeftLeaves(... | https://leetcode.com/problems/sum-of-left-leaves/discuss/1558223/Python-DFSRecursion-Easy-%2B-Intuitive | 36 | Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.... | Python DFS/Recursion Easy + Intuitive | 2,000 | sum-of-left-leaves | 0.563 | aayushisingh1703 | Easy | 7,041 | 404 |
convert a number to hexadecimal | class Solution:
def toHex(self, num: int) -> str:
hex="0123456789abcdef" #created string for reference
ot="" # created a string variable to store and update output string
if num==0:
return "0"
elif num<0:
num+=2**32
while num:
ot=hex[num%16... | https://leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/1235709/easy-solution-with-explanation | 12 | Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to... | easy solution with explanation | 756 | convert-a-number-to-hexadecimal | 0.462 | souravsingpardeshi | Easy | 7,071 | 405 |
queue reconstruction by height | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
output=[]
# sort the array in decreasing order of height
# within the same height group, you would sort it in increasing order of k
# eg: Input : [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
... | https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2211602/Python-Easy-Greedy-O(1)-Space-approach | 79 | You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.
Reconstruct and return the queue that is represen... | Python Easy Greedy O(1) Space approach | 3,300 | queue-reconstruction-by-height | 0.728 | constantine786 | Medium | 7,092 | 406 |
trapping rain water ii | class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
if not heightMap or not heightMap[0]:
return 0
# Initial
# Board cells cannot trap the water
m, n = len(heightMap), len(heightMap[0])
if m < 3 or n < 3:
return 0
# Add Bo... | https://leetcode.com/problems/trapping-rain-water-ii/discuss/1138028/Python3Visualization-BFS-Solution-With-Explanation | 209 | Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Example 1:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
Explanation: After the rain, water is trapped between the blocks.
We have t... | [Python3][Visualization] BFS Solution With Explanation | 4,700 | trapping-rain-water-ii | 0.475 | Picassos_Shoes | Hard | 7,114 | 407 |
longest palindrome | class Solution:
def longestPalindrome(self, s: str) -> int:
oddFlag=0
count=collections.Counter(s)
ans=0
for k,v in count.items():
if v%2==1:
ans+=v-1
oddFlag= 1
else:
ans+=v
if... | https://leetcode.com/problems/longest-palindrome/discuss/2221045/Python-oror-counter-oror-explanation | 9 | Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that ca... | Python || counter || explanation | 465 | longest-palindrome | 0.547 | palashbajpai214 | Easy | 7,120 | 409 |
split array largest sum | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def isPossible(maxSum):
curr = count = 0
for i in nums:
count += (i + curr > maxSum)
curr = curr + i if i + curr <= maxSum else i
return count + 1 <= m
l... | https://leetcode.com/problems/split-array-largest-sum/discuss/1901138/Python-Short-and-Simple-NLogSum | 3 | Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.
Return the minimized largest sum of the split.
A subarray is a contiguous part of the array.
Example 1:
Input: nums = [7,2,5,10,8], k = 2
Output: 18
Explanation: There are four w... | ✅ Python Short and Simple NLogSum | 112 | split-array-largest-sum | 0.533 | dhananjay79 | Hard | 7,161 | 410 |
fizz buzz | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ['FizzBuzz' if i%15 == 0 else 'Buzz' if i%5 == 0 else 'Fizz' if i%3 == 0 else str(i) for i in range(1,n+1)]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/fizz-buzz/discuss/380065/Solution-in-Python-3-(beats-~98)-(one-line) | 6 | Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output: ["1",... | Solution in Python 3 (beats ~98%) (one line) | 1,900 | fizz-buzz | 0.69 | junaidmansuri | Easy | 7,186 | 412 |
arithmetic slices | class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
count = 0
for i in range(len(nums)-2):
j = i+1
while(j<len(nums)-1):
if nums[j]-nums[j-1] == nums[j+1]-nums[j]:
count += 1
j += 1
... | https://leetcode.com/problems/arithmetic-slices/discuss/1816132/beginners-solution-Easy-to-understand | 3 | An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarr... | beginners solution, Easy to understand | 201 | arithmetic-slices | 0.651 | harshsatpute16201 | Medium | 7,239 | 413 |
third maximum number | class Solution:
def thirdMax(self, nums: List[int]) -> int:
n, T = list(set(nums)), [float('-inf')]*3
for i in n:
if i > T[0]:
T = [i,T[0],T[1]]
continue
if i > T[1]:
T = [T[0],i,T[1]]
continue
if i > T[2]:
T = [T[0],T[1],i]
return T[2] if T[2] != ... | https://leetcode.com/problems/third-maximum-number/discuss/352011/Solution-in-Python-3-(beats-~99)-(-O(n)-) | 18 | Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Example 1:
Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
Example 2:
In... | Solution in Python 3 (beats ~99%) ( O(n) ) | 3,500 | third-maximum-number | 0.326 | junaidmansuri | Easy | 7,282 | 414 |
add strings | class Solution:
def addStrings(self, num1: str, num2: str) -> str:
num1 = list(num1)
num2 = list(num2)
car = 0
res = ""
while num1 or num2 or car:
if num1:
car += int(num1.pop())
if num2:
car += int(num2.pop())
res += str((car % 10))
car //= 10
return res[::-1] | https://leetcode.com/problems/add-strings/discuss/1591891/Python-Straightforward-Solution-or-Easy-to-Understand | 10 | Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
Input: num1 = "11", n... | Python Straightforward Solution | Easy to Understand | 605 | add-strings | 0.526 | leet_satyam | Easy | 7,334 | 415 |
partition equal subset sum | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums)%2: # or if sum(nums)&1
return False
# main logic here | https://leetcode.com/problems/partition-equal-subset-sum/discuss/1624391/Python-DP-and-DFS-Solutions-Easy-to-understand-with-Explanation | 38 | Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
O... | [Python] DP & DFS Solutions - Easy-to-understand with Explanation | 5,800 | partition-equal-subset-sum | 0.466 | zayne-siew | Medium | 7,384 | 416 |
pacific atlantic water flow | class Solution:
def pacificAtlantic(self, ht: List[List[int]]) -> List[List[int]]:
def pac(i,j):
if rp[i][j]:
return True
k=False
h=ht[i][j]
ht[i][j]=100001
if ht[i-1][j]<=h:
k=k or pac(i-1,j)
... | https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2507252/PYTHON-oror-EXPLAINED-oror | 16 | There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights... | 🥇 PYTHON || EXPLAINED || ; ] | 1,900 | pacific-atlantic-water-flow | 0.541 | karan_8082 | Medium | 7,432 | 417 |
battleships in a board | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
count = 0
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == 'X':
var = 1
if (r > 0 and board[r-1][c] == 'X') or (c > 0 and board[r... | https://leetcode.com/problems/battleships-in-a-board/discuss/1523048/Simple-Easy-to-Understand-Python-O(1)-extra-memory | 9 | Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any ... | Simple Easy to Understand Python O(1) extra memory | 638 | battleships-in-a-board | 0.747 | bshien | Medium | 7,472 | 419 |
strong password checker | class Solution:
def strongPasswordChecker(self, password: str) -> int:
#vimla_kushwaha
s = password
missing_type = 3
if any('a' <= c <= 'z' for c in s): missing_type -= 1
if any('A' <= c <= 'Z' for c in s): missing_type -= 1
if any(c.isdigit() for c in s): missing_typ... | https://leetcode.com/problems/strong-password-checker/discuss/2345991/Runtime%3A-23-ms-or-Memory-Usage%3A-13.9-MB-or-python3 | 2 | A password is considered strong if the below conditions are all met:
It has at least 6 characters and at most 20 characters.
It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.
It does not contain three repeating characters in a row (i.e., "Baaabb0" is weak, but "Baaba0" is... | Runtime: 23 ms | Memory Usage: 13.9 MB | python3 | 309 | strong-password-checker | 0.143 | vimla_kushwaha | Hard | 7,489 | 420 |
maximum xor of two numbers in an array | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
# need to know the largest binary representation
# bin prepends '0b', ignore
L = len(bin(max(nums))) - 2
# preprocess step - left-pad zeros to ensure each number has L bits
# (x >> i) & 1 produces the bit at position i for number... | https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/404504/Python-O(N)-Trie-Solution-wcomments-and-explanations | 2 | Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
Example 1:
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
Example 2:
Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127
Constraints:
1 <= nums.length <= 2 * ... | Python O(N) Trie Solution w/comments and explanations | 904 | maximum-xor-of-two-numbers-in-an-array | 0.545 | crippled_baby | Medium | 7,492 | 421 |
reconstruct original digits from english | class Solution:
def originalDigits(self, s: str) -> str:
c = collections.Counter(s)
digit_count = [0] * 10
digit_count[0] = c['z']
digit_count[2] = c['w']
digit_count[4] = c['u']
digit_count[6] = c['x']
digit_count[8] = c['g']
digit_c... | https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/1556493/Python3-One-pass-solution | 2 | Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.
Example 1:
Input: s = "owoztneoer"
Output: "012"
Example 2:
Input: s = "fviefuro"
Output: "45"
Constraints:
1 <= s.length <= 105
s[i] is one of the characters ["e","g","f","i","h","o","n","s","r",... | [Python3] One pass solution | 361 | reconstruct-original-digits-from-english | 0.513 | maosipov11 | Medium | 7,499 | 423 |
longest repeating character replacement | class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# Maintain a dictionary that keeps track of last 'window' characters
# See if 'window' size minus occurrences of the most common char is <= k, if so it's valid
# Run time is O(length of string * size of alphabet)... | https://leetcode.com/problems/longest-repeating-character-replacement/discuss/900524/Simple-Python-solution-moving-window-O(n)-time-O(1)-space | 16 | You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Example... | Simple Python solution, moving window O(n) time, O(1) space | 2,100 | longest-repeating-character-replacement | 0.515 | wesleyliao3 | Medium | 7,505 | 424 |
construct quad tree | class Solution:
def construct(self, grid: List[List[int]]) -> 'Node':
def fn(x0, x1, y0, y1):
"""Return QuadTree subtree."""
val = {grid[i][j] for i, j in product(range(x0, x1), range(y0, y1))}
if len(val) == 1: return Node(val.pop(), True, None, None, None, Non... | https://leetcode.com/problems/construct-quad-tree/discuss/874250/Python3-building-tree-recursively | 2 | Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree.
Return the root of the Quad-Tree representing grid.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
val: True if the node represents a grid of 1's... | [Python3] building tree recursively | 167 | construct-quad-tree | 0.663 | ye15 | Medium | 7,552 | 427 |
n ary tree level order traversal | class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
result = []
q = deque([root] if root else [])
while q:
result.append([])
for _ in range(len(q)):
node = q.popleft()
result[-1].append(node.val)
... | https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532005/Python-BFS | 14 | Given an n-ary tree, return the level order traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]
Example 2:
Input: ... | Python, BFS | 1,300 | n-ary-tree-level-order-traversal | 0.706 | blue_sky5 | Medium | 7,558 | 429 |
flatten a multilevel doubly linked list | class Solution:
def flatten(self, head: 'Node') -> 'Node':
def getTail(node):
prev = None
while node:
_next = node.next
if node.child:
# ... <-> node <-> node.child <-> ...
node.next = node.child
node.child ... | https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1550377/Python-Recursion%3A-Easy-to-understand-with-Explanation | 6 | You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, ... | Python Recursion: Easy-to-understand with Explanation | 501 | flatten-a-multilevel-doubly-linked-list | 0.595 | zayne-siew | Medium | 7,597 | 430 |
minimum genetic mutation | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
dic=defaultdict(lambda :0)
lst=[[start,0]]
dic[start]=1
while lst:
x,d=lst.pop(0)
if x==end:
return d
for i in range(len(bank)):
ct... | https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769493/SIMPLE-PYTHON-SOLUTION-USING-BFS | 2 | A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.
Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string.
For example, "AACCGGTT" --> "AACCGGT... | SIMPLE PYTHON SOLUTION USING BFS | 148 | minimum-genetic-mutation | 0.52 | beneath_ocean | Medium | 7,622 | 433 |
number of segments in a string | class Solution:
def countSegments(self, s: str) -> int:
return len([i for i in s.split(" ") if i!=""]) | https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1015806/One-Line-python-Solution | 3 | Given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
Example 1:
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
Example 2:
Input: s = "Hello"
Output: 1
Constrai... | One Line python Solution | 464 | number-of-segments-in-a-string | 0.377 | moazmar | Easy | 7,656 | 434 |
non overlapping intervals | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1])
n = len(intervals)
ans, curr = 1, intervals[0]
for i in range(n):
if intervals[i][0] >= curr[1]:
ans += 1
curr = interva... | https://leetcode.com/problems/non-overlapping-intervals/discuss/1896849/Python-easy-to-read-and-understand-or-sorting | 2 | Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are ... | Python easy to read and understand | sorting | 196 | non-overlapping-intervals | 0.499 | sanial2001 | Medium | 7,682 | 435 |
find right interval | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
start = sorted([[intervals[i][0], i] for i in range(len(intervals))])
end = sorted([[intervals[i][1], i] for i in range(len(intervals))])
i = 0
res = []
for endVal, endIdx in end:
... | https://leetcode.com/problems/find-right-interval/discuss/2812012/Python-Sort-and-Two-Pointers-(Same-approach-as-826.-Most-Profit-Assigning-Work) | 0 | You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.
The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.
Return an array of right interval indices for each interval i. If no right interval exists ... | [Python] Sort and Two Pointers (Same approach as # 826. Most Profit Assigning Work) | 4 | find-right-interval | 0.504 | low_key_low_key | Medium | 7,700 | 436 |
path sum iii | class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
global result
result = 0
def dfs(node, target):
if node is None: return
find_path_from_node(node, target)
dfs(node.left, target)
dfs(node.right, target)
... | https://leetcode.com/problems/path-sum-iii/discuss/1049652/Python-Solution | 14 | Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:
Input: root = [10... | Python Solution | 631 | path-sum-iii | 0.486 | dev-josh | Medium | 7,713 | 437 |
find all anagrams in a string | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# take counter of first n elements in s_dict with n = len(p) - 1
s_dict = collections.Counter(s[:len(p)-1])
# counter of p, this should not be changed
p_dict = collections.Counter(p)
start = 0
# fi... | https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738367/Python-Sliding-Window(-)-algorithm-Detailed-Explanation-Concise-Soln-or-Faster-than-80 | 16 | Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "cbaebabacd", p... | 🔎 Python - Sliding Window( 🚅 🪟) algorithm Detailed Explanation, Concise Soln | Faster than 80% | 1,400 | find-all-anagrams-in-a-string | 0.49 | mystic_sd2001 | Medium | 7,723 | 438 |
k th smallest in lexicographical order | class Solution:
def findKthNumber(self, n: int, k: int) -> int:
def fn(x):
"""Return node counts in denary trie."""
ans, diff = 0, 1
while x <= n:
ans += min(n - x + 1, diff)
x *= 10
diff *= 10
retur... | https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/discuss/1608540/Python3-traverse-denary-trie | 3 | Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].
Example 1:
Input: n = 13, k = 2
Output: 10
Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
Example 2:
Input: n = 1, k = 1
Output: 1
Constrain... | [Python3] traverse denary trie | 435 | k-th-smallest-in-lexicographical-order | 0.308 | ye15 | Hard | 7,769 | 440 |
arranging coins | class Solution:
def arrangeCoins(self, n: int) -> int:
first = 1
last = n
if n==1:
return 1
while first <= last:
mid = (first+last)//2
if mid*(mid+1) == 2*n:
return mid
elif mid*(mid+1) > 2*n:
last = mi... | https://leetcode.com/problems/arranging-coins/discuss/2801813/Python-Simple-Binary-Search | 2 | You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.
Given the integer n, return the number of complete rows of the staircase you will build.
Example 1:
Input: n = 5
Output: 2
Expla... | Python Simple Binary Search | 69 | arranging-coins | 0.462 | BhavyaBusireddy | Easy | 7,770 | 441 |
find all duplicates in an array | class Solution:
def findDuplicates(self, N: List[int]) -> List[int]:
S, A = set(), []
for n in N:
if n in S: A.append(n)
else: S.add(n)
return A | https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/396890/Two-Solutions-in-Python-3-(-O(n)-time-)-(-O(1)-space-) | 9 | Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
Example 1:
Input: nums = [4,3,2,7,8,2,3,... | Two Solutions in Python 3 ( O(n) time ) ( O(1) space ) | 1,700 | find-all-duplicates-in-an-array | 0.734 | junaidmansuri | Medium | 7,818 | 442 |
string compression | class Solution:
def compress(self, chars: List[str]) -> int:
if not chars:
return 0
mychar = chars[0]
count = 0
length = len(chars)
chars.append(" ") # Append a space so last char group is not left out in loop
for i in range(length+1): #+1 for extra space ... | https://leetcode.com/problems/string-compression/discuss/1025555/Python3-Simple-and-Intuitive | 10 | Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
The compressed string s should ... | Python3 Simple and Intuitive | 1,800 | string-compression | 0.489 | upenj | Medium | 7,866 | 443 |
add two numbers ii | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
n1 = n2 = 0
ptr1, ptr2 = l1, l2
stack = []
while ptr1: n1 += 1; ptr1 = ptr1.next
while ptr2: n2 += 1; ptr2 = ptr2.next
max_len = max(n1, n2)
while max_len:
... | https://leetcode.com/problems/add-two-numbers-ii/discuss/486730/Python-Using-One-Stack-Memory-Usage%3A-Less-than-100 | 11 | You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
... | Python - Using One Stack [Memory Usage: Less than 100%] | 766 | add-two-numbers-ii | 0.595 | mmbhatk | Medium | 7,889 | 445 |
arithmetic slices ii subsequence | class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
ans = 0
freq = [defaultdict(int) for _ in range(len(nums))] # arithmetic sub-seqs
for i, x in enumerate(nums):
for ii in range(i):
diff = x - nums[ii]
ans += freq[ii].ge... | https://leetcode.com/problems/arithmetic-slices-ii-subsequence/discuss/1292744/Python3-freq-tables | 2 | Given an integer array nums, return the number of all the arithmetic subsequences of nums.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arit... | [Python3] freq tables | 120 | arithmetic-slices-ii-subsequence | 0.399 | ye15 | Hard | 7,914 | 446 |
number of boomerangs | class Solution:
def numberOfBoomerangs(self, p: List[List[int]]) -> int:
L, t = len(p), 0
D = [[0]*L for i in range(L)]
for i in range(L):
E = {}
for j in range(L):
if j > i: D[i][j] = D[j][i] = (p[j][0]-p[i][0])**2 + (p[j][1]-p[i][1])**2
E[D[i][j]] = E[... | https://leetcode.com/problems/number-of-boomerangs/discuss/355205/Solution-in-Python-3 | 2 | You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Return the number of boomerangs.
Example 1:
Input: points = [[0,0],[1,0],[2,0]]... | Solution in Python 3 | 847 | number-of-boomerangs | 0.547 | junaidmansuri | Medium | 7,917 | 447 |
find all numbers disappeared in an array | class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
for n in nums:
a = abs(n) - 1
if nums[a] > 0: nums[a] *= -1
return [i+1 for i in range(len(nums)) if nums[i] > 0] | https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/313703/Python-3 | 54 | Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= ... | Python 3 | 7,900 | find-all-numbers-disappeared-in-an-array | 0.597 | slight_edge | Easy | 7,919 | 448 |
delete node in a bst | class Solution:
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root:
return None
if root.val > key:
# Target node is smaller than currnet node, search left subtree
root.left = self.deleteNode( root.left, key )
elif ... | https://leetcode.com/problems/delete-node-in-a-bst/discuss/543124/Python-O(-h-)-with-BST-property.-85%2B-w-Comment | 8 | Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Example 1:
Input: root = [5,3,6,2,4,n... | Python O( h ) with BST property. 85%+ [w/ Comment ] | 605 | delete-node-in-a-bst | 0.5 | brianchiang_tw | Medium | 7,962 | 450 |
sort characters by frequency | class Solution:
def frequencySort(self, s: str) -> str:
ans_str = ''
# Find unique characters
characters = set(s)
counts = []
# Count their frequency
for i in characters:
counts.append([i,s.count(i)])
# Sort characters accordin... | https://leetcode.com/problems/sort-characters-by-frequency/discuss/1024318/Python3-Solution-or-24-MS-Runtime-or-15.2-MB-Memoryor-Easy-to-understand-solution | 5 | Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Return the sorted string. If there are multiple answers, return any of them.
Example 1:
Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice ... | Python3 Solution | 24 MS Runtime | 15.2 MB Memory| Easy to understand solution | 401 | sort-characters-by-frequency | 0.686 | dakshal33 | Medium | 7,984 | 451 |
minimum number of arrows to burst balloons | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
pts = sorted(points, key=lambda el: el[1])
res, combo = 0, (float("-inf"), float("-inf"))
for start, end in pts:
if start <= combo[1]: # overlaps?
combo = (max(combo[0], start), ... | https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686588/Python3-COMBO-Explained | 9 | There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
Arrows... | ✔️ [Python3] ➵ COMBO 🌸, Explained | 290 | minimum-number-of-arrows-to-burst-balloons | 0.532 | artod | Medium | 8,027 | 452 |
minimum moves to equal array elements | class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - (len(nums) * min(nums)) | https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1909521/1-line-solution-beats-98-O(N)-time-and-96-O(1)-space-easy-to-understand | 10 | Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1 elements of the array by 1.
Example 1:
Input: nums = [1,2,3]
Output: 3
Explanation: Only three moves are needed (remember each move increments two elements):
[1,2,3... | 1 line solution; beats 98% O(N) time and 96% O(1) space; easy to understand | 461 | minimum-moves-to-equal-array-elements | 0.557 | sahajamatya | Medium | 8,053 | 453 |
4sum ii | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
# hashmap and final result count
nums12, res = defaultdict(int), 0
# storing all possible combinations of sum
for i in nums1:
for j in ... | https://leetcode.com/problems/4sum-ii/discuss/1741072/Python-Clean-and-concise-or-Detail-explanation-or-One-linear | 19 | Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Example 1:
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
Explanation:
The two tuples are:
1.... | [Python] Clean and concise | Detail explanation | One linear | 939 | 4sum-ii | 0.573 | sidheshwar_s | Medium | 8,069 | 454 |
assign cookies | class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort() # O(nlogn)
s.sort() # O(nlogn)
child_point = 0
cookie_point = 0
counter = 0
# O(n)
while child_point < len(g) and cookie_point < len(s):
... | https://leetcode.com/problems/assign-cookies/discuss/1334075/Python-Solution-or-Two-Pointers-or-O(nlogn) | 2 | Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie ... | Python Solution | Two Pointers | O(nlogn) | 267 | assign-cookies | 0.505 | peatear-anthony | Easy | 8,099 | 455 |
132 pattern | class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums)<3:
return False
second_num = -math.inf
stck = []
# Try to find nums[i] < second_num < stck[-1]
for i in range(len(nums) - 1, -1, -1):
if nums[i] < second_num:
... | https://leetcode.com/problems/132-pattern/discuss/2015125/Python-Solution-using-Stack | 37 | Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
Example 1:
Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pa... | ✅ Python Solution using Stack | 3,400 | 132-pattern | 0.325 | constantine786 | Medium | 8,121 | 456 |
circular array loop | class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
n, visited = len(nums), set()
for i in range(n):
if i not in visited:
local_s = set()
while True:
if i in local_s: return True
if i in visited: br... | https://leetcode.com/problems/circular-array-loop/discuss/1317119/Python-3-or-Short-Python-Set-or-Explanation | 10 | You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:
If nums[i] is positive, move nums[i] steps forward, and
If nums[i] is negative, move nums[i] steps backward.
Since the array is circular, ... | Python 3 | Short Python, Set | Explanation | 1,200 | circular-array-loop | 0.323 | idontknoooo | Medium | 8,141 | 457 |
poor pigs | class Solution:
def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1)); | https://leetcode.com/problems/poor-pigs/discuss/935581/C%2B%2BPythonPicture-1-line-greedy-solution-with-N-dimension-puzzle-cube-scan | 34 | There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.
You can feed the pigs a... | [C++/Python/Picture] 1-line greedy solution with N-dimension puzzle cube scan | 3,400 | poor-pigs | 0.643 | codedayday | Hard | 8,151 | 458 |
repeated substring pattern | class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return s in s[1:] + s[:-1] | https://leetcode.com/problems/repeated-substring-pattern/discuss/2304034/Python-93.74-fasters-or-Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Slicing | 6 | Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Expla... | Python 93.74% fasters | Python Simplest Solution With Explanation | Beg to adv | Slicing | 332 | repeated-substring-pattern | 0.437 | rlakshay14 | Easy | 8,155 | 459 |
hamming distance | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
def get_bin(num):
res = []
while num > 0:
res.append(num % 2)
num //= 2
return ''.join(str(num) for num in res[::-1])
if x < y:
x, y = y, x
... | https://leetcode.com/problems/hamming-distance/discuss/1585601/Handmade-binary-function-(time%3A-O(L)) | 3 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Example 1:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions w... | Handmade binary function (time: O(L)) | 121 | hamming-distance | 0.749 | kryuki | Easy | 8,184 | 461 |
minimum moves to equal array elements ii | class Solution:
def minMoves2(self, nums: List[int]) -> int:
nums.sort()
mid = nums[len(nums)//2]
result = 0
for i in nums:
result+=abs(mid-i)
return result | https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/discuss/2218363/Python3-simple-solution%3A-Get-the-mid-element-from-the-sorted-array | 6 | Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1.
Test cases are designed so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation... | 📌 Python3 simple solution: Get the mid element from the sorted array | 68 | minimum-moves-to-equal-array-elements-ii | 0.602 | Dark_wolf_jss | Medium | 8,223 | 462 |
island perimeter | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
M, N, p = len(grid), len(grid[0]), 0
for m in range(M):
for n in range(N):
if grid[m][n] == 1:
if m == 0 or grid[m-1][n] == 0: p += 1
if n == 0 or grid[m][n-1] == 0: p += 1
if n == N-1 or gri... | https://leetcode.com/problems/island-perimeter/discuss/343154/Solution-in-Python-3 | 36 | You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island do... | Solution in Python 3 | 3,200 | island-perimeter | 0.695 | junaidmansuri | Easy | 8,271 | 463 |
can i win | class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
if desiredTotal == 0: return True # edge case 1
if maxChoosableInteger * (maxChoosableInteger+1)//2 < desiredTotal: return False # edge case 2
@lru_cache(None)
def fn(mask, total):
... | https://leetcode.com/problems/can-i-win/discuss/850051/Python3-top-down-dp | 3 | In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
For example, two players might take turns drawing from a common pool of numbers fro... | [Python3] top-down dp | 423 | can-i-win | 0.298 | ye15 | Medium | 8,316 | 464 |
count the repetitions | class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
cnt = idx = 0
count = []
index = []
for i in range(n1):
for ch in s1:
if ch == s2[idx]:
idx += 1
if idx == len(s2):
... | https://leetcode.com/problems/count-the-repetitions/discuss/2521184/Python3-repeating-patterns | 0 | We define str = [s, n] as the string str which consists of the string s concatenated n times.
For example, str == ["abc", 3] =="abcabcabc".
We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.
For example, s1 = "abc" can be obtained from s2 = "abdbec"... | [Python3] repeating patterns | 22 | count-the-repetitions | 0.293 | ye15 | Hard | 8,321 | 466 |
unique substrings in wraparound string | class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
consecutive = 1
# stores the maximum length of a substring ending at a character
maxSubstr = defaultdict(int)
maxSubstr[p[0]] = 1
ans = 0
for x in range(1, len(p)):
... | https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/1705570/Python3-DP-O(N)-time-O(1)-space | 1 | We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Given a string s, return the number of unique non-empty substrings of s are present in base.
Example 1:
Input: s = "a"
Output... | Python3 DP O(N) time O(1) space | 92 | unique-substrings-in-wraparound-string | 0.383 | srihariv | Medium | 8,322 | 467 |
validate ip address | class Solution:
def validIPAddress(self, query: str) -> str:
dot = query.count(".")
colon = query.count(":")
if colon == 0 and dot == 3:
arr = [i for i in query.split(".")]
print(arr)
flag = True
for i in arr:
if i.isdigit() and int(i) <= 255:
x = int(i)
if str(x) != i:
flag = Fal... | https://leetcode.com/problems/validate-ip-address/discuss/2440773/Python-or-Easiest-solution-Faster-than-99-or-easy-if-and-else | 0 | Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are... | Python | Easiest solution Faster than 99% | easy if and else | 134 | validate-ip-address | 0.266 | sami2002 | Medium | 8,326 | 468 |
concatenated words | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
ddic = lambda: defaultdict(ddic)
trie = ddic()
for word in words:
cur = trie
for char in word:
cur = cur[char]
cur['end'] = True
... | https://leetcode.com/problems/concatenated-words/discuss/2189673/Python3-TRIE-WITH-RECURSION-(-)-Explained | 4 | Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.
Example 1:
Input: words = ["cat","cats","catsdogcats","... | ✔️ [Python3] TRIE WITH RECURSION ᕕ( ᐛ )ᕗ, Explained | 100 | concatenated-words | 0.458 | artod | Hard | 8,332 | 472 |
matchsticks to square | class Solution:
def makesquare(self, arr: List[int]) -> bool:
# no way to make the square if total length not divisble by 4
if sum(arr) % 4:
return False
# target side length
side = sum(arr) // 4
@lru_cache(None)
def dp(k, mask, s):
# finish all f... | https://leetcode.com/problems/matchsticks-to-square/discuss/2270373/Python-3DP-%2B-Bitmask | 6 | You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false othe... | [Python 3]DP + Bitmask | 662 | matchsticks-to-square | 0.404 | chestnut890123 | Medium | 8,344 | 473 |
ones and zeroes | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
counter=[[s.count("0"), s.count("1")] for s in strs]
@cache
def dp(i,j,idx):
if i<0 or j<0:
return -math.inf
if idx==len(strs):
return ... | https://leetcode.com/problems/ones-and-zeroes/discuss/2065208/Python-Easy-DP-2-approaches | 71 | You are given an array of binary strings strs and two integers m and n.
Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.
A set x is a subset of a set y if all elements of x are also elements of y.
Example 1:
Input: strs = ["10","0001","111001","1","0"], m = 5, n... | Python Easy DP 2 approaches | 4,300 | ones-and-zeroes | 0.467 | constantine786 | Medium | 8,360 | 474 |
heaters | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
if len(heaters) == 1:
return max(abs(houses[0] - heaters[0]), abs(houses[-1] - heaters[0]))
m_value = -1
f, s, ind_heat = heaters[0], heaters[1], 2
... | https://leetcode.com/problems/heaters/discuss/2711430/python-99.84-speed-O(1)-memory | 2 | Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of houses and heaters on a horizontal line, return the minimum radius standa... | python 99.84% speed O(1) memory | 234 | heaters | 0.361 | Yaro1 | Medium | 8,383 | 475 |
number complement | class Solution:
def findComplement(self, num: int) -> int:
bit_mask = 2**num.bit_length() -1
return ( num ^ bit_mask ) | https://leetcode.com/problems/number-complement/discuss/488055/Python-O(-lg-n-)-sol.-by-XOR-masking.-85%2B-With-explanation | 17 | The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
Example 1:
Input: num = 5
Output: 2
E... | Python O( lg n ) sol. by XOR masking. 85%+ [ With explanation ] | 1,100 | number-complement | 0.672 | brianchiang_tw | Easy | 8,398 | 476 |
total hamming distance | class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
ans = 0
for i in range(32):
zero = one = 0
mask = 1 << i
for num in nums:
if mask & num: one += 1
else: zero += 1
ans += one * zero
... | https://leetcode.com/problems/total-hamming-distance/discuss/851194/Python-3-or-Bit-Manipulation-O(N)-or-Explanations | 26 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.
Example 1:
Input: nums = [4,14,2]
Output: 6
Explanation: In binary representation, the 4 i... | Python 3 | Bit Manipulation O(N) | Explanations | 1,300 | total-hamming-distance | 0.522 | idontknoooo | Medium | 8,437 | 477 |
generate random point in a circle | class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.x = x_center
self.y = y_center
self.radius = radius
def randPoint(self) -> List[float]:
first = random.uniform(-self.radius, self.radius)
secondmax = (self.radius ** 2 - first ** 2... | https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/1113715/Python-wrong-test-cases | 4 | Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.
Implement the Solution class:
Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of ... | Python, wrong test cases? | 322 | generate-random-point-in-a-circle | 0.396 | warmr0bot | Medium | 8,444 | 478 |
largest palindrome product | class Solution:
def largestPalindrome(self, n: int) -> int:
# just to forget about 1-digit case
if n == 1:
return 9
# minimal number with n digits (for ex. for n = 4, min_num = 1000)
min_num = 10 ** (n - 1)
# maximal number with n digits... | https://leetcode.com/problems/largest-palindrome-product/discuss/1521512/Python3-Solution-with-explanation | 8 | Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.
Example 1:
Input: n = 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Example 2:
Input: n = 1
Output: 9
Constraints:
1 <... | Python3 Solution with explanation | 741 | largest-palindrome-product | 0.317 | frolovdmn | Hard | 8,450 | 479 |
sliding window median | class Solution:
# TC - O((n - k)*log(k))
# SC - O(k)
# 121 ms, faster than 96.23%
def find_median(self, max_heap, min_heap, heap_size):
if heap_size % 2 == 1:
return -max_heap[0]
else:
return (-max_heap[0] + min_heap[0]) / 2
def medianSlidingWindow(self, nums: ... | https://leetcode.com/problems/sliding-window-median/discuss/1942580/Easiest-Python-O(n-log-k)-Two-Heaps-(Lazy-Removal)-96.23 | 4 | The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
You are given an integer array num... | ✅ Easiest Python O(n log k) Two Heaps (Lazy Removal), 96.23% | 480 | sliding-window-median | 0.414 | AntonBelski | Hard | 8,453 | 480 |
magical string | class Solution:
def magicalString(self, n: int) -> int:
arr, i = [1,2,2], 2
while len(arr) < n:
arr.extend([arr[-1]^3]*arr[i])
i += 1
return arr[:n].count(1) | https://leetcode.com/problems/magical-string/discuss/2558509/481.-Magical-String | 3 | A magical string s consists of only '1' and '2' and obeys the following rules:
The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.
The first few elements of s is s = "1221121221221121122……". If we group the consecutive 1's and 2's i... | 481. Magical String | 417 | magical-string | 0.505 | warrenruud | Medium | 8,460 | 481 |
license key formatting | class Solution:
def licenseKeyFormatting(self, S: str, K: int) -> str:
# Eliminate all dashes
S = S.replace('-', '')
head = len(S) % K
grouping = []
# Special handle for first group
if head:
grouping.append( S[:head] )
... | https://leetcode.com/problems/license-key-formatting/discuss/540266/PythonJSC%2B%2B-O(n)-by-string-operation.-w-Explanation | 35 | You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.
We want to reformat the string s such that each group contains exactly k characters, except for the first group, which c... | Python/JS/C++ O(n) by string operation. [w/ Explanation] | 1,700 | license-key-formatting | 0.432 | brianchiang_tw | Easy | 8,466 | 482 |
smallest good base | class Solution:
def smallestGoodBase(self, n: str) -> str:
import math
n = int(n)
max_m = math.floor(math.log(n, 2))
ans = 0
for m in range(max_m, 0, -1):
k = int(n ** (1 / m))
if (k ** (m + 1) - 1) // (k - 1) == n:
return str(k)
... | https://leetcode.com/problems/smallest-good-base/discuss/2368982/faster-than-97.27-or-python | 1 | Given an integer n represented as a string, return the smallest good base of n.
We call k >= 2 a good base of n, if all digits of n base k are 1's.
Example 1:
Input: n = "13"
Output: "3"
Explanation: 13 base 3 is 111.
Example 2:
Input: n = "4681"
Output: "8"
Explanation: 4681 base 8 is 11111.
Example 3:
Input: n = "1... | faster than 97.27% | python | 107 | smallest-good-base | 0.384 | vimla_kushwaha | Hard | 8,493 | 483 |
max consecutive ones | class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
c1,c2=0,0
for i in nums:
if i==1:
c1+=1
elif i==0:
c1=0
if c1>c2:
c2=c1
return c2 | https://leetcode.com/problems/max-consecutive-ones/discuss/1011637/Simple-and-easy-if-else-solution-faster-than-99.91 | 8 | Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
Constraint... | Simple and easy if-else solution, faster than 99.91% | 688 | max-consecutive-ones | 0.561 | thisisakshat | Easy | 8,495 | 485 |
predict the winner | class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
def helper(i, j):
if i == j:
return nums[i]
if (i, j) in memo:
return memo[(i, j)]
score = max(nums[j] - helper(i, j-1), nums[i] - helper(i+1, j)... | https://leetcode.com/problems/predict-the-winner/discuss/414803/Python-AC-98-Both-Recursion-and-DP-with-detailed-explanation. | 19 | You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums... | Python [AC 98%] Both Recursion & DP with detailed explanation. | 1,300 | predict-the-winner | 0.509 | bos | Medium | 8,546 | 486 |
zuma game | class Solution:
def findMinStep(self, board: str, hand: str) -> int:
# start from i and remove continues ball
def remove_same(s, i):
if i < 0:
return s
left = right = i
while left > 0 and s[left-1] == s[i]:
lef... | https://leetcode.com/problems/zuma-game/discuss/1568450/Python-Easy-BFS-solution-with-explain | 8 | You are playing a variation of the game Zuma.
In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.
Your goal is to clear all of the balls from the board. On e... | [Python] Easy BFS solution with explain | 634 | zuma-game | 0.346 | nightybear | Hard | 8,564 | 488 |
increasing subsequences | class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
def dfs(i, num, curr):
if len(curr)>=2:
ans.add(curr[:])
if i>=len(nums):
return
for j in range(i, len(nums)):
if nums[j]>=num:
... | https://leetcode.com/problems/increasing-subsequences/discuss/1577928/Python-DFS | 3 | Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.
Example 1:
Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
Example 2:
Input: nums = [4,4,3,2,1]
... | Python DFS | 293 | increasing-subsequences | 0.521 | hX_ | Medium | 8,566 | 491 |
construct the rectangle | class Solution:
def constructRectangle(self, area: int) -> List[int]:
for i in range(int(area**0.5),0,-1):
if area % i == 0: return [area//i,i] | https://leetcode.com/problems/construct-the-rectangle/discuss/1990625/Python-Easy-Solution-or-Faster-Than-92-Submits | 3 | A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area.
The ... | [ Python ] Easy Solution | Faster Than 92% Submits | 300 | construct-the-rectangle | 0.538 | crazypuppy | Easy | 8,583 | 492 |
reverse pairs | class Solution:
def reversePairs(self, nums: List[int]) -> int:
ans = 0
seen = []
for x in nums:
k = bisect_right(seen, 2*x)
ans += len(seen) - k
insort(seen, x)
return ans | https://leetcode.com/problems/reverse-pairs/discuss/1205560/Python3-summarizing-4-solutions | 5 | Given an integer array nums, return the number of reverse pairs in the array.
A reverse pair is a pair (i, j) where:
0 <= i < j < nums.length and
nums[i] > 2 * nums[j].
Example 1:
Input: nums = [1,3,2,3,1]
Output: 2
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] ... | [Python3] summarizing 4 solutions | 223 | reverse-pairs | 0.309 | ye15 | Hard | 8,600 | 493 |
target sum | class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
dic = defaultdict(int)
def dfs(index=0, total=0):
key = (index, total)
if key not in dic:
if index == len(nums):
... | https://leetcode.com/problems/target-sum/discuss/1198338/Python-recursive-solution-with-memoization-(DFS) | 22 | You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build th... | Python, recursive solution with memoization (DFS) | 1,500 | target-sum | 0.456 | swissified | Medium | 8,608 | 494 |
teemo attacking | class Solution(object):
def findPoisonedDuration(self, timeSeries, duration):
repeat = 0
for i in range(len(timeSeries)-1):
diff = timeSeries[i+1] - timeSeries[i]
if diff < duration:
repeat += duration - diff
return len(timeSeries)*duration - repeat | https://leetcode.com/problems/teemo-attacking/discuss/1602614/Python-6-lines-O(n)-concise-solution | 8 | Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the t... | Python 6 lines O(n) concise solution | 330 | teemo-attacking | 0.57 | caitlinttl | Easy | 8,652 | 495 |
next greater element i | class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
# a stack with monotonic decreasing
monotonic_stack = []
# dictionary:
# key: number
# value: next greater number of key
dict_of_greater_number = ... | https://leetcode.com/problems/next-greater-element-i/discuss/640416/Python-sol-by-monotonic-stack-and-dict-w-Comment | 14 | The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and dete... | Python sol by monotonic stack and dict [w/ Comment ] | 968 | next-greater-element-i | 0.714 | brianchiang_tw | Easy | 8,673 | 496 |
random point in non overlapping rectangles | class Solution:
def __init__(self, rects: List[List[int]]):
self.rects = rects
self.search_space = []
for i, rect in enumerate(rects):
a, b, c, d = rect
self.search_space.append((d - b + 1) * (c - a + 1))
if i != 0:
self.search_space[i] +=... | https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/discuss/1453111/Python-Binary-Search | 1 | You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space cove... | Python Binary Search | 155 | random-point-in-non-overlapping-rectangles | 0.393 | ypatel38 | Medium | 8,722 | 497 |
diagonal traverse | class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if not matrix:
return res
# group values in matrix by the sum of their indices in a map
map = {}
for i in range(len(matrix) + len(matrix[0]) - 1):
map[i] = []
... | https://leetcode.com/problems/diagonal-traverse/discuss/272114/Simple-Python-Solution-(with-comments) | 5 | Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-1... | Simple Python Solution (with comments) | 612 | diagonal-traverse | 0.581 | AnthonyChao | Medium | 8,726 | 498 |
keyboard row | class Solution:
def findWords(self, wds: List[str]) -> List[str]:
st = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2, 'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, 'n': 3, 'm': 3}
ret = []
f... | https://leetcode.com/problems/keyboard-row/discuss/1525751/Easy-Python-Solution-or-Faster-than-97-(24-ms) | 5 | Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
the first row consists of the characters "qwertyuiop",
the second row consists of the characters "asdfghjkl", and
the third row consists ... | Easy Python Solution | Faster than 97% (24 ms) | 462 | keyboard-row | 0.692 | the_sky_high | Easy | 8,764 | 500 |
find mode in binary search tree | class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
def traverse(root: TreeNode) -> None:
if not root:
return
nonlocal maxcount, count, prevval, modes
traverse(root.left)
... | https://leetcode.com/problems/find-mode-in-binary-search-tree/discuss/1722526/Python3-Inorder-traversal-beats-99 | 2 | Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the no... | [Python3] Inorder traversal; beats 99% | 90 | find-mode-in-binary-search-tree | 0.487 | cwkirby | Easy | 8,812 | 501 |
ipo | class Solution:
def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
capital, profits = zip(*sorted(zip(capital, profits)))
i = 0
pq = []
for _ in range(k):
while i < len(capital) and capital[i] <= w:
heappush(p... | https://leetcode.com/problems/ipo/discuss/1492025/Python3-greedy | 1 | Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way ... | [Python3] greedy | 144 | ipo | 0.45 | ye15 | Hard | 8,832 | 502 |
next greater element ii | class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
stack, res = [], [-1] * len(nums) # taking an empty stack for storing index, a list with the lenght same as of nums so that we wont add unnecessary elements.
# [-1] * len(nums) = this will produce a list with len of nums an... | https://leetcode.com/problems/next-greater-element-ii/discuss/2520585/Python-Stack-98.78-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack | 3 | Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its nex... | Python Stack 98.78% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack | 279 | next-greater-element-ii | 0.631 | rlakshay14 | Medium | 8,836 | 503 |
base 7 | class Solution:
def convertToBase7(self, num: int) -> str:
if not num:
return "0"
l=[]
x=num
if num<0:
num=-num
while num>0:
r=num%7
l.append(str(r))
num//=7
return "".join(l[::-1]) if x>=0 else "-"+ "".join(... | https://leetcode.com/problems/base-7/discuss/1014922/Simple-and-easy-faster-than-99.31 | 4 | Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100
Output: "202"
Example 2:
Input: num = -7
Output: "-10"
Constraints:
-107 <= num <= 107 | Simple and easy - faster than 99.31% | 607 | base-7 | 0.48 | thisisakshat | Easy | 8,882 | 504 |
relative ranks | class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
rankings = []
for i, val in enumerate(score):
heappush(rankings, (-val, i))
ans = [''] * len(score)
r = 1
rank = ["Gold Medal", "Silver Medal", "Bronze Medal"]
while len(rankings) ... | https://leetcode.com/problems/relative-ranks/discuss/1705542/Python-Simple-Solution-using-Max-Heap | 8 | You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The p... | [Python] Simple Solution using Max-Heap | 573 | relative-ranks | 0.592 | anCoderr | Easy | 8,896 | 506 |
perfect number | class Solution:
def checkPerfectNumber(self, num: int) -> bool:
if num == 1:
return False
res = 1
for i in range(2,int(num**0.5)+1):
if num%i == 0:
res += i + num//i
return res == num | https://leetcode.com/problems/perfect-number/discuss/1268856/Python3-simple-solution | 10 | A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
Given an integer n, return true if n is a perfect number, otherwise return false.
Example 1:
Input: num = 28
Output: true
Explanation... | Python3 simple solution | 439 | perfect-number | 0.378 | EklavyaJoshi | Easy | 8,928 | 507 |
most frequent subtree sum | class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
counts = collections.Counter()
def dfs(node):
if not node: return 0
result = node.val + dfs(node.left) + dfs(node.right)
counts[result] += 1
... | https://leetcode.com/problems/most-frequent-subtree-sum/discuss/1101640/A-Basic-Python | 1 | Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
Example 1:
Input: root ... | A Basic Python | 117 | most-frequent-subtree-sum | 0.644 | dev-josh | Medium | 8,945 | 508 |
fibonacci number | class Solution:
def fib(self, N: int) -> int:
a, b = 0, 1
for i in range(N): a, b = b, a + b
return a
- Python 3
- Junaid Mansuri | https://leetcode.com/problems/fibonacci-number/discuss/336501/Solution-in-Python-3-(beats-~100)-(three-lines) | 41 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).
Example 1:
Input: n = 2
Output: 1
Explanation: F(2... | Solution in Python 3 (beats ~100%) (three lines) | 6,700 | fibonacci-number | 0.692 | junaidmansuri | Easy | 8,953 | 509 |
find bottom left tree value | class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
q=[[root]]
nodes=[]
while q:
nodes = q.pop(0)
t=[]
for n in nodes:
if n.left:
t.append(n.left)
if n.right:
... | https://leetcode.com/problems/find-bottom-left-tree-value/discuss/2680305/Pyhton3-BFS-Solution-oror-BGG | 1 | Given the root of a binary tree, return the leftmost value in the last row of the tree.
Example 1:
Input: root = [2,1,3]
Output: 1
Example 2:
Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1 | Pyhton3 BFS Solution || BGG | 151 | find-bottom-left-tree-value | 0.665 | hoo__mann | Medium | 9,027 | 513 |
freedom trail | class Solution:
def findRotateSteps(self, ring: str, key: str) -> int:
locs = {}
for i, ch in enumerate(ring): locs.setdefault(ch, []).append(i)
@cache
def fn(i, j):
"""Return turns to finish key[j:] startin from ith position on ring."""
if j ==... | https://leetcode.com/problems/freedom-trail/discuss/1367426/Python3-top-down-dp | 2 | In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.
Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that n... | [Python3] top-down dp | 165 | freedom-trail | 0.467 | ye15 | Hard | 9,051 | 514 |
find largest value in each tree row | class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
res = []
def helper(root, depth):
if root is None:
return
if depth == len(res):
res.append(root.val)
else:
res[depth] = ma... | https://leetcode.com/problems/find-largest-value-in-each-tree-row/discuss/1620422/Python-3-easy-dfs-recursive-solution-faster-than-94 | 1 | Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Example 2:
Input: root = [1,2,3]
Output: [1,3]
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-231 <= Node.val <= 231 - ... | Python 3, easy dfs recursive solution, faster than 94% | 109 | find-largest-value-in-each-tree-row | 0.646 | dereky4 | Medium | 9,053 | 515 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.