text
stringlengths
37
1.41M
# {'fried_chicken': '2'} def calculatePrice(foodClassified): total_price = 0 for foodItem,quantity in foodClassified.items() : if foodItem == "fried_chicken": total_price += int(quantity)*2 elif foodItem == "rice": total_price += int(quantity)*1 elif foodItem == "...
'''Напишите программу, которая считывает список чисел lst из первой строки и число x из второй строки, которая выводит все позиции, на которых встречается число x в переданном списке lst. Позиции нумеруются с нуля, если число x не встречается в списке, вывести строку "Отсутствует" (без кавычек, с большой буквы). П...
'''Жители страны Малевии часто экспериментируют с планировкой комнат. Комнаты бывают треугольные, прямоугольные и круглые. Чтобы быстро вычислять жилплощадь, требуется написать программу, на вход которой подаётся тип фигуры комнаты и соответствующие параметры, которая бы выводила площадь получившейся комнаты. Для чис...
import numpy as np import matplotlib.pyplot as plt from pygsp import graphs, plotting # Question 3 - Bipartite graph n = 3 m = 5 #Undirected W_bi_u = np.zeros((m+n,m+n)) for i in range(n): for j in range(m): W_bi_u[n+j][i] = 1 np.fill_diagonal(W_bi_u, 0) W_bi_u = W_bi_u + W_bi_u.T G_bi_u ...
import re from pyphen import Pyphen def parse_words(text): '''returns a list of words given a string of alphanumeric words separated by spaces and punctuation''' # Remove apostrophes text = re.sub("['\[\]]", "", text) word = "\w+" return re.findall(word, text) def parse_paragraphs(text): ...
import turtle import math bob = turtle.Turtle() #draw right angle #bob.fd(100) #bob.lt(90) #bob.fd(100) #draw a squre #for i in range(4): # bob.fd(100) # bob.lt(90) def square(t, length): for i in range(4): t.fd(length) t.lt(90) turtle.mainloop() #square(bob, 600) def polygon(t, length...
# 6. Crear un programa que lea un entero positivo, n, introducido por el usuario y después muestre en pantalla la suma de todos los enteros desde 1 hasta n. n = int(input('Ingrese un número: ')) suma = 0 # creo la variable suma como contenedor de de los enteros de 1 a n y le sumo el indice del for for i i...
''' Crear un script llamado **personas.py** que lea los datos de un fichero de texto, que transforme cada fila en un diccionario y lo añada a una lista llamada personas. Luego recorre las personas de la lista y para cada una muestra de forma amigable todos sus campos. El fichero de texto se denominará **personas.txt**...
# 7. El siguiente programa debería imprimir el número 2 si se le ingresan como valores x=5, y=1 pero en su lugar imprime 5. ¿Qué hay que corregir? # def maximo(a,b): def maximo(x,y): if x>y: return x else: return y #def minimo(a,b): hay que pasarle por paramtros las funciones del programa principal def ...
#Faça um Programa que leia um vetor de 10 caracteres, e diga quantas consoantes foram lidas. # Imprima as consoantes. listaInput = [] consoantes = 0 vogal = 0 print ('Informe os caracters') for i in range(10): lista = input('Coloque as letras aqui: ') listaInput.append(lista) characters = listaInput[i] ...
#Faça um Programa que leia um vetor de 5 números inteiros e mostre-os. vetor = [1,3,6,8,9] print(vetor) # com while vetorList = [1, 4, 9, 22, 18] i = 0 while i < len(vetorList): print(vetorList[i]) i = i + 1 #com for listaNumeros = [] print ('Informe os 5 numeros') for i in range(5): listaNumeros.appen...
#Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. import getpass while True: login = input('nome do usuário: ') senha = getpass.getpass('senha: ') if login != senha : print("...
# -*- coding: utf-8 -*- from neuronalNetwork import NeuronalNetwork from repository import Repository import matplotlib.pyplot as mpl import numpy as np class Controller: def __init__(self, repository : Repository): self.repository = repository def plotL(self, iterations,loss): mpl.plot(i...
a = 4 b = 4 def con(a,b): return (a*b) print(con(4,4)) def is_even(n): if n % 2 == 0: return (n, 'is an even num') else: print('%s is not even no' %n) print(is_even(11))
def even(n): i=0 b=[] while i<len(n): if n[i]%2==0: b.append(n[i]) i=i+1 return b print(even(([1,2,3,4,5,6,7,8])))
def speed(n): if n<=70: print("Ok") elif n>70: i=70 c=0 while i<n: c=c+1 i=i+5 print(c,"points") if c>12: print("licensed suspended") n=int(input("enter a num:")) speed(n)
import numpy as np import itertools def isnumb(x): while type(x) != float: try: x = float(x) except ValueError: print("Помилка. Введене значення не є числом") x = input("Введіть числове значення елемента (дробові числа вводяться з крапкою):") retu...
""" https://leetcode.com/problems/linked-list-in-binary-tree/ """ from test_helper import ListNode, TreeNode class Solution: def isSubPath(self, head: ListNode, root: TreeNode) -> bool: def dfs(head: ListNode, root: TreeNode) -> bool: if not head: return True if ...
""" https://leetcode.com/problems/make-the-string-great/ """ class Solution: def makeGood(self, s: str) -> str: stack: list[str] = [] for c in s: if stack and stack[-1] != c and stack[-1].lower() == c.lower(): stack.pop() else: stack.append(c...
""" https://leetcode.com/problems/advantage-shuffle/ """ from collections import defaultdict class Solution: def advantageCount(self, A: list[int], B: list[int]) -> list[int]: """ For sorted A and B, start scanning from the end, and if B[-1] < A[-1], pair the target item from A. ...
""" https://leetcode.com/problems/minimum-index-sum-of-two-lists/ """ from typing import List class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: memo1 = {s: i for i, s in enumerate(list1)} memo2 = {s: i for i, s in enumerate(list2)} commons = {s: m...
""" https://leetcode.com/problems/average-waiting-time/ """ class Solution: def averageWaitingTime(self, customers: list[list[int]]) -> float: totalWaitTime, readyTime = 0, None for arrivalTime, prepareTime in customers: if readyTime is None or readyTime < arrivalTime: ...
""" https://leetcode.com/problems/largest-substring-between-two-equal-characters/ """ class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: BASE = ord('a') memo: list[list[int | None]] = [[None, None] for _ in range(26)] for i, c in enumerate(s): offset = or...
""" https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ """ from test_helper import TreeNode from typing import List class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: """ Taking advantage of BST and inorder traversal. """ ...
""" https://leetcode.com/problems/increasing-order-search-tree/ """ from test_helper import TreeNode class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: currNode, stack = root, [] newRoot = currRoot = None while currNode or stack: while currNode: ...
""" https://leetcode.com/problems/palindrome-number/ """ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0 or (x % 10 == 0 and x != 0): return False n = 0 while x > n: # Reverse only half digits of x to avoi...
""" https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ """ class Solution: def hasValidPath(self, grid: list[list[int]]) -> bool: R, C = len(grid) - 1, len(grid[0]) - 1 cells: list[list[int]] = [(0, 0, grid[0][0])] visited: set[tuple[int]] = {(0, 0)} for r, c, ...
""" https://leetcode.com/problems/minimum-distance-to-the-target-element/ """ class Solution: def getMinDistance(self, nums: list[int], target: int, start: int) -> int: minDistance = len(nums) + 1 for i, num in enumerate(nums): if num == target: minDistance = min(minDis...
""" https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ """ class Solution: def oddCells(self, m: int, n: int, indices: list[list[int]]) -> int: """ Simply count the odd number of rows and odd number of cols, then for m - rowSum stands for each row with even operations, then ...
""" https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ """ from typing import List class Solution: def search(self, nums: List[int], target: int) -> bool: if not nums: return False l, r = 0, len(nums) - 1 while l <= r: m = (l + r) // 2 if...
""" https://leetcode.com/problems/count-sub-islands/ """ class Solution: def countSubIslands(self, grid1: list[list[int]], grid2: list[list[int]]) -> int: def dfs(r: int, c: int): if r < 0 or r >= R or c < 0 or c >= C or not grid2[r][c]: return grid2[r]...
""" https://leetcode.com/problems/replace-all-digits-with-characters/ """ class Solution: def replaceDigits(self, s: str) -> str: def shift(c: str, x: int): if x <= 0: return c return chr(ord(c) + x) chars = list(s) for i in range(0, len(s) - 1, 2)...
""" https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ """ from typing import List class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: rslt = [-1, -1] if not nums: # Empty list. return rslt low, high = 0, len(n...
""" https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/ """ from collections import Counter class Solution: def numWays(self, words: list[str], target: str) -> int: N, MOD = len(target), 10 ** 9 + 7 # The number of ways to form the first j chars in target. ...
""" https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ """ from typing import List class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: start = None for end in range(len(nums)): if nums[end]: if start is not None and e...
""" https://leetcode.com/problems/implement-magic-dictionary/ """ from typing import List from collections import defaultdict class MagicDictionary: def __init__(self): self.memo = defaultdict(list) def buildDict(self, dictionary: List[str]) -> None: for w in dictionary: self.m...
""" https://leetcode.com/problems/remove-palindromic-subsequences/ """ class Solution: def removePalindromeSub(self, s: str) -> int: if not s: # s is empty. return 0 if s[::-1] == s: # s is already a palindrome. return 1 return 2 # Remove all a in s, then remov...
""" https://leetcode.com/problems/divisor-game/ """ class Solution: def divisorGame(self, n: int) -> bool: """ 1. Base case is when the player has a current number 2, which leads to the next player lose the game. 2. So at first the number is odd, as odd numbers only have odd fa...
""" https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ """ class Solution: def sortByBits(self, arr: list[int]) -> list[int]: def count_digits(num: int) -> int: cnt = 0 while num: cnt += 1 num &= num - 1 # Unset the rightmost valid...
""" https://leetcode.com/problems/maximum-subarray/ """ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: """ Take dp[i] as the max sub array which contains nums[i] at its end. Then dp[i + 1] = nums[i + 1] + max(0, dp[i]) """ currMax, m...
""" https://leetcode.com/problems/combination-sum-iv/ """ from typing import List class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: # When the target is zero while all the numbers in nums are # positive, the only combination is that we don't select any number. ...
""" https://leetcode.com/problems/reshape-the-matrix/ """ from typing import List, Iterator class Solution: def matrixReshape( self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: def old_matrix() -> Iterator[int]: for row in nums: for num in row: ...
""" https://leetcode.com/problems/cat-and-mouse/ """ from typing import Iterator from collections import defaultdict, deque class Solution: def catMouseGame(self, graph: list[list[int]]) -> int: def parents(m: int, c: int, t: int) -> Iterator[tuple[int]]: if t == 2: for m2 in...
""" https://leetcode.com/problems/delete-and-earn/ """ from typing import List from collections import Counter class Solution: def deleteAndEarn(self, nums: List[int]) -> int: """ 1. If we take one number, we should take all its duplicates as well since if we remove all its neighbo...
""" https://leetcode.com/problems/find-eventual-safe-states/ """ from collections import deque class Solution: def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]: """ 1. For those nodes having no outgoing edges, they are already safe nodes. 2. Then for the node ...
""" https://leetcode.com/problems/prefix-and-suffix-search/ """ from typing import List class Trie: """ Prefix tree. """ def __init__(self): self._root = {} # '#' marks the maximum index at the word end. def add_word(self, idx: int, w: str) -> None: currNode = self._root ...
""" https://leetcode.com/problems/dinner-plate-stacks/ """ from heapq import heappush, heappop class DinnerPlates: def __init__(self, capacity: int): self.availableIndexes = [] self.allStacks = [] self.capacity = capacity def push(self, val: int) -> None: # Remove the full ...
""" https://leetcode.com/problems/degree-of-an-array/ """ from typing import List class Solution: def findShortestSubArray(self, nums: List[int]) -> int: memo, maxFreq, minLen = {}, 0, len(nums) + 1 for end, num in enumerate(nums): if num not in memo: memo[num] = [end...
""" https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ """ from test_helper import TreeNode class Solution: def flatten(self, root: TreeNode) -> None: currNode, preRights = root, [] while currNode or preRights: while currNode and currNode.left: if currN...
""" https://leetcode.com/problems/repeated-dna-sequences/ """ from typing import List class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: n = len(s) if n < 11: return [] visited, rslt = set(), set() for i in range(n - 9): chkStr = s[i...
""" https://leetcode.com/problems/throne-inheritance/ """ from collections import defaultdict class ThroneInheritance: def __init__(self, kingName: str): self.deadPeople: set[str] = set() self.children: defaultdict[str, list[str]] = defaultdict(list) self.parents: dict[str, str] = {} ...
""" https://leetcode.com/problems/rabbits-in-forest/ """ class Solution: def numRabbits(self, answers: list[int]) -> int: """ 1. If x + 1 rabbits have the same color, then we will have x + 1 rabbits answer x. 2. So each time we come across a new answer x, we suppose there are ...
""" https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/ """ from collections import defaultdict from heapq import heappush, heappop class Solution: def reachableNodes( self, edges: list[list[int]], maxMoves: int, n: int) -> int: """ 1. Use Dijkstra's algorithm to find ...
""" https://leetcode.com/problems/letter-case-permutation/ """ class Solution: def letterCasePermutation(self, S: str) -> list[str]: if S[0].isdigit(): currLevel = [S[0]] else: currLevel = [S[0].lower(), S[0].upper()] for i in range(1, len(S)): c = S[i]...
""" https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ """ class Solution: def minInsertions(self, s: str) -> int: """ Find the longest palindrome subsequence in s first, then the required insertion steps is N - len(subSequence). """ def chec...
""" https://leetcode.com/problems/running-sum-of-1d-array/ """ class Solution: def runningSum(self, nums: list[int]) -> list[int]: prefixSums: list[int] = [0] for num in nums: prefixSums.append(prefixSums[-1] + num) return prefixSums[1:]
""" https://leetcode.com/problems/longest-harmonious-subsequence/ """ from typing import List from collections import Counter class Solution: def findLHS(self, nums: List[int]) -> int: memo = {} rslt = 0 for num in nums: memo[num] = memo.get(num, 0) + 1 if num +...
""" https://leetcode.com/problems/tag-validator/ """ import re class Solution: def isValid(self, code: str) -> bool: if not code: # The input code is empty. return False P_CDATA = re.compile(r""" <!\[CDATA\[ # Initial string .*? # Match the smallest string...
""" https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ """ from collections import defaultdict class Solution: def minTime( self, n: int, edges: list[list[int]], hasApple: list[bool] ) -> int: def walk(currNode: int) -> int: if cur...
""" https://leetcode.com/problems/insertion-sort-list/ """ from test_helper import ListNode class Solution: def insertionSortList(self, head: ListNode) -> ListNode: dummyHead = ListNode(None) currNode, dummyHead.next, preInsertPos = head, head, dummyHead while currNode and currNode.next:...
""" https://leetcode.com/problems/valid-palindrome/ """ class Solution: def isPalindrome(self, s: str) -> bool: l, r = 0, len(s) - 1 while l < r: if not s[l].isalnum(): l += 1 continue if not s[r].isalnum(): r -= 1 ...
""" https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/ """ class Solution: def minSwaps(self, grid: list[list[int]]) -> int: """ Count the trailing zeros for each row first, then for each row, try to swap with the nearest row that satisfy the current row requirement. ...
""" https://leetcode.com/problems/word-break/ """ from typing import List from collections import deque class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: """ Using BFS solution. """ visited, queue = set(), deque([0]) # Get the maximum length of th...
""" https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/ """ class Solution: def findTheLongestSubstring(self, s: str) -> int: memo = {c: i for i, c in enumerate('aeiou')} seen = {0: -1} # Store the first occurring index of mask. maxLen = 0 cu...
""" https://leetcode.com/problems/intersection-of-two-linked-lists/ """ from test_helper import ListNode class Solution(object): def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: # Either list is empty. return None nodeA, nodeB =...
""" https://leetcode.com/problems/restore-ip-addresses/ """ from typing import List class Solution: def restoreIpAddresses(self, s: str) -> List[str]: # Presumption: s only contains digit chars. n, rslt, chkRange = len(s), [], [1, 2, 3] for w1 in chkRange: for w2 in chkRange: ...
""" https://leetcode.com/problems/path-with-minimum-effort/ """ from typing import List from heapq import heappush, heappop class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: """ 1. Take each cell as a node and the effort when traveling from one cell to a...
""" https://leetcode.com/problems/numbers-with-repeated-digits/ """ from math import perm class Solution: def numDupDigitsAtMostN(self, n: int) -> int: """ 1. Transfer the problem to find the total number of positive integers that have non-repeating digits. 2. Suppose n has k...
""" https://leetcode.com/problems/backspace-string-compare/ """ from itertools import zip_longest class Solution: def backspaceCompare(self, S: str, T: str) -> bool: def gen(s: str) -> str: """ Start to check from the end of the input string s, so that we could make s...
""" https://leetcode.com/problems/construct-the-rectangle/ """ from typing import List class Solution: def constructRectangle(self, area: int) -> List[int]: """ L is always greater or equal to W, which means area = L*W >= W^2, so we have W <= area^0.5. Then we could scan from the largest...
""" https://leetcode.com/problems/single-number/ """ from typing import List class Solution: def singleNumber(self, nums: List[int]) -> int: """ Use exclusive or action on each number in the nums. Since a ^ b ^ a = a ^ a ^ b = 0 ^ b = b, after walking through all the number we wi...
""" https://leetcode.com/problems/check-if-a-string-can-break-another-string/ """ class Solution: def checkIfCanBreak(self, s1: str, s2: str) -> bool: ss1, ss2 = sorted(s1), sorted(s2) return ( all(c1 >= c2 for c1, c2 in zip(ss1, ss2)) or all(c1 <= c2 for c1, c2 in zip(ss1,...
""" https://leetcode.com/problems/game-of-life/ """ from typing import List class Solution: def gameOfLife(self, board: List[List[int]]): """ The below solution are the normal case when the board is not too large. Suppose the board is infinite, a possible idea could be: In orde...
""" https://leetcode.com/problems/diagonal-traverse-ii/ """ from collections import defaultdict class Solution: def findDiagonalOrder(self, nums: list[list[int]]) -> list[int]: """ 1. For elements on the same diagonal, their row + col are equal to each other. 2. Then we could...
""" https://leetcode.com/problems/peak-index-in-a-mountain-array/ """ class Solution: def peakIndexInMountainArray(self, arr: list[int]) -> int: l, r = 0, len(arr) - 1 while l < r: m = l + ((r - l) >> 1) if arr[m] < arr[m + 1]: l = m + 1 else: ...
""" https://leetcode.com/problems/smallest-string-with-swaps/ """ from collections import defaultdict class DSU: def __init__(self, size: int) -> None: self.parents = list(range(size)) def find(self, x: int) -> int: if self.parents[x] != x: self.parents[x] = self.find(self.paren...
""" https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/ """ class Solution: def minDifficulty(self, jobDifficulty: list[int], d: int) -> int: def dfs(start: int, remainingDays: int) -> int: if (start, remainingDays) not in memo: if remainingDays == 1: # Only on...
""" https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ """ from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 rslt, minPrice = 0, prices[0] for price in prices: if price < minPrice: ...
""" https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ """ class Solution: def canMakeArithmeticProgression(self, arr: list[int]) -> bool: if len(arr) < 3: return True sortedArr = sorted(arr) for end in range(2, len(sortedArr)): if sortedA...
""" https://leetcode.com/problems/power-of-four/ """ class Solution: def isPowerOfFour(self, num: int) -> bool: """ 1. num must be greater than zero. 2. num must be a power of 2. 3. for power of 4, the position of the only bit 1 should be in an odd position. """...
""" https://leetcode.com/problems/boats-to-save-people/ """ from typing import List class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: weights = sorted(people) l, r, boats = 0, len(weights) - 1, 0 while l <= r: # Either the heaviest person cannot ...
""" https://leetcode.com/problems/score-of-parentheses/ """ class Solution: def scoreOfParentheses(self, S: str) -> int: stack = [] for c in S: if c == '(': stack.append(c) else: score = 0 while stack[-1] != '(': ...
""" https://leetcode.com/problems/valid-parentheses/ """ class Solution: def isValid(self, s: 'str') -> 'bool': workStack = [] refDict = {')': '(', ']': '[', '}': '{'} for c in s: if c in refDict: # New close bracket. if workStack: chkChar ...
""" https://leetcode.com/problems/even-odd-tree/ """ from test_helper import TreeNode class Solution: def isEvenOddTree(self, root: TreeNode) -> bool: level = 0 allNodesInCurrentLevel = [root] while allNodesInCurrentLevel: allNodesInNextLevel: list[TreeNode] = [] ...
""" https://leetcode.com/problems/accounts-merge/ """ from typing import List from collections import defaultdict class DSU: def __init__(self, size: int): self._parents = list(range(size + 1)) def find_ancestor(self, x: int) -> int: """ For all ancestors, its parent equals to its...
""" https://leetcode.com/problems/is-subsequence/ """ from bisect import bisect_left class Solution: def isSubsequence(self, s: str, t: str) -> bool: if not s: return True start, end = 0, len(s) for c in t: if c == s[start]: start += 1 ...
""" https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/ """ from collections import Counter class Solution: def maxFreq( self, s: str, maxLetters: int, minSize: int, maxSize: int ) -> int: """ 1. If a string has x occurrences, it...
""" https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/ """ class Solution: def maximumTime(self, time: str) -> str: time = list(time) if time[0] == '?': if int(time[1] if time[1] != '?' else 0) <= 3: time[0] = '2' else: tim...
""" https://leetcode.com/problems/invert-binary-tree/ """ from test_helper import TreeNode from collections import deque class Solution: def invertTree(self, root: TreeNode) -> TreeNode: queue = deque([root]) while queue: currNode = queue.popleft() if currNode: ...
""" https://leetcode.com/problems/contains-duplicate-ii/ """ from typing import List class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: memo = {} # number:index. for i, num in enumerate(nums): if num in memo and i <= k + memo[num]: re...
""" https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ """ class Solution: def maxDistance(self, nums1: list[int], nums2: list[int]) -> int: i = j = 0 maxDistance = 0 while i < len(nums1) and j < len(nums2): if nums1[i] > nums2[j]: i += 1 ...
""" https://leetcode.com/problems/find-right-interval/ """ from typing import List from bisect import bisect_left class Solution: def findRightInterval(self, intervals: List[List[int]]) -> List[int]: """ Presumptions: 1. The start of each interval is unique. 2. For each interval...
""" https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/ """ class Solution: def findBestValue(self, arr: list[int], target: int) -> int: """ Simply sorte the list in reverse order, then starting checking the minimum number at the tail of the sorted list: 1. If cu...
""" https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ """ from typing import List class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: """ The question equals to find the total number of the minimum overlapped intervals. """ ...
""" https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ """ class Solution: def getNoZeroIntegers(self, n: int) -> list[int]: def is_zero_integer(x: int) -> bool: return '0' in str(x) for x in range(1, (n >> 1) + 1): y = n - x if n...
""" https://leetcode.com/problems/spiral-matrix/ """ from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: # List is empty or None. return [] startRow, startCol = 0, 0 endRow, endCol = len(matrix) - 1, len(matrix[...
""" https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ """ from test_helper import TreeNode class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: currNode = root stack = [] currSum = 0 while currNode or stack: while currNode: ...
""" https://leetcode.com/problems/search-suggestions-system/ """ from bisect import bisect_left class Solution: def suggestedProducts( self, products: list[str], searchWord: str ) -> list[list[str]]: sortedWords = sorted(products) prefix = '' rslt = [] ...
""" https://leetcode.com/problems/distance-between-bus-stops/ """ class Solution: def distanceBetweenBusStops( self, distance: list[int], start: int, destination: int ) -> int: if start == destination: return 0 if start > destination: re...
""" https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ """ from typing import List class Solution: def findLongestWord(self, s: str, d: List[str]) -> str: for t in sorted(d, key=lambda x: (-len(x), x)): iterS = iter(s) if all(c in iterS for c in t): ...