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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
baseball game | class Solution:
def calPoints(self, s: List[str]) -> int:
p = []
for i in s:
if i == 'C': p.pop()
elif i == 'D': p.append(2*p[-1])
elif i == '+': p.append(p[-1]+p[-2])
else: p.append(int(i))
return sum(p) | https://leetcode.com/problems/baseball-game/discuss/380544/Two-Solutions-in-Python-3-(beats-~99) | 7 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:
An integer x.
Record a new score of x.
'+'.
Reco... | Two Solutions in Python 3 (beats ~99%) | 928 | baseball-game | 0.737 | junaidmansuri | Easy | 11,273 | 682 |
redundant connection | class Solution(object):
def findRedundantConnection(self, edges):
self.parent = dict()
for e in edges:
f0 = self.find(e[0])
f1 = self.find(e[1])
if f0 == f1:
return e
self.parent[f0] = f1
... | https://leetcode.com/problems/redundant-connection/discuss/2755933/Python-Union-Find-Easy | 1 | In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represen... | Python - Union Find - Easy | 8 | redundant-connection | 0.62 | lokeshsenthilkumar | Medium | 11,323 | 684 |
repeated string match | class Solution:
def repeatedStringMatch(self, A: str, B: str) -> int:
if set(B).issubset(set(A)) == False: return -1
for i in range(1,int(len(B)/len(A))+3):
if B in A*i: return i
return -1
- Python3
- Junaid Mansuri | https://leetcode.com/problems/repeated-string-match/discuss/330741/Simple-Python3-Solution-(beats-~100)-(my-first-post-on-LeetCode-!!!) | 15 | Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".
Exampl... | Simple Python3 Solution (beats ~100%) (my first post on LeetCode !!!) | 1,600 | repeated-string-match | 0.34 | junaidmansuri | Medium | 11,336 | 686 |
longest univalue path | class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
def dfs(node):
"""Return longest univalue branch and longest univalue path (post-order traversal)."""
if not node: return 0, 0
(lx, llup), (rx, rlup) = dfs(node.left), dfs(node.right)
... | https://leetcode.com/problems/longest-univalue-path/discuss/902315/Python3-dfs-(post-order) | 4 | Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [5,4,5,1,1,null,5]
Output: 2
Exp... | [Python3] dfs (post order) | 215 | longest-univalue-path | 0.402 | ye15 | Medium | 11,345 | 687 |
knight probability in chessboard | class Solution:
def knightProbability(self, n: int, k: int, row0: int, col0: int) -> float:
# precalculate possible moves
adj_list = defaultdict(list)
d = ((-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2))
for row in range(n):
for col in range(n):
... | https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2193242/Python3-DFS-with-DP-beats-99-()()-Explained | 6 | On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a ... | ✔️ [Python3] DFS with DP, beats 99% ٩(๑・ิᴗ・ิ)۶٩(・ิᴗ・ิ๑)۶, Explained | 164 | knight-probability-in-chessboard | 0.521 | artod | Medium | 11,351 | 688 |
maximum sum of 3 non overlapping subarrays | class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
@cache
def fn(i, n):
"""Return max sum of 3 non-overlapping subarrays."""
if n == 0: return []
... | https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/1342651/Python3-dp | 1 | Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example 1:
... | [Python3] dp | 73 | maximum-sum-of-3-non-overlapping-subarrays | 0.489 | ye15 | Hard | 11,367 | 689 |
employee importance | class Solution:
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
id_to_emp = {employee.id: employee for employee in employees}
importance = 0
stack = [id_to_emp[id]]
while stack:
cu... | https://leetcode.com/problems/employee-importance/discuss/332600/Iterative-Python-beats-99.73 | 5 | You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees employees where:
employees[i].id is the ID of the ith employee.
employees[i].importance is the importance value of the ith employee.
employees[i].sub... | Iterative Python, beats 99.73% | 962 | employee-importance | 0.652 | hgrsd | Medium | 11,373 | 690 |
stickers to spell word | class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
freqs = [Counter(x) for x in stickers]
@cache
def fn(x):
"""Return min sticks to give x."""
if not x: return 0
ans = inf
freq = Counter(x)
for... | https://leetcode.com/problems/stickers-to-spell-word/discuss/1366983/Python3-dp | 4 | We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of e... | [Python3] dp | 234 | stickers-to-spell-word | 0.463 | ye15 | Hard | 11,388 | 691 |
top k frequent words | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
#Have a dict of word and its freq
counts = collections.Counter(words)
#get a array wchich will have a tuple of word and count
heap = [(-count, word) for word, count in counts.items()]
... | https://leetcode.com/problems/top-k-frequent-words/discuss/1657648/Simple-or-4-lines-or-using-heap-or-With-explanation | 25 | Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love... | Simple | 4 lines | using heap | With explanation | 2,000 | top-k-frequent-words | 0.569 | shraddhapp | Medium | 11,394 | 692 |
binary number with alternating bits | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
s = bin(n).replace('0b','')
for i in range(len(s)-1):
if s[i] == s[i+1]:
return False
return True | https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1095502/Python3-simple-solution | 2 | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3... | Python3 simple solution | 54 | binary-number-with-alternating-bits | 0.613 | EklavyaJoshi | Easy | 11,432 | 693 |
max area of island | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
maxArea = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1: # run dfs only when we find a land
... | https://leetcode.com/problems/max-area-of-island/discuss/1459194/python-Simple-and-intuitive-DFS-approach-!!! | 15 | You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an islan... | [python] Simple and intuitive DFS approach !!! | 1,400 | max-area-of-island | 0.717 | nandanabhishek | Medium | 11,454 | 695 |
count binary substrings | class Solution:
def countBinarySubstrings(self, s: str) -> int:
stack = [[], []]
latest = int(s[0])
stack[latest].append(latest)
result = 0
for i in range(1,len(s)):
v = int(s[i])
if v != latest:
stack[v].clear()
latest ... | https://leetcode.com/problems/count-binary-substrings/discuss/384054/Only-using-stack-with-one-iteration-logic-solution-in-Python-O(N) | 7 | Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example 1:
Input: s = "00110011"
Output: 6
Explan... | Only using stack with one iteration, logic solution in Python O(N) | 994 | count-binary-substrings | 0.656 | zouqiwu09 | Easy | 11,505 | 696 |
degree of an array | class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
C = {}
for i, n in enumerate(nums):
if n in C: C[n].append(i)
else: C[n] = [i]
M = max([len(i) for i in C.values()])
return min([i[-1]-i[0] for i in C.values() if len(i) == M]) + 1
- Junaid Mansuri | https://leetcode.com/problems/degree-of-an-array/discuss/349801/Solution-in-Python-3-(beats-~98) | 43 | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1]
Output: 2
Explana... | Solution in Python 3 (beats ~98%) | 3,000 | degree-of-an-array | 0.559 | junaidmansuri | Easy | 11,520 | 697 |
partition to k equal sum subsets | class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
if k==1:
return True
total = sum(nums)
n = len(nums)
if total%k!=0:
return False
nums.sort(reverse=True)
average = total//k
if nums[0]>average:
... | https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1627241/python-simple-with-detailed-explanation-or-96.13 | 5 | Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:... | python simple with detailed explanation | 96.13% | 563 | partition-to-k-equal-sum-subsets | 0.408 | 1579901970cg | Medium | 11,531 | 698 |
falling squares | class Solution:
def fallingSquares(self, positions):
height, pos, max_h,res = [0],[0],0,[]
for left, side in positions:
i = bisect.bisect_right(pos, left)
j = bisect.bisect_left(pos, left + side)
high = max(height[i - 1:j] or [0]) + side
... | https://leetcode.com/problems/falling-squares/discuss/2397036/faster-than-90.37-or-python-or-solution-or-explained | 1 | There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time... | faster than 90.37% | python | solution | explained | 57 | falling-squares | 0.444 | vimla_kushwaha | Hard | 11,556 | 699 |
search in a binary search tree | class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return
if root.val==val:
return root
if root.val<val:
return self.searchBST(root.right,val)
else:
return self.searchBST(root.left,val) | https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/943397/Python-Simple-Solution | 20 | You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Input: root = [4,2,7,1,3... | Python Simple Solution | 1,300 | search-in-a-binary-search-tree | 0.772 | lokeshsenthilkumar | Easy | 11,558 | 700 |
insert into a binary search tree | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return TreeNode(val)
cur, next = None, root
while next:
cur = next
next = cur.left if val < cur.val else cur.right
if val < cu... | https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1683883/Python3-ITERATIVE-(-)-Explained | 26 | You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST... | ✔️ [Python3] ITERATIVE (づ ̄ ³ ̄)づ ❤, Explained | 1,300 | insert-into-a-binary-search-tree | 0.746 | artod | Medium | 11,594 | 701 |
binary search | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
right = mid-1
... | https://leetcode.com/problems/binary-search/discuss/2700642/Python-Classic-Binary-Search-Problem-or-99-Faster-or-Fastest-Solution | 47 | Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output... | ✔️ Python Classic Binary Search Problem | 99% Faster | Fastest Solution | 6,000 | binary-search | 0.551 | pniraj657 | Easy | 11,628 | 704 |
design hashset | # Linked List Solution
class MyHashSet(object):
def __init__(self):
self.keyRange = 769
self.bucketArray = [LinkedList() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
bucketIndex = self._hash(key)
... | https://leetcode.com/problems/design-hashset/discuss/1947672/Python3-Linked-List-Solution-(faster-than-83) | 0 | Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, d... | Python3 Linked List Solution (faster than 83%) | 105 | design-hashset | 0.659 | Mr_Watermelon | Easy | 11,682 | 705 |
to lower case | class Solution:
def toLowerCase(self, s: str) -> str:
# Instead of using .lower(), let's implement with ASCII
# ord() returns the ascii value of a passed character
# Uncomment the line below to see the ASCII value of some important characters
# print(ord('a'), ord('z'), ord(... | https://leetcode.com/problems/to-lower-case/discuss/2411462/Python3-ToLowerCase-Explanation-using-ASCII | 2 | Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.
Example 1:
Input: s = "Hello"
Output: "hello"
Example 2:
Input: s = "here"
Output: "here"
Example 3:
Input: s = "LOVELY"
Output: "lovely"
Constraints:
1 <= s.length <= 100
s consists of printable ASCII charact... | [Python3] ToLowerCase - Explanation - using ASCII | 84 | to-lower-case | 0.82 | connorthecrowe | Easy | 11,684 | 709 |
random pick with blacklist | class Solution:
def __init__(self, n: int, blacklist: List[int]):
self.hashmap={}
for b in blacklist:
self.hashmap[b]=-1
self.length=n-len(blacklist)
flag=n-1
for b in blacklist:
if b<self.length:
while flag in self.hashmap:
... | https://leetcode.com/problems/random-pick-with-blacklist/discuss/2389935/faster-than-99.73-or-Python3-or-solution | 1 | You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned.
Optimize your algorithm such that it minimizes the... | faster than 99.73% | Python3 | solution | 152 | random-pick-with-blacklist | 0.337 | vimla_kushwaha | Hard | 11,729 | 710 |
minimum ascii delete sum for two strings | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
def lcs(s,p):
m,n = len(s),len(p)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m):
for j in range(n):
if s[i]==p[j]:
dp[i+1][j+1] = dp[i][j]+ord(s[i]... | https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/1516574/Greedy-oror-DP-oror-Same-as-LCS | 4 | Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are eq... | 📌📌 Greedy || DP || Same as LCS 🐍 | 94 | minimum-ascii-delete-sum-for-two-strings | 0.623 | abhi9Rai | Medium | 11,736 | 712 |
subarray product less than k | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
# Quick response for invalid k on product of positive numbers
return 0
else:
left_sentry = 0
num_of_subarray = 0
product_of... | https://leetcode.com/problems/subarray-product-less-than-k/discuss/481917/Python-sol.-based-on-sliding-window.-run-time-90%2B-w-Explanation | 3 | Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, ... | Python sol. based on sliding window. run-time 90%+ [ w/ Explanation ] | 723 | subarray-product-less-than-k | 0.452 | brianchiang_tw | Medium | 11,743 | 713 |
best time to buy and sell stock with transaction fee | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = inf, 0
for x in prices:
buy = min(buy, x)
sell = max(sell, x - buy)
return sell | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | 4 | You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note:
You may not engag... | [Python3] dp | 78 | best-time-to-buy-and-sell-stock-with-transaction-fee | 0.644 | ye15 | Medium | 11,758 | 714 |
1 bit and 2 bit characters | class Solution:
def isOneBitCharacter(self, bits):
i, n, numBits = 0, len(bits), 0
while i < n:
bit = bits[i]
if bit == 1:
i += 2
numBits = 2
else:
i += 1
numBits = 1
return numBits == 1 | https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2012976/Python-Clean-and-Simple! | 2 | We have two special characters:
The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
Example 1:
Input: bits = [1,0,0]
Output: true
Explanation: The... | Python - Clean and Simple! | 146 | 1-bit-and-2-bit-characters | 0.46 | domthedeveloper | Easy | 11,781 | 717 |
maximum length of repeated subarray | class Solution:
# DP Approach - Similar to 1143. Longest Common Subsequence
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n, m = len(nums1), len(nums2)
# dp[i][j] means the length of repeated subarray of nums1[:i] and nums2[:j]
dp = [[0] * (m + 1) for _ in range(n + 1)... | https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599501/LeetCode-The-Hard-Way-Explained-Line-By-Line | 32 | Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
Ex... | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 2,000 | maximum-length-of-repeated-subarray | 0.515 | wingkwong | Medium | 11,796 | 718 |
find k th smallest pair distance | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
def getPairs(diff):
l = 0
count = 0
for r in range(len(nums)):
while nums[r] - nums[l] > diff:
l += 1
count += r - l
return count
nums.sort()
l, r = 0, nums[-1] - nums[0]
while l < r:
mid = (l + r)... | https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/2581420/Simple-python-binary-search | 1 | The distance of a pair of integers a and b is defined as the absolute difference between a and b.
Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Example 1:
Input: nums = [1,3,1], k = 1
Output: 0
Explanation: Here a... | Simple python binary search | 123 | find-k-th-smallest-pair-distance | 0.364 | shubhamnishad25 | Hard | 11,831 | 719 |
longest word in dictionary | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort() # for smallest lexicographical order
visited = {""} # hashset to keep a track of visited words
res = ''
for word in words:
if word[:-1] in visited: # ... | https://leetcode.com/problems/longest-word-in-dictionary/discuss/2075147/Python-O(n-log(n))-Time-O(n)-Space-Faster-Than-95 | 4 | Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty stri... | [Python] O(n log(n)) Time, O(n) Space Faster Than 95% | 217 | longest-word-in-dictionary | 0.518 | samirpaul1 | Medium | 11,834 | 720 |
accounts merge | class Solution:
def dfs(self, graph, node, visit):
visit.add(node)
for nei in graph[node]:
if nei not in visit:
self.dfs(graph, nei, visit)
self.res.append(node)
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
graph = collec... | https://leetcode.com/problems/accounts-merge/discuss/2014051/Python-easy-to-read-and-understand-or-DFS | 7 | Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some commo... | Python easy to read and understand | DFS | 507 | accounts-merge | 0.564 | sanial2001 | Medium | 11,844 | 721 |
remove comments | class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans, inComment = [], False
new_str = ""
for c in source:
if not inComment: new_str = ""
i, n = 0, len(c)
# inComment, we find */
while i < n:
if inComment... | https://leetcode.com/problems/remove-comments/discuss/2446606/Easy-to-understand-using-Python | 3 | Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'.
In C++, there are two types of comments, line comments, and block comm... | Easy to understand using Python | 567 | remove-comments | 0.38 | fguo10 | Medium | 11,857 | 722 |
find pivot index | class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]
right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
for i, num in enumerate(nums): # we can use normal for loop as well.
... | https://leetcode.com/problems/find-pivot-index/discuss/2321669/Python-99.85-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | 9 | Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
If the index is on the left edge of the array, then the left sum is 0 because th... | Python 99.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | 725 | find-pivot-index | 0.535 | rlakshay14 | Easy | 11,865 | 724 |
split linked list in parts | class Solution:
def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:
size = self.get_size(head)
min_len, one_more = divmod(size, k)
res = []
current = ListNode()
current.next = head
for i in range(k):
ans = current
for _ in ran... | https://leetcode.com/problems/split-linked-list-in-parts/discuss/1322974/Clean-Python-and-Java | 4 | Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence ... | Clean Python and Java | 456 | split-linked-list-in-parts | 0.572 | aquafie | Medium | 11,919 | 725 |
number of atoms | class Solution:
def countOfAtoms(self, formula: str) -> str:
# constant declarations
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower=upper.lower()
digits = "0123456789"
# variables
count=defaultdict(int)
element_name = None
element_name_parse_start=F... | https://leetcode.com/problems/number-of-atoms/discuss/1335787/efficient-O(N)-python3-solution-using-stack-of-stacks-with-explanation-of-code-and-approach | 2 | Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is... | efficient O(N) python3 solution, using stack of stacks with explanation of code and approach | 258 | number-of-atoms | 0.522 | anupamkumar | Hard | 11,932 | 726 |
self dividing numbers | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for i in range(left, right+ 1):
if "0" in str(i): continue
val = i
while val > 0:
n = val % 10
if i % n != 0:
val = -1
val = val // 10
if val != -1: result.append(i)
return result | https://leetcode.com/problems/self-dividing-numbers/discuss/1233710/WEEB-DOES-PYTHON(BEATS-91.49) | 4 | A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.
Given two integers left and right, return a list of all the self-dividing num... | WEEB DOES PYTHON(BEATS 91.49%) | 278 | self-dividing-numbers | 0.776 | Skywalker5423 | Easy | 11,934 | 728 |
my calendar i | # Binary Search Tree Solution -> If exact matching of intervals found then return False
# Else you can add this interval to that particular node's left or right
class Node:
def __init__(self, s, e):
self.s = s
self.e = e
self.left = None
self.right = No... | https://leetcode.com/problems/my-calendar-i/discuss/2731671/Fastest-Python-solution-greater-Create-a-Binary-Search-Tree | 0 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.
A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers start and end th... | Fastest Python solution -> Create a Binary Search Tree🥶 | 17 | my-calendar-i | 0.572 | shiv-codes | Medium | 11,969 | 729 |
count different palindromic subsequences | class Solution:
def countPalindromicSubsequences(self, s:str) -> int:
@cache
def fn(ch, i, j):
if i > j:
return 0
if i == j and s[i] == ch:
return 1
if s[i] == s[j] == ch:
return 2 ... | https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/1612723/DP-Python | 2 | Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequen... | DP Python | 469 | count-different-palindromic-subsequences | 0.445 | yshawn | Hard | 11,970 | 730 |
flood fill | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
h, w = len(image), len(image[0])
def dfs( r, c, src_color):
if r < 0 or c < 0 or r >= h or c >= w or image[r][c] == newColor or image[r][c] !... | https://leetcode.com/problems/flood-fill/discuss/626424/PythonJSGoC%2B%2B-sol-by-DFS-w-Comment | 17 | An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels... | Python/JS/Go/C++ sol by DFS [w/ Comment] | 4,300 | flood-fill | 0.607 | brianchiang_tw | Easy | 11,975 | 733 |
asteroid collision | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for a in asteroids:
if a > 0:
stack.append(a)
else:
while stack and stack[-1] > 0 and stack[-1] + a < 0:
stack.pop()
... | https://leetcode.com/problems/asteroid-collision/discuss/646757/Python3-concise-solution-Asteroid-Collision | 5 | We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. ... | Python3 concise solution - Asteroid Collision | 426 | asteroid-collision | 0.444 | r0bertz | Medium | 12,030 | 735 |
parse lisp expression | class Solution:
def evaluate(self, expression: str) -> int:
stack = []
parenEnd = {}
# Get the end parenthesis location
for idx, ch in enumerate(expression):
if ch == '(':
stack.append(idx)
if ch == ')':
parenEnd[stack... | https://leetcode.com/problems/parse-lisp-expression/discuss/2149196/Python3-Solution | 1 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
(An i... | Python3 Solution | 113 | parse-lisp-expression | 0.515 | krzys2194 | Hard | 12,056 | 736 |
monotone increasing digits | class Solution:
def monotoneIncreasingDigits(self, N: int) -> int:
nums = [int(x) for x in str(N)] # digits
stack = []
for i, x in enumerate(nums):
while stack and stack[-1] > x: x = stack.pop() - 1
stack.append(x)
if len(stack) <= i: break
ret... | https://leetcode.com/problems/monotone-increasing-digits/discuss/921119/Python3-O(N)-via-stack | 1 | An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.
Example 1:
Input: n = 10
Output: 9
Example 2:
Input: n = 1234
Output: 1234
Example 3:
Input: n = ... | [Python3] O(N) via stack | 126 | monotone-increasing-digits | 0.471 | ye15 | Medium | 12,058 | 738 |
daily temperatures | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
result = [0] * len(temperatures) # having list with 0`s elements of same lenght as temperature array.
stack = [] # taking empty stack.
for index, temp in enumerate(temperatures): # Traversing through provided... | https://leetcode.com/problems/daily-temperatures/discuss/2506436/Python-Stack-97.04-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack | 6 | Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures ... | Python Stack 97.04% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack | 473 | daily-temperatures | 0.666 | rlakshay14 | Medium | 12,066 | 739 |
delete and earn | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
mp = {}
for x in nums: mp[x] = x + mp.get(x, 0)
@lru_cache(None)
def fn(i):
"""Return maximum points one can earn from nums[i:]."""
if i >= len(nums): return 0
if nums[i] +... | https://leetcode.com/problems/delete-and-earn/discuss/916859/Python3-top-down-dp | 7 | You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maxim... | [Python3] top-down dp | 273 | delete-and-earn | 0.573 | ye15 | Medium | 12,113 | 740 |
cherry pickup | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
n = len(grid)
@lru_cache(None)
def fn(t, i, ii):
"""Return maximum cherries collected at kth step when two robots are at ith and iith row"""
j, jj = t - i, t - ii #columns
if n... | https://leetcode.com/problems/cherry-pickup/discuss/699169/Python3-dp | 2 | You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through,
1 means the cell contains a cherry that you can pick up and pass through, or
-1 means the cell contains a thorn that blocks your way.
Return the maximum number o... | [Python3] dp | 241 | cherry-pickup | 0.363 | ye15 | Hard | 12,161 | 741 |
network delay time | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
adj_list = defaultdict(list)
for x,y,w in times:
adj_list[x].append((w, y))
visited=set()
heap = [(0, k)]
while heap:
travel_time, node... | https://leetcode.com/problems/network-delay-time/discuss/2036405/Python-Simple-Dijkstra-Beats-~90 | 39 | You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Re... | Python Simple Dijkstra Beats ~90% | 2,200 | network-delay-time | 0.515 | constantine786 | Medium | 12,164 | 743 |
find smallest letter greater than target | class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
# if the number is out of bound
if target >= letters[-1] or target < letters[0]:
return letters[0]
... | https://leetcode.com/problems/find-smallest-letter-greater-than-target/discuss/1568523/Python-easy-solution-with-detail-explanation-(modified-binary-search) | 71 | You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.
Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in l... | Python easy solution with detail explanation (modified binary search) | 3,300 | find-smallest-letter-greater-than-target | 0.448 | Abeni | Easy | 12,197 | 744 |
min cost climbing stairs | class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
cur = 0
dp0 = cost[0]
if len(cost) >= 2:
dp1 = cost[1]
for i in range(2, len(cost)):
cur = cost[i] + min(dp0, dp1)
dp0 = dp1
dp1 = cur
return min(dp0, dp1) | https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2260902/94-FASTER-97-Space-Efficient-Python-solutions-Different-approaches | 34 | You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [10,15,20]
... | 94% FASTER 97% Space Efficient Python solutions Different approaches | 2,300 | min-cost-climbing-stairs | 0.625 | anuvabtest | Easy | 12,252 | 746 |
largest number at least twice of others | class Solution:
def dominantIndex(self, nums: List[int]) -> int:
if len(nums) is 1:
return 0
dom = max(nums)
i = nums.index(dom)
nums.remove(dom)
if max(nums) * 2 <= dom:
return i
return -1 | https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2069691/no-loops | 3 | You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Explanation:... | no loops | 90 | largest-number-at-least-twice-of-others | 0.465 | andrewnerdimo | Easy | 12,316 | 747 |
shortest completing word | class Solution:
def shortestCompletingWord(self, P: str, words: List[str]) -> str:
alphs=""
res=""
for p in P:
if p.isalpha():
alphs+=p.lower()
for word in words:
if all(alphs.count(alphs[i]) <= word.coun... | https://leetcode.com/problems/shortest-completing-word/discuss/1277850/Python3-Simple-solution-without-Dictionary | 4 | Given a string licensePlate and an array of strings words, find the shortest completing word in words.
A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it ... | Python3 Simple solution without Dictionary | 335 | shortest-completing-word | 0.592 | Rei4126 | Easy | 12,352 | 748 |
contain virus | class Solution:
def containVirus(self, mat: List[List[int]]) -> int:
m,n = len(mat),len(mat[0])
def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area
if 0<=i<m and 0<=j<n and (i,j) not in visited:
if mat[i][j]==2: # Already quarantined... | https://leetcode.com/problems/contain-virus/discuss/2224726/Pyhon-Easy-Solution-oror-DFS-oror-Time-O(m*n*max(m-n))-oror-Faster | 4 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be ... | Pyhon Easy Solution || DFS || Time O(m*n*max(m , n)) || Faster | 378 | contain-virus | 0.509 | Laxman_Singh_Saini | Hard | 12,362 | 749 |
open the lock | class Solution:
def openLock(self, deadends: List[str], end: str) -> int:
if end in deadends or "0000" in deadends:
return -1
if end == "0000":
return 0
start, end, deadends = 0, int(end), {int(deadend) for deadend in deadends}
def distance(cur: int, target: ... | https://leetcode.com/problems/open-the-lock/discuss/1251501/Python-or-Bi-directional-A-star-BFS-or-99.7-or-52ms-or-14.3MB | 3 | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000',... | Python | Bi-directional A star, BFS | 99.7% | 52ms | 14.3MB | 110 | open-the-lock | 0.555 | PuneethaPai | Medium | 12,365 | 752 |
cracking the safe | class Solution:
def crackSafe(self, n: int, k: int) -> str:
def dfs(path, visitedCombinations, targetNumVisited, combos):
# Base Case. We've visited all possible combinations
if len(visitedCombinations) == targetNumVisited:
combos.append(''.join([str(x) for x in path]... | https://leetcode.com/problems/cracking-the-safe/discuss/2825347/DFS-Solution-in-Python | 0 | There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.
For example, the correct p... | DFS Solution in Python | 1 | cracking-the-safe | 0.555 | user0138r | Hard | 12,382 | 753 |
reach a number | class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target)
step = 0
far = 0
while far < target or far%2 != target%2:
step += 1
far +=step
return step | https://leetcode.com/problems/reach-a-number/discuss/991390/Python-Dummy-math-solution-easy-to-understand | 1 | You are standing at position 0 on an infinite number line. There is a destination at position target.
You can make some number of moves numMoves so that:
On each move, you can either go left or right.
During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.
Given the intege... | [Python] Dummy math solution, easy to understand | 47 | reach-a-number | 0.426 | KevinZzz666 | Medium | 12,384 | 754 |
pyramid transition matrix | class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
mp = {}
for x, y, z in allowed: mp.setdefault((x, y), set()).add(z)
def fn(row):
"""Return list of rows built from given row."""
ans = [""]
for x, y in zip(... | https://leetcode.com/problems/pyramid-transition-matrix/discuss/921324/Python3-progressively-building-new-rows | 2 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pa... | [Python3] progressively building new rows | 215 | pyramid-transition-matrix | 0.531 | ye15 | Medium | 12,387 | 756 |
set intersection size at least two | class Solution:
def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x:x[1])
size = 0
prev_start = -1
prev_end = -1
for curr_start, curr_end in intervals:
if prev_start == -1 or prev_end < curr_start: #if intervals do not ... | https://leetcode.com/problems/set-intersection-size-at-least-two/discuss/2700915/Python-Explained-or-O(nlogn) | 1 | You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.
A containing set is an array nums where each interval from intervals has at least two integers in nums.
For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2... | Python [Explained] | O(nlogn) | 545 | set-intersection-size-at-least-two | 0.439 | diwakar_4 | Hard | 12,391 | 757 |
special binary string | class Solution:
def makeLargestSpecial(self, s: str) -> str:
l = 0
balance = 0
sublist = []
for r in range(len(s)):
balance += 1 if s[r]=='1' else -1
if balance==0:
sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0")
l = r+1
sublist.sort(rev... | https://leetcode.com/problems/special-binary-string/discuss/1498369/Easy-Approach-oror-Well-Explained-oror-Substring | 5 | Special binary strings are binary strings with the following two properties:
The number of 0's is equal to the number of 1's.
Every prefix of the binary string has at least as many 1's as 0's.
You are given a special binary string s.
A move consists of choosing two consecutive, non-empty, special substrings of s, and s... | 📌📌 Easy-Approach || Well-Explained || Substring 🐍 | 371 | special-binary-string | 0.604 | abhi9Rai | Hard | 12,394 | 761 |
prime number of set bits in binary representation | class Solution:
def isPrime(self,x):
flag=0
if x==1:
return False
for i in range(2,x):
if x%i==0:
flag=1
break
if flag==1:
return False
return True
def countPrimeSetBits(self, left: int, right: i... | https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1685874/Simple-python-code | 1 | Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.
Recall that the number of set bits an integer has is the number of 1's present when written in binary.
For example, 21 written in binary is 10101, which h... | Simple python code | 105 | prime-number-of-set-bits-in-binary-representation | 0.678 | amannarayansingh10 | Easy | 12,396 | 762 |
partition labels | class Solution:
def partitionLabels(self, s: str) -> List[int]:
L = len(s)
last = {s[i]: i for i in range(L)} # last appearance of the letter
i, ans = 0, []
while i < L:
end, j = last[s[i]], i + 1
while j < end: # validation of the part [i, end]
... | https://leetcode.com/problems/partition-labels/discuss/1868757/Python3-GREEDY-VALIDATION-(-)-Explained | 63 | You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
... | ✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained | 5,700 | partition-labels | 0.798 | artod | Medium | 12,410 | 763 |
largest plus sign | class Solution:
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
mat = [[1]*N for _ in range(N)]
for x, y in mines: mat[x][y] = 0 # create matrix with mine
up = [[0]*N for _ in range(N)] # count 1s above mat[i][j] if ... | https://leetcode.com/problems/largest-plus-sign/discuss/833937/Python-3-or-DP-Bomb-Enemy-or-Explanations | 5 | You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.
Return the order of the largest axis-aligned plus sign of 1's contained in grid. If... | Python 3 | DP - Bomb Enemy | Explanations | 396 | largest-plus-sign | 0.484 | idontknoooo | Medium | 12,461 | 764 |
couples holding hands | class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
loc = {x: i for i, x in enumerate(row)}
ans = 0
for i in range(0, len(row), 2):
p = row[i] - 1 if row[i]&1 else row[i]+1
if row[i+1] != p:
ans += 1
ii = loc[p]
... | https://leetcode.com/problems/couples-holding-hands/discuss/1258087/Python3-a-few-approaches | 3 | There are n couples sitting in 2n seats arranged in a row and want to hold hands.
The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with th... | [Python3] a few approaches | 84 | couples-holding-hands | 0.569 | ye15 | Hard | 12,469 | 765 |
toeplitz matrix | class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]])->bool:
r_len, c_len = len(matrix),len(matrix[0])
for r in range (1, r_len):
for c in range (1, c_len):
if matrix[r][c]!=matrix[r-1][c-1]:
return False
return ... | https://leetcode.com/problems/toeplitz-matrix/discuss/2761795/Python-Simple-and-Easy-Way-to-Solve-or-97-Faster | 3 | Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]",... | ✔️ Python Simple and Easy Way to Solve | 97% Faster 🔥 | 182 | toeplitz-matrix | 0.688 | pniraj657 | Easy | 12,473 | 766 |
reorganize string | class Solution:
def reorganizeString(self, S: str) -> str:
counter = collections.Counter(S)
i, res, n = 0, [None] * len(S), len(S)
for k in sorted(counter, key = counter.get, reverse = True):
if counter[k] > n // 2 + (n % 2): return ""
for j in range(counter[k]):
... | https://leetcode.com/problems/reorganize-string/discuss/488325/Python-8-Liner-Memory-usage-less-than-100 | 9 | Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
1 <= s.length <= 500
s consists of lowercase Engli... | Python - 8 Liner - Memory usage less than 100% | 1,700 | reorganize-string | 0.528 | mmbhatk | Medium | 12,530 | 767 |
max chunks to make sorted ii | class Solution:
def maxChunksToSorted(self, nums: List[int]) -> int:
st = []
for n in nums:
if len(st)==0 or st[-1]<=n:
st.append(n)
else:
ma = st[-1]
while st and st[-1]>n:
ma = max(ma,st.pop())
st.append(ma)
return l... | https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1498733/Easy-to-Understand-oror-98-faster-oror-Well-Explained | 14 | You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [5,4,3,2,1]
Output: 1
Explana... | 📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍 | 659 | max-chunks-to-make-sorted-ii | 0.528 | abhi9Rai | Hard | 12,556 | 768 |
max chunks to make sorted | class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
stack = []
for num in arr:
lagest = num
while stack and num < stack[-1]:
lagest = max(lagest, stack.pop())
stack.append(lagest)
return len(stack) | https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/1579999/Python3-Solution-with-using-stack | 1 | You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we c... | [Python3] Solution with using stack | 95 | max-chunks-to-make-sorted | 0.582 | maosipov11 | Medium | 12,563 | 769 |
jewels and stones | class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(i in J for i in S)
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(S.count(i) for i in J)
from collections import Counter
class Solution:
def numJewelsInStones(self, J: str, S: str)... | https://leetcode.com/problems/jewels-and-stones/discuss/362196/Solution-in-Python-3-(beats-~94)-(one-line)-(three-solutions) | 28 | You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone fr... | Solution in Python 3 (beats ~94%) (one line) (three solutions) | 4,500 | jewels-and-stones | 0.881 | junaidmansuri | Easy | 12,569 | 771 |
sliding puzzle | class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
def isSolved(board):
if board[-1] != 0: return False
for i in range(5):
if board[i] != i + 1: return False
return True
swap = {
0: [1, 3],
1: [... | https://leetcode.com/problems/sliding-puzzle/discuss/2831256/Python-BFS%3A-77-time-70-space | 0 | On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of... | Python BFS: 77% time, 70% space | 2 | sliding-puzzle | 0.639 | hqz3 | Hard | 12,629 | 773 |
global and local inversions | class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
for i, a in enumerate(A):
if (abs(a - i) > 1):
return False
return True | https://leetcode.com/problems/global-and-local-inversions/discuss/1084172/(Optimal-Solution)-Thinking-Process-Explained-in-More-Detail-than-You'd-Ever-Want | 3 | You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].
The number of global inversions is the number of the different pairs (i, j) where:
0 <= i < j < n
nums[i] > nums[j]
The number of local inversions is the number of indices i where:
0 <= i < n - 1
... | (Optimal Solution) Thinking Process Explained in More Detail than You'd Ever Want | 215 | global-and-local-inversions | 0.436 | valige7091 | Medium | 12,635 | 775 |
swap adjacent in lr string | class Solution:
def canTransform(self, S, E):
L, R, X = 0, 0, 0
for i, j in zip(S, E):
L += (j == 'L')
R += (i == 'R')
if i == 'R' and L: return False
if j == 'L' and R: return False
L -= (i == 'L')
R -= (j == 'R')
i... | https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/2712752/Python3-Solution-or-O(n)-or-Clean-and-Concise | 0 | In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform... | ✔ Python3 Solution | O(n) | Clean and Concise | 10 | swap-adjacent-in-lr-string | 0.371 | satyam2001 | Medium | 12,645 | 777 |
swim in rising water | class Solution:
# O(max(n^2, m)) time, h --> the highest elevation in the grid
# O(n^2) space,
# Approach: BFS, Priority queue
# I wld advise to do task scheduler question, it's pretty similar
# except that u apply bfs to traverse the grid 4 directionally
def swimInWater(self, grid: List[List[in... | https://leetcode.com/problems/swim-in-rising-water/discuss/2464943/Easy-to-follow-python3-solutoon | 1 | You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individuall... | Easy to follow python3 solutoon | 34 | swim-in-rising-water | 0.597 | destifo | Hard | 12,652 | 778 |
k th symbol in grammar | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
if N == 1:
return 0
half = 2**(N - 2)
if K > half:
return 1 if self.kthGrammar(N - 1, K - half) == 0 else 0
else:
return self.kthGrammar(N - 1, K) | https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/945679/Python-recursive-everything-you-need-to-know | 6 | We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and... | Python recursive, everything you need to know | 343 | k-th-symbol-in-grammar | 0.409 | lattices | Medium | 12,665 | 779 |
reaching points | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
if sx > tx or sy > ty: return False
if sx == tx: return (ty-sy)%sx == 0 # only change y
if sy == ty: return (tx-sx)%sy == 0
if tx > ty:
return self.reachingPoints(sx, sy, tx%ty, ty) # m... | https://leetcode.com/problems/reaching-points/discuss/808072/Python-recursive-solution-runtime-beats-98.91 | 14 | Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.
The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).
Example 1:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output... | Python recursive solution runtime beats 98.91 % | 3,300 | reaching-points | 0.324 | yiz486 | Hard | 12,688 | 780 |
rabbits in forest | class Solution:
def numRabbits(self, answers: List[int]) -> int:
return sum((key+1) * math.ceil(freq / (key+1)) if key+1 < freq else key+1 for key, freq in collections.Counter(answers).items()) | https://leetcode.com/problems/rabbits-in-forest/discuss/838445/Python-3-or-Hash-Table-1-liner-or-Explanations | 1 | There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Exam... | Python 3 | Hash Table 1 liner | Explanations | 178 | rabbits-in-forest | 0.552 | idontknoooo | Medium | 12,696 | 781 |
transform to chessboard | class Solution:
def movesToChessboard(self, board: List[List[int]]) -> int:
n = len(board)
def fn(vals):
"""Return min moves to transform to chessboard."""
total = odd = 0
for i, x in enumerate(vals):
if vals[0] == x:
... | https://leetcode.com/problems/transform-to-chessboard/discuss/1305763/Python3-alternating-numbers | 8 | You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-dire... | [Python3] alternating numbers | 379 | transform-to-chessboard | 0.518 | ye15 | Hard | 12,706 | 782 |
minimum distance between bst nodes | class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
# list with two element
# the first for the previous element
# the second for the min value
pre_mn = [-float("inf"), float("inf")]
def dfs(tree):
if not tree:
... | https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1957176/Python-In-Order-Traversal-Explained-Well-Via-Comments | 1 | Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 100].
0 <... | Python In-Order Traversal, Explained Well Via Comments | 89 | minimum-distance-between-bst-nodes | 0.569 | Hejita | Easy | 12,707 | 783 |
letter case permutation | class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
def backtrack(sub="", i=0):
if len(sub) == len(S):
res.append(sub)
else:
if S[i].isalpha():
backtrack... | https://leetcode.com/problems/letter-case-permutation/discuss/379928/Python-clear-solution | 164 | Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example 1:
Input: s = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: s = "3z4"
Output: ["3z4","3Z4... | Python clear solution | 7,000 | letter-case-permutation | 0.735 | DenysCoder | Medium | 12,721 | 784 |
is graph bipartite | class Solution:
def isBipartite(self, graph: list[list[int]]) -> bool:
vis = [False for n in range(0, len(graph))]
while sum(vis) != len(graph): # Since graph isn't required to be connected this process needs to be repeated
ind = vis.index(False) # Find the first entry in th... | https://leetcode.com/problems/is-graph-bipartite/discuss/1990803/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022 | 3 | There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties... | [Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022 | 356 | is-graph-bipartite | 0.527 | cucerdariancatalin | Medium | 12,773 | 785 |
k th smallest prime fraction | class Solution:
def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
if len(arr) > 2:
res = [] # list for storing the list: [prime fraction of arr[i]/arr[j], arr[i], arr[j]]
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
# creating and adding the sublist to res
... | https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2121258/Explained-Easiest-Python-Solution | 2 | You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of in... | [Explained] Easiest Python Solution | 180 | k-th-smallest-prime-fraction | 0.509 | the_sky_high | Medium | 12,814 | 786 |
cheapest flights within k stops | class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
#Make graph
adj_list = {i:[] for i in range(n)}
for frm, to, price in flights:
adj_list[frm].append((to, price))
best_visited = [2**31]*n # Initializ... | https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2066105/Python-Easy-Solution-using-Dijkstra's-Algorithm | 6 | There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops.... | Python Easy Solution using Dijkstra's Algorithm | 445 | cheapest-flights-within-k-stops | 0.359 | samirpaul1 | Medium | 12,820 | 787 |
rotated digits | class Solution:
def rotatedDigits(self, N: int) -> int:
count = 0
for x in range(1, N+1):
x = str(x)
if '3' in x or '4' in x or '7' in x:
continue
if '2' in x or '5' in x or '6' in x or '9' in x:
count+=1
return count | https://leetcode.com/problems/rotated-digits/discuss/1205605/Python3-simple-solution-using-two-approaches | 4 | An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. For example:
0, 1, and 8 rotate to themselves,
2 and 5 rotate ... | Python3 simple solution using two approaches | 207 | rotated-digits | 0.568 | EklavyaJoshi | Medium | 12,834 | 788 |
escape the ghosts | class Solution:
def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:
t_x, t_y = target
m_x, m_y = abs(t_x), abs(t_y)
for x, y in ghosts:
manhattan = abs(t_x - x) + abs(t_y - y)
if manhattan <= m_x + m_y:
return False
retu... | https://leetcode.com/problems/escape-the-ghosts/discuss/1477363/Python-3-or-Manhattan-Distance-Math-or-Explanation | 1 | You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] repr... | Python 3 | Manhattan Distance, Math | Explanation | 117 | escape-the-ghosts | 0.607 | idontknoooo | Medium | 12,845 | 789 |
domino and tromino tiling | class Solution(object):
def numTilings(self, n):
dp = [1, 2, 5] + [0] * n
for i in range(3, n):
dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007
return dp[n - 1] | https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620809/PythonJAVACC%2B%2B-DP-oror-Image-Visualized-Explanation-oror-100-Faster-oror-O(N) | 84 | You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and on... | ✅ [Python/JAVA/C/C++] DP || Image Visualized Explanation || 100% Faster || O(N) | 2,800 | domino-and-tromino-tiling | 0.484 | linfq | Medium | 12,849 | 790 |
custom sort string | class Solution:
def customSortString(self, order: str, s: str) -> str:
rank = [26]*26
for i in range(len(order)):
rank[ord(order[i]) - ord('a')] = i
return "".join(sorted(list(s), key= lambda x: rank[ord(x) - ord('a')])) | https://leetcode.com/problems/custom-sort-string/discuss/2237060/Simple-yet-interview-friendly-or-Faster-than-99.97-or-Custom-Sorting-in-Python | 2 | You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the per... | ✅ Simple yet interview friendly | Faster than 99.97% | Custom Sorting in Python | 62 | custom-sort-string | 0.693 | reinkarnation | Medium | 12,858 | 791 |
number of matching subsequences | class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
def is_sub(word):
index=-1
for ch in word:
index=s.find(ch,index+1)
if index==-1:
return False
return True
c=0
for word in words:
if is_sub(word):
... | https://leetcode.com/problems/number-of-matching-subsequences/discuss/1289476/Easy-Approach-oror-Well-explained-oror-95-faster | 27 | Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subse... | 📌 Easy-Approach || Well-explained || 95% faster 🐍 | 1,200 | number-of-matching-subsequences | 0.519 | abhi9Rai | Medium | 12,887 | 792 |
preimage size of factorial zeroes function | class Solution:
def preimageSizeFZF(self, k: int) -> int:
lo, hi = 0, 1 << 32
while lo <= hi:
mid = lo + hi >> 1
x, y = mid, 0
while x:
x //= 5
y += x
if y < k: lo = mid + 1
elif y > k: hi = mid - 1
... | https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/discuss/1306028/Python3-binary-search | 1 | Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.
For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the pr... | [Python3] binary search | 69 | preimage-size-of-factorial-zeroes-function | 0.428 | ye15 | Hard | 12,919 | 793 |
valid tic tac toe state | class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
# The two criteria for a valid board are:
# 1) num of Xs - num of Os is 0 or 1
# 2) X is not a winner if the # o... | https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/2269469/Python3-oror-int-array-7-lines-w-explanation-oror-TM%3A-98-49 | 4 | Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-T... | Python3 || int array, 7 lines, w/ explanation || T/M: 98%/ 49% | 221 | valid-tic-tac-toe-state | 0.351 | warrenruud | Medium | 12,922 | 794 |
number of subarrays with bounded maximum | class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
start,end = -1, -1
res = 0
for i in range(len(nums)):
if nums[i] > right:
start = end = i
continue
if nums[i] >= left:
... | https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/2304108/Python-or-Two-pointer-technique-or-Easy-solution | 2 | Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,1,... | Python | Two pointer technique | Easy solution | 79 | number-of-subarrays-with-bounded-maximum | 0.527 | __Asrar | Medium | 12,935 | 795 |
rotate string | class Solution:
def rotateString(self, s: str, goal: str) -> bool:
return len(s) == len(goal) and s in goal+goal | https://leetcode.com/problems/rotate-string/discuss/2369025/or-python3-or-ONE-LINE-or-FASTER-THAN-99-or | 18 | Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
For example, if s = "abcde", then it will be "bcdea" after one shift.
Example 1:
Input: s = "abcde", goal = "cdeab"
Output... | ✅ | python3 | ONE LINE | FASTER THAN 99% | 🔥💪 | 628 | rotate-string | 0.542 | sahelriaz | Easy | 12,939 | 796 |
all paths from source to target | class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
q = [[0]]
result = []
target = len(graph) - 1
while q:
temp = q.pop(0)
if temp[-1] == target:
... | https://leetcode.com/problems/all-paths-from-source-to-target/discuss/752799/Python-simple-BFS-solution-explained | 6 | Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Example 1:... | Python simple BFS solution explained | 787 | all-paths-from-source-to-target | 0.815 | spec_he123 | Medium | 12,966 | 797 |
smallest rotation with highest score | class Solution:
def bestRotation(self, nums: List[int]) -> int:
diff = [0]*(len(nums) + 1)
for i, x in enumerate(nums):
diff[i+1] += 1
if x <= i: diff[0] += 1
diff[(i-x)%len(nums) + 1] -= 1
ans = prefix = 0
mx = -inf
for i, x in... | https://leetcode.com/problems/smallest-rotation-with-highest-score/discuss/1307760/Python3-difference-array | 0 | You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and... | [Python3] difference array | 137 | smallest-rotation-with-highest-score | 0.498 | ye15 | Hard | 13,011 | 798 |
champagne tower | class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
dp = [[0 for _ in range(x)] for x in range(1, query_row + 2)]
dp[0][0] = poured
for i in range(query_row):
for j in range(len(dp[i])):
temp = (dp[i][j] - 1) ... | https://leetcode.com/problems/champagne-tower/discuss/1818232/Python-Easy-Solution-or-95-Faster-or-Dynamic-Programming | 24 | We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass im... | ✔️ Python Easy Solution | 95% Faster | Dynamic Programming | 1,300 | champagne-tower | 0.513 | pniraj657 | Medium | 13,013 | 799 |
minimum swaps to make sequences increasing | class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
ans = sm = lg = mx = 0
for x, y in zip(A, B):
if mx < min(x, y): # prev max < current min
ans += min(sm, lg) # update answer & reset
sm = lg = 0
mx = max(x, y)
... | https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/discuss/932390/Python3-two-counters | 8 | You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].
For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
Return the minimum number of needed operat... | [Python3] two counters | 237 | minimum-swaps-to-make-sequences-increasing | 0.393 | ye15 | Hard | 13,030 | 801 |
find eventual safe states | class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n=len(graph)
status=[0]*(n)
res=[]
def dfs(i):# this function will check is there any loop, cycle and i is a part of that loop,cycle
if status[i]=="visited": #if this node is alrea... | https://leetcode.com/problems/find-eventual-safe-states/discuss/1317749/Python-DFS-Easy | 9 | There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if there are no outgoing ed... | Python-DFS-Easy | 575 | find-eventual-safe-states | 0.553 | manmohan1105 | Medium | 13,032 | 802 |
unique morse code words | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
MORSE = {
'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.',
'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.',
'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't':... | https://leetcode.com/problems/unique-morse-code-words/discuss/2438206/Python-Elegant-and-Short-or-Two-lines-or-No-loops | 5 | International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.... | Python Elegant & Short | Two lines | No loops | 395 | unique-morse-code-words | 0.827 | Kyrylo-Ktl | Easy | 13,048 | 804 |
split array with same average | class Solution(object):
def splitArraySameAverage(self, A):
if len(A)==1: return False
global_avg = sum(A)/float(len(A))
for lenB in range(1, len(A)/2+1):
if int(lenB*global_avg) == lenB*global_avg:
if self.exist(lenB*global_avg, lenB, A):
retu... | https://leetcode.com/problems/split-array-with-same-average/discuss/120654/Simple-python-with-explanation | 26 | You are given an integer array nums.
You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).
Return true if it is possible to achieve that and false otherwise.
Note that for an array arr, average(arr) is the sum of all the elements of arr ov... | Simple python with explanation | 4,200 | split-array-with-same-average | 0.259 | licaiuu | Hard | 13,097 | 805 |
number of lines to write string | class Solution:
def numberOfLines(self, widths: List[int], s: str) -> List[int]:
count = ans = wi = 0
s = list(s)
while s:
val = ord(s[0]) - 97
if(widths[val] + wi > 100):
wi = 0
count += 1
wi += w... | https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1170893/Python3-97-Faster-Solution | 2 | You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.
You are trying to write s across several lines, where each line is no longer than 100 pixels. S... | [Python3] 97% Faster Solution | 80 | number-of-lines-to-write-string | 0.662 | VoidCupboard | Easy | 13,100 | 806 |
max increase to keep city skyline | class Solution:
def maxIncreaseKeepingSkyline(self, G: List[List[int]]) -> int:
M, N, R, C = len(G), len(G[0]), [max(r) for r in G], [max(c) for c in zip(*G)]
return sum(min(R[i],C[j]) - G[i][j] for i,j in itertools.product(range(M),range(N)))
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/445773/Python-3-(two-lines)-(beats-~100) | 5 | There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.
A city's skyline is the outer contour formed b... | Python 3 (two lines) (beats ~100%) | 1,200 | max-increase-to-keep-city-skyline | 0.86 | junaidmansuri | Medium | 13,111 | 807 |
soup servings | class Solution:
def soupServings(self, n: int) -> float:
@cache # cache the result for input (a, b)
def dfs(a, b):
if a <= 0 and b > 0: return 1 # set criteria probability
elif a <= 0 and b <= 0: return 0.5
elif a > 0 and b <= ... | https://leetcode.com/problems/soup-servings/discuss/1651208/Python-3-or-Bottom-up-and-Top-down-DP-or-Explanation | 5 | There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B,
Serve 75 ml of soup A and 25 ml of soup B,
Serve 50 ml of soup A and 50 ml of soup B, and
Serve 25 ml of soup A and 75 ml of soup B.
When we serve ... | Python 3 | Bottom-up & Top-down DP | Explanation | 660 | soup-servings | 0.433 | idontknoooo | Medium | 13,134 | 808 |
expressive words | class Solution:
def expressiveWords(self, s: str, words: List[str]) -> int:
def summarize(word):
res = []
n = len(word)
i, j = 0, 0
while i<=j and j <= n-1:
while j <= n-1 and word[j] == word[i]:
j += 1... | https://leetcode.com/problems/expressive-words/discuss/1507874/Problem-description-is-horrible...-but-here's-simple-python-solution | 3 | Sometimes people repeat letters to represent extra feeling. For example:
"hello" -> "heeellooo"
"hi" -> "hiiii"
In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
You are given a string s and an array of query strings words. A query word is stretchy if ... | Problem description is horrible... but here's simple python solution | 483 | expressive-words | 0.463 | byuns9334 | Medium | 13,139 | 809 |
chalkboard xor game | class Solution:
def xorGame(self, nums):
#create a variable 0
x = 0
#iterate over the elements in the nums
for i in nums:
#do xor of all the elements
x ^= i
#Alice wins in two situations :
#1.if the xor is already 0 (x == 0 )
#2.if t... | https://leetcode.com/problems/chalkboard-xor-game/discuss/2729320/Simple-python-code-with-explanation | 0 | You are given an array of integers nums represents the numbers written on a chalkboard.
Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XO... | Simple python code with explanation | 11 | chalkboard-xor-game | 0.554 | thomanani | Hard | 13,150 | 810 |
subdomain visit count | class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
d = defaultdict(int)
for s in cpdomains:
cnt, s = s.split()
cnt = int(cnt)
d[s] += cnt
pos = s.find('.') + 1
while pos > 0:
d[s[pos:]] += cnt
... | https://leetcode.com/problems/subdomain-visit-count/discuss/914736/Python3-100-faster-100-less-memory-(32ms-14.1mb) | 10 | A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitl... | Python3 100% faster, 100% less memory (32ms, 14.1mb) | 1,300 | subdomain-visit-count | 0.752 | haasosaurus | Medium | 13,152 | 811 |
largest triangle area | class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
area = 0
n = len(points)
for i in range(n):
x1,y1 = points[i]
for j in range(i+1,n):
x2,y2 = points[j]
for k in range(j+1,n):
... | https://leetcode.com/problems/largest-triangle-area/discuss/1585033/Python-oror-Faster-than-93-oror-Simple-maths-oror-with-explanation | 19 | Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2.00000
Explanation: The ... | Python || Faster than 93% || Simple maths || with explanation | 1,300 | largest-triangle-area | 0.6 | ana_2kacer | Easy | 13,172 | 812 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.