- Видео 130
- Просмотров 9 811
LeekCodeDev
Добавлен 28 дек 2011
Doing all sorts of programming related stuff.
ASMR LeetCode: Maximum Population Year | Chill Coding
reporting alive status with jet lag
Просмотров: 2
Видео
ASMR LeetCode: Minimum Number of Changes to Make Binary String Beautiful | Chill Coding
Просмотров 8721 день назад
pairge
ASMR LeetCode: Majority Element | Chill Coding
Просмотров 3628 дней назад
guess we didn't need to use dictionaries :D
ASMR LeetCode: Delete Characters to Make Fancy String | Chill Coding
Просмотров 4128 дней назад
its november
ASMR LeetCode: Flip Equivalent Binary Trees | Chill Coding
Просмотров 26Месяц назад
i think leetcode is bugged i keep getting 0ms runtime
ASMR LeetCode: Minimum Time to Type Word Using Special Typewriter | Chill Coding
Просмотров 26Месяц назад
BEATS 100% TIME COMPLEXITY AGAIN LETSGOOOOOOOOO
ASMR LeetCode: Kth Largest Sum in a Binary Tree | Chill Coding
Просмотров 34Месяц назад
ITS ALMOST SPOOKY DAYY
ASMR LeetCode: Longest Happy String | Chill Coding
Просмотров 129Месяц назад
BEATS 100% LETS GOOOOOOOO
ASMR LeetCode: Separate Black and White Balls | Chill Coding
Просмотров 23Месяц назад
ASMR LeetCode: Separate Black and White Balls | Chill Coding
ASMR LeetCode: Maximal Score After Applying K Operations | Chill Coding
Просмотров 37Месяц назад
ASMR LeetCode: Maximal Score After Applying K Operations | Chill Coding
ASMR LeetCode: Minimum Add to Make Parentheses Valid | Chill Coding
Просмотров 24Месяц назад
ASMR LeetCode: Minimum Add to Make Parentheses Valid | Chill Coding
ASMR LeetCode: Sum Root to Leaf Numbers | Chill Coding
Просмотров 86Месяц назад
ASMR LeetCode: Sum Root to Leaf Numbers | Chill Coding
ASMR LeetCode: Path Sum | Chill Coding
Просмотров 104Месяц назад
ASMR LeetCode: Path Sum | Chill Coding
ASMR LeetCode: Minimum String Length After Removing Substrings | Chill Coding
Просмотров 20Месяц назад
ASMR LeetCode: Minimum String Length After Removing Substrings | Chill Coding
ASMR LeetCode: Divide Players Into Teams of Equal Skill | Chill Coding
Просмотров 123Месяц назад
ASMR LeetCode: Divide Players Into Teams of Equal Skill | Chill Coding
ASMR LeetCode: Minimum Size Subarray Sum | Chill Coding
Просмотров 35Месяц назад
ASMR LeetCode: Minimum Size Subarray Sum | Chill Coding
ASMR LeetCode: Rank Transform of an Array | Chill Coding
Просмотров 15Месяц назад
ASMR LeetCode: Rank Transform of an Array | Chill Coding
ASMR LeetCode: Check If Array Pairs Are Divisible by k | Chill Coding
Просмотров 119Месяц назад
ASMR LeetCode: Check If Array Pairs Are Divisible by k | Chill Coding
ASMR LeetCode: Design a Stack With Increment Operation | Chill Coding
Просмотров 402 месяца назад
ASMR LeetCode: Design a Stack With Increment Operation | Chill Coding
ASMR LeetCode: House Robber | Chill Coding
Просмотров 152 месяца назад
ASMR LeetCode: House Robber | Chill Coding
ASMR LeetCode: My Calendar I | Chill Coding
Просмотров 1162 месяца назад
ASMR LeetCode: My Calendar I | Chill Coding
ASMR LeetCode: Pascal's Triangle | Chill Coding
Просмотров 222 месяца назад
ASMR LeetCode: Pascal's Triangle | Chill Coding
ASMR LeetCode: Valid Anagram | Chill Coding
Просмотров 222 месяца назад
ASMR LeetCode: Valid Anagram | Chill Coding
Source Code: class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: ''' To solve this problem, I first thought of creating a basic array that has indices that represent the years of people that were still alive during that time, and increment 1 for each year for that person was alive. I keep doing this for each person, and at the end, this array will have one year where we had the most number of people alive. I will return this index as a year and get our answer! :D ''' max_years = 0 best_year = 0 years_alive = [0] * 101 for birth,death in logs: for i in range(death-birth): years_alive[birth-1950+i] += 1 for i in range(len(years_alive)): if years_alive[i] > max_years: max_years = years_alive[i] best_year = i return best_year + 1950
Source Code: class Solution: def primeSubOperation(self, nums: List[int]) -> bool: ''' To solve this problem, we're first going to obtain a list of prime numbers that are less than or equal to 1000, using the Sieve of Erosthathenes, and then we iterate through each element in nums and subtract the prime that will minimize the current value but still remains bigger than the previous number. We repeat this process, and when we find out that a number can't be bigger than the previous element no matter what changes we make,we return false, otherwise we return true! ''' primes = [True] * 1001 primes[0] = primes[1] = False for i in range(2,int(math.sqrt(1000))): if primes[i]: j = i*i while(j <= 1000): primes[j] = False j += i primes_list = [i for i,j in enumerate(primes) if j] for i in range(len(nums)): if i == 0: if nums[i] == 1 or nums[i] == 2: continue else: bestPrime = 0 for prime in primes_list: if prime < nums[i]: bestPrime = prime else: break nums[0] -= bestPrime else: bestPrime = 0 for prime in primes_list: if prime < nums[i] - nums[i-1]: bestPrime = prime else: break nums[i] -= bestPrime if nums[i] <= nums[i-1]: return False return True
Thanks 👍
Source Code: class Solution: def canSortArray(self, nums: List[int]) -> bool: ''' To solve this problem, I wanted to use some sort of a bubble sort-like approach, where I compare pairs of adjacent numbers and swap if I can make a valid swap. A valid swap in this case would be to check if the set bits are the same between the numbers, and that the previous number is bigger than the number that comes after it. While we make these swaps, If I ever have a iteration where I don't make any swaps (this means I can't make any more swaps), I end the loop early, and check if my final array is equal to the desired sorted array of nums. This is faster than the original bubble sort, because bubble sort will keep iterating for n times the length of the array, but this method will allow us to stop earlier if no swaps are valid anymore :D ''' sorted_nums = sorted(nums) n = len(nums) modified = 1 while(modified): modified = 0 for i in range(n-1): if nums[i] > nums[i+1] and bin(nums[i]).count('1') == bin(nums[i+1]).count('1'): nums[i],nums[i+1] = nums[i+1],nums[i] modified += 1 return nums == sorted_nums
Thanks 😅
Anything for you ;)
Source Code: class Solution: def minChanges(self, s: str) -> int: ''' Solving this problem takes a realization that because we eventually want to partition into beautiful substrings, the minimal length we have to check first whether we need to add changes to is a substring of length 2, because any further substrings will be composed of this initial length of 2, as all even substrings must be a factor of 2. Thus, we can go through each pairs of substrings and check that if they're different values, we add one change, and if not we don't need to do anything :D ''' res = 0 for i in range(1,len(s),2): if s[i] != s[i-1]: res += 1 return res
Source Code: class Solution: def simplifyPath(self, path: str) -> str: ''' To solve this problem, I'm first going to separate the path and split them by the "/" character. This way, I can always go through the array just looking at folder names or .. or . operations. We basically keep only the important information. Then, we keep a running stack, and when we encounter and empty character or a . operator, we don't do anything, when we encounter a ".." operator, we take off the stack as long as there is something in the stack. This replicates the "going back" folder operation. Everything else, we just add to the stack as if we're just going into more and more subfolder and its directories. At the end, our stack is going to have all the important folder directories left, so we can just join them with the "/" operator :D ''' stack = [] split_path = path.split("/") for element in split_path: if element == "" or element == ".": continue elif element == "..": if stack: stack.pop() else: stack.append(element) return "/" + "/".join(stack)
Source Code: class Solution: def compressedString(self, word: str) -> str: ''' To solve this problem, I first thought of using sliding window technique, using two pointers, let's call them left and right. left is going to be the index as I iterate through each character from left to right in the word, and for each character I keep a while loop to see if the next character is also the same. I keep count of everytime it is the same, so I can add to the final result string of the count and the specific character, just like the format wants in the question. If the count ever exceeds 9, then I will break my loop, reset the count, and repeat this process. We do this until we reach the end of the string, as there are no more characters we can possibly add to our final string! :D ''' res = "" n = len(word) left,right = 0,0 count = 0 while left < n: while right < n and word[left] == word[right]: if count == 9: break count += 1 right += 1 res += (str(count)+word[left]) left = right count = 0 return res
Source Code: class Solution: def rotateString(self, s: str, goal: str) -> bool: ''' To solve this problem, I'm going to add the string s to itself so that I can check if the goal is in the doubled string. The purpose of doubling the s string is to account for all the possible different shift versions of the original string :D ''' if len(s) != len(goal): return False check = s * 2 return goal in check
Source Code: class Solution: def majorityElement(self, nums: List[int]) -> int: ''' To solve this problem, I keep track of a count and its respective character associated with that count. If I encounter a character that isn't the current designated character, then I decrement the count as long as the current count is greater than 0. However, if the current count is 0, that means that we have a possibility for a new most frequent element, so we update our designated character and keep a new count of that specific element. We repeat this process until we get our final designated element. This element was what was seen the most, as it still remains! :D ''' count = 0 curr = nums[0] for num in nums: if num == curr: count += 1 else: if count == 0: curr = num else: count -= 1 return curr
Source Code: class Solution: def isCircularSentence(self, sentence: str) -> bool: ''' To solve this problem, I'm first going to split up the sentence into a list of individual words. Then, I'm going to check each word if the next word's first character is equal to the last character of my current word, and just check that the last word character is equal to the beginning word beginning character. If we have all these cases covered, we should be good to go! :D ''' word_list = sentence.split() n = len(word_list) for i in range(n): if word_list[i][-1] != word_list[(i+1)%n][0]: return False return True
Source Code: class Solution: def makeFancyString(self, s: str) -> str: ''' To solve this problem, we basically have to identify the part of the string where there are at least 3 consecutive characters. To idenfity this, we can go through each character in the string, and check if the current character is equal to the two characters right before it. If it is, we don't add that character in our character building string. If it isn't , we continue adding it on to our result final string :D ''' res = "" for i in range(len(s)): if i > 1 and s[i] == s[i-1] == s[i-2]: continue else: res += s[i] return res
Source Code: class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: ''' To solve this problem, we're going to use dynamic programming. In other words, when we encounter a '1' in the matrix, we check for the left, topleft, and top values to see what the maximum square we could make with thoseother matrix values. We take the minimum of those three values and add 1, and this will get us our current maximum length square that we can make in the current index of the matrix. We repeat this process, and we will eventually find the best length of a square that contains just 1's :D ''' m = len(matrix) n = len(matrix[0]) dp =[[0] * n for _ in range(m)] best_length = 0 for i in range(m): for j in range(n): val = matrix[i][j] if val == '0': dp[i][j] = 0 else: if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = 1 + min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) best_length = max(best_length, dp[i][j]) return best_length ** 2
Source Code: # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: ''' To solve this problem, for each node, I'm going to compare the children for the two roots we are given. If the left and right values are the same, or they're just flipped, I keep recursing down the tree and return True if i reach None, because this means that we found no inequalities. However, if the property of the children values being the same gets broken, we return False up to the roots and we will return False! We repeat this process to get our final True or False value, whether we can flip the equivalent binary Tree :D ''' if not root1 and not root2: return True elif not root1 or not root2: return False elif root1.val != root2.val: return False root1_left_child_val = 0 if root1.left is None else root1.left.val root1_right_child_val = 0 if root1.right is None else root1.right.val root2_left_child_val = 0 if root2.left is None else root2.left.val root2_right_child_val = 0 if root2.right is None else root2.right.val if root1_left_child_val == root2_left_child_val and root1_right_child_val == root2_right_child_val: return self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right) elif root1_left_child_val == root2_right_child_val and root1_right_child_val == root2_left_child_val: return self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left) else: return False
Source Code: class Solution: def minTimeToType(self, word: str) -> int: ''' To solve this problem, we essentially have to minimize the difference in steps that we take from each character to the next. There are two different ways, counterclockwise and clockwise. Some will give a higher distance, and some will not. For example, if we set "a" to be index 0, and "d" is 3", and "z" is 25, then going from d->z would take 22 seconds, but going the opposite direction would take only 4 seconds. This is because 3 is also rewritten as (26+3) = 29 - 25 = 4. So, we always have to compare the normal absolute distance and the distance of 26 minus that distance, because that is essentially the other direction that we could've taken! :D ''' prev = 'a' seconds = 0 for c in word: diff = abs(ord(c) - ord(prev)) seconds += min(diff, 26 - diff) seconds += 1 prev = c return seconds
Source Code: # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: ''' To solve this problem, I'm first going to check if I have enough levels for k, if not I can just return -1 immediately. If I do have enough levels, I'm going to traverse through each node, and mark their levels, and depending on their level, I'm going to use that as the index of a master array and increment the total at that index. This way, I can keep track of total sums for each level, and at the end I can simply return the kth largest by sorting the array with the biggest coming first :D ''' def checkLevels(root): if not root: return 0 return 1 + max(checkLevels(root.left),checkLevels(root.right)) arr = [0] * 100000 levels = checkLevels(root) if levels < k: return -1 def traverse(root,level): if not root: return 0 arr[level] += root.val traverse(root.left,level+1) traverse(root.right,level+1) traverse(root,0) return sorted(arr,reverse=True)[k-1]
Is there any hope for me as a Web dev if I suck at leetcode?
Absolutely! To be frank web dev interview questions are more structured around your front-end skills rather than your knowledge in algorithms/data structures, so you'll be fine. It certainly doesn't hurt to know SOME leetcode, but I'd say at a bare minimum level. Focus your time in developing your front-end skills, such as HTML, CSS, Javscript, and frameworks of your choice :D
@@LeekCodeDev I'm a dotnet(C#)+Angular full stack developer with 1.5 years of experience. I'm going to Dubai in a couple of months to try to get a job there as the dev jobs in my country don't pay that well. I was thinking about leetcode that I suck at it and hopefully they dont ask me to invert a binary tree with hashmap in O(1) xD. Any advice from you would be more than welcome:P
@@LeekCodeDev I'm a dotnet(C#)+Angular Full stack developer with 1.5 years of experience and I'm going to Dubai in a couple of months to try to get a job there as the dev jobs in my country dont pay so well. I keep thinking about how to clear the interviews there without any leetcode, what if they ask me to reverse some shite with hashmap and stuff xD. Just hoping they stick to web dev and not this Competitive programming stuff. Any advice from you would be more than welcome!
I'm a dotnet(C#)+Angular Full stack developer with 1.5 years of experience and I'm going to Dubai in a couple of months to get a job there as the Dev jobs in my country don't pay so well. I was wondering how will I clear interviews without leetcode, what if they ask me to reverse some stuff with hashmap in O(1) xD. I just hope they ask about web dev things and not Competitive programming stuff. Any advice from you would be more than welcome!
I been working as programmer for years and I still suck at leetcode lol
bro is him
i might just be goated
Source Code: class Solution: def minimumSteps(self, s: str) -> int: ''' To solve this problem, I realized that at the end of the day, we just want all the black balls (1) to go to the right, and all the white balls (0) to go to the left. So, knowing this, when I move from left to right, the moment I encounter a 0, I count the number of 1's I've seen up to that point, and I add that amount to the total number of swaps I must do. This works because we want to shift that much 1's to the right and move 0 to the left correspondingly. We repeat this process, and we'll have found the total number of swaps we need to get our balls separated :D ''' num_ones_seen = 0 swaps = 0 for c in s: if c == '0': swaps += num_ones_seen else: num_ones_seen += 1 return swaps
Source Code: class Solution: def maxKelements(self, nums: List[int], k: int) -> int: ''' To solve this problem, we can utilize a priority queue. Particularly, we always want to extract the biggest element from the list to add to our score. Since we want to emulate a max heap, we just make all our elements in our list negative, since the biggest negative will come out first, and we can just negate it to get our original positive value. After taking out the biggest number we add the divided by 3 ceiling value back to our heap and we repeat this process for k times :D ''' nums = [-x for x in nums] heapq.heapify(nums) total = 0 for _ in range(k): best = -heapq.heappop(nums) total += best heapq.heappush(nums,-math.ceil(best/3)) return total
Source Code: class Solution: def minAddToMakeValid(self, s: str) -> int: ''' To solve this problem, we're going to be utilizing a stack. Basically, when we encounter an opening tag, we simply add it to the stack. Then, when we encounter a closing tag, we check if the topmost stack is an opening tag, because this would mean that there is a corresponding matching tag, allowing us to pop that item off the stack, and continue on wards. If there isn't any opening matching tag on the stack, we simply add the closing tag to the stack, as this will add to the number of unbalanced tags we have. At the end, while we repeat this process, the length of the stack (the size) will have the count of all the unbalanced parantheses, which is what we want for our answer! :D ''' stack = [] for c in s: if c == '(': stack.append(c) else: if stack and stack[-1] == "(": stack.pop() else: stack.append(c) return len(stack)
🔥🔥🔥🔥🔥🔥🔥🔥
Source Code: # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: ''' To solve this problem, we recurse the nodes in the tree until we hit a child node, and then we check if our current running total is equal to the targetSum. If it is, we return true and if not we return false :D ''' def travel(root, total): if not root: return False total += root.val if root.left == None and root.right == None: return targetSum == total return travel(root.left,total) or travel(root.right,total) return travel(root,0)
Source Code: class Solution: def minLength(self, s: str) -> int: ''' To solve this problem, we take a look at our given string, and look for any patterns of "AB" or "CD". If we find any of them, then we simply remove them from our string. We'll keep a continuous while loop to check for if our current string STILL has any patterns of "AB" or "CD" left, and once there are no more left to remove, we can simply remove the final length of our string! :D ''' while ("AB" in s or "CD" in s): while("AB" in s): s = s.replace("AB",'') while("CD" in s): s = s.replace("CD",'') return len(s)
Source Code: class Solution: def dividePlayers(self, skill: List[int]) -> int: ''' To solve this question, I realized that the only way to get valid pairs that could potentially have the equal totals is by taking the smallest and biggest values, and updating the smallest to be the 2nd smallest, the biggest to be the 2nd biggest... and so on and adding their totals. This makes it so that we have the highest likeliehood of making everything the same, since the sum will be accordingly. Small one gets bigger, in exchange the bigger value gets smaller. If one of the total pairs fails, then we can just return -1. This definitely works because there is no guarantee of a "better pair" nor will you miss any valid pairs, because the approach of taking the smallest and biggest will always try to get us the goal total. : D ''' n = len(skill) skill.sort() goal = skill[0] + skill[-1] chemistry = 0 for i in range(int(n/2)): if skill[i] + skill[n-1-i] != goal: return -1 else: chemistry += (skill[i] * skill[n-1-i]) return chemistry
Source Code: class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: ''' To solve this problem, we're going to use a sliding window technique! In other words, we're going to keep track of a subarray and its leftmost and rightmost points, and calculate the current sum total in its subarray. If that total is greater than or equal to the target, we check the window's length and see if it's the smallest we've seen, and update accordingly. While the sum is still greater than the target, we will shift our leftmost point of our window to the left to change the window or subarray that we're looking at, and subtract the values we shift left from, as the subarray total is going to change. We continue onwards to shift our rightmost part of our window if our subarray is still smaller than our target. We repeat this process,and we simply return the smallest window length we've seen! :D ''' n = len(nums) if sum(nums) < target: return 0 left,right = 0,0 running_total = 0 min_length = n while right < n: running_total += nums[right] if running_total >= target: while(running_total >= target): min_length = min(min_length, right-left + 1) running_total -= nums[left] left += 1 right += 1 return min_length
Source Code: class Solution: def arrayRankTransform(self, arr: List[int]) -> List[int]: ''' To solve this problem, I'm going to first make a list of all the unique numbers in the array, sorted in ascending order. Notice now that the index+1 represents the "rank" of each of these values. I can go through this array now and make a key,value pair for a hash map, where the key is the element and the value represents its index + 1, aka its rank! Now, we can just iterate through the original array and find the respective ranks for each element :D ''' sorted_arr = sorted(list(set(arr))) rankMap = defaultdict(int) for i,j in enumerate(sorted_arr): rankMap[j] = i + 1 return [rankMap[x] for x in arr]
👻
Source Code: class Solution: def canArrange(self, arr: List[int], k: int) -> bool: ''' To solve this problem, we're first going to go through the entire list, and calculate the value modulo by k. This gives us the remainder that we have left to get to k. After getting the remainders for each value, we also needed to have kept a count of each respective modulo inside a hash map. Why is this, you ask? Well, remember, we're looking for PAIRS of sums of values that will get us to be divisible by k, right? Which means, that if for example, the k value was 5, and we have a remainder of 2 and 3, adding this remainders will give us a remainder of 5, making this a valid pair. We just have to make sure that their counts are the same, because if we have three 2's and 2 3's, there will be a mismatch and therefore we can't create valid pairs! When we encounter a remainder that is 0, we just need to make sure its count is even, (since pairs come in two) :D ''' modMap = defaultdict(int) for val in arr: modMap[val % k] += 1 for val in arr: curRemainder = val % k if curRemainder == 0: if modMap[curRemainder] % 2: return False elif modMap[curRemainder] != modMap[k-curRemainder]: return False #if nothing returns false, then we have valid pairs!! return True
Yo subbed 🙌🔥
Thank you!
Source Code: class CustomStack: def __init__(self, maxSize: int): self.arr = [] self.maxSize = maxSize def push(self, x: int) -> None: if(len(self.arr) < self.maxSize): self.arr.append(x) def pop(self) -> int: if(len(self.arr) > 0): return self.arr.pop() else: return -1 def increment(self, k: int, val: int) -> None: if k > len(self.arr): for i in range(len(self.arr)): self.arr[i] += val else: for i in range(k): self.arr[i] += val # Your CustomStack object will be instantiated and called as such: # obj = CustomStack(maxSize) # obj.push(x) # param_2 = obj.pop() # obj.increment(k,val) ''' Solving this problem basically boils down to understanding how arrays really work in Python. We can use the basic append and pop methods, and for going through each element, we can just use a for loop for updating the values :D '''
Source Code: class MyCalendar: def __init__(self): self.arr = [] def book(self, start: int, end: int) -> bool: self.arr.append((start,end)) self.arr.sort(key = lambda x : x[0]) index = self.arr.index((start,end)) if len(self.arr) > 1: if index == 0: if end <= self.arr[index+1][0]: return True else: self.arr.pop(index) return False elif index == len(self.arr) - 1: if start >= self.arr[index-1][1]: return True else: self.arr.pop(index) return False else: if(start >= self.arr[index-1][1] and end <= self.arr[index+1][0]): return True else: self.arr.pop(index) return False else: return True # Your MyCalendar object will be instantiated and called as such: # obj = MyCalendar() # param_1 = obj.book(start,end) ''' To solve this problem, we take into an array of all the intervals, and when we add an interval to our array, we sort them based on the start time. After adding to the list, we check if the time before and time after the interval we just put in is valid, aka just check the min and max of the times, and if it's valid we keep it in the array and we return True, otherwise, we take it off the array we just put in and return False. We repeat this process :D '''
doesn't the sorting make it O(n log(n)?
Yes, you're absolutely right! If you want to use the "best" solution, you would need to implement DFS, where the runtime would be O(n). I personally find one-liners to be pretty neat, so I wrote it as such. You know what they say, if it ain't broke, don't fix it :D
damn
goated one-liner solution
Thanks :D
n1
Source Code: class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: ''' TO solve this problem, we're first going to create a bitmask that contains 1's in the alphabetical index of where the letters are allowed. Then we're going to go through each word in the words array, go through each character in the word, and shift the allowedBits mask to the right the number of times of the alphabetical index. This allows us to isolate whether that alphabet is legal(1) or illegal(0) We repeat this process and just keep count of words that are allowed :D ''' allowedBits = 0 for c in allowed: allowedBits |= 1 << (ord(c) - ord('a')) #now our allowedBits should contain 1's in proper areas goodCount = 0 for word in words: isGood = True for c in word: bit = allowedBits >> (ord(c)-ord('a')) & 1 #this was a 0 if not bit: isGood = False break if isGood: goodCount += 1 return goodCount
lol
class Solution: def minBitFlips(self, start: int, goal: int) -> int: ''' To solve this problem, we basically need to convert start and goal into their respective binary formats. Then, we look at the positions where the numbers differ, because that is the number of times we have to flip the bits. There is no need to flip the bits if the value at the same index is the same! We can use xor in Python: ^ operator, and doing this between the start and goal will return a binary number that has 1's(true) where the values of the index are different, because exclusive or will only return true if one of the number is true, like (1 or 0) and (0 or 1), if it's (0 or 0) and (1 or 1), which we don't want since they're the same values, it will return false. This is why we want to use the xor function here. Then, we take this xor result and & it with 1 each time to see if there is a 1 at the place, and we keep shifting the bits to the right to repeat this process until we used up all the bits in the xor number :D ''' count = 0 xor = start ^ goal while xor: #if the and operator gives us 1, aka, there was a 1 in the xor result if xor & 1: count += 1 #shift the bits to the right to look at next bit xor >>= 1 return count
Source Code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]: ''' To break this problem down simpler, we need to go through all the nodes and take a look at their next nodes(if they exist) and create a ListNode containing the value of the greatest common divisor, and then set that node's next equal to the next value that we kept from previous iteration. We will call this "temp". We will also use a "dummy" iterator to go through the nodes in the linked list. The steps should go like this: 1. create dum iterator 2. set temp as dum.next 3. create a new node containing gcd, and set dum.next to it 4. set gcd.next to the temp 5. set dum as temp and we repeat this process :D ''' dum = head while(dum.next): temp = dum.next gcdNode = ListNode(math.gcd(dum.val,temp.val)) dum.next= gcdNode gcdNode.next = temp dum = temp return head
Before writing the code, it would be very helpful if you explain the logic first.
I use to before, but analytics show that most people aren't too bothered to see the logic of the question. I can put up a poll to see if you guys want me to bring back the written explanations!
@@LeekCodeDev i am ready to hear your explanation. Just giving people the code will not make them a problem solver. The important part of problem solving is how you reached to that conclusion. If i can understand the logic, then i dont have to look at peoples code. I can write the program myself after that.
never in my more than 2 decades of life did i ever think leetcode asmd would be a thing
Source Code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: resMatrix = [[0] * n for _ in range(m)] left,top =0,0 right,bottom = n,m while left < right and top < bottom: for i in range(left,right): if head: resMatrix[top][i] = head.val head = head.next else: resMatrix[top][i] = -1 top += 1 for j in range(top,bottom): if head: resMatrix[j][right-1] = head.val head = head.next else: resMatrix[j][right-1] = -1 right -= 1 #do check here if not (left < right and top < bottom): break for k in range(right-1,left-1,-1): if head: resMatrix[bottom-1][k] = head.val head = head.next else: resMatrix[bottom-1][k] = -1 bottom -= 1 for l in range(bottom-1, top -1, -1): if head: resMatrix[l][left] = head.val head = head.next else: resMatrix[l][left] = -1 left += 1 return resMatrix
Source Code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]: res = [] arr_lens = [] ll_length = 0 counter = head while(counter): ll_length += 1 counter = counter.next if(ll_length < k): for _ in range(k): if head: iterator = head head = iterator.next iterator.next = None res.append(iterator) else: res.append(None) else: avg = ll_length // k for _ in range(k): arr_lens.append(avg) mod = ll_length % k if(mod != 0): for i in range(mod): arr_lens[i] += 1 for lens in arr_lens: iterator = head for _ in range(lens-1): iterator = iterator.next temp = iterator.next iterator.next = None res.append(head) head = temp return res
Source Code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool: def checkPossible(head,root): if not root or root.val != head.val: return False if root.val == head.val: if head.next is None: return True else: return checkPossible(head.next,root.left) or checkPossible(head.next,root.right) if not root: return False return checkPossible(head,root) or self.isSubPath(head,root.left) or self.isSubPath(head,root.right)
Source Code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]: numSet = set(nums) first = ListNode() first.next = head iterator = first while(iterator != None): if(iterator.next != None and iterator.next.val in numSet): dum = iterator while(dum.next != None and dum.next.val in numSet): dum = dum.next iterator.next = dum.next iterator = dum.next else: iterator = iterator.next return first.next
Source Code: class Solution: def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: res= [] m = len(rolls) totalSum = (m+n)*mean remaining = totalSum - sum(rolls) if remaining > 6*n or remaining < n: return res if n == 1: return [remaining] else: avg = remaining // n mod = remaining % n for _ in range(n-1): res.append(avg) remaining -= avg res.append(remaining) if mod > 6: for i in range(mod): res[i] += 1 res[-1] -= 1 return res
Source Code: class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: ''' Solving this problem comes down to being able to simulate the process of walking the robot. It seems like we'll need some directions array so that we need to switch the direction when we encounter a -2 or a -1. We'll also make a hash set of the obstacles to make lookup faster... Then we simply just go through each commands, stop when there's an obstacle, calculate if the distance from the origin is greater than our best distance, and update accordingly :D ''' directions = [(0,1),(1,0),(0,-1),(-1,0)] cur_dir = 0 #North cur_pos = [0,0] #origin best_dist = 0 obstaclesSet = set(map(tuple,obstacles)) for command in commands: if command == -2: cur_dir = (cur_dir + 3) % 4 elif command == -1: cur_dir = (cur_dir + 1) % 4 else: #going forward going = directions[cur_dir] for _ in range(command): next_pos = [cur_pos[0] + going[0],cur_pos[1] + going[1]] if tuple(next_pos) in obstaclesSet: break cur_pos = next_pos if (cur_pos[0]**2 + cur_pos[1]**2 > best_dist): best_dist = cur_pos[0]**2 + cur_pos[1] ** 2 return best_dist
Source Code: /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} To solve this problem, I'm going to run a loop through the entire array nums, and I'm going to change the value of init as the return value of the function fn(val, nums[i]), This way, the val used for each function will be the previous val that we calculated from the previous iteration. All we have left after our loop terminates is to simply return the value now :D */ var reduce = function(nums, fn, init) { for(let i=0;i<nums.length;i++) { init = fn(init, nums[i]); } return init; };