Dataset Viewer
Auto-converted to Parquet Duplicate
task_id
stringlengths
3
79
prompt
stringlengths
255
3.9k
two-sum
def twoSum(nums: List[int], target: int) -> List[int]: """ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: >>> twoSum(nums = [2,7,11,15], target = 9) >>> [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: >>> twoSum(nums = [3,2,4], target = 6) >>> [1,2] Example 3: >>> twoSum(nums = [3,3], target = 6) >>> [0,1] """
add-two-numbers
# 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 digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1: >>> __init__(l1 = [2,4,3], l2 = [5,6,4]) >>> [7,0,8] Explanation: 342 + 465 = 807. Example 2: >>> __init__(l1 = [0], l2 = [0]) >>> [0] Example 3: >>> __init__(l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]) >>> [8,9,9,9,0,0,0,1] """
longest-substring-without-repeating-characters
def lengthOfLongestSubstring(s: str) -> int: """ Given a string s, find the length of the longest substring without repeating characters. Example 1: >>> lengthOfLongestSubstring(s = "abcabcbb") >>> 3 Explanation: The answer is "abc", with the length of 3. Example 2: >>> lengthOfLongestSubstring(s = "bbbbb") >>> 1 Explanation: The answer is "b", with the length of 1. Example 3: >>> lengthOfLongestSubstring(s = "pwwkew") >>> 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. """
median-of-two-sorted-arrays
def findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float: """ 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)). Example 1: >>> findMedianSortedArrays(nums1 = [1,3], nums2 = [2]) >>> 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: >>> findMedianSortedArrays(nums1 = [1,2], nums2 = [3,4]) >>> 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. """
longest-palindromic-substring
def longestPalindrome(s: str) -> str: """ Given a string s, return the longest palindromic substring in s. Example 1: >>> longestPalindrome(s = "babad") >>> "bab" Explanation: "aba" is also a valid answer. Example 2: >>> longestPalindrome(s = "cbbd") >>> "bb" """
zigzag-conversion
def convert(s: str, numRows: int) -> str: """ The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: >>> convert(s = "PAYPALISHIRING", numRows = 3) >>> "PAHNAPLSIIGYIR" Example 2: >>> convert(s = "PAYPALISHIRING", numRows = 4) >>> "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: >>> convert(s = "A", numRows = 1) >>> "A" """
reverse-integer
def reverse(x: int) -> int: """ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: >>> reverse(x = 123) >>> 321 Example 2: >>> reverse(x = -123) >>> -321 Example 3: >>> reverse(x = 120) >>> 21 """
string-to-integer-atoi
def myAtoi(s: str) -> int: """ Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Whitespace: Ignore any leading whitespace (" "). Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: >>> myAtoi(s = "42") >>> 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) ^ Example 2: >>> myAtoi(s = " -042") >>> -42 Explanation: Step 1: " -042" (leading whitespace is read and ignored) ^ Step 2: " -042" ('-' is read, so the result should be negative) ^ Step 3: " -042" ("042" is read in, leading zeros ignored in the result) ^ Example 3: >>> myAtoi(s = "1337c0d3") >>> 1337 Explanation: Step 1: "1337c0d3" (no characters read because there is no leading whitespace) ^ Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+') ^ Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit) ^ Example 4: >>> myAtoi(s = "0-1") >>> 0 Explanation: Step 1: "0-1" (no characters read because there is no leading whitespace) ^ Step 2: "0-1" (no characters read because there is neither a '-' nor '+') ^ Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit) ^ Example 5: >>> myAtoi(s = "words and 987") >>> 0 Explanation: Reading stops at the first non-digit character 'w'. """
palindrome-number
def isPalindrome(x: int) -> bool: """ Given an integer x, return true if x is a palindrome, and false otherwise. Example 1: >>> isPalindrome(x = 121) >>> true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: >>> isPalindrome(x = -121) >>> false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: >>> isPalindrome(x = 10) >>> false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. """
regular-expression-matching
def isMatch(s: str, p: str) -> bool: """ Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character.​​​​ '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example 1: >>> isMatch(s = "aa", p = "a") >>> false Explanation: "a" does not match the entire string "aa". Example 2: >>> isMatch(s = "aa", p = "a*") >>> true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: >>> isMatch(s = "ab", p = ".*") >>> true Explanation: ".*" means "zero or more (*) of any character (.)". """
container-with-most-water
def maxArea(height: List[int]) -> int: """ You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. Example 1: >>> maxArea(height = [1,8,6,2,5,4,8,3,7]) >>> 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example 2: >>> maxArea(height = [1,1]) >>> 1 """
integer-to-roman
def intToRoman(num: int) -> str: """ Seven different symbols represent Roman numerals with the following values: Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral. If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM). Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form. Given an integer, convert it to a Roman numeral. Example 1: >>> intToRoman(num = 3749) >>> "MMMDCCXLIX" Explanation: 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places Example 2: >>> intToRoman(num = 58) >>> "LVIII" Explanation: 50 = L 8 = VIII Example 3: >>> intToRoman(num = 1994) >>> "MCMXCIV" Explanation: 1000 = M 900 = CM 90 = XC 4 = IV """
roman-to-integer
def romanToInt(s: str) -> int: """ Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Example 1: >>> romanToInt(s = "III") >>> 3 Explanation: III = 3. Example 2: >>> romanToInt(s = "LVIII") >>> 58 Explanation: L = 50, V= 5, III = 3. Example 3: >>> romanToInt(s = "MCMXCIV") >>> 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. """
longest-common-prefix
def longestCommonPrefix(strs: List[str]) -> str: """ Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: >>> longestCommonPrefix(strs = ["flower","flow","flight"]) >>> "fl" Example 2: >>> longestCommonPrefix(strs = ["dog","racecar","car"]) >>> "" Explanation: There is no common prefix among the input strings. """
3sum
def threeSum(nums: List[int]) -> List[List[int]]: """ Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: >>> threeSum(nums = [-1,0,1,2,-1,-4]) >>> [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: >>> threeSum(nums = [0,1,1]) >>> [] Explanation: The only possible triplet does not sum up to 0. Example 3: >>> threeSum(nums = [0,0,0]) >>> [[0,0,0]] Explanation: The only possible triplet sums up to 0. """
3sum-closest
def threeSumClosest(nums: List[int], target: int) -> int: """ Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: >>> threeSumClosest(nums = [-1,2,1,-4], target = 1) >>> 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: >>> threeSumClosest(nums = [0,0,0], target = 1) >>> 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). """
letter-combinations-of-a-phone-number
def letterCombinations(digits: str) -> List[str]: """ Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1: >>> letterCombinations(digits = "23") >>> ["ad","ae","af","bd","be","bf","cd","ce","cf"] Example 2: >>> letterCombinations(digits = "") >>> [] Example 3: >>> letterCombinations(digits = "2") >>> ["a","b","c"] """
4sum
def fourSum(nums: List[int], target: int) -> List[List[int]]: """ Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < n a, b, c, and d are distinct. nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order. Example 1: >>> fourSum(nums = [1,0,-1,0,-2,2], target = 0) >>> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] Example 2: >>> fourSum(nums = [2,2,2,2,2], target = 8) >>> [[2,2,2,2]] """
remove-nth-node-from-end-of-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(head: Optional[ListNode], n: int) -> Optional[ListNode]: """ Given the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: >>> __init__(head = [1,2,3,4,5], n = 2) >>> [1,2,3,5] Example 2: >>> __init__(head = [1], n = 1) >>> [] Example 3: >>> __init__(head = [1,2], n = 1) >>> [1] """
valid-parentheses
def isValid(s: str) -> bool: """ Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. Example 1: >>> isValid(s = "()") >>> true Example 2: >>> isValid(s = "()[]{}") >>> true Example 3: >>> isValid(s = "(]") >>> false Example 4: >>> isValid(s = "([])") >>> true """
merge-two-sorted-lists
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: """ You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: >>> __init__(list1 = [1,2,4], list2 = [1,3,4]) >>> [1,1,2,3,4,4] Example 2: >>> __init__(list1 = [], list2 = []) >>> [] Example 3: >>> __init__(list1 = [], list2 = [0]) >>> [0] """
generate-parentheses
def generateParenthesis(n: int) -> List[str]: """ Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: >>> generateParenthesis(n = 3) >>> ["((()))","(()())","(())()","()(())","()()()"] Example 2: >>> generateParenthesis(n = 1) >>> ["()"] """
merge-k-sorted-lists
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(lists: List[Optional[ListNode]]) -> Optional[ListNode]: """ You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: >>> __init__(lists = [[1,4,5],[1,3,4],[2,6]]) >>> [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 Example 2: >>> __init__(lists = []) >>> [] Example 3: >>> __init__(lists = [[]]) >>> [] """
swap-nodes-in-pairs
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(head: Optional[ListNode]) -> Optional[ListNode]: """ Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) Example 1: >>> __init__(head = [1,2,3,4]) >>> [2,1,4,3] Explanation: Example 2: >>> __init__(head = []) >>> [] Example 3: >>> __init__(head = [1]) >>> [1] Example 4: >>> __init__(head = [1,2,3]) >>> [2,1,3] """
reverse-nodes-in-k-group
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(head: Optional[ListNode], k: int) -> Optional[ListNode]: """ Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed. Example 1: >>> __init__(head = [1,2,3,4,5], k = 2) >>> [2,1,4,3,5] Example 2: >>> __init__(head = [1,2,3,4,5], k = 3) >>> [3,2,1,4,5] """
remove-duplicates-from-sorted-array
def removeDuplicates(nums: List[int]) -> int: """ Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things: Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted. Example 1: >>> removeDuplicates(nums = [1,1,2]) >>> 2, nums = [1,2,_] Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: >>> removeDuplicates(nums = [0,0,1,1,1,2,2,3,3,4]) >>> 5, nums = [0,1,2,3,4,_,_,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). """
remove-element
def removeElement(nums: List[int], val: int) -> int: """ Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things: Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted. Example 1: >>> removeElement(nums = [3,2,2,3], val = 3) >>> 2, nums = [2,2,_,_] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: >>> removeElement(nums = [0,1,2,2,3,0,4,2], val = 2) >>> 5, nums = [0,1,4,0,3,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). """
find-the-index-of-the-first-occurrence-in-a-string
def strStr(haystack: str, needle: str) -> int: """ Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: >>> strStr(haystack = "sadbutsad", needle = "sad") >>> 0 Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. Example 2: >>> strStr(haystack = "leetcode", needle = "leeto") >>> -1 Explanation: "leeto" did not occur in "leetcode", so we return -1. """
divide-two-integers
def divide(dividend: int, divisor: int) -> int: """ Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231. Example 1: >>> divide(dividend = 10, divisor = 3) >>> 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: >>> divide(dividend = 7, divisor = -3) >>> -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2. """
substring-with-concatenation-of-all-words
def findSubstring(s: str, words: List[str]) -> List[int]: """ You are given a string s and an array of strings words. All the strings of words are of the same length. A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated. For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated string because it is not the concatenation of any permutation of words. Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order. Example 1: >>> findSubstring(s = "barfoothefoobarman", words = ["foo","bar"]) >>> [0,9] Explanation: The substring starting at 0 is "barfoo". It is the concatenation of ["bar","foo"] which is a permutation of words. The substring starting at 9 is "foobar". It is the concatenation of ["foo","bar"] which is a permutation of words. Example 2: >>> findSubstring(s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]) >>> [] Explanation: There is no concatenated substring. Example 3: >>> findSubstring(s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]) >>> [6,9,12] Explanation: The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"]. The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"]. The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"]. """
next-permutation
def nextPermutation(nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ """ A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). For example, the next permutation of arr = [1,2,3] is [1,3,2]. Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory. Example 1: >>> nextPermutation(nums = [1,2,3]) >>> [1,3,2] Example 2: >>> nextPermutation(nums = [3,2,1]) >>> [1,2,3] Example 3: >>> nextPermutation(nums = [1,1,5]) >>> [1,5,1] """
longest-valid-parentheses
def longestValidParentheses(s: str) -> int: """ Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring. Example 1: >>> longestValidParentheses(s = "(()") >>> 2 Explanation: The longest valid parentheses substring is "()". Example 2: >>> longestValidParentheses(s = ")()())") >>> 4 Explanation: The longest valid parentheses substring is "()()". Example 3: >>> longestValidParentheses(s = "") >>> 0 """
search-in-rotated-sorted-array
def search(nums: List[int], target: int) -> int: """ There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: >>> search(nums = [4,5,6,7,0,1,2], target = 0) >>> 4 Example 2: >>> search(nums = [4,5,6,7,0,1,2], target = 3) >>> -1 Example 3: >>> search(nums = [1], target = 0) >>> -1 """
find-first-and-last-position-of-element-in-sorted-array
def searchRange(nums: List[int], target: int) -> List[int]: """ Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: >>> searchRange(nums = [5,7,7,8,8,10], target = 8) >>> [3,4] Example 2: >>> searchRange(nums = [5,7,7,8,8,10], target = 6) >>> [-1,-1] Example 3: >>> searchRange(nums = [], target = 0) >>> [-1,-1] """
search-insert-position
def searchInsert(nums: List[int], target: int) -> int: """ Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: >>> searchInsert(nums = [1,3,5,6], target = 5) >>> 2 Example 2: >>> searchInsert(nums = [1,3,5,6], target = 2) >>> 1 Example 3: >>> searchInsert(nums = [1,3,5,6], target = 7) >>> 4 """
valid-sudoku
def isValidSudoku(board: List[List[str]]) -> bool: """ Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. Example 1: [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] >>> isValidSudoku(board =) >>> true Example 2: [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] >>> isValidSudoku(board =) >>> false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. """
sudoku-solver
def solveSudoku(board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ """ Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells. Example 1: >>> solveSudoku(board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]) >>> [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] Explanation: The input board is shown above and the only valid solution is shown below: """
count-and-say
def countAndSay(n: int) -> str: """ The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the run-length encoding of countAndSay(n - 1). Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "3322251" we replace "33" with "23", replace "222" with "32", replace "5" with "15" and replace "1" with "11". Thus the compressed string becomes "23321511". Given a positive integer n, return the nth element of the count-and-say sequence. Example 1: >>> countAndSay(n = 4) >>> "1211" Explanation: countAndSay(1) = "1" countAndSay(2) = RLE of "1" = "11" countAndSay(3) = RLE of "11" = "21" countAndSay(4) = RLE of "21" = "1211" Example 2: >>> countAndSay(n = 1) >>> "1" Explanation: This is the base case. """
combination-sum
def combinationSum(candidates: List[int], target: int) -> List[List[int]]: """ Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: >>> combinationSum(candidates = [2,3,6,7], target = 7) >>> [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. Example 2: >>> combinationSum(candidates = [2,3,5], target = 8) >>> [[2,2,2,2],[2,3,3],[3,5]] Example 3: >>> combinationSum(candidates = [2], target = 1) >>> [] """
combination-sum-ii
def combinationSum2(candidates: List[int], target: int) -> List[List[int]]: """ Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1: >>> combinationSum2(candidates = [10,1,2,7,6,1,5], target = 8) >>> [ [1,1,6], [1,2,5], [1,7], [2,6] ] Example 2: >>> combinationSum2(candidates = [2,5,2,1,2], target = 5) >>> [ [1,2,2], [5] ] """
first-missing-positive
def firstMissingPositive(nums: List[int]) -> int: """ Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. Example 1: >>> firstMissingPositive(nums = [1,2,0]) >>> 3 Explanation: The numbers in the range [1,2] are all in the array. Example 2: >>> firstMissingPositive(nums = [3,4,-1,1]) >>> 2 Explanation: 1 is in the array but 2 is missing. Example 3: >>> firstMissingPositive(nums = [7,8,9,11,12]) >>> 1 Explanation: The smallest positive integer 1 is missing. """
trapping-rain-water
def trap(height: List[int]) -> int: """ Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: >>> trap(height = [0,1,0,2,1,0,1,3,2,1,2,1]) >>> 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: >>> trap(height = [4,2,0,3,2,5]) >>> 9 """
multiply-strings
def multiply(num1: str, num2: str) -> str: """ Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. Example 1: >>> multiply(num1 = "2", num2 = "3") >>> "6" Example 2: >>> multiply(num1 = "123", num2 = "456") >>> "56088" """
wildcard-matching
def isMatch(s: str, p: str) -> bool: """ Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Example 1: >>> isMatch(s = "aa", p = "a") >>> false Explanation: "a" does not match the entire string "aa". Example 2: >>> isMatch(s = "aa", p = "*") >>> true Explanation: '*' matches any sequence. Example 3: >>> isMatch(s = "cb", p = "?a") >>> false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. """
jump-game-ii
def jump(nums: List[int]) -> int: """ You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: 0 <= j <= nums[i] and i + j < n Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. Example 1: >>> jump(nums = [2,3,1,1,4]) >>> 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: >>> jump(nums = [2,3,0,1,4]) >>> 2 """
permutations
def permute(nums: List[int]) -> List[List[int]]: """ Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: >>> permute(nums = [1,2,3]) >>> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: >>> permute(nums = [0,1]) >>> [[0,1],[1,0]] Example 3: >>> permute(nums = [1]) >>> [[1]] """
permutations-ii
def permuteUnique(nums: List[int]) -> List[List[int]]: """ Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Example 1: >>> permuteUnique(nums = [1,1,2]) >>> [[1,1,2], [1,2,1], [2,1,1]] Example 2: >>> permuteUnique(nums = [1,2,3]) >>> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] """
rotate-image
def rotate(matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ """ You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: >>> rotate(matrix = [[1,2,3],[4,5,6],[7,8,9]]) >>> [[7,4,1],[8,5,2],[9,6,3]] Example 2: >>> rotate(matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]) >>> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] """
group-anagrams
def groupAnagrams(strs: List[str]) -> List[List[str]]: """ Given an array of strings strs, group the anagrams together. You can return the answer in any order. Example 1: >>> groupAnagrams(strs = ["eat","tea","tan","ate","nat","bat"]) >>> [["bat"],["nat","tan"],["ate","eat","tea"]] Explanation: There is no string in strs that can be rearranged to form "bat". The strings "nat" and "tan" are anagrams as they can be rearranged to form each other. The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other. Example 2: >>> groupAnagrams(strs = [""]) >>> [[""]] Example 3: >>> groupAnagrams(strs = ["a"]) >>> [["a"]] """
powx-n
def myPow(x: float, n: int) -> float: """ Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Example 1: >>> myPow(x = 2.00000, n = 10) >>> 1024.00000 Example 2: >>> myPow(x = 2.10000, n = 3) >>> 9.26100 Example 3: >>> myPow(x = 2.00000, n = -2) >>> 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 """
n-queens
def solveNQueens(n: int) -> List[List[str]]: """ The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. Example 1: >>> solveNQueens(n = 4) >>> [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Example 2: >>> solveNQueens(n = 1) >>> [["Q"]] """
n-queens-ii
def totalNQueens(n: int) -> int: """ The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. Example 1: >>> totalNQueens(n = 4) >>> 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown. Example 2: >>> totalNQueens(n = 1) >>> 1 """
maximum-subarray
def maxSubArray(nums: List[int]) -> int: """ Given an integer array nums, find the subarray with the largest sum, and return its sum. Example 1: >>> maxSubArray(nums = [-2,1,-3,4,-1,2,1,-5,4]) >>> 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6. Example 2: >>> maxSubArray(nums = [1]) >>> 1 Explanation: The subarray [1] has the largest sum 1. Example 3: >>> maxSubArray(nums = [5,4,-1,7,8]) >>> 23 Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. """
spiral-matrix
def spiralOrder(matrix: List[List[int]]) -> List[int]: """ Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: >>> spiralOrder(matrix = [[1,2,3],[4,5,6],[7,8,9]]) >>> [1,2,3,6,9,8,7,4,5] Example 2: >>> spiralOrder(matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]) >>> [1,2,3,4,8,12,11,10,9,5,6,7] """
jump-game
def canJump(nums: List[int]) -> bool: """ You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. Example 1: >>> canJump(nums = [2,3,1,1,4]) >>> true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: >>> canJump(nums = [3,2,1,0,4]) >>> false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. """
merge-intervals
def merge(intervals: List[List[int]]) -> List[List[int]]: """ Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: >>> merge(intervals = [[1,3],[2,6],[8,10],[15,18]]) >>> [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. Example 2: >>> merge(intervals = [[1,4],[4,5]]) >>> [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. """
insert-interval
def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: """ You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. Note that you don't need to modify intervals in-place. You can make a new array and return it. Example 1: >>> insert(intervals = [[1,3],[6,9]], newInterval = [2,5]) >>> [[1,5],[6,9]] Example 2: >>> insert(intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]) >>> [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. """
length-of-last-word
def lengthOfLastWord(s: str) -> int: """ Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: >>> lengthOfLastWord(s = "Hello World") >>> 5 Explanation: The last word is "World" with length 5. Example 2: >>> lengthOfLastWord(s = " fly me to the moon ") >>> 4 Explanation: The last word is "moon" with length 4. Example 3: >>> lengthOfLastWord(s = "luffy is still joyboy") >>> 6 Explanation: The last word is "joyboy" with length 6. """
spiral-matrix-ii
def generateMatrix(n: int) -> List[List[int]]: """ Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example 1: >>> generateMatrix(n = 3) >>> [[1,2,3],[8,9,4],[7,6,5]] Example 2: >>> generateMatrix(n = 1) >>> [[1]] """
permutation-sequence
def getPermutation(n: int, k: int) -> str: """ The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Example 1: >>> getPermutation(n = 3, k = 3) >>> "213" Example 2: >>> getPermutation(n = 4, k = 9) >>> "2314" Example 3: >>> getPermutation(n = 3, k = 1) >>> "123" """
rotate-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(head: Optional[ListNode], k: int) -> Optional[ListNode]: """ Given the head of a linked list, rotate the list to the right by k places. Example 1: >>> __init__(head = [1,2,3,4,5], k = 2) >>> [4,5,1,2,3] Example 2: >>> __init__(head = [0,1,2], k = 4) >>> [2,0,1] """
unique-paths
def uniquePaths(m: int, n: int) -> int: """ There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. Example 1: >>> uniquePaths(m = 3, n = 7) >>> 28 Example 2: >>> uniquePaths(m = 3, n = 2) >>> 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down """
unique-paths-ii
def uniquePathsWithObstacles(obstacleGrid: List[List[int]]) -> int: """ You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. Example 1: >>> uniquePathsWithObstacles(obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]) >>> 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right Example 2: >>> uniquePathsWithObstacles(obstacleGrid = [[0,1],[0,0]]) >>> 1 """
minimum-path-sum
def minPathSum(grid: List[List[int]]) -> int: """ 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. Example 1: >>> minPathSum(grid = [[1,3,1],[1,5,1],[4,2,1]]) >>> 7 Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. Example 2: >>> minPathSum(grid = [[1,2,3],[4,5,6]]) >>> 12 """
valid-number
def isNumber(s: str) -> bool: """ Given a string s, return whether s is a valid number. For example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789", while the following are not valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53". Formally, a valid number is defined using one of the following definitions: An integer number followed by an optional exponent. A decimal number followed by an optional exponent. An integer number is defined with an optional sign '-' or '+' followed by digits. A decimal number is defined with an optional sign '-' or '+' followed by one of the following definitions: Digits followed by a dot '.'. Digits followed by a dot '.' followed by digits. A dot '.' followed by digits. An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number. The digits are defined as one or more digits. Example 1: >>> isNumber(s = "0") >>> true Example 2: >>> isNumber(s = "e") >>> false Example 3: >>> isNumber(s = ".") >>> false """
plus-one
def plusOne(digits: List[int]) -> List[int]: """ You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. Example 1: >>> plusOne(digits = [1,2,3]) >>> [1,2,4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4]. Example 2: >>> plusOne(digits = [4,3,2,1]) >>> [4,3,2,2] Explanation: The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus, the result should be [4,3,2,2]. Example 3: >>> plusOne(digits = [9]) >>> [1,0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus, the result should be [1,0]. """
add-binary
def addBinary(a: str, b: str) -> str: """ Given two binary strings a and b, return their sum as a binary string. Example 1: >>> addBinary(a = "11", b = "1") >>> "100" Example 2: >>> addBinary(a = "1010", b = "1011") >>> "10101" """
text-justification
def fullJustify(words: List[str], maxWidth: int) -> List[str]: """ Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note: A word is defined as a character sequence consisting of non-space characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word. Example 1: >>> fullJustify(words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16) >>> [    "This    is    an",    "example  of text",    "justification.  " ] Example 2: >>> fullJustify(words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16) >>> [   "What   must   be",   "acknowledgment  ",   "shall be        " ] Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. Example 3: >>> fullJustify(words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20) >>> [   "Science  is  what we", "understand      well",   "enough to explain to",   "a  computer.  Art is",   "everything  else  we",   "do                  " ] """
sqrtx
def mySqrt(x: int) -> int: """ Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. Example 1: >>> mySqrt(x = 4) >>> 2 Explanation: The square root of 4 is 2, so we return 2. Example 2: >>> mySqrt(x = 8) >>> 2 Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. """
climbing-stairs
def climbStairs(n: int) -> int: """ You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: >>> climbStairs(n = 2) >>> 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: >>> climbStairs(n = 3) >>> 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step """
simplify-path
def simplifyPath(path: str) -> str: """ You are given an absolute path for a Unix-style file system, which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path. The rules of a Unix-style file system are as follows: A single period '.' represents the current directory. A double period '..' represents the previous/parent directory. Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'. Any sequence of periods that does not match the rules above should be treated as a valid directory or file name. For example, '...' and '....' are valid directory or file names. The simplified canonical path should follow these rules: The path must start with a single slash '/'. Directories within the path must be separated by exactly one slash '/'. The path must not end with a slash '/', unless it is the root directory. The path must not have any single or double periods ('.' and '..') used to denote current or parent directories. Return the simplified canonical path. Example 1: >>> simplifyPath(path = "/home/") >>> "/home" Explanation: The trailing slash should be removed. Example 2: >>> simplifyPath(path = "/home//foo/") >>> "/home/foo" Explanation: Multiple consecutive slashes are replaced by a single one. Example 3: >>> simplifyPath(path = "/home/user/Documents/../Pictures") >>> "/home/user/Pictures" Explanation: A double period ".." refers to the directory up a level (the parent directory). Example 4: >>> simplifyPath(path = "/../") >>> "/" Explanation: Going one level up from the root directory is not possible. Example 5: >>> simplifyPath(path = "/.../a/../b/c/../d/./") >>> "/.../b/d" Explanation: "..." is a valid name for a directory in this problem. """
edit-distance
def minDistance(word1: str, word2: str) -> int: """ Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: >>> minDistance(word1 = "horse", word2 = "ros") >>> 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: >>> minDistance(word1 = "intention", word2 = "execution") >>> 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') """
set-matrix-zeroes
def setZeroes(matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ """ Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place. Example 1: >>> setZeroes(matrix = [[1,1,1],[1,0,1],[1,1,1]]) >>> [[1,0,1],[0,0,0],[1,0,1]] Example 2: >>> setZeroes(matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]) >>> [[0,0,0,0],[0,4,5,0],[0,3,1,0]] """
search-a-2d-matrix
def searchMatrix(matrix: List[List[int]], target: int) -> bool: """ You are given an m x n integer matrix matrix with the following two properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Given an integer target, return true if target is in matrix or false otherwise. You must write a solution in O(log(m * n)) time complexity. Example 1: >>> searchMatrix(matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3) >>> true Example 2: >>> searchMatrix(matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13) >>> false """
sort-colors
def sortColors(nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ """ Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. Example 1: >>> sortColors(nums = [2,0,2,1,1,0]) >>> [0,0,1,1,2,2] Example 2: >>> sortColors(nums = [2,0,1]) >>> [0,1,2] """
minimum-window-substring
def minWindow(s: str, t: str) -> str: """ Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. Example 1: >>> minWindow(s = "ADOBECODEBANC", t = "ABC") >>> "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. Example 2: >>> minWindow(s = "a", t = "a") >>> "a" Explanation: The entire string s is the minimum window. Example 3: >>> minWindow(s = "a", t = "aa") >>> "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. """
combinations
def combine(n: int, k: int) -> List[List[int]]: """ Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order. Example 1: >>> combine(n = 4, k = 2) >>> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Explanation: There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. Example 2: >>> combine(n = 1, k = 1) >>> [[1]] Explanation: There is 1 choose 1 = 1 total combination. """
subsets
def subsets(nums: List[int]) -> List[List[int]]: """ Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: >>> subsets(nums = [1,2,3]) >>> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: >>> subsets(nums = [0]) >>> [[],[0]] """
word-search
def exist(board: List[List[str]], word: str) -> bool: """ Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. Example 1: >>> exist(board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED") >>> true Example 2: >>> exist(board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE") >>> true Example 3: >>> exist(board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB") >>> false """
remove-duplicates-from-sorted-array-ii
def removeDuplicates(nums: List[int]) -> int: """ Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted. Example 1: >>> removeDuplicates(nums = [1,1,1,2,2,3]) >>> 5, nums = [1,1,2,2,3,_] Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: >>> removeDuplicates(nums = [0,0,1,1,1,1,2,3,3]) >>> 7, nums = [0,0,1,1,2,3,3,_,_] Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). """
search-in-rotated-sorted-array-ii
def search(nums: List[int], target: int) -> bool: """ There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible. Example 1: >>> search(nums = [2,5,6,0,0,1,2], target = 0) >>> true Example 2: >>> search(nums = [2,5,6,0,0,1,2], target = 3) >>> false """
remove-duplicates-from-sorted-list-ii
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(head: Optional[ListNode]) -> Optional[ListNode]: """ Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: >>> __init__(head = [1,2,3,3,4,4,5]) >>> [1,2,5] Example 2: >>> __init__(head = [1,1,1,2,3]) >>> [2,3] """
remove-duplicates-from-sorted-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(head: Optional[ListNode]) -> Optional[ListNode]: """ Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: >>> __init__(head = [1,1,2]) >>> [1,2] Example 2: >>> __init__(head = [1,1,2,3,3]) >>> [1,2,3] """
largest-rectangle-in-histogram
def largestRectangleArea(heights: List[int]) -> int: """ Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Example 1: >>> largestRectangleArea(heights = [2,1,5,6,2,3]) >>> 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. Example 2: >>> largestRectangleArea(heights = [2,4]) >>> 4 """
maximal-rectangle
def maximalRectangle(matrix: List[List[str]]) -> int: """ Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. Example 1: >>> maximalRectangle(matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]) >>> 6 Explanation: The maximal rectangle is shown in the above picture. Example 2: >>> maximalRectangle(matrix = [["0"]]) >>> 0 Example 3: >>> maximalRectangle(matrix = [["1"]]) >>> 1 """
partition-list
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def partition(head: Optional[ListNode], x: int) -> Optional[ListNode]: """ Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: >>> __init__(head = [1,4,3,2,5,2], x = 3) >>> [1,2,2,4,3,5] Example 2: >>> __init__(head = [2,1], x = 2) >>> [1,2] """
scramble-string
def isScramble(s1: str, s2: str) -> bool: """ We can scramble a string s to get a string t using the following algorithm: If the length of the string is 1, stop. If the length of the string is > 1, do the following: Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y. Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x. Apply step 1 recursively on each of the two substrings x and y. Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false. Example 1: >>> isScramble(s1 = "great", s2 = "rgeat") >>> true Explanation: One possible scenario applied on s1 is: "great" --> "gr/eat" // divide at random index. "gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order. "gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them. "g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t". "r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is "rgeat" which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. Example 2: >>> isScramble(s1 = "abcde", s2 = "caebd") >>> false Example 3: >>> isScramble(s1 = "a", s2 = "a") >>> true """
merge-sorted-array
def merge(nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ """ You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. Example 1: >>> merge(nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3) >>> [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. Example 2: >>> merge(nums1 = [1], m = 1, nums2 = [], n = 0) >>> [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1]. Example 3: >>> merge(nums1 = [0], m = 0, nums2 = [1], n = 1) >>> [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. """
gray-code
def grayCode(n: int) -> List[int]: """ An n-bit gray code sequence is a sequence of 2n integers where: Every integer is in the inclusive range [0, 2n - 1], The first integer is 0, An integer appears no more than once in the sequence, The binary representation of every pair of adjacent integers differs by exactly one bit, and The binary representation of the first and last integers differs by exactly one bit. Given an integer n, return any valid n-bit gray code sequence. Example 1: >>> grayCode(n = 2) >>> [0,1,3,2] Explanation: The binary representation of [0,1,3,2] is [00,01,11,10]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit Example 2: >>> grayCode(n = 1) >>> [0,1] """
subsets-ii
def subsetsWithDup(nums: List[int]) -> List[List[int]]: """ Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: >>> subsetsWithDup(nums = [1,2,2]) >>> [[],[1],[1,2],[1,2,2],[2],[2,2]] Example 2: >>> subsetsWithDup(nums = [0]) >>> [[],[0]] """
decode-ways
def numDecodings(s: str) -> int: """ You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping: "1" -> 'A' "2" -> 'B' ... "25" -> 'Y' "26" -> 'Z' However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2" and "5" vs "25"). For example, "11106" can be decoded into: "AAJF" with the grouping (1, 1, 10, 6) "KJF" with the grouping (11, 10, 6) The grouping (1, 11, 06) is invalid because "06" is not a valid code (only "6" is valid). Note: there may be strings that are impossible to decode. Given a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0. The test cases are generated so that the answer fits in a 32-bit integer. Example 1: >>> numDecodings(s = "12") >>> 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). Example 2: >>> numDecodings(s = "226") >>> 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). Example 3: >>> numDecodings(s = "06") >>> 0 Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). In this case, the string is not a valid encoding, so return 0. """
reverse-linked-list-ii
# class ListNode: # def __init__(val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: """ Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. Example 1: >>> __init__(head = [1,2,3,4,5], left = 2, right = 4) >>> [1,4,3,2,5] Example 2: >>> __init__(head = [5], left = 1, right = 1) >>> [5] """
restore-ip-addresses
def restoreIpAddresses(s: str) -> List[str]: """ A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order. Example 1: >>> restoreIpAddresses(s = "25525511135") >>> ["255.255.11.135","255.255.111.35"] Example 2: >>> restoreIpAddresses(s = "0000") >>> ["0.0.0.0"] Example 3: >>> restoreIpAddresses(s = "101023") >>> ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"] """
binary-tree-inorder-traversal
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(root: Optional[TreeNode]) -> List[int]: """ Given the root of a binary tree, return the inorder traversal of its nodes' values. Example 1: >>> __init__(root = [1,null,2,3]) >>> [1,3,2] Explanation: Example 2: >>> __init__(root = [1,2,3,4,5,null,8,null,null,6,7,9]) >>> [4,2,6,5,7,1,3,9,8] Explanation: Example 3: >>> __init__(root = []) >>> [] Example 4: >>> __init__(root = [1]) >>> [1] """
unique-binary-search-trees
def numTrees(n: int) -> int: """ Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: >>> numTrees(n = 3) >>> 5 Example 2: >>> numTrees(n = 1) >>> 1 """
interleaving-string
def isInterleave(s1: str, s2: str, s3: str) -> bool: """ Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that: s = s1 + s2 + ... + sn t = t1 + t2 + ... + tm |n - m| <= 1 The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... Note: a + b is the concatenation of strings a and b. Example 1: >>> isInterleave(s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac") >>> true Explanation: One way to obtain s3 is: Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a". Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac". Since s3 can be obtained by interleaving s1 and s2, we return true. Example 2: >>> isInterleave(s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc") >>> false Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3. Example 3: >>> isInterleave(s1 = "", s2 = "", s3 = "") >>> true """
validate-binary-search-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(root: Optional[TreeNode]) -> bool: """ 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 subtrees must also be binary search trees. Example 1: >>> __init__(root = [2,1,3]) >>> true Example 2: >>> __init__(root = [5,1,4,null,null,3,6]) >>> false Explanation: The root node's value is 5 but its right child's value is 4. """
recover-binary-search-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def recoverTree(root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ """ You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Example 1: >>> __init__(root = [1,3,null,null,2]) >>> [3,1,null,null,2] Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. Example 2: >>> __init__(root = [3,1,4,null,null,2]) >>> [2,1,4,null,null,3] Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. """
same-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: """ Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: >>> __init__(p = [1,2,3], q = [1,2,3]) >>> true Example 2: >>> __init__(p = [1,2], q = [1,null,2]) >>> false Example 3: >>> __init__(p = [1,2,1], q = [1,1,2]) >>> false """
symmetric-tree
# class TreeNode: # def __init__(val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(root: Optional[TreeNode]) -> bool: """ Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: >>> __init__(root = [1,2,2,3,4,4,3]) >>> true Example 2: >>> __init__(root = [1,2,2,null,3,null,3]) >>> false """
End of preview. Expand in Data Studio

HumanEval-LeetCode Input-Only

本数据集由 LeetCode 题目自动转换而来,目标是生成 HumanEval 风格的 Input-Only 提示(prompt)。每条样本包含题目描述与函数签名,描述中的 Input/Output 被转换成 >>> func(...) / >>> output 的交互式示例,便于直接用于代码生成评测或训练。

数据格式

每行是一个 JSON 对象(JSONL):

  • task_id:题目唯一标识
  • prompt:包含函数签名与 docstring 的完整提示

示例字段:

  • task_id: string
  • prompt: string

生成流程(概述)

  1. 读取 LeetCode 题目(题目描述 + starter code)。
  2. 提取函数名。
  3. 将题目描述中的 Input/Output 转为:
    • >>> func(inputs...)
    • >>> output
  4. 输出为 JSONL。

数据划分

  • train.jsonl
  • test.jsonl

使用方式

Python 读取示例:

import json

with open("train.jsonl", "r", encoding="utf-8") as f:
    for line in f:
        item = json.loads(line)
        print(item["task_id"], item["prompt"][:80])
        break

许可协议

MIT

引用

如果使用该数据集,请注明来源或引用本项目。

Downloads last month
13