task_id stringlengths 3 79 | prompt stringlengths 255 3.9k |
|---|---|
sort-transformed-array | def sortTransformedArray(nums: List[int], a: int, b: int, c: int) -> List[int]:
"""
Given a sorted integer array nums and three integers a, b and c, apply a quadratic function of the form f(x) = ax2 + bx + c to each element nums[i] in the array, and return the array in a sorted order.
Example 1:
>>... |
bomb-enemy | def maxKilledEnemies(grid: List[List[str]]) -> int:
"""
Given an m x n matrix grid where each cell is either a wall 'W', an enemy 'E' or empty '0', return the maximum enemies you can kill using one bomb. You can only place the bomb in an empty cell.
The bomb kills all the enemies in the same row and column ... |
max-sum-of-rectangle-no-larger-than-k | def maxSumSubmatrix(matrix: List[List[int]], k: int) -> int:
"""
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.
It is guaranteed that there will be a rectangle with a sum no larger than k.
Example 1:
... |
water-and-jug-problem | def canMeasureWater(x: int, y: int, target: int) -> bool:
"""
You are given two jugs with capacities x liters and y liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach target using the following operations:
Fill either jug completely with water.
... |
find-leaves-of-binary-tree | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findLeaves(root: Optional[TreeNode]) -> List[List[int]]:
"""
Given the root of a binary tree, collect a tree's nodes as if you were doing t... |
valid-perfect-square | def isPerfectSquare(num: int) -> bool:
"""
Given a positive integer num, return true if num is a perfect square or false otherwise.
A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library functi... |
largest-divisible-subset | def largestDivisibleSubset(nums: List[int]) -> List[int]:
"""
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
answer[i] % answer[j] == 0, or
answer[j] % answer[i] == 0
If ther... |
plus-one-linked-list | # class ListNode:
# def __init__(val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def plusOne(head: Optional[ListNode]) -> Optional[ListNode]:
"""
Given a non-negative integer represented as a linked list of digits, plus one to the integer.
The digits are stored... |
range-addition | def getModifiedArray(length: int, updates: List[List[int]]) -> List[int]:
"""
You are given an integer length and an array updates where updates[i] = [startIdxi, endIdxi, inci].
You have an array arr of length length with all zeros, and you have some operation to apply on arr. In the ith operation, you shou... |
sum-of-two-integers | def getSum(a: int, b: int) -> int:
"""
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Example 1:
>>> getSum(a = 1, b = 2)
>>> 3
Example 2:
>>> getSum(a = 2, b = 3)
>>> 5
"""
|
find-k-pairs-with-smallest-sums | def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
"""
You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.
Define a pair (u, v) which consists of one element from the first array and one element from the second array.
Return t... |
guess-number-higher-or-lower-ii | def getMoneyAmount(n: int) -> int:
"""
We are playing the Guessing Game. The game will work as follows:
I pick a number between 1 and n.
You guess a number.
If you guess the right number, you win the game.
If you guess the wrong number, then I will tell you whether the number I picked is hi... |
wiggle-subsequence | def wiggleMaxLength(nums: List[int]) -> int:
"""
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equ... |
combination-sum-iv | def combinationSum4(nums: List[int], target: int) -> int:
"""
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
The test cases are generated so that the answer can fit in a 32-bit integer.
Example 1:
>>> ... |
kth-smallest-element-in-a-sorted-matrix | def kthSmallest(matrix: List[List[int]], k: int) -> int:
"""
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
You must find a s... |
ransom-note | def canConstruct(ransomNote: str, magazine: str) -> bool:
"""
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
>>> canConstruct(... |
lexicographical-numbers | def lexicalOrder(n: int) -> List[int]:
"""
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.
Example 1:
>>> lexicalOrder(n = 13)
>>> [1,10,11,12,13,2,3,4,5,6,7,8,9]
... |
first-unique-character-in-a-string | def firstUniqChar(s: str) -> int:
"""
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Example 1:
>>> firstUniqChar(s = "leetcode")
>>> 0
Explanation:
The character 'l' at index 0 is the first character that does ... |
longest-absolute-file-path | def lengthLongestPath(input: str) -> int:
"""
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contai... |
find-the-difference | def findTheDifference(s: str, t: str) -> str:
"""
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
>>> findTheDifference(s = "abcd", t = "abcde")
... |
elimination-game | def lastRemaining(n: int) -> int:
"""
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:
Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
Repea... |
perfect-rectangle | def isRectangleCover(rectangles: List[List[int]]) -> bool:
"""
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
Return true if all the rectangles together form ... |
is-subsequence | def isSubsequence(s: str, t: str) -> bool:
"""
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions o... |
utf-8-validation | def validUtf8(data: List[int]) -> bool:
"""
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
For a... |
decode-string | def decodeString(s: str) -> str:
"""
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input strin... |
longest-substring-with-at-least-k-repeating-characters | def longestSubstring(s: str, k: int) -> int:
"""
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
if no such substring exists, return 0.
Example 1:
>>> longestSubstr... |
rotate-function | def maxRotateFunction(nums: List[int]) -> int:
"""
You are given an integer array nums of length n.
Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
... |
integer-replacement | def integerReplacement(n: int) -> int:
"""
Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:... |
evaluate-division | def calcEquation(equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
"""
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a strin... |
nth-digit | def findNthDigit(n: int) -> int:
"""
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].
Example 1:
>>> findNthDigit(n = 3)
>>> 3
Example 2:
>>> findNthDigit(n = 11)
>>> 0
Explanation: The 11th digit ... |
binary-watch | def readBinaryWatch(turnedOn: int) -> List[str]:
"""
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
For example, the below binary watch reads "4... |
remove-k-digits | def removeKdigits(num: str, k: int) -> str:
"""
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Example 1:
>>> removeKdigits(num = "1432219", k = 3)
>>> "1219"
Explanation: Remove the thr... |
frog-jump | def canCross(stones: List[int]) -> bool:
"""
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 or... |
sum-of-left-leaves | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(root: Optional[TreeNode]) -> int:
"""
Given the root of a binary tree, return the sum of all left leaves.
A leaf is a n... |
convert-a-number-to-hexadecimal | def toHex(num: int) -> str:
"""
Given a 32-bit integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except... |
queue-reconstruction-by-height | def reconstructQueue(people: List[List[int]]) -> List[List[int]]:
"""
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height ... |
trapping-rain-water-ii | def trapRainWater(heightMap: List[List[int]]) -> int:
"""
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Example 1:
>>> trapRainWater(heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2... |
valid-word-abbreviation | def validWordAbbreviation(word: str, abbr: str) -> bool:
"""
A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.
For example, a string such as "substitution" could be abbreviated as (but not limited to):
... |
longest-palindrome | def longestPalindrome(s: str) -> int:
"""
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome.
Example 1:
>>> longes... |
split-array-largest-sum | def splitArray(nums: List[int], k: int) -> int:
"""
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.
Return the minimized largest sum of the split.
A subarray is a contiguous part of the array.
Example 1:... |
minimum-unique-word-abbreviation | def minAbbreviation(target: str, dictionary: List[str]) -> str:
"""
A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n" ("s ubstitutio n")
"sub4u4" ("sub ... |
fizz-buzz | def fizzBuzz(n: int) -> List[str]:
"""
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of th... |
arithmetic-slices | def numberOfArithmeticSlices(nums: List[int]) -> int:
"""
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Give... |
third-maximum-number | def thirdMax(nums: List[int]) -> int:
"""
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Example 1:
>>> thirdMax(nums = [3,2,1])
>>> 1
Explanation:
The first distinct maximum is 3.... |
add-strings | def addStrings(num1: str, num2: str) -> str:
"""
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the in... |
partition-equal-subset-sum | def canPartition(nums: List[int]) -> bool:
"""
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
>>> canPartition(nums = [1,5,11,5])
>>> true
Explanation: Th... |
pacific-atlantic-water-flow | def pacificAtlantic(heights: List[List[int]]) -> List[List[int]]:
"""
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is part... |
sentence-screen-fitting | def wordsTyping(sentence: List[str], rows: int, cols: int) -> int:
"""
Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen.
The order of words in the sentence must remain unchanged, and a word cannot be split i... |
battleships-in-a-board | def countBattleships(board: List[List[str]]) -> int:
"""
Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (... |
strong-password-checker | def strongPasswordChecker(password: str) -> int:
"""
A password is considered strong if the below conditions are all met:
It has at least 6 characters and at most 20 characters.
It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.
It does not contain... |
maximum-xor-of-two-numbers-in-an-array | def findMaximumXOR(nums: List[int]) -> int:
"""
Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
Example 1:
>>> findMaximumXOR(nums = [3,10,5,25,2,8])
>>> 28
Explanation: The maximum result is 5 XOR 25 = 28.
Example 2:
... |
valid-word-square | def validWordSquare(words: List[str]) -> bool:
"""
Given an array of strings words, return true if it forms a valid word square.
A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns).
Example 1:
>>> vali... |
reconstruct-original-digits-from-english | def originalDigits(s: str) -> str:
"""
Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.
Example 1:
>>> originalDigits(s = "owoztneoer")
>>> "012"
Example 2:
>>> originalDigits(s = "fviefuro")
>>> "45"
"""
|
longest-repeating-character-replacement | def characterReplacement(s: str, k: int) -> int:
"""
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 le... |
word-squares | def wordSquares(words: List[str]) -> List[List[str]]:
"""
Given an array of unique strings words, return all the word squares you can build from words. The same word from words can be used multiple times. You can return the answer in any order.
A sequence of strings forms a valid word square if the kth row ... |
minimum-genetic-mutation | def minMutation(startGene: str, endGene: str, bank: List[str]) -> int:
"""
A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.
Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined a... |
number-of-segments-in-a-string | def countSegments(s: str) -> int:
"""
Given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
Example 1:
>>> countSegments(s = "Hello, my name is John")
>>> 5
Explanation: The five segments are ["Hello... |
non-overlapping-intervals | def eraseOverlapIntervals(intervals: List[List[int]]) -> int:
"""
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note that intervals which only touch at a point are non-ov... |
find-right-interval | def findRightInterval(intervals: List[List[int]]) -> List[int]:
"""
You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.
The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.
Return ... |
path-sum-iii | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(root: Optional[TreeNode], targetSum: int) -> int:
"""
Given the root of a binary tree and an integer targetSum, return the number o... |
find-all-anagrams-in-a-string | def findAnagrams(s: str, p: str) -> List[int]:
"""
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
Example 1:
>>> findAnagrams(s = "cbaebabacd", p = "abc")
>>> [0,6]
Explanation:
The substring with st... |
ternary-expression-parser | def parseTernary(expression: str) -> str:
"""
Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it.
You can always assume that the given expression is valid and only contains digits, '?', ':', 'T', and 'F' where 'T' is true and '... |
k-th-smallest-in-lexicographical-order | def findKthNumber(n: int, k: int) -> int:
"""
Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].
Example 1:
>>> findKthNumber(n = 13, k = 2)
>>> 10
Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so ... |
arranging-coins | def arrangeCoins(n: int) -> int:
"""
You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.
Given the integer n, return the number of complete rows of the staircase you will... |
find-all-duplicates-in-an-array | def findDuplicates(nums: List[int]) -> List[int]:
"""
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears at most twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses onl... |
string-compression | def compress(chars: List[str]) -> int:
"""
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the chara... |
sequence-reconstruction | def sequenceReconstruction(nums: List[int], sequences: List[List[int]]) -> bool:
"""
You are given an integer array nums of length n where nums is a permutation of the integers in the range [1, n]. You are also given a 2D integer array sequences where sequences[i] is a subsequence of nums.
Check if nums is ... |
add-two-numbers-ii | # class ListNode:
# def __init__(val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
"""
You are given two non-empty linked lists representing two non-negative integers. The most s... |
arithmetic-slices-ii-subsequence | def numberOfArithmeticSlices(nums: List[int]) -> int:
"""
Given an integer array nums, return the number of all the arithmetic subsequences of nums.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
... |
number-of-boomerangs | def numberOfBoomerangs(points: List[List[int]]) -> int:
"""
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Return th... |
find-all-numbers-disappeared-in-an-array | def findDisappearedNumbers(nums: List[int]) -> List[int]:
"""
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
Example 1:
>>> findDisappearedNumbers(nums = [4,3,2,7,8,2,3,1])
>>> [5,6]
... |
delete-node-in-a-bst | # class TreeNode:
# def __init__(val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
"""
Given a root node reference of a BST and a key, delete the node w... |
sort-characters-by-frequency | def frequencySort(s: str) -> str:
"""
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Return the sorted string. If there are multiple answers, return any of them.
Example 1:
... |
minimum-number-of-arrows-to-burst-balloons | def findMinArrowShots(points: List[List[int]]) -> int:
"""
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xe... |
minimum-moves-to-equal-array-elements | def minMoves(nums: List[int]) -> int:
"""
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1 elements of the array by 1.
Example 1:
>>> minMoves(nums = [1,2,3])
>>> 3
Explanation:... |
4sum-ii | def fourSumCount(nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
"""
Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
... |
assign-cookies | def findContentChildren(g: List[int], s: List[int]) -> int:
"""
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; a... |
132-pattern | def find132pattern(nums: List[int]) -> bool:
"""
Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
Example 1:
... |
circular-array-loop | def circularArrayLoop(nums: List[int]) -> bool:
"""
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:
If nums[i] is positive, move nums[i] steps forward, and
If nums[i... |
poor-pigs | def poorPigs(buckets: int, minutesToDie: int, minutesToTest: int) -> int:
"""
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have... |
repeated-substring-pattern | def repeatedSubstringPattern(s: str) -> bool:
"""
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
>>> repeatedSubstringPattern(s = "abab")
>>> true
Explanation: It is the substring "ab" twi... |
hamming-distance | def hammingDistance(x: int, y: int) -> int:
"""
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Example 1:
>>> hammingDistance(x = 1, y = 4)
>>> 2
... |
minimum-moves-to-equal-array-elements-ii | def minMoves2(nums: List[int]) -> int:
"""
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1.
Test cases are designed so that the answer will fit in a 32-bit intege... |
island-perimeter | def islandPerimeter(grid: List[List[int]]) -> int:
"""
You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly... |
can-i-win | def canIWin(maxChoosableInteger: int, desiredTotal: int) -> bool:
"""
In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
... |
optimal-account-balancing | def minTransfers(transactions: List[List[int]]) -> int:
"""
You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi.
Return the minimum number of transactions required to settle the... |
count-the-repetitions | def getMaxRepetitions(s1: str, n1: int, s2: str, n2: int) -> int:
"""
We define str = [s, n] as the string str which consists of the string s concatenated n times.
For example, str == ["abc", 3] =="abcabcabc".
We define that string s1 can be obtained from string s2 if we can remove some charac... |
unique-substrings-in-wraparound-string | def findSubstringInWraproundString(s: str) -> int:
"""
We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Given a string s, return the number of unique ... |
validate-ip-address | def validIPAddress(queryIP: str) -> str:
"""
Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leadin... |
convex-polygon | def isConvex(points: List[List[int]]) -> bool:
"""
You are given an array of points on the X-Y plane points where points[i] = [xi, yi]. The points form a polygon when joined sequentially.
Return true if this polygon is convex and false otherwise.
You may assume the polygon formed by given points is alwa... |
encode-string-with-shortest-length | def encode(s: str) -> str:
"""
Given a string s, encode the string such that its encoded length is the shortest.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. k should be a positive integer.
If an encoding process does not... |
concatenated-words | def findAllConcatenatedWordsInADict(words: List[str]) -> List[str]:
"""
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily dis... |
matchsticks-to-square | def makesquare(matchsticks: List[int]) -> bool:
"""
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one ... |
ones-and-zeroes | def findMaxForm(strs: List[str], m: int, n: int) -> int:
"""
You are given an array of binary strings strs and two integers m and n.
Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.
A set x is a subset of a set y if all elements of x are also eleme... |
heaters | def findRadius(houses: List[int], heaters: List[int]) -> int:
"""
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the posit... |
number-complement | def findComplement(num: int) -> int:
"""
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer ... |
total-hamming-distance | def totalHammingDistance(nums: List[int]) -> int:
"""
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.
Example 1:
... |
largest-palindrome-product | def largestPalindrome(n: int) -> int:
"""
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.
Example 1:
>>> largestPalindrome(n = 2)
>>> 987
Explanation: ... |
sliding-window-median | def medianSlidingWindow(nums: List[int], k: int) -> List[float]:
"""
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For example... |
magical-string | def magicalString(n: int) -> int:
"""
A magical string s consists of only '1' and '2' and obeys the following rules:
The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.
The first few elements of s is s = "1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.