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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
two sum | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, j in enumerate(nums):
r = target - j
if r in d: return [d[r], i]
d[j] = i
# An Upvote will be encouraging | https://leetcode.com/problems/two-sum/discuss/2361743/Python-Simple-Solution-oror-O(n)-Time-oror-O(n)-Space | 288 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? | Python Simple Solution || O(n) Time || O(n) Space | 21,600 | two-sum | 0.491 | rajkumarerrakutti | Easy | 0 | 1 |
add two numbers | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = dummy = ListNode()
carry = 0
while l1 or l2:
v1, v2 = 0, 0
if l1: v1, l1 = l1.val, l1.next
if l2: v2, l2 = l2.val, l2.next
val = carry + v1 + v2
res.next = ListNode(val%10)
res, carry = res.next, val//10
if carry:
res.next = ListNode(carry)
return dummy.next | https://leetcode.com/problems/add-two-numbers/discuss/1835217/Python3-DUMMY-CARRY-(-**-)-Explained | 44 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, 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.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros. | ✔️ [Python3] DUMMY CARRY ( •⌄• ू )✧, Explained | 7,100 | add-two-numbers | 0.398 | artod | Medium | 46 | 2 |
longest substring without repeating characters | class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int abcabcbb
"""
if len(s) == 0:
return 0
seen = {}
left, right = 0, 0
longest = 1
while right < len(s):
if s[right] in seen:
left = max(left,seen[s[right]]+1)
longest = max(longest, right - left + 1)
seen[s[right]] = right
right += 1
print(left, right, longest)
return longest | https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/742926/Simple-Explanation-or-Concise-or-Thinking-Process-and-Example | 290 | Given a string s, find the length of the longest
substring
without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces. | Simple Explanation | Concise | Thinking Process & Example | 13,100 | longest-substring-without-repeating-characters | 0.338 | ivankatrump | Medium | 77 | 3 |
median of two sorted arrays | class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# Get the lengths of both lists
l1,l2 = len(nums1), len(nums2)
# Determine the middle
middle = (l1 + l2) / 2
# EDGE CASE:
# If we only have 1 value (e.g. [1], []), return nums1[0] if the length of
# that list is greater than the length of l2, otherwise return nums2[1]
if middle == 0.5: return float(nums1[0]) if l1 > l2 else float(nums2[0])
# Initialize 2 pointers
x = y = 0
# Initialize 2 values to store the previous and current value (in case of an even
# amount of values, we need to average 2 values)
cur = prev = 0
# Determine the amount of loops we need. If the middle is even, loop that amount + 1:
# eg: [1, 2, 3, 4, 5, 6] 6 values, middle = 3, loops = 3+1
# ^ ^
# | +-- cur
# +----- prev
# If the middle is odd, loop that amount + 0.5
# eg: [1, 2, 3, 4, 5] 5 values, middle = 2.5, loops = 2.5+0.5
# ^
# +--- cur
loops = middle+1 if middle % 1 == 0 else middle+0.5
# Walk forward the amount of loops
for _ in range(int(loops)):
# Store the value of cur in prev
prev = cur
# If the x pointer is equal to the amount of elements of nums1 (l1 == len(nums1))
if x == l1:
# Store nums2[y] in cur, 'cause we hit the end of nums1
cur = nums2[y]
# Move the y pointer one ahead
y += 1
# If the y pointer is equal to the amount of elements of nums2 (l2 == len(nums2))
elif y == l2:
# Store nums1[x] in cur, 'cause we hit the end of nums2
cur = nums1[x]
# Move the x pointer one ahead
x += 1
# If the value in nums1 is bigger than the value in nums2
elif nums1[x] > nums2[y]:
# Store nums2[y] in cur, because it's the lowest value
cur = nums2[y]
# Move the y pointer one ahead
y += 1
# If the value in nums2 is bigger than the value in nums1
else:
# Store nums1[x] in, because it's the lowest value
cur = nums1[x]
# Move the x pointer one ahead
x += 1
# If middle is even
if middle % 1 == 0.0:
# Return the average of the cur + prev values (which will return a float)
return (cur+prev)/2
# If middle is odd
else:
# Return the cur value, as a float
return float(cur) | https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/949705/Python3-two-pointer-greater9621-runtime-commented | 32 | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106 | Python3 two pointer >96,21% runtime [commented] | 5,100 | median-of-two-sorted-arrays | 0.353 | tomhagen | Hard | 133 | 4 |
longest palindromic substring | class Solution:
def longestPalindrome(self, s: str) -> str:
n=len(s)
def expand_pallindrome(i,j):
while 0<=i<=j<n and s[i]==s[j]:
i-=1
j+=1
return (i+1, j)
res=(0,0)
for i in range(n):
b1 = expand_pallindrome(i,i)
b2 = expand_pallindrome(i,i+1)
res=max(res, b1, b2,key=lambda x: x[1]-x[0]+1) # find max based on the length of the pallindrome strings.
return s[res[0]:res[1]] | https://leetcode.com/problems/longest-palindromic-substring/discuss/2156659/Python-Easy-O(1)-Space-approach | 47 | Given a string s, return the longest
palindromic
substring
in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters. | ✅ Python Easy O(1) Space approach | 6,600 | longest-palindromic-substring | 0.324 | constantine786 | Medium | 181 | 5 |
zigzag conversion | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
row_arr = [""] * numRows
row_idx = 1
going_up = True
for ch in s:
row_arr[row_idx-1] += ch
if row_idx == numRows:
going_up = False
elif row_idx == 1:
going_up = True
if going_up:
row_idx += 1
else:
row_idx -= 1
return "".join(row_arr) | https://leetcode.com/problems/zigzag-conversion/discuss/817306/Very-simple-and-intuitive-O(n)-python-solution-with-explanation | 96 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000 | Very simple and intuitive O(n) python solution with explanation | 3,000 | zigzag-conversion | 0.432 | wmv3317 | Medium | 230 | 6 |
reverse integer | class Solution:
def reverse(self, x: int) -> int:
retval = int(str(abs(x))[::-1])
if(retval.bit_length()>31):
return 0
if x<0:
return -1*retval
else:
return retval | https://leetcode.com/problems/reverse-integer/discuss/1061403/Clean-pythonic-solution | 20 | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Constraints:
-231 <= x <= 231 - 1 | Clean pythonic solution | 3,300 | reverse-integer | 0.273 | njain07 | Medium | 277 | 7 |
string to integer (atoi) | class Solution:
def myAtoi(self, s: str) -> int:
if not s:
return 0
sign = 1
integer = 0
i = 0
while i < len(s) and s[i] == ' ':
i+=1 #skipping leading white space
if i < len(s) and (s[i] == '-' or s[i] == '+'):
if s[i] == '-':
sign = -1
i+=1
while(i < len(s) and s[i].isdigit()):
integer = integer * 10 + int(s[i])
i+=1
integer = sign*integer
ans = self.limit(integer)
return ans
def limit(self, num):
if num > pow(2, 31) -1:
return pow(2, 31) -1
if num < -1*pow(2, 31):
return -1*pow(2, 31)
return num | https://leetcode.com/problems/string-to-integer-atoi/discuss/1510014/Python-Simple-Solution-without-Strip-beats-95 | 7 | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
Whitespace: Ignore any leading whitespace (" ").
Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity is neither present.
Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.
Return the integer as the final result.
Example 1:
Input: s = "42"
Output: 42
Explanation:
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
Example 2:
Input: s = " -042"
Output: -42
Explanation:
Step 1: " -042" (leading whitespace is read and ignored)
^
Step 2: " -042" ('-' is read, so the result should be negative)
^
Step 3: " -042" ("042" is read in, leading zeros ignored in the result)
^
Example 3:
Input: s = "1337c0d3"
Output: 1337
Explanation:
Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)
^
Example 4:
Input: s = "0-1"
Output: 0
Explanation:
Step 1: "0-1" (no characters read because there is no leading whitespace)
^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)
^
Example 5:
Input: s = "words and 987"
Output: 0
Explanation:
Reading stops at the first non-digit character 'w'.
Constraints:
0 <= s.length <= 200
s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'. | Python Simple Solution without Strip beats 95% | 790 | string-to-integer-atoi | 0.166 | emerald19 | Medium | 331 | 8 |
palindrome number | class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
res = 0
temp = x
while temp:
temp, n = divmod(temp, 10)
res = (res * 10) + n
return res == x | https://leetcode.com/problems/palindrome-number/discuss/2797115/Easy-Python-Solution-with-O(1)-space | 11 | Given an integer x, return true if x is a
palindrome
, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string? | Easy Python Solution with O(1) space | 1,900 | palindrome-number | 0.53 | tragob | Easy | 382 | 9 |
regular expression matching | class Solution:
def isMatch(self, s, p):
n = len(s)
m = len(p)
dp = [[False for _ in range (m+1)] for _ in range (n+1)]
dp[0][0] = True
for c in range(1,m+1):
if p[c-1] == '*' and c > 1:
dp[0][c] = dp[0][c-2]
for r in range(1,n+1):
for c in range(1,m+1):
if p[c-1] == s[r-1] or p[c-1] == '.':
dp[r][c] = dp[r-1][c-1]
elif c > 1 and p[c-1] == '*':
if p[c-2] =='.' or s[r-1]==p[c-2]:
dp[r][c] =dp[r][c-2] or dp[r-1][c]
else:
dp[r][c] = dp[r][c-2]
return dp[n][m] | https://leetcode.com/problems/regular-expression-matching/discuss/2383634/Fastest-Solution-Explained0ms100-O(n)time-complexity-O(n)space-complexity | 10 | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Constraints:
1 <= s.length <= 20
1 <= p.length <= 20
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. | [Fastest Solution Explained][0ms][100%] O(n)time complexity O(n)space complexity | 1,300 | regular-expression-matching | 0.282 | cucerdariancatalin | Hard | 425 | 10 |
container with most water | class Solution:
def maxArea(self, height: List[int]) -> int:
l, r, area = 0, len(height) - 1, 0
while l < r:
area = max(area, (r - l) * min(height[l], height[r]))
if height[l] < height[r]:
l += 1
else:
r -= 1
return area | https://leetcode.com/problems/container-with-most-water/discuss/1915108/Python3-GREEDY-TWO-POINTERS-~(~)-Explained | 133 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104 | ✔️ [Python3] GREEDY TWO POINTERS ~(˘▾˘~), Explained | 9,600 | container-with-most-water | 0.543 | artod | Medium | 446 | 11 |
integer to roman | class Solution:
def intToRoman(self, num: int) -> str:
# Creating Dictionary for Lookup
num_map = {
1: "I",
5: "V", 4: "IV",
10: "X", 9: "IX",
50: "L", 40: "XL",
100: "C", 90: "XC",
500: "D", 400: "CD",
1000: "M", 900: "CM",
}
# Result Variable
r = ''
for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:
# If n in list then add the roman value to result variable
while n <= num:
r += num_map[n]
num-=n
return r | https://leetcode.com/problems/integer-to-roman/discuss/2724200/Python's-Simple-and-Easy-to-Understand-Solution-or-99-Faster | 53 | Seven different symbols represent Roman numerals with the following values:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:
If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.
Given an integer, convert it to a Roman numeral.
Example 1:
Input: num = 3749
Output: "MMMDCCXLIX"
Explanation:
3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)
700 = DCC as 500 (D) + 100 (C) + 100 (C)
40 = XL as 10 (X) less of 50 (L)
9 = IX as 1 (I) less of 10 (X)
Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places
Example 2:
Input: num = 58
Output: "LVIII"
Explanation:
50 = L
8 = VIII
Example 3:
Input: num = 1994
Output: "MCMXCIV"
Explanation:
1000 = M
900 = CM
90 = XC
4 = IV
Constraints:
1 <= num <= 3999 | ✔️ Python's Simple and Easy to Understand Solution | 99% Faster 🔥 | 2,600 | integer-to-roman | 0.615 | pniraj657 | Medium | 496 | 12 |
roman to integer | class Solution:
def romanToInt(self, s: str) -> int:
translations = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
number = 0
s = s.replace("IV", "IIII").replace("IX", "VIIII")
s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
for char in s:
number += translations[char]
return number | https://leetcode.com/problems/roman-to-integer/discuss/264743/Clean-Python-beats-99.78. | 1,200 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999]. | Clean Python, beats 99.78%. | 60,900 | roman-to-integer | 0.582 | hgrsd | Easy | 548 | 13 |
longest common prefix | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
pre = strs[0]
for i in strs:
while not i.startswith(pre):
pre = pre[:-1]
return pre | https://leetcode.com/problems/longest-common-prefix/discuss/1351149/Python-and-startswith | 72 | Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters. | Python & startswith | 4,500 | longest-common-prefix | 0.408 | lokeshsenthilkumar | Easy | 595 | 14 |
binary tree level order traversal | class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
def order(node, level):
if level >= len(levels):
levels.append([])
if node:
levels[level].append(node.val)
if node.left:
order(node.left, level + 1)
if node.right:
order(node.right, level + 1)
if not root:
return []
order(root, 0)
return levels | https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/2790811/Python-solution | 0 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000 | Python solution | 3 | binary-tree-level-order-traversal | 0.634 | maomao1010 | Medium | 613 | 102 |
binary tree zigzag level order traversal | class Solution:
def zigzagLevelOrder(self, root):
res = []
if not root: return res
zigzag = True
q = collections.deque()
q.append(root)
while q:
n = len(q)
nodesOfThisLevel = []
for i in range(n):
node = q.popleft()
nodesOfThisLevel.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
if zigzag:
res.append(nodesOfThisLevel)
zigzag = False
else:
res.append(nodesOfThisLevel[::-1])
zigzag = True
return res
# Time: O(N)
# Space: O(N) | https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2098804/Python3-Clean-Solution-using-Queue-Level-Order-Traversal | 7 | Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100 | [Python3] Clean Solution using Queue Level Order Traversal | 240 | binary-tree-zigzag-level-order-traversal | 0.552 | samirpaul1 | Medium | 614 | 103 |
maximum depth of binary tree | class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 | https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/359949/Python-recursive-and-iterative-solution | 219 | Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100 | Python recursive and iterative solution | 18,300 | maximum-depth-of-binary-tree | 0.732 | amchoukir | Easy | 630 | 104 |
construct binary tree from preorder and inorder traversal | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
loc = {x : i for i, x in enumerate(inorder)}
root = None
stack = []
for x in preorder:
if not root: root = node = TreeNode(x)
elif loc[x] < loc[node.val]:
stack.append(node)
node.left = node = TreeNode(x)
else:
while stack and loc[stack[-1].val] < loc[x]: node = stack.pop() # backtracking
node.right = node = TreeNode(x)
return root | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/689647/Python3-stack-O(N) | 7 | Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
Constraints:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder and inorder consist of unique values.
Each value of inorder also appears in preorder.
preorder is guaranteed to be the preorder traversal of the tree.
inorder is guaranteed to be the inorder traversal of the tree. | [Python3] stack O(N) | 371 | construct-binary-tree-from-preorder-and-inorder-traversal | 0.609 | ye15 | Medium | 671 | 105 |
construct binary tree from inorder and postorder traversal | class Solution:
def buildTree(self, inorder, postorder):
inorderIndexDict = {ch : i for i, ch in enumerate(inorder)}
self.rootIndex = len(postorder) - 1
def solve(l, r):
if l > r: return None
root = TreeNode(postorder[self.rootIndex])
self.rootIndex -= 1
i = inorderIndexDict[root.val]
# As we a approaching from end and all right side nodes of i in inorder are
# from right sub-tree so first call solve for right then left.
root.right = solve(i+1, r)
root.left = solve(l, i-1)
return root
return solve(0, len(inorder)-1)
# Time: O(N)
# Space: O(1) | https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/2098606/Python3-O(n)-Time-O(1)-Space-Solution-faster-than-95 | 3 | Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder and postorder consist of unique values.
Each value of postorder also appears in inorder.
inorder is guaranteed to be the inorder traversal of the tree.
postorder is guaranteed to be the postorder traversal of the tree. | [Python3] O(n) Time, O(1) Space Solution faster than 95% | 159 | construct-binary-tree-from-inorder-and-postorder-traversal | 0.575 | samirpaul1 | Medium | 707 | 106 |
binary tree level order traversal ii | class Solution:
def helper(self, result, depth, node):
if not node:
return
if len(result) < depth:
result.append([])
result[depth-1].append(node.val)
self.helper(result, depth+1, node.left)
self.helper(result, depth+1, node.right)
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
result = []
depth = 1
self.helper(result, depth, root)
result.reverse()
return result | https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/359962/Python-recursive-and-iterative | 4 | Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000 | Python recursive and iterative | 519 | binary-tree-level-order-traversal-ii | 0.604 | amchoukir | Medium | 717 | 107 |
convert sorted array to binary search tree | class Solution(object):
def sortedArrayToBST(self, nums):
# Base condition...
if len(nums) == 0:
return None
# set the middle node...
mid = len(nums)//2
# Initialise root node with value same as nums[mid]
root = TreeNode(nums[mid])
# Assign left subtrees as the same function called on left subranges...
root.left = self.sortedArrayToBST(nums[:mid])
# Assign right subtrees as the same function called on right subranges...
root.right = self.sortedArrayToBST(nums[mid+1:])
# Return the root node...
return root | https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/2428167/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-(Java-C%2B%2B-Python-JS-C-Python3) | 19 | Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced
binary search tree.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order. | Easy || 0 ms || 100% || Fully Explained || (Java, C++, Python, JS, C, Python3) | 900 | convert-sorted-array-to-binary-search-tree | 0.692 | PratikSen07 | Easy | 735 | 108 |
convert sorted list to binary search tree | class Solution:
l = 'left'
r = 'right'
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
if not head: return None
nums = []
while head:
nums.append(head.val)
head = head.next
mid = len(nums) // 2
treeNode = TreeNode(nums[mid])
self.binarySearchTree(nums[:mid], self.l, treeNode)
self.binarySearchTree(nums[(mid + 1):], self.r, treeNode)
return treeNode
def binarySearchTree(self, nums, direction, treeNode):
if len(nums) <= 0: return
mid = len(nums) // 2
left, right = nums[:mid], nums[(mid + 1):]
if direction == self.l:
treeNode.left = TreeNode(nums[mid])
self.binarySearchTree(left, self.l, treeNode.left)
self.binarySearchTree(right, self.r, treeNode.left)
else:
treeNode.right = TreeNode(nums[mid])
self.binarySearchTree(left, self.l, treeNode.right)
self.binarySearchTree(right, self.r, treeNode.right) | https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/2767308/Python-beats-86-(recursive-solution) | 2 | Given the head of a singly linked list where elements are sorted in ascending order, convert it to a
height-balanced
binary search tree.
Example 1:
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = []
Output: []
Constraints:
The number of nodes in head is in the range [0, 2 * 104].
-105 <= Node.val <= 105 | Python beats 86% (recursive solution) | 150 | convert-sorted-list-to-binary-search-tree | 0.574 | farruhzokirov00 | Medium | 759 | 109 |
balanced binary tree | class Solution(object):
def isBalanced(self, root):
return (self.Height(root) >= 0)
def Height(self, root):
if root is None: return 0
leftheight, rightheight = self.Height(root.left), self.Height(root.right)
if leftheight < 0 or rightheight < 0 or abs(leftheight - rightheight) > 1: return -1
return max(leftheight, rightheight) + 1 | https://leetcode.com/problems/balanced-binary-tree/discuss/2428871/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JavaScript-Python3) | 83 | Given a binary tree, determine if it is
height-balanced
.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
Input: root = []
Output: true
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-104 <= Node.val <= 104 | Very Easy || 100% || Fully Explained (C++, Java, Python, JavaScript, Python3) | 6,700 | balanced-binary-tree | 0.483 | PratikSen07 | Easy | 780 | 110 |
minimum depth of binary tree | class Solution(object):
def minDepth(self, root):
# Base case...
# If the subtree is empty i.e. root is NULL, return depth as 0...
if root is None: return 0
# Initialize the depth of two subtrees...
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(root.right)
# If the both subtrees are empty...
if root.left is None and root.right is None:
return 1
# If the left subtree is empty, return the depth of right subtree after adding 1 to it...
if root.left is None:
return 1 + rightDepth
# If the right subtree is empty, return the depth of left subtree after adding 1 to it...
if root.right is None:
return 1 + leftDepth
# When the two child function return its depth...
# Pick the minimum out of these two subtrees and return this value after adding 1 to it...
return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees... | https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2429057/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JS-C-Python3) | 32 | Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:
The number of nodes in the tree is in the range [0, 105].
-1000 <= Node.val <= 1000 | Very Easy || 100% || Fully Explained (C++, Java, Python, JS, C, Python3) | 2,200 | minimum-depth-of-binary-tree | 0.437 | PratikSen07 | Easy | 804 | 111 |
path sum | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None:
return target == root.val
return self.hasPathSum( root.left, target - root.val) or \
self.hasPathSum(root.right, target - root.val) | https://leetcode.com/problems/path-sum/discuss/2658792/Python-Elegant-and-Short-or-DFS | 10 | Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Example 3:
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000 | Python Elegant & Short | DFS | 422 | path-sum | 0.477 | Kyrylo-Ktl | Easy | 837 | 112 |
path sum ii | class Solution:
def pathSum(self, R: TreeNode, S: int) -> List[List[int]]:
A, P = [], []
def dfs(N):
if N == None: return
P.append(N.val)
if (N.left,N.right) == (None,None) and sum(P) == S: A.append(list(P))
else: dfs(N.left), dfs(N.right)
P.pop()
dfs(R)
return A
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/path-sum-ii/discuss/484120/Python-3-(beats-~100)-(nine-lines)-(DFS) | 9 | Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: []
Example 3:
Input: root = [1,2], targetSum = 0
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000 | Python 3 (beats ~100%) (nine lines) (DFS) | 2,200 | path-sum-ii | 0.567 | junaidmansuri | Medium | 871 | 113 |
flatten binary tree to linked list | class Solution:
def __init__(self):
self.prev = None
def flatten(self, root: Optional[TreeNode]) -> None:
if not root: return
self.flatten(root.right)
self.flatten(root.left)
root.right = self.prev
root.left = None
self.prev = root | https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2340445/Python-or-intuitive-explained-or-O(1)-space-ignoring-recursion-stack-or-O(n)-time | 7 | Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Example 1:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)? | Python | intuitive, explained | O(1) space ignoring recursion stack | O(n) time | 223 | flatten-binary-tree-to-linked-list | 0.612 | mync | Medium | 899 | 114 |
distinct subsequences | class Solution:
def numDistinct(self, s: str, t: str) -> int:
m = len(s)
n = len(t)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(m+1):
dp[i][0] = 1
"""redundant, as we have initialised dp table with full of zeros"""
# for i in range(1, n+1):
# dp[0][i] = 0
for i in range(1, m+1):
for j in range(1, n+1):
dp[i][j] += dp[i-1][j] #if current character is skipped
if s[i-1] == t[j-1]:
dp[i][j] += dp[i-1][j-1] #if current character is used
return dp[-1][-1] | https://leetcode.com/problems/distinct-subsequences/discuss/1472969/Python-Bottom-up-DP-Explained | 6 | Given two strings s and t, return the number of distinct subsequences of s which equals t.
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from s.
rabbbit
rabbbit
rabbbit
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from s.
babgbag
babgbag
babgbag
babgbag
babgbag
Constraints:
1 <= s.length, t.length <= 1000
s and t consist of English letters. | Python - Bottom up DP - Explained | 475 | distinct-subsequences | 0.439 | ajith6198 | Hard | 924 | 115 |
populating next right pointers in each node | class Solution:
def connect(self, root: 'Node') -> 'Node':
# edge case check
if not root:
return None
# initialize the queue with root node (for level order traversal)
queue = collections.deque([root])
# start the traversal
while queue:
size = len(queue) # get number of nodes on the current level
for i in range(size):
node = queue.popleft() # pop the node
# An important check so that we do not wire the node to the node on the next level.
if i < size-1:
node.next = queue[0] # because the right node of the popped node would be the next in the queue.
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root | https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/719347/Python-Solution-O(1)-and-O(n)-memory. | 10 | You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 212 - 1].
-1000 <= Node.val <= 1000
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem. | Python Solution O(1) and O(n) memory. | 534 | populating-next-right-pointers-in-each-node | 0.596 | darshan_22 | Medium | 956 | 116 |
populating next right pointers in each node ii | class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
q = deque()
q.append(root)
dummy=Node(-999) # to initialize with a not null prev
while q:
length=len(q) # find level length
prev=dummy
for _ in range(length): # iterate through all nodes in the same level
popped=q.popleft()
if popped.left:
q.append(popped.left)
prev.next=popped.left
prev=prev.next
if popped.right:
q.append(popped.right)
prev.next=popped.right
prev=prev.next
return root | https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/2033286/Python-Easy%3A-BFS-and-O(1)-Space-with-Explanation | 39 | Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 6000].
-100 <= Node.val <= 100
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem. | Python Easy: BFS and O(1) Space with Explanation | 3,000 | populating-next-right-pointers-in-each-node-ii | 0.498 | constantine786 | Medium | 996 | 117 |
pascals triangle | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
l=[0]*numRows
for i in range(numRows):
l[i]=[0]*(i+1)
l[i][0]=1
l[i][i]=1
for j in range(1,i):
l[i][j]=l[i-1][j-1]+l[i-1][j]
return l | https://leetcode.com/problems/pascals-triangle/discuss/1490520/Python3-easy-code-faster-than-96.67 | 44 | Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30 | Python3 easy code- faster than 96.67% | 3,600 | pascals-triangle | 0.694 | Rosh_65 | Easy | 1,033 | 118 |
pascals triangle ii | class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
# Base case
return [1]
elif rowIndex == 1:
# Base case
return [1, 1]
else:
# General case:
last_row = self.getRow( rowIndex-1 )
size = len(last_row)
return [ last_row[0] ] + [ last_row[idx] + last_row[idx+1] for idx in range( size-1) ] + [ last_row[-1] ] | https://leetcode.com/problems/pascals-triangle-ii/discuss/467945/Pythonic-O(-k-)-space-sol.-based-on-math-formula-90%2B | 15 | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1]
Constraints:
0 <= rowIndex <= 33
Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space? | Pythonic O( k ) space sol. based on math formula, 90%+ | 1,800 | pascals-triangle-ii | 0.598 | brianchiang_tw | Easy | 1,084 | 119 |
triangle | class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
for i in range(1, len(triangle)): # for each row in triangle (skipping the first),
for j in range(i+1): # loop through each element in the row
triangle[i][j] += min(triangle[i-1][j-(j==i)], # minimum sum from coordinate (x-1, y)
triangle[i-1][j-(j>0)]) # minimum sum from coordinate (x-1, y-1)
return min(triangle[-1]) # obtain minimum sum from last row | https://leetcode.com/problems/triangle/discuss/2144882/Python-In-place-DP-with-Explanation | 18 | Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
Example 2:
Input: triangle = [[-10]]
Output: -10
Constraints:
1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == triangle[i - 1].length + 1
-104 <= triangle[i][j] <= 104
Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle? | [Python] In-place DP with Explanation | 1,400 | triangle | 0.54 | zayne-siew | Medium | 1,132 | 120 |
best time to buy and sell stock | class Solution(object):
def maxProfit(self, prices):
n = len(prices)
dp = [0]*n # initializing the dp table
dp[0] = [prices[0],0] # filling the the first dp table --> low_price = prices[0] max_profit=0
min_price = max_profit = 0
# Note that ---> indixing the dp table --> dp[i-1][0] stores minimum price and dp[i-1][1] stores maximum profit
for i in range(1,n):
min_price = min(dp[i-1][0], prices[i]) # min(previous_min_price, cur_min_price)
max_profit = max(dp[i-1][1], prices[i]-dp[i-1][0]) # max(previoius_max_profit, current_profit)
dp[i] =[min_price,max_profit]
return dp[n-1][1]
#Runtime: 1220 ms,
#Memory Usage: 32.4 MB, | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/1545423/Python-easy-to-understand-solution-with-explanation-%3A-Tracking-and-Dynamic-programming | 58 | You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 104 | Python easy to understand solution with explanation : Tracking and Dynamic programming | 3,200 | best-time-to-buy-and-sell-stock | 0.544 | Abeni | Easy | 1,190 | 121 |
best time to buy and sell stock ii | class Solution:
def maxProfit(self, prices: List[int]) -> int:
@cache
def trade(day_d):
if day_d == 0:
# Hold on day_#0 = buy stock at the price of day_#0
# Not-hold on day_#0 = doing nothing on day_#0
return -prices[day_d], 0
prev_hold, prev_not_hold = trade(day_d-1)
hold = max(prev_hold, prev_not_hold - prices[day_d] )
not_hold = max(prev_not_hold, prev_hold + prices[day_d] )
return hold, not_hold
# --------------------------------------------------
last_day= len(prices)-1
# Max profit must come from not_hold state (i.e., no stock position) on last day
return trade(last_day)[1] | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2040292/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 12 | You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
Constraints:
1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104 | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | 605 | best-time-to-buy-and-sell-stock-ii | 0.634 | cucerdariancatalin | Medium | 1,247 | 122 |
best time to buy and sell stock iii | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = [inf]*2, [0]*2
for x in prices:
for i in range(2):
if i: buy[i] = min(buy[i], x - sell[i-1])
else: buy[i] = min(buy[i], x)
sell[i] = max(sell[i], x - buy[i])
return sell[1] | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2040316/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 16 | You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105 | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | 821 | best-time-to-buy-and-sell-stock-iii | 0.449 | cucerdariancatalin | Hard | 1,306 | 123 |
binary tree maximum path sum | class Solution:
def __init__(self):
self.maxSum = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def traverse(root):
if root:
left = traverse(root.left)
right = traverse(root.right)
self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)
return max(root.val,root.val + left,root.val + right)
else:
return 0
traverse(root)
return self.maxSum | https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2040330/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 17 | A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
Example 1:
Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Example 2:
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
Constraints:
The number of nodes in the tree is in the range [1, 3 * 104].
-1000 <= Node.val <= 1000 | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | 1,100 | binary-tree-maximum-path-sum | 0.385 | cucerdariancatalin | Hard | 1,335 | 124 |
valid palindrome | class Solution:
def isPalindrome(self, s: str) -> bool:
s = [i for i in s.lower() if i.isalnum()]
return s == s[::-1] | https://leetcode.com/problems/valid-palindrome/discuss/350929/Solution-in-Python-3-(beats-~100)-(two-lines)-(-O(1)-solution-as-well-) | 50 | A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105
s consists only of printable ASCII characters. | Solution in Python 3 (beats ~100%) (two lines) ( O(1) solution as well ) | 8,600 | valid-palindrome | 0.437 | junaidmansuri | Easy | 1,367 | 125 |
word ladder ii | class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
d = defaultdict(list)
for word in wordList:
for i in range(len(word)):
d[word[:i]+"*"+word[i+1:]].append(word)
if endWord not in wordList:
return []
visited1 = defaultdict(list)
q1 = deque([beginWord])
visited1[beginWord] = []
visited2 = defaultdict(list)
q2 = deque([endWord])
visited2[endWord] = []
ans = []
def dfs(v, visited, path, paths):
path.append(v)
if not visited[v]:
if visited is visited1:
paths.append(path[::-1])
else:
paths.append(path[:])
for u in visited[v]:
dfs(u, visited, path, paths)
path.pop()
def bfs(q, visited1, visited2, frombegin):
level_visited = defaultdict(list)
for _ in range(len(q)):
u = q.popleft()
for i in range(len(u)):
for v in d[u[:i]+"*"+u[i+1:]]:
if v in visited2:
paths1 = []
paths2 = []
dfs(u, visited1, [], paths1)
dfs(v, visited2, [], paths2)
if not frombegin:
paths1, paths2 = paths2, paths1
for a in paths1:
for b in paths2:
ans.append(a+b)
elif v not in visited1:
if v not in level_visited:
q.append(v)
level_visited[v].append(u)
visited1.update(level_visited)
while q1 and q2 and not ans:
if len(q1) <= len(q2):
bfs(q1, visited1, visited2, True)
else:
bfs(q2, visited2, visited1, False)
return ans | https://leetcode.com/problems/word-ladder-ii/discuss/2422401/46ms-Python-97-Faster-Working-Multiple-solutions-95-memory-efficient-solution | 35 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Explanation: There are 2 shortest transformation sequences:
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
"hit" -> "hot" -> "lot" -> "log" -> "cog"
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 5
endWord.length == beginWord.length
1 <= wordList.length <= 500
wordList[i].length == beginWord.length
beginWord, endWord, and wordList[i] consist of lowercase English letters.
beginWord != endWord
All the words in wordList are unique.
The sum of all shortest transformation sequences does not exceed 105. | 46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution | 2,800 | word-ladder-ii | 0.276 | anuvabtest | Hard | 1,418 | 126 |
word ladder | class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
graph = defaultdict(list)
for word in wordList:
for index in range(len(beginWord)):
graph[word[:index] + "_" + word[index+1:]].append(word)
queue = deque()
queue.append((beginWord, 1))
visited = set()
while queue:
current_node, current_level = queue.popleft()
if current_node == endWord: return current_level
for index in range(len(beginWord)):
node = current_node[:index] + "_" + current_node[index+1:]
for neighbour in graph[node]:
if neighbour not in visited:
queue.append((neighbour, current_level + 1))
visited.add(neighbour)
graph[node] = []
return 0 | https://leetcode.com/problems/word-ladder/discuss/1332551/Elegant-Python-Iterative-BFS | 4 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord, endWord, and wordList[i] consist of lowercase English letters.
beginWord != endWord
All the words in wordList are unique. | Elegant Python Iterative BFS | 366 | word-ladder | 0.368 | soma28 | Hard | 1,434 | 127 |
longest consecutive sequence | class Node:
def __init__(self, val):
self.val = val
self.parent = self
self.size = 1
class UnionFind:
def find(self, node):
if node.parent != node:
node.parent = self.find(node.parent)
return node.parent
def union(self, node1, node2):
parent_1 = self.find(node1)
parent_2 = self.find(node2)
if parent_1 != parent_2:
parent_2.parent = parent_1
parent_1.size += parent_2.size
return parent_1.size
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
uf = UnionFind()
nodes = {}
max_size = 0
for num in nums:
if num not in nodes:
node = Node(num)
nodes[num] = node
size = 1
if num + 1 in nodes:
size = uf.union(node, nodes[num+1])
if num - 1 in nodes:
size = uf.union(node, nodes[num-1])
max_size = max(max_size, size)
return max_size
``` | https://leetcode.com/problems/longest-consecutive-sequence/discuss/1109808/Python-Clean-Union-Find-with-explanation | 21 | Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109 | [Python] Clean Union Find with explanation | 1,800 | longest-consecutive-sequence | 0.489 | l3arner | Medium | 1,459 | 128 |
sum root to leaf numbers | class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
def helper(node, num):
if node is None:
return 0
num = num * 10 + node.val
if node.left is None and node.right is None:
return num
return helper(node.left, num) + helper(node.right, num)
return helper(root, 0) | https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557540/Python-99-speed-99-memory | 4 | You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 9
The depth of the tree will not exceed 10. | Python 99% speed, 99% memory | 391 | sum-root-to-leaf-numbers | 0.588 | dereky4 | Medium | 1,509 | 129 |
surrounded regions | class Solution:
def dfs(self,board,i,j):
if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]!='O':
return
board[i][j]='$' # converting to a dollar sign
self.dfs(board,i+1,j)
self.dfs(board,i-1,j)
self.dfs(board,i,j+1)
self.dfs(board,i,j-1)
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if len(board)==0:
return None
m=len(board)
n=len(board[0])
for i in range(m): # call dfs on all border 'O's and turn them to '$'
for j in range(n):
if i==0 or i==m-1:
self.dfs(board,i,j)
if j==0 or j==n-1:
self.dfs(board,i,j)
#all border O and others connected them were already converted to $ sign
#so left out zeros are surely surrounded by 'X' . Turn all of them to 'X'
for i in range(m):
for j in range(n):
if board[i][j]=='O':
board[i][j]='X'
# turn the border zeros and their adjacents to their initial form. ie $ -> O
for i in range(m):
for j in range(n):
if board[i][j]=='$':
board[i][j]='O' | https://leetcode.com/problems/surrounded-regions/discuss/558746/Python-DFS-Easy-solution-with-comments | 12 | Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example 1:
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
Example 2:
Input: board = [["X"]]
Output: [["X"]]
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j] is 'X' or 'O'. | Python DFS Easy solution with comments | 440 | surrounded-regions | 0.361 | JoyRafatAshraf | Medium | 1,541 | 130 |
palindrome partitioning | class Solution(object):
@cache # the memory trick can save some time
def partition(self, s):
if not s: return [[]]
ans = []
for i in range(1, len(s) + 1):
if s[:i] == s[:i][::-1]: # prefix is a palindrome
for suf in self.partition(s[i:]): # process suffix recursively
ans.append([s[:i]] + suf)
return ans | https://leetcode.com/problems/palindrome-partitioning/discuss/1667786/Python-Simple-Recursion-oror-Detailed-Explanation-oror-Easy-to-Understand | 209 | Given a string s, partition s such that every
substring
of the partition is a
palindrome
. Return all possible palindrome partitioning of s.
Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a"
Output: [["a"]]
Constraints:
1 <= s.length <= 16
s contains only lowercase English letters. | ✅ [Python] Simple Recursion || Detailed Explanation || Easy to Understand | 9,200 | palindrome-partitioning | 0.626 | linfq | Medium | 1,593 | 131 |
palindrome partitioning ii | class Solution:
def minCut(self, s: str) -> int:
#pre-processing
palin = dict()
for k in range(len(s)):
for i, j in (k, k), (k, k+1):
while 0 <= i and j < len(s) and s[i] == s[j]:
palin.setdefault(i, []).append(j)
i, j = i-1, j+1
#dp
@lru_cache(None)
def fn(i):
"""Return minimum palindrome partitioning of s[i:]"""
if i == len(s): return 0
return min(1 + fn(ii+1) for ii in palin[i])
return fn(0)-1 | https://leetcode.com/problems/palindrome-partitioning-ii/discuss/713271/Python3-dp-(top-down-and-bottom-up) | 2 | Given a string s, partition s such that every
substring
of the partition is a
palindrome
.
Return the minimum cuts needed for a palindrome partitioning of s.
Example 1:
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Example 2:
Input: s = "a"
Output: 0
Example 3:
Input: s = "ab"
Output: 1
Constraints:
1 <= s.length <= 2000
s consists of lowercase English letters only. | [Python3] dp (top-down & bottom-up) | 131 | palindrome-partitioning-ii | 0.337 | ye15 | Hard | 1,633 | 132 |
clone graph | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node: return node
q, clones = deque([node]), {node.val: Node(node.val, [])}
while q:
cur = q.popleft()
cur_clone = clones[cur.val]
for ngbr in cur.neighbors:
if ngbr.val not in clones:
clones[ngbr.val] = Node(ngbr.val, [])
q.append(ngbr)
cur_clone.neighbors.append(clones[ngbr.val])
return clones[node.val] | https://leetcode.com/problems/clone-graph/discuss/1792858/Python3-ITERATIVE-BFS-(beats-98)-'less()greater''-Explained | 181 | Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
Constraints:
The number of nodes in the graph is in the range [0, 100].
1 <= Node.val <= 100
Node.val is unique for each node.
There are no repeated edges and no self-loops in the graph.
The Graph is connected and all nodes can be visited starting from the given node. | ✔️ [Python3] ITERATIVE BFS (beats 98%) ,、’`<(❛ヮ❛✿)>,、’`’`,、, Explained | 15,100 | clone-graph | 0.509 | artod | Medium | 1,641 | 133 |
gas station | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
# base case
if sum(gas) - sum(cost) < 0:
return -1
gas_tank = 0 # gas available in car till now
start_index = 0 # Consider first gas station as starting point
for i in range(len(gas)):
gas_tank += gas[i] - cost[i]
if gas_tank < 0: # the car has deficit of petrol
start_index = i+1 # change the starting point
gas_tank = 0 # make the current gas to 0, as we will be starting again from next station
return start_index | https://leetcode.com/problems/gas-station/discuss/1276287/Simple-one-pass-python-solution | 9 | There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
Constraints:
n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104 | Simple one pass python solution | 796 | gas-station | 0.451 | nandanabhishek | Medium | 1,676 | 134 |
candy | class Solution:
def candy(self, ratings: List[int]) -> int:
n=len(ratings)
temp = [1]*n
for i in range(1,n):
if(ratings[i]>ratings[i-1]):
temp[i]=temp[i-1]+1
if(n>1):
if(ratings[0]>ratings[1]):
temp[0]=2
for i in range(n-2,-1,-1):
if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]):
temp[i]=temp[i+1]+1
return sum(temp) | https://leetcode.com/problems/candy/discuss/2234828/Python-oror-Two-pass-oror-explanation-oror-intuition-oror-greedy | 11 | There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
Constraints:
n == ratings.length
1 <= n <= 2 * 104
0 <= ratings[i] <= 2 * 104 | Python || Two pass || explanation || intuition || greedy | 1,200 | candy | 0.408 | palashbajpai214 | Hard | 1,707 | 135 |
single number | class Solution(object):
def singleNumber(self, nums):
# Initialize the unique number...
uniqNum = 0;
# TRaverse all elements through the loop...
for idx in nums:
# Concept of XOR...
uniqNum ^= idx;
return uniqNum; # Return the unique number... | https://leetcode.com/problems/single-number/discuss/2438883/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | 24 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Each element in the array appears twice except for one element which appears only once. | Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3) | 2,100 | single-number | 0.701 | PratikSen07 | Easy | 1,747 | 136 |
single number ii | class Solution(object):
def singleNumber(self, nums):
a, b = 0, 0
for x in nums:
a, b = (~x&a&~b)|(x&~a&b), ~a&(x^b)
return b | https://leetcode.com/problems/single-number-ii/discuss/1110333/3-python-solutions-with-different-approaches | 9 | Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Constraints:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
Each element in nums appears exactly three times except for one element which appears once. | 3 python solutions with different approaches | 796 | single-number-ii | 0.579 | mritunjoyhalder79 | Medium | 1,796 | 137 |
copy list with random pointer | class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
hm, zero = dict(), Node(0)
cur, copy = head, zero
while cur:
copy.next = Node(cur.val)
hm[cur] = copy.next
cur, copy = cur.next, copy.next
cur, copy = head, zero.next
while cur:
copy.random = hm[cur.random] if cur.random else None
cur, copy = cur.next, copy.next
return zero.next | https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841010/Python3-JUST-TWO-STEPS-()-Explained | 43 | A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Constraints:
0 <= n <= 1000
-104 <= Node.val <= 104
Node.random is null or is pointing to some node in the linked list. | ✔️ [Python3] JUST TWO STEPS ヾ(´▽`;)ゝ, Explained | 1,700 | copy-list-with-random-pointer | 0.506 | artod | Medium | 1,827 | 138 |
word break | class Solution:
def wordBreak(self, s, wordDict):
dp = [False]*(len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[-1] | https://leetcode.com/problems/word-break/discuss/748479/Python3-Solution-with-a-Detailed-Explanation-Word-Break | 51 | Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique. | Python3 Solution with a Detailed Explanation - Word Break | 4,600 | word-break | 0.455 | peyman_np | Medium | 1,863 | 139 |
word break ii | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
def wordsEndingIn(i):
if i == len(s):
return [""]
ans = []
for j in range(i+1, len(s)+1):
if s[i:j] in wordDict:
for tail in wordsEndingIn(j):
if tail != '':
ans.append(s[i:j] + " " + tail)
else:
ans.append(s[i:j])
return ans
return wordsEndingIn(0) | https://leetcode.com/problems/word-break-ii/discuss/744674/Diagrammatic-Python-Intuitive-Solution-with-Example | 10 | Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]
Example 2:
Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []
Constraints:
1 <= s.length <= 20
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 10
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique.
Input is generated in a way that the length of the answer doesn't exceed 105. | Diagrammatic Python Intuitive Solution with Example | 526 | word-break-ii | 0.446 | ivankatrump | Hard | 1,916 | 140 |
linked list cycle | class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None return False
slow_ref = head
fast_ref = head
while fast_ref and fast_ref.next:
slow_ref = slow_ref.next
fast_ref = fast_ref.next.next
if slow_ref == fast_ref:
return True
return False
If you get it please Upvote. | https://leetcode.com/problems/linked-list-cycle/discuss/1047819/Easy-in-Pythonor-O(1)-or-Beats-91 | 13 | Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory? | Easy in Python| O(1) | Beats 91% | 948 | linked-list-cycle | 0.47 | vsahoo | Easy | 1,966 | 141 |
linked list cycle ii | class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast, slow = head, head
while(fast and fast.next):
fast = fast.next.next
slow = slow.next
if(fast == slow):
slow = head
while(slow is not fast):
fast = fast.next
slow = slow.next
return slow
return None | https://leetcode.com/problems/linked-list-cycle-ii/discuss/2184711/O(1)-Space-Python-solution-with-clear-explanation-faster-than-90-solutions | 30 | Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory? | O(1) Space Python solution with clear explanation faster than 90% solutions | 844 | linked-list-cycle-ii | 0.465 | saiamrit | Medium | 2,010 | 142 |
reorder list | class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
if not head.next or not head.next.next:
return
# search for the middle
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
tail, cur = None, slow.next
slow.next = None # detach list on the middle
# reverse right part
while cur:
cur.next, tail, cur = tail, cur, cur.next
# rearrange nodes as asked
headCur, headNext = head, head.next
tailCur, tailNext = tail, tail.next
while True:
headCur.next, tailCur.next = tailCur, headNext
if not tailNext:
return
tailCur, headCur = tailNext, headNext
tailNext, headNext = tailNext.next, headNext.next | https://leetcode.com/problems/reorder-list/discuss/1640529/Python3-ONE-PASS-L(o)-Explained | 5 | You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Constraints:
The number of nodes in the list is in the range [1, 5 * 104].
1 <= Node.val <= 1000 | ✔️ [Python3] ONE PASS, L(・o・)」, Explained | 482 | reorder-list | 0.513 | artod | Medium | 2,043 | 143 |
binary tree preorder traversal | class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
stack = [root]
while stack:
temp = stack.pop()
if temp:
ans.append(temp.val)
stack.append(temp.right) #as we are using stack which works on LIFO, we need to push right tree first so that left will be popped out
stack.append(temp.left)
return ans | https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/1403244/3-Simple-Python-solutions | 14 | Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively? | 3 Simple Python solutions | 1,100 | binary-tree-preorder-traversal | 0.648 | shraddhapp | Easy | 2,070 | 144 |
binary tree postorder traversal | class Solution(object):
def postorderTraversal(self, root):
# Base case...
if not root: return []
# Create an array list to store the solution result...
sol = []
# Create an empty stack and push the root node...
bag = [root]
# Loop till stack is empty...
while bag:
# Pop a node from the stack...
node = bag.pop()
sol.append(node.val)
# Push the left child of the popped node into the stack...
if node.left:
bag.append(node.left)
# Append the right child of the popped node into the stack...
if node.right:
bag.append(node.right)
return sol[::-1] # Return the solution list... | https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2443702/Easy-oror-Recursive-and-Iterative-oror-100-oror-Explained-(Java-C%2B%2B-Python-Python3) | 16 | Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of the nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively? | Easy || Recursive & Iterative || 100% || Explained (Java, C++, Python, Python3) | 1,100 | binary-tree-postorder-traversal | 0.668 | PratikSen07 | Easy | 2,093 | 145 |
lru cache | class ListNode:
def __init__(self, key=0, val=0, prev=None, next=None):
self.key = key
self.val = val
self.prev = prev
self.next = next
class LRUCache:
def __init__(self, capacity: int):
"""Initialize hash table & dll"""
self.cpty = capacity
self.htab = dict() #hash table
self.head = ListNode() #doubly linked list
self.tail = ListNode()
self.head.next = self.tail
self.tail.prev = self.head
def _del(self, key: int) -> int:
"""Delete given key from hash table & dll"""
node = self.htab.pop(key)
node.prev.next = node.next
node.next.prev = node.prev
return node.val
def _ins(self, key: int, value: int) -> None:
"""Insert at tail"""
node = ListNode(key, value, self.tail.prev, self.tail)
self.tail.prev.next = self.tail.prev = node
self.htab[key] = node
def get(self, key: int) -> int:
if key not in self.htab: return -1
value = self._del(key)
self._ins(key, value)
return value
def put(self, key: int, value: int) -> None:
if key in self.htab: self._del(key)
self._ins(key, value)
if len(self.htab) > self.cpty:
self._del(self.head.next.key)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) | https://leetcode.com/problems/lru-cache/discuss/442751/Python3-hashmap-and-doubly-linked-list | 8 | Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exists, otherwise return -1.
void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.
Example 1:
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Constraints:
1 <= capacity <= 3000
0 <= key <= 104
0 <= value <= 105
At most 2 * 105 calls will be made to get and put. | [Python3] hashmap & doubly-linked list | 457 | lru-cache | 0.405 | ye15 | Medium | 2,129 | 146 |
insertion sort list | class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
# No need to sort for empty list or list of size 1
if not head or not head.next:
return head
# Use dummy_head will help us to handle insertion before head easily
dummy_head = ListNode(val=-5000, next=head)
last_sorted = head # last node of the sorted part
cur = head.next # cur is always the next node of last_sorted
while cur:
if cur.val >= last_sorted.val:
last_sorted = last_sorted.next
else:
# Search for the position to insert
prev = dummy_head
while prev.next.val <= cur.val:
prev = prev.next
# Insert
last_sorted.next = cur.next
cur.next = prev.next
prev.next = cur
cur = last_sorted.next
return dummy_head.next | https://leetcode.com/problems/insertion-sort-list/discuss/1176552/Python3-188ms-Solution-(explanation-with-visualization) | 28 | Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
It repeats until no input elements remain.
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Constraints:
The number of nodes in the list is in the range [1, 5000].
-5000 <= Node.val <= 5000 | [Python3] 188ms Solution (explanation with visualization) | 834 | insertion-sort-list | 0.503 | EckoTan0804 | Medium | 2,176 | 147 |
sort list | class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
# Split the list into two halfs
left = head
right = self.getMid(head)
tmp = right.next
right.next = None
right = tmp
left = self.sortList(left)
right = self.sortList(right)
return self.merge(left, right)
def getMid(self, head):
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
# Merge the list
def merge(self, list1, list2):
newHead = tail = ListNode()
while list1 and list2:
if list1.val > list2.val:
tail.next = list2
list2 = list2.next
else:
tail.next = list1
list1 = list1.next
tail = tail.next
if list1:
tail.next = list1
if list2:
tail.next = list2
return newHead.next | https://leetcode.com/problems/sort-list/discuss/1796085/Sort-List-or-Python-O(nlogn)-Solution-or-95-Faster | 25 | Given the head of a linked list, return the list after sorting it in ascending order.
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is in the range [0, 5 * 104].
-105 <= Node.val <= 105
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)? | ✔️ Sort List | Python O(nlogn) Solution | 95% Faster | 1,900 | sort-list | 0.543 | pniraj657 | Medium | 2,197 | 148 |
max points on a line | class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
if len(points) <= 2:
return len(points)
def find_slope(p1, p2):
x1, y1 = p1
x2, y2 = p2
if x1-x2 == 0:
return inf
return (y1-y2)/(x1-x2)
ans = 1
for i, p1 in enumerate(points):
slopes = defaultdict(int)
for j, p2 in enumerate(points[i+1:]):
slope = find_slope(p1, p2)
slopes[slope] += 1
ans = max(slopes[slope], ans)
return ans+1 | https://leetcode.com/problems/max-points-on-a-line/discuss/1983010/Python-3-Using-Slopes-and-Hash-Tables-or-Clean-Python-solution | 33 | Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Output: 3
Example 2:
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Constraints:
1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
All the points are unique. | [Python 3] Using Slopes and Hash Tables | Clean Python solution | 1,200 | max-points-on-a-line | 0.218 | hari19041 | Hard | 2,219 | 149 |
evaluate reverse polish notation | class Solution:
def evalRPN(self, tokens: List[str]) -> int:
def update(sign):
n2,n1=stack.pop(),stack.pop()
if sign=="+": return n1+n2
if sign=="-": return n1-n2
if sign=="*": return n1*n2
if sign=="/": return int(n1/n2)
stack=[]
for n in tokens:
if n.isdigit() or len(n)>1:
stack.append(int(n))
else:
stack.append(update(n))
return stack.pop() | https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1732651/Super-Simple-Python-stack-solution | 6 | You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Constraints:
1 <= tokens.length <= 104
tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]. | Super Simple Python 🐍 stack solution | 380 | evaluate-reverse-polish-notation | 0.441 | InjySarhan | Medium | 2,242 | 150 |
reverse words in a string | class Solution:
def reverseWords(self, s: str) -> str:
#Time: O(n) since we scan through the input, where n = len(s)
#Space: O(n)
words = []
slow, fast = 0, 0
#Use the first char to determine if we're starting on a " " or a word
mode = 'blank' if s[0] == ' ' else 'word'
while fast < len(s):
#If we start on a word and our fast ptr lands on a white space
#means that we have singled out a word
if mode == 'word' and s[fast] == ' ':
words.append(s[slow:fast])
slow = fast #Make the slow ptr catch up
mode = 'blank'
#If we start on a white space and our fast ptr runs into a character
#means we are at the start of a word
elif mode == 'blank' and s[fast] != ' ':
slow = fast #Make the slow ptr catch up
mode = 'word'
fast += 1 #Increment the fast pointer
#Append the last word
#Edge cases where the last chunk of string are white spaces
if (lastWord := s[slow:fast]).isalnum():
words.append(lastWord)
return ' '.join(words[::-1]) | https://leetcode.com/problems/reverse-words-in-a-string/discuss/1632928/Intuitive-Two-Pointers-in-Python-without-strip()-or-split() | 10 | Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 104
s contains English letters (upper-case and lower-case), digits, and spaces ' '.
There is at least one word in s.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space? | Intuitive Two Pointers in Python without strip() or split() | 490 | reverse-words-in-a-string | 0.318 | surin_lovejoy | Medium | 2,290 | 151 |
maximum product subarray | class Solution:
def maxProduct(self, nums: List[int]) -> int:
curMax, curMin = 1, 1
res = nums[0]
for n in nums:
vals = (n, n * curMax, n * curMin)
curMax, curMin = max(vals), min(vals)
res = max(res, curMax)
return res | https://leetcode.com/problems/maximum-product-subarray/discuss/1608907/Python3-DYNAMIC-PROGRAMMING-Explained | 90 | Given an integer array nums, find a
subarray
that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. | ✔️[Python3] DYNAMIC PROGRAMMING, Explained | 9,700 | maximum-product-subarray | 0.349 | artod | Medium | 2,340 | 152 |
find minimum in rotated sorted array | class Solution:
def findMin(self, nums: List[int]) -> int:
start = 0
end = len(nums) - 1
if(nums[start] <= nums[end]):
return nums[0]
while start <= end:
mid = (start + end) // 2
if(nums[mid] > nums[mid+1]):
return nums[mid+1]
if(nums[mid-1] > nums[mid]):
return nums[mid]
if(nums[mid] > nums[0]):
start = mid + 1
else:
end = mid - 1
return nums[start] | https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2211586/Python3-simple-naive-solution-with-binary-search | 6 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
All the integers of nums are unique.
nums is sorted and rotated between 1 and n times. | 📌 Python3 simple naive solution with binary search | 105 | find-minimum-in-rotated-sorted-array | 0.485 | Dark_wolf_jss | Medium | 2,389 | 153 |
find minimum in rotated sorted array ii | class Solution:
def findMin(self, a: List[int]) -> int:
def solve(l,h):
while l<h:
m=(l+h)//2
if a[m]<a[m-1]:
return a[m]
elif a[m]>a[h-1]:
l=m+1
elif a[m]<a[h-1]:
h=m
else:
if len(set(a[l:m+1]))==1:
return min(a[m],solve(m+1,h))
else:
return min(a[m],solve(l,m))
return a[min(l,len(a)-1)]
return solve(0,len(a)) | https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/2087295/Binary-Search-oror-Explained-oror-PYTHON | 2 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
[4,5,6,7,0,1,4] if it was rotated 4 times.
[0,1,4,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
Example 1:
Input: nums = [1,3,5]
Output: 1
Example 2:
Input: nums = [2,2,2,0,1]
Output: 0
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums is sorted and rotated between 1 and n times.
Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?
| Binary Search || Explained || PYTHON | 69 | find-minimum-in-rotated-sorted-array-ii | 0.434 | karan_8082 | Hard | 2,439 | 154 |
min stack | class MinStack:
stackWithMinElements = collections.namedtuple("stackWithMinElements", ("element", "minimum"))
def __init__(self):
self.stack : List[self.stackWithMinElements] = []
def push(self, x: int) -> None:
self.stack.append(self.stackWithMinElements(
x, min(x, self.getMin()) if len(self.stack)>0 else x))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1].element
def getMin(self) -> int:
return self.stack[-1].minimum | https://leetcode.com/problems/min-stack/discuss/825972/Python-3-greater-91-faster-using-namedtuple | 5 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
-231 <= val <= 231 - 1
Methods pop, top and getMin operations will always be called on non-empty stacks.
At most 3 * 104 calls will be made to push, pop, top, and getMin. | Python 3 -> 91% faster using namedtuple | 554 | min-stack | 0.519 | mybuddy29 | Medium | 2,457 | 155 |
intersection of two linked lists | class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
first_set=set()
curr=headA
while curr:
first_set.add(curr)
curr=curr.next
curr = headB
while curr:
if curr in first_set:
return curr
curr=curr.next
return None | https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/2116127/Python-oror-Easy-2-approaches-oror-O(1)-space | 75 | Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Custom Judge:
The inputs to the judge are given as follows (your program is not given these inputs):
intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.
listA - The first linked list.
listB - The second linked list.
skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Constraints:
The number of nodes of listA is in the m.
The number of nodes of listB is in the n.
1 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA < m
0 <= skipB < n
intersectVal is 0 if listA and listB do not intersect.
intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.
Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory? | Python || Easy 2 approaches || O(1) space | 5,200 | intersection-of-two-linked-lists | 0.534 | constantine786 | Easy | 2,513 | 160 |
find peak element | class Solution:
def findPeakElement(self, lst: List[int]) -> int:
start, end = 0, len(lst) - 1
while start < end:
mid = start + (end - start) // 2
if lst[mid] > lst[mid + 1]:
end = mid
else:
start = mid + 1
return start | https://leetcode.com/problems/find-peak-element/discuss/1440424/Python-oror-Easy-Solution | 8 | A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1] for all valid i. | Python || Easy Solution | 619 | find-peak-element | 0.462 | naveenrathore | Medium | 2,545 | 162 |
maximum gap | class Solution:
def maximumGap(self, nums: List[int]) -> int:
if len(nums) == 0: return 0 #edge case
mn, mx = min(nums), max(nums)
step = max(1, (mx - mn)//(len(nums)-1)) #n-1 holes
size = (mx - mn)//step + 1
buckets = [[inf, -inf] for _ in range(size)]
for num in nums:
i = (num - mn)//step
x, xx = buckets[i]
buckets[i] = min(x, num), max(xx, num)
ans = 0
prev = mn
for i in range(size):
x, xx = buckets[i]
if x < inf:
ans = max(ans, x - prev)
prev = xx
return ans | https://leetcode.com/problems/maximum-gap/discuss/727709/Python3-group-data-into-buckets | 6 | Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: nums = [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109 | [Python3] group data into buckets | 291 | maximum-gap | 0.428 | ye15 | Hard | 2,589 | 164 |
compare version numbers | class Solution:
def compareVersion(self, v1: str, v2: str) -> int:
v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.')))
for rev1, rev2 in zip_longest(v1, v2, fillvalue=0):
if rev1 == rev2:
continue
return -1 if rev1 < rev2 else 1
return 0 | https://leetcode.com/problems/compare-version-numbers/discuss/1797594/Python3-SOLUTION-Explained | 47 | Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.
To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.
Return the following:
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
Example 1:
Input: version1 = "1.2", version2 = "1.10"
Output: -1
Explanation:
version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.
Example 2:
Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation:
Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
Example 3:
Input: version1 = "1.0", version2 = "1.0.0.0"
Output: 0
Explanation:
version1 has less revisions, which means every missing revision are treated as "0".
Constraints:
1 <= version1.length, version2.length <= 500
version1 and version2 only contain digits and '.'.
version1 and version2 are valid version numbers.
All the given revisions in version1 and version2 can be stored in a 32-bit integer. | ✔️ [Python3] SOLUTION, Explained | 3,400 | compare-version-numbers | 0.354 | artod | Medium | 2,610 | 165 |
fraction to recurring decimal | class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator % denominator == 0:
return str(numerator // denominator)
prefix = ''
if (numerator > 0) != (denominator > 0):
prefix = '-'
# Operation must be on positive values
if numerator < 0:
numerator = - numerator
if denominator < 0:
denominator = - denominator
digit, remainder = divmod(numerator, denominator)
res = prefix + str(digit) + '.' # EVERYTHING BEFORE DECIMAL
table = {}
suffix = ''
while remainder not in table.keys():
# Store index of the reminder in the table
table[remainder] = len(suffix)
val, remainder = divmod(remainder*10, denominator)
suffix += str(val)
# No repeating
if remainder == 0:
return res + suffix
indexOfRepeatingPart = table[remainder]
decimalTillRepeatingPart = suffix[:indexOfRepeatingPart]
repeatingPart = suffix[indexOfRepeatingPart:]
return res + decimalTillRepeatingPart + '(' + repeatingPart + ')'
s = Solution()
print(s.fractionToDecimal(2, 3)) | https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/998707/Python-solution-with-detail-explanation | 3 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 4, denominator = 333
Output: "0.(012)"
Constraints:
-231 <= numerator, denominator <= 231 - 1
denominator != 0 | Python solution with detail explanation | 650 | fraction-to-recurring-decimal | 0.241 | imasterleet | Medium | 2,647 | 166 |
two sum ii input array is sorted | class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i = 0
j = len(numbers) -1
while i<j:
s = numbers[i] + numbers[j]
if s == target:
return [i + 1 , j + 1]
if s > target:
j-=1
else:
i+=1
return [] | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2128459/Python-Easy-O(1)-Space | 51 | Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
Constraints:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution. | Python Easy O(1) Space | 3,700 | two-sum-ii-input-array-is-sorted | 0.6 | constantine786 | Medium | 2,656 | 167 |
excel sheet column title | class Solution(object):
def convertToTitle(self, columnNumber):
# Create an empty string for storing the characters...
output = ""
# Run a while loop while columnNumber is positive...
while columnNumber > 0:
# Subtract 1 from columnNumber and get current character by doing modulo of columnNumber by 26...
output = chr(ord('A') + (columnNumber - 1) % 26) + output
# Divide columnNumber by 26...
columnNumber = (columnNumber - 1) // 26
# Return the output string.
return output | https://leetcode.com/problems/excel-sheet-column-title/discuss/2448578/Easy-oror-0-ms-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-Python3) | 22 | Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input: columnNumber = 701
Output: "ZY"
Constraints:
1 <= columnNumber <= 231 - 1 | Easy || 0 ms || 100% || Fully Explained (Java, C++, Python, Python3) | 1,300 | excel-sheet-column-title | 0.348 | PratikSen07 | Easy | 2,709 | 168 |
majority element | class Solution:
def majorityElement(self, nums: List[int]) -> int:
curr, count = nums[0], 1 # curr will store the current majority element, count will store the count of the majority
for i in range(1,len(nums)):
count += (1 if curr == nums[i] else -1) # if i is equal to current majority, they're in same team, hence added, else one current majority and i both will be dead
if not count: # if count is 0 means King is de-throwned
curr = nums[i+1] if i + 1 < len(nums) else None # the next element is the new King
count = 0 # starting it with 0 because we can't increment the i of the for loop, the count will be 1 in next iteration, and again the battle continues after next iteration
return curr | https://leetcode.com/problems/majority-element/discuss/1788112/Python-easy-solution-O(n)-or-O(1)-or-explained | 18 | Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Constraints:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
Follow-up: Could you solve the problem in linear time and in O(1) space? | ✅ Python easy solution O(n) | O(1) | explained | 1,700 | majority-element | 0.639 | dhananjay79 | Easy | 2,746 | 169 |
excel sheet column number | class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans, pos = 0, 0
for letter in reversed(columnTitle):
digit = ord(letter)-64
ans += digit * 26**pos
pos += 1
return ans | https://leetcode.com/problems/excel-sheet-column-number/discuss/1790567/Python3-CLEAN-SOLUTION-()-Explained | 105 | Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Constraints:
1 <= columnTitle.length <= 7
columnTitle consists only of uppercase English letters.
columnTitle is in the range ["A", "FXSHRXW"]. | ✔️ [Python3] CLEAN SOLUTION (๑❛ꆚ❛๑), Explained | 8,500 | excel-sheet-column-number | 0.614 | artod | Easy | 2,793 | 171 |
factorial trailing zeroes | class Solution:
def trailingZeroes(self, n: int) -> int:
quotient = n // 5
return quotient + self.trailingZeroes(quotient) if quotient >= 5 else quotient | https://leetcode.com/problems/factorial-trailing-zeroes/discuss/1152167/Python3-O(log(n))-time-O(1)-space.-Explanation | 12 | Given an integer n, return the number of trailing zeroes in n!.
Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.
Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Example 3:
Input: n = 0
Output: 0
Constraints:
0 <= n <= 104
Follow up: Could you write a solution that works in logarithmic time complexity? | Python3 O(log(n)) time, O(1) space. Explanation | 472 | factorial-trailing-zeroes | 0.418 | ryancodrai | Medium | 2,851 | 172 |
binary search tree iterator | class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.iter = self._inorder(root)
self.nxt = next(self.iter, None)
def _inorder(self, node: Optional[TreeNode]) -> Generator[int, None, None]:
if node:
yield from self._inorder(node.left)
yield node.val
yield from self._inorder(node.right)
def next(self) -> int:
res, self.nxt = self.nxt, next(self.iter, None)
return res
def hasNext(self) -> bool:
return self.nxt is not None | https://leetcode.com/problems/binary-search-tree-iterator/discuss/1965156/Python-TC-O(1)-SC-O(h)-Generator-Solution | 34 | Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:
Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
Constraints:
The number of nodes in the tree is in the range [1, 105].
0 <= Node.val <= 106
At most 105 calls will be made to hasNext, and next.
Follow up:
Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree? | [Python] TC O(1) SC O(h) Generator Solution | 2,300 | binary-search-tree-iterator | 0.692 | zayne-siew | Medium | 2,878 | 173 |
dungeon game | class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
m, n = len(dungeon), len(dungeon[0])
@cache
def fn(i, j):
"""Return min health at (i,j)."""
if i == m or j == n: return inf
if i == m-1 and j == n-1: return max(1, 1 - dungeon[i][j])
return max(1, min(fn(i+1, j), fn(i, j+1)) - dungeon[i][j])
return fn(0, 0) | https://leetcode.com/problems/dungeon-game/discuss/699433/Python3-dp | 1 | The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Return the knight's minimum initial health so that he can rescue the princess.
Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
Example 1:
Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
Output: 7
Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
Example 2:
Input: dungeon = [[0]]
Output: 1
Constraints:
m == dungeon.length
n == dungeon[i].length
1 <= m, n <= 200
-1000 <= dungeon[i][j] <= 1000 | [Python3] dp | 45 | dungeon-game | 0.373 | ye15 | Hard | 2,911 | 174 |
largest number | class Solution:
def largestNumber(self, nums: List[int]) -> str:
nums = sorted(nums,key=lambda x:x / (10 ** len(str(x)) - 1 ), reverse=True)
str_nums = [str(num) for num in nums]
res = ''.join(str_nums)
res = str(int(res))
return res | https://leetcode.com/problems/largest-number/discuss/1391073/python-easy-custom-sort-solution!!!!!!! | 9 | Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: "210"
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 109 | python easy custom sort solution!!!!!!! | 900 | largest-number | 0.341 | user0665m | Medium | 2,928 | 179 |
repeated dna sequences | class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
res, d = [], {}
for i in range(len(s)):
if s[i:i+10] not in d: d[s[i:i+10]] = 0
elif s[i:i+10] not in res: res.append(s[i:i+10])
return res
# An Upvote will be encouraging | https://leetcode.com/problems/repeated-dna-sequences/discuss/2223482/Simple-Python-Solution-oror-O(n)-Time-oror-O(n)-Space-oror-Sliding-Window | 2 | The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.
For example, "ACGAATTCCG" is a DNA sequence.
When studying DNA, it is useful to identify repeated sequences within the DNA.
Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.
Example 1:
Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
Output: ["AAAAACCCCC","CCCCCAAAAA"]
Example 2:
Input: s = "AAAAAAAAAAAAA"
Output: ["AAAAAAAAAA"]
Constraints:
1 <= s.length <= 105
s[i] is either 'A', 'C', 'G', or 'T'. | Simple Python Solution || O(n) Time || O(n) Space || Sliding Window | 121 | repeated-dna-sequences | 0.463 | rajkumarerrakutti | Medium | 2,949 | 187 |
best time to buy and sell stock iv | class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
# no transaction, no profit
if k == 0: return 0
# dp[k][0] = min cost you need to spend at most k transactions
# dp[k][1] = max profit you can achieve at most k transactions
dp = [[1000, 0] for _ in range(k + 1)]
for price in prices:
for i in range(1, k + 1):
# price - dp[i - 1][1] is how much you need to spend
# i.e use the profit you earned from previous transaction to buy the stock
# we want to minimize it
dp[i][0] = min(dp[i][0], price - dp[i - 1][1])
# price - dp[i][0] is how much you can achieve from previous min cost
# we want to maximize it
dp[i][1] = max(dp[i][1], price - dp[i][0])
# return max profit at most k transactions
# or you can write `return dp[-1][1]`
return dp[k][1] | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2555699/LeetCode-The-Hard-Way-7-Lines-or-Line-By-Line-Explanation | 62 | You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Constraints:
1 <= k <= 100
1 <= prices.length <= 1000
0 <= prices[i] <= 1000 | 🔥 [LeetCode The Hard Way] 🔥 7 Lines | Line By Line Explanation | 3,600 | best-time-to-buy-and-sell-stock-iv | 0.381 | wingkwong | Hard | 2,969 | 188 |
rotate array | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def twopt(arr, i, j):
while (i < j):
arr[i], arr[j] = arr[j], arr[i]
i += 1
j -= 1
return arr
if k > len(nums):
k %= len(nums)
if (k > 0):
twopt(nums, 0, len(nums) - 1) # rotate entire array
twopt(nums, 0, k - 1) # rotate array upto k elements
twopt(nums, k, len(nums) - 1) # rotate array from k to end of array | https://leetcode.com/problems/rotate-array/discuss/1419527/Python-or-Two-Pointers-solution | 31 | Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105
Follow up:
Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
Could you do it in-place with O(1) extra space? | Python | Two-Pointers solution | 3,900 | rotate-array | 0.392 | Shreya19595 | Medium | 3,000 | 189 |
reverse bits | class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for _ in range(32):
res = (res<<1) + (n&1)
n>>=1
return res | https://leetcode.com/problems/reverse-bits/discuss/1791099/Python-3-(40ms)-or-Real-BIT-Manipulation-Solution | 22 | Reverse bits of a given 32 bits unsigned integer.
Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Example 1:
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Constraints:
The input must be a binary string of length 32
Follow up: If this function is called many times, how would you optimize it? | Python 3 (40ms) | Real BIT Manipulation Solution | 1,800 | reverse-bits | 0.525 | MrShobhit | Easy | 3,053 | 190 |
number of 1 bits | class Solution:
def hammingWeight(self, n: int) -> int:
return sum((n & (1<<i))!=0 for i in range(32)) | https://leetcode.com/problems/number-of-1-bits/discuss/2074152/Easy-O(1)-Space-PythonC%2B%2B | 21 | Write a function that takes the binary representation of a positive integer and returns the number of
set bits
it has (also known as the Hamming weight).
Example 1:
Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.
Example 2:
Input: n = 128
Output: 1
Explanation:
The input binary string 10000000 has a total of one set bit.
Example 3:
Input: n = 2147483645
Output: 30
Explanation:
The input binary string 1111111111111111111111111111101 has a total of thirty set bits.
Constraints:
1 <= n <= 231 - 1
Follow up: If this function is called many times, how would you optimize it? | Easy O(1) Space - Python/C++ | 2,800 | number-of-1-bits | 0.65 | constantine786 | Easy | 3,104 | 191 |
house robber | class Solution:
def __init__(self):
self.cache = {}
def rob_rec(self, nums, start):
if start >= len(nums):
return 0
if start in self.cache:
return self.cache[start]
self.cache[start] = nums[start] + max(self.rob_rec(nums, start+2), self.rob_rec(nums, start+3))
return self.cache[start]
def rob(self, nums: List[int]) -> int:
return max(self.rob_rec(nums, 0), self.rob_rec(nums, 1)) | https://leetcode.com/problems/house-robber/discuss/378700/Python-multiple-solutions | 23 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 400 | Python multiple solutions | 2,500 | house-robber | 0.488 | amchoukir | Medium | 3,149 | 198 |
binary tree right side view | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
def solve(root, lvl):
if root:
if len(res)==lvl:
res.append(root.val)
solve(root.right, lvl + 1)
solve(root.left, lvl + 1)
return
res = []
solve(root,0)
return res | https://leetcode.com/problems/binary-tree-right-side-view/discuss/2266055/C%2B%2B-oror-PYTHON-oror-EXPLAINED-oror | 80 | Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100 | ✔️ C++ || PYTHON || EXPLAINED || ; ] | 4,400 | binary-tree-right-side-view | 0.612 | karan_8082 | Medium | 3,210 | 199 |
number of islands | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid: return 0
m, n = len(grid), len(grid[0])
ans = 0
def dfs(i, j):
grid[i][j] = '2'
for di, dj in (0, 1), (0, -1), (1, 0), (-1, 0):
ii, jj = i+di, j+dj
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] == '1':
dfs(ii, jj)
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
dfs(i, j)
ans += 1
return ans | https://leetcode.com/problems/number-of-islands/discuss/863366/Python-3-or-DFS-BFS-Union-Find-All-3-methods-or-Explanation | 50 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'. | Python 3 | DFS, BFS, Union Find, All 3 methods | Explanation | 5,200 | number-of-islands | 0.564 | idontknoooo | Medium | 3,235 | 200 |
bitwise and of numbers range | class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
shift = 0
# find the common MSB bits.
while m != n:
m = m >> 1
n = n >> 1
shift += 1
return m << shift | https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/469130/Python-iterative-sol.-based-on-bit-manipulation | 9 | Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <= right <= 231 - 1 | Python iterative sol. based on bit-manipulation | 723 | bitwise-and-of-numbers-range | 0.423 | brianchiang_tw | Medium | 3,287 | 201 |
happy number | class Solution(object):
def isHappy(self, n):
hset = set()
while n != 1:
if n in hset: return False
hset.add(n)
n = sum([int(i) ** 2 for i in str(n)])
else:
return True | https://leetcode.com/problems/happy-number/discuss/2383810/Very-Easy-0-ms-100(Fully-Explained)(C%2B%2B-Java-Python-JS-C-Python3) | 18 | Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input: n = 2
Output: false
Constraints:
1 <= n <= 231 - 1 | Very Easy 0 ms 100%(Fully Explained)(C++, Java, Python, JS, C, Python3) | 1,700 | happy-number | 0.545 | PratikSen07 | Easy | 3,301 | 202 |
remove linked list elements | class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(-1)
dummy_head.next = head
current_node = dummy_head
while current_node.next != None:
if current_node.next.val == val:
current_node.next = current_node.next.next
else:
current_node = current_node.next
return dummy_head.next | https://leetcode.com/problems/remove-linked-list-elements/discuss/158651/Simple-Python-solution-with-explanation-(single-pointer-dummy-head). | 429 | Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
The number of nodes in the list is in the range [0, 104].
1 <= Node.val <= 50
0 <= val <= 50 | Simple Python solution with explanation (single pointer, dummy head). | 28,900 | remove-linked-list-elements | 0.449 | Hai_dee | Easy | 3,349 | 203 |
count primes | class Solution:
def countPrimes(self, n: int) -> int:
if n<2:
return 0
#initialize a list of length n
prime=[1]*n
#mark 0th and 1st index as 0
prime[0]=prime[1]=0
#we will check for multiple from range 2 to sqrt(n)
for i in range(2,int(sqrt(n))+1):
if prime[i] == 1:
#mark all multiple of prime number as 0
prime[i*i:n:i] = [0] * ((n-1-i*i)//i + 1)
#return total count of prime
return sum(prime) | https://leetcode.com/problems/count-primes/discuss/1267254/Python-3-solution-97.7-faster | 11 | Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5 * 106 | Python 3 solution 97.7% faster | 1,700 | count-primes | 0.331 | ritesh98 | Medium | 3,375 | 204 |
isomorphic strings | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return [*map(s.index, s)] == [*map(t.index, t)] | https://leetcode.com/problems/isomorphic-strings/discuss/2472118/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashMap) | 44 | Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Constraints:
1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character. | Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashMap) | 5,500 | isomorphic-strings | 0.426 | PratikSen07 | Easy | 3,395 | 205 |
reverse linked list | class Solution(object):
def reverseList(self, head):
# Initialize prev pointer as NULL...
prev = None
# Initialize the curr pointer as the head...
curr = head
# Run a loop till curr points to NULL...
while curr:
# Initialize next pointer as the next pointer of curr...
next = curr.next
# Now assign the prev pointer to curr’s next pointer.
curr.next = prev
# Assign curr to prev, next to curr...
prev = curr
curr = next
return prev # Return the prev pointer to get the reverse linked list... | https://leetcode.com/problems/reverse-linked-list/discuss/2458632/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Recursive-and-Iterative) | 92 | Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? | Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Recursive & Iterative) | 6,800 | reverse-linked-list | 0.726 | PratikSen07 | Easy | 3,451 | 206 |
course schedule | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph=defaultdict(list)
indegree={}
#initialising dictionary
for i in range(numCourses):
indegree[i]=0
#filling graph and indegree dictionaries
for child,parent in prerequisites:
graph[parent].append(child)
indegree[child]+=1
queue=deque()
for key,value in indegree.items():
if value==0:
queue.append(key)
courseSequence=[]
while queue:
course=queue.popleft()
courseSequence.append(course)
for neighbour in graph[course]:
indegree[neighbour]-=1
if indegree[neighbour]==0:
queue.append(neighbour)
return len(courseSequence)==numCourses: | https://leetcode.com/problems/course-schedule/discuss/1627381/Simple-and-Easy-Topological-Sorting-code-beats-97.63-python-submissions | 11 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai, bi < numCourses
All the pairs prerequisites[i] are unique. | Simple and Easy Topological Sorting code, beats 97.63% python submissions | 1,400 | course-schedule | 0.454 | RaghavGupta22 | Medium | 3,483 | 207 |
minimum size subarray sum | class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0 # keep track of left pointer
rsum = 0 # keep the running sum
res = None # Answer we will return
# Iterate through the array, the index will be your right pointer
for right in range(len(nums)):
# Add the current value to the running sum
rsum += nums[right]
# Once you reach a value at or equal to the target you
# can use a while loop to start subtracting the values from left
# to right so that you can produce the minimum size subarray
while rsum >= target:
# The result is either the current result you have,
# or the count of numbers from the current left position
# to the rightmost position. You need it to be right + 1
# because index starts at 0 (if you based the right as the
# last index it would be 4 or len(nums) - 1)
# If res is None we compare it against the max float,
# saves us from having an if/else
res = min(res or float('inf'), right + 1 - left)
# Subtract the number to see if we can continue subtracting based
# on the while loop case and increment the left pointer
rsum -= nums[left]
left += 1
return res or 0 | https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1774062/Python-Explanation-of-sliding-window-using-comments | 8 | Given an array of positive integers nums and a positive integer target, return the minimal length of a
subarray
whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Constraints:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)). | Python - Explanation of sliding window using comments | 376 | minimum-size-subarray-sum | 0.445 | iamricks | Medium | 3,530 | 209 |
course schedule ii | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# Handle edge case.
if not prerequisites: return [course for course in range(numCourses)]
# 'parents' maps each course to a list of its pre
# -requisites.
parents = {course: [] for course in range(numCourses)}
for course, prerequisite in prerequisites:
parents[course].append(prerequisite)
topological_order = []
visited, current_path = [False]*numCourses, [False]*numCourses
# Returns False if the digraph rooted at 'course'
# is acyclic, else, appends courses to 'topological
# _order' in topological order and returns True.
def dfs(course):
if current_path[course]: return False
if visited[course]: return True
visited[course], current_path[course] = True, True
if parents[course]:
for parent in parents[course]:
if not dfs(parent): return False
topological_order.append(course)
current_path[course] = False
return True
for course in range(numCourses):
if not dfs(course): return []
return topological_order | https://leetcode.com/problems/course-schedule-ii/discuss/1327646/Elegant-Python-DFS | 4 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
Example 2:
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
Example 3:
Input: numCourses = 1, prerequisites = []
Output: [0]
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
All the pairs [ai, bi] are distinct. | Elegant Python DFS | 467 | course-schedule-ii | 0.481 | soma28 | Medium | 3,580 | 210 |
word search ii | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
res = []
d = [[0, 1], [0, -1], [1, 0], [-1, 0]]
ref = set()
for i in range(m):
for j in range(n-1):
ref.add(board[i][j] + board[i][j+1])
for j in range(n):
for i in range(m-1):
ref.add(board[i][j] + board[i+1][j])
for word in words:
f = True
for i in range(len(word)-1):
if word[i:i+2] not in ref and word[i+1] + word[i] not in ref:
f = False
break
if not f:
continue
if self.findWord(word, m, n, board, d):
res.append(word)
return res
def findWord(self, word, m, n, board, d) -> bool:
if word[:4] == word[0] * 4:
word = ''.join([c for c in reversed(word)])
starts = []
stack = []
visited = set()
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
if len(word) == 1:
return True
starts.append((i, j))
for start in starts:
stack.append(start)
visited.add((start, ))
l = 1
while stack != [] and l < len(word):
x, y = stack[-1]
for dxy in d:
nx, ny = x + dxy[0], y + dxy[1]
if 0 <= nx < m and 0 <= ny < n:
if board[nx][ny] == word[l]:
if (nx, ny) not in stack and tuple(stack) + ((nx, ny),) not in visited:
stack.append((nx, ny))
visited.add(tuple(stack))
l += 1
if l == len(word):
return True
break
else:
stack.pop()
l -= 1
else:
return False | https://leetcode.com/problems/word-search-ii/discuss/2351408/python3-solution-oror-99-more-faster-oror-39-ms | 3 | Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] is a lowercase English letter.
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
All the strings of words are unique. | python3 solution || 99% more faster || 39 ms | 301 | word-search-ii | 0.368 | vimla_kushwaha | Hard | 3,627 | 212 |
house robber ii | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dp = {}
def getResult(a,i):
if i>=len(a):
return 0
if i in dp:
return dp[i]
sum = 0
if i<len(a)-1:
sum+= max(a[i]+getResult(a,i+2),a[i+1]+getResult(a,i+3))
else:
sum+=a[i]+getResult(a,i+2)
dp[i] = sum
return sum
x = getResult(nums[:len(nums)-1],0)
dp = {}
y = getResult(nums[1:],0)
return max(x, y) | https://leetcode.com/problems/house-robber-ii/discuss/2158878/Do-house-robber-twice | 4 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
Example 2:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 3:
Input: nums = [1,2,3]
Output: 3
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000 | 📌 Do house robber twice | 104 | house-robber-ii | 0.407 | Dark_wolf_jss | Medium | 3,648 | 213 |