text stringlengths 37 1.41M |
|---|
#Given an integer num, return a string of its base 7 representation.
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0: return '0'
map = '0123456'
result = ''
neg = False
if num < 0:
neg= True
num = -nu... |
'''
A perfectly straight street is represented by a number line. The street has building(s) on it and is represented by a 2D integer array buildings, where buildings[i] = [starti, endi, heighti]. This means that there is a building with heighti in the half-closed segment [starti, endi).
You want to describe the height... |
'''
An ugly number is a positive integer that is divisible by a, b, or c.
Given four integers n, a, b, and c, return the nth ugly number.
'''
from math import gcd
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
def lcm( x, y):
# Fro... |
'''
You are given an elevation map represents as an integer array heights where heights[i] representing the height of the terrain at index i. The width at each index is 1. You are also given two integers volume and k. volume units of water will fall at index k.
Water first drops at the index k and rests on top of the... |
'''
You are given an array points where points[i] = [xi, yi] represents a point on an X-Y plane.
Straight lines are going to be added to the X-Y plane, such that every point is covered by at least one line.
Return the minimum number of straight lines needed to cover all the points.
'''
Explanation
The data scale for... |
'''
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given a... |
'''
(This problem is an interactive problem.)
Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship.
You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one sh... |
'''
In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return ... |
'''
You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
'''
'''
Intuition
Do this first:
Given pref, find arr that
pref[i] = arr[0] + ... |
'''
You are given a 0-indexed integer array nums of size n and a positive integer k.
We call an index i in the range k <= i < n - k good if the following conditions are satisfied:
The k elements that are just before the index i are in non-increasing order.
The k elements that are just after the index i are in non-dec... |
You are given a positive integer n representing the number of nodes in a connected undirected graph containing exactly one cycle. The nodes are numbered from 0 to n - 1 (inclusive).
You are also given a 2D integer array edges, where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting node... |
'''
Given three integer arrays nums1, nums2, and nums3, return a
distinct array containing all the values that are present in at
least two out of the three arrays. You may return the values in any order.
'''
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int... |
'''
A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators. In this ... |
'''
A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
It can jump exactly a positions forward (to the right).
It can jump exactly b positions backward (to the left).
It cannot jump backward twice in a row.
It cannot jump to any fo... |
'''
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference
between pairs (nums[w], num... |
'''
Напишите функцию fizzbuzztest, которая возвращает массив, который формируется по следующим правилам:
Обрабатываются числа от 1 до 100
Если число кратно трем, то в массив заносим слово Fizz
Если число кратно пяти, то в массив заносим слово Buzz
Если число кратно и трем, и пяти, то в массив заносим слово FizzBuzz
Ес... |
'''
Given a string s, find the length of the longest substring without repeating characters.
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = 0
r = 0
res = 0
seen = set()
while l < len(s):
seen.clear()
r = l
... |
'''
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.
The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed).
Find the kth largest value (1-indexed) of all the coordinates of matrix.... |
'''
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one
stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achi... |
'''
You are given the head of a linked list.
Remove every node which has a node with a strictly greater value anywhere to the right side of it.
Return the head of the modified linked list.
'''
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse(n: ListNode) -> ListNode... |
'''
На вход подается массив arr состоящий из
произвольного количества кортежей, в каждом из которых
также содержится произвольное количество элементов. Необходимо написать фукнцию flat, которая будет возвращать список из всех элементов, входящих в состав каждого кортежа.
'''
import itertools
class Answer:
def ... |
'''
You are given an integer n. A perfectly straight street is represented by a number line ranging from 0 to n - 1. You are given a 2D integer array lights representing the street lamp(s) on the street. Each lights[i] = [positioni, rangei] indicates that there is a street lamp at position positioni that lights up the... |
'''
The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that... |
'''
Given a positive integer n, find the sum of all integers in the range [1, n] inclusive that are divisible by 3, 5, or 7.
Return an integer denoting the sum of all numbers in the given range satisfying the constraint.
'''
class Solution:
def sumOfMultiples(self, n: int) -> int:
res = 0
for i... |
'''
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.
When writing suc... |
'''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" c... |
'''
Given a non-negative integer num, Return its encoding string.
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:
'''
class Solution:
def encode(self, num: int) -> str:
return str(bin(num+1))[3:]
-------------------... |
'''
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree
nodes with value val as cur's le... |
'''
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
'''
def pruneTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
... |
'''
Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character
otherwise it is denoted by a '.' character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot
see the answers of the stu... |
'''
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.
'''
class Solution:
def longestUnivaluePath... |
'''
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the FreqStack class:
FreqStack() constructs an empty frequency stack.
void push(int val) pushes an integer val onto the top of the stack.
int pop() removes and returns the most frequent ele... |
'''
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differ... |
'''
Given a binary string s, return the number of substrings
with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.
'''
def numSub(self, s: str) -> int:
ans = cum = 0
for x in s:
if x == "1":
cum+=1
ans+=cum
else:
cum = 0
r... |
'''
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.
In one move, you can either:
Increment the current integer by one (i.e., x = x + 1).
Double the current integer (i.e., x = 2 * x).
You can use the increment operation any number of times, however, you can ... |
'''
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[... |
'''
You are given two string arrays words1 and words2.
A string b is a subset of string a if every letter in b occurs in a including multiplicity.
For example, "wrr" is a subset of "warrior" but is not a subset of "world".
A string a from words1 is universal if for every string b in words2, b is a subset of a.
Retur... |
'''
Given an integer n, return a list
of integers from 1 to n as strings except
for multiples of 3 use “Fizz” instead of the
integer and for the multiples of 5 use “Buzz”. For integers
which are multiples of both 3 and 5 use “FizzBuzz”.
'''
class Solution:
def solve(self, n):
res = list()
f... |
'''
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
'''
#my own solution - O(nlogn)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
... |
'''
Толя-Карп запросил для себя n посылок с «Аллигатор-экспресс».
Посылка представляет из себя ящик. Внутри ящика лежит целое число ai. Номер на ящике di указывает на цвет числа, лежащего внутри.
Толю-Карпа интересует, чему будут равны значения чисел, если сложить между собой все те, что имеют одинаковый цвет. Напиши... |
'''
Given the root of a binary tree, return the length of the longest consecutive path in the tree.
A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.
For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but th... |
# Given a sorted array, A, with possibly duplicated elements,
# find the indices of the first and last occurrences of a
# target element, x. Return -1 if the target is not found.
def first_last(l, target):
res = list()
for i in range(len(l)):
if l[i] == target:
if len(res) == 0:
res.append(i)
... |
'''
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
'''
... |
'''
A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10
as shown in the figure above.
Given the array reservedSeats containing the numbers of seats already
reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is ... |
'''
You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree.
A binary search tree is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node... |
#An array is monotonic if it is either monotone increasing or monotone decreasing.
#An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
#Return true if and only if the given array A is monotonic.
class Solution:
def isMonotonic(s... |
'''
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test c... |
'''
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
'''
class Solution:
def preorder(self, root: 'Node') -> List[int]:
def ... |
#my annoying solution
'''
Your code needs to read the
current time from the standard input stream (console). The input
format is such as hh:mm:ss, which represents hour, minute, and second respectively, and
then a positive integer x is given to find the elapsed time. The time after x seconds is
expressed, and the... |
'''
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.
Du... |
'''
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
'''
class Solution:
def validPalindrome(self, s: str) -> bool:
l = 0
r = len(s)-1
while l <= r:
if s[l] != s[r]:
s1 = s[:l] + s[(l+1):]
... |
'''
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".
'''
class Solution:
def longestDupSubs... |
'''
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by l... |
'''
You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.
To cut a piece of wood, you must m... |
#my code - actually good solution
if __name__ == "__main__":
l = list(map(int, input().split()))
min1 = l[0]
changed = False
for i in range(len(l)):
if l[i] < min1 and l[i] % 2 == 0:
changed = True
min1 = l[i]
if not changed:
print('no existe: -1')
else:
... |
'''
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choo... |
'''
You are given a list of integers cells, representing sizes of different cells. In each iteration, the two largest cells a and b interact according to these rules:
If a = b, they both die.
Otherwise, the two cells merge and their size becomes floor((a + b) / 3).
Return the size of the last cell or return -1 if ther... |
'''
You are given a stream of points on the X-Y plane. Design an algorithm that:
Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.
Given a query point, counts the number of ways to choose three points from the data structure such that the thr... |
'''
You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
A subsequence ... |
'''
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... |
'''
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
'''
class Solution:
def countPairs(... |
'''
Given a m x n grid filled
with non-negative numbers, find a path
from top left to bottom right which minimizes
the sum of all numbers along its path.
Note: You can only move either down or right at any point in time
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
s = 0
... |
'''
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are giv... |
'''
This is an interactive problem.
There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and nei... |
'''
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
'''
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
count= 0
fo... |
'''
You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.
Your goal is to satisfy one of the following three conditions:
Every letter in a is strictly less than every letter in b in the alphabet.
Every letter in b is stri... |
'''
You are playing a game that has n levels numbered from 0 to n - 1. You are given a 0-indexed integer array damage where damage[i] is the amount of health you will lose to complete the ith level.
You are also given an integer armor. You may use your armor ability at most once during the game on any level which wil... |
'''
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
'''
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(nums2) < len(nums1): nums... |
'''
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right... |
'''
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].
Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo ... |
'''
You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents:
A land cell if grid[r][c] = 0, or
A water cell containing grid[r][c] fish, if grid[r][c] > 0.
A fisher can start at any water cell (r, c) and can do the following operations any number of times:
Catch all the fish at cell (r, c), or
... |
'''
You are given an array nums consisting of positive integers.
Split the array into one or more disjoint subarrays such that:
Each element of the array belongs to exactly one subarray, and
The GCD of the elements of each subarray is strictly greater than 1.
Return the minimum number of subarrays that can be obtaine... |
'''
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
'''
class Solution:
def kSimilarity(self, s1: str, ... |
'''
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Return the maximum score you can get by erasing exactly one subarray.
An array b is called to be a subarray of a if it forms a co... |
'''
The score of an array is defined as the product of its sum and its length.
For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.
Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.
A subarray is a contiguo... |
'''
You are given a 0-indexed integer array nums of length n.
The average difference of the index i is the absolute difference between the average of
the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.
Return the index with the... |
'''
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a score. To find the score of a node, consider ... |
'''
There is a function signFunc(x) that returns:
1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.
You are given an integer array nums. Let product be the product of all values in the array nums.
Return signFunc(product).
'''
#my own solution
class Solution:
def arraySign(self, nums: List[int]) ->... |
'''
A happy string is a string that:
consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given tw... |
'''
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
'''
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
digit... |
'''
You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.
The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0.
The value of the character is defined in the following way:
If... |
'''
Given a 0-indexed integer array nums, return the number of
subarrays
of nums having an even product.
'''
from collections import defaultdict
class Solution:
def evenProduct(self, nums: List[int]) -> int:
i = -1
res = 0
for j,num in enumerate(nums):
if num%2 == 0:
... |
'''
Given a list of integers prices representing the stock prices of a company in chronological order, return the
maximum profit you could have made from buying and selling that stock any number of times.
You must buy before you can sell it. But you are not required to buy or sell the stock.
'''
class Solution:
... |
'''
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.
The grammar can best be understood through simple examples:
Single letters represent a singleton set containing that word.
R("a") = {"a"}
R("w") = {"w"}
When we take a comm... |
'''
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# ... |
'''
You are given the head of a linked list.
The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,
The 1st node is assigned to the first group.
Th... |
'''
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
'''
class Solution:
def ... |
'''
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the smallest sorted list of ranges that cover every missing number exactly. That ... |
'''
Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.
Return how many groups have the largest size.
'''
class Solution:
def countLargestGroup(self, n: int) -> int:
list_sums = dict.fromkeys([i for i in range(1,37)])
for i in list_sums.keys():
... |
'''
There are n people, each person has a unique id between
0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.
Level 1 of videos are all
watched videos by your friends, level 2... |
'''
Given an integer n, return a binary string representing its representation in base -2.
Note that the returned string should not have leading zeros unless the string is "0".
'''
class Solution:
def baseNeg2(self, N: int) -> str:
if N in [0, 1]: return str(N)
if N % 2 == 0:
return se... |
class TrieNode():
def __init__(self):
self.child = defaultdict(TrieNode)
class Trie():
def __init__(self):
self.root = TrieNode()
self.list = []
def add(self, word):
node = self.root
for ch in word:
node = node.child[ch]
self.list.append((node, len(word)+1))
class Solution(obj... |
'''
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more... |
'''
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of s... |
'''
Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels.
A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.
Example 1:
Input: picture = [["W","W","B"],["W","B",... |
'''
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.
Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence ... |
'''
Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values ... |
'''
There are n servers numbered from 0 to n - 1 connected by undirected
server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection
between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connectio... |
'''
Given a string s, partition s such that every
substring
of the partition is a
palindrome
.
Return the minimum cuts needed for a palindrome partitioning of s.
'''
# python code
class Solution(object):
def minCut(self, s):
"""
s="abcgcbafj"
:type s: str
:rtype: int
""... |
'''
Please complete the code in solution.py to realize the function
of reverse_k_group. The reverse_k_group function has two parameters: the string str_in and the
positive integer k. Given a string, reverse each of k characters, and finally returns the updated string.
If the last remaining strings are less than k, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.