A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | AA | AB | AC | AD | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | nivel_pergunta | link_pergunta | enunciado_submetido | link_submissao | codigo_resposta | avaliacao_resposta | tempo_de_execução_ms | memoria_usada_mb | Tempo_maximo_de_execução_ms | memoria_maxima_mb | tempo_minimo_de_execução_ms | memoria_minima_mb | erro_gerado | numero_tentativas | contem_imagem | topicos relacionados 1 | topicos relacionados 2 | topicos relacionados 3 | topicos relacionados 4 | topicos relacionados 5 | ||||||||||
2 | easy | https://leetcode.com/problems/two-sum/ | 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: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. | https://leetcode.com/problems/two-sum/submissions/872670911/ | class Solution(object): def twoSum(self, nums, target): for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [-1, -1] | Correta | 8781 | 14.3 | 8781 | 14.5 | 70 | 13.4 | 1 | FALSE | array | hash table | ||||||||||||||
3 | easy | https://leetcode.com/problems/palindrome-number// | Given an integer x, return true if x is a palindrome , and false otherwise. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. | https://leetcode.com/problems/palindrome-number/submissions/872653917/ | class Solution(object): def isPalindrome(self, x): # Convert x to a string and store it in s s = str(x) # Return True if s is equal to its reverse, False otherwise return s == s[::-1] | Correta | 131 | 13.4 | 180 | 13.5 | 21 | 12.6 | 1 | FALSE | math | |||||||||||||||
4 | easy | https://leetcode.com/problems/roman-to-integer/ | 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: Input: s = "III" Output: 3 Explanation: III = 3. Example 2: Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 3: Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. Constraints: 1 <= s.length <= 15 s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). It is guaranteed that s is a valid roman numeral in the range [1, 3999]. | https://leetcode.com/problems/roman-to-integer/submissions/876918114/ | class Solution: def romanToInt(self, s: str) -> int: roman_to_int = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} result = 0 for i in range(len(s)): if i > 0 and roman_to_int[s[i]] > roman_to_int[s[i - 1]]: result += roman_to_int[s[i]] - 2 * roman_to_int[s[i - 1]] else: result += roman_to_int[s[i]] return result | Correta | 60 | 13.7 | 132 | 13.9 | 23 | 13.1 | 1 | FALSE | hash table | math | string | |||||||||||||
5 | easy | https://leetcode.com/problems/longest-common-prefix/ | 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: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters. | https://leetcode.com/problems/valid-parentheses/submissions/872684565/ | class Solution(object): def longestCommonPrefix(self, strs): # Edge case: if the input array is empty, return an empty string if not strs: return "" # Sort the array so that we can compare the first and last strings strs.sort() # Get the first and last strings first = strs[0] last = strs[-1] # Initialize the common prefix to an empty string prefix = "" # Iterate through the characters in the first string for i, char in enumerate(first): # If the characters at the same index in the first and last strings are the same, # add the character to the prefix if char == last[i]: prefix += char # If the characters are not the same, return the prefix else: return prefix # If we finish iterating through the characters in the first string, return the prefix return prefix | Correta | 43 | 13.5 | 70 | 13.8 | 4 | 13.1 | 1 | FALSE | string | trie | ||||||||||||||
6 | easy | https://leetcode.com/problems/valid-parentheses/ | 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: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'. | https://leetcode.com/problems/valid-parentheses/submissions/872684565/ | 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. | Correta | 43 | 13.7 | 68 | 13.8 | 3 | 12.9 | 1 | FALSE | string | stack | ||||||||||||||
7 | easy | https://leetcode.com/problems/merge-two-sorted-lists/ | You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a 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: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: list1 = [], list2 = [] Output: [] Example 3: Input: list1 = [], list2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order. | https://leetcode.com/problems/merge-two-sorted-lists/submissions/872713369/ | class Solution(object): def mergeTwoLists(self, l1, l2): # Edge case: if either list is empty if not l1 or not l2: return l1 or l2 # Pick the smaller value if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 | Correta | 52 | 13.5 | 62 | 13.6 | 4 | 12.9 | 1 | TRUE | linked list | recursion | ||||||||||||||
8 | easy | https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ | 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 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: Input: nums = [1,1,2] Output: 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: Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 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). Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is sorted in non-decreasing order. | https://leetcode.com/problems/remove-duplicates-from-sorted-array/submissions/872718532/ | class Solution(object): def removeDuplicates(self, nums): # Edge case: if the input array is empty if not nums: return 0 # Initialize the index to store the unique elements index = 1 # Iterate through the array, starting from the second element for i in range(1, len(nums)): # If the current element is not a duplicate, add it to the array if nums[i] != nums[i-1]: nums[index] = nums[i] index += 1 # Return the number of unique elements return index | Correta | 142 | 14.9 | 433 | 15.1 | 45 | 13.7 | 1 | FALSE | array | two pointers | ||||||||||||||
9 | easy | https://leetcode.com/problems/remove-element/description/ | 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: Input: nums = [3,2,2,3], val = 3 Output: 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: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 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). Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100 | https://leetcode.com/problems/remove-element/submissions/872721536/ | class Solution(object): def removeElement(self, nums, val): # Initialize the index to store the non-matching elements index = 0 # Iterate through the array for i in range(len(nums)): # If the current element does not match the value to remove, add it to the array if nums[i] != val: nums[index] = nums[i] index += 1 # Return the number of non-matching elements return index | Correta | 34 | 13.3 | 48 | 13.5 | 4 | 12.7 | 1 | FALSE | array | two pointers | ||||||||||||||
10 | easy | https://leetcode.com/problems/search-insert-position/ | 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: Input: nums = [1,3,5,6], target = 5 Output: 2 Example 2: Input: nums = [1,3,5,6], target = 2 Output: 1 Example 3: Input: nums = [1,3,5,6], target = 7 Output: 4 Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums contains distinct values sorted in ascending order. -104 <= target <= 104 | https://leetcode.com/problems/search-insert-position/submissions/876901073/ | class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left = 0 right = len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return left | Correta | 52 | 14.6 | 125 | 14.8 | 30 | 14.2 | 1 | FALSE | array | binary search | ||||||||||||||
11 | easy | https://leetcode.com/problems/length-of-last-word/ | 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: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Example 2: Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4. Example 3: Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6. Constraints: 1 <= s.length <= 104 s consists of only English letters and spaces ' '. There will be at least one word in s. | https://leetcode.com/problems/length-of-last-word/submissions/876902033/ | class Solution: def lengthOfLastWord(self, s: str) -> int: words = s.split() if not words: return 0 return len(words[-1]) | Correta | 23 | 13.9 | 68 | 14 | 11 | 13.3 | 1 | FALSE | string | |||||||||||||||
12 | easy | https://leetcode.com/problems/plus-one/ | 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: Input: digits = [1,2,3] Output: [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: Input: digits = [4,3,2,1] Output: [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: Input: digits = [9] Output: [1,0] Explanation: The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus, the result should be [1,0]. Constraints: 1 <= digits.length <= 100 0 <= digits[i] <= 9 digits does not contain any leading 0's. | https://leetcode.com/problems/plus-one/submissions/872716004/ | class Solution(object): def plusOne(self, digits): # Edge case: if the input is empty if not digits: return [] # Add one to the last digit and carry over any excess digits[-1] += 1 carry = digits[-1] // 10 digits[-1] %= 10 # If there is no carry, we're done if carry == 0: return digits # Otherwise, add the carry to the next digit for i in range(len(digits)-2, -1, -1): digits[i] += carry carry = digits[i] // 10 digits[i] %= 10 # If there is no carry, we're done if carry == 0: return digits # If we get here, there is a carry left over # Prepend a 1 to the front of the array return [1] + digits | Correta | 41 | 13.6 | 46 | 13 | 3 | 13.6 | 1 | FALSE | array | math | ||||||||||||||
13 | easy | https://leetcode.com/problems/add-binary/ | Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: 1 <= a.length, b.length <= 104 a and b consist only of '0' or '1' characters. Each string does not contain leading zeros except for the zero itself. | https://leetcode.com/problems/add-binary/ | class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] | Correta | 32 | 13.6 | 82 | 13.9 | 15 | 13.2 | 1 | FALSE | math | string | bit manipulation | simulation | ||||||||||||
14 | easy | https://leetcode.com/problems/sqrtx/ | 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: Input: x = 4 Output: 2 Explanation: The square root of 4 is 2, so we return 2. Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. Constraints: 0 <= x <= 231 - 1 | https://leetcode.com/problems/sqrtx/submissions/876900239/ | class Solution: def mySqrt(self, x: int) -> int: if x == 0: return 0 if x == 1: return 1 left = 0 right = x while left <= right: mid = (left + right) // 2 if mid * mid <= x < (mid + 1) * (mid + 1): return mid elif x < mid * mid: right = mid else: left = mid + 1 | Correta | 40 | 13.8 | 6359 | 13.9 | 40 | 12.7 | 1 | FALSE | math | binary searcn | ||||||||||||||
15 | easy | https://leetcode.com/problems/climbing-stairs/ | 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: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: n = 3 Output: 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 Constraints: 1 <= n <= 45 | https://leetcode.com/problems/climbing-stairs/submissions/876902926/ | class Solution: def climbStairs(self, n: int) -> int: if n == 1: return 1 if n == 2: return 2 dp = [0] * n dp[0], dp[1] = 1, 2 for i in range(2, n): dp[i] = dp[i-1] + dp[i-2] return dp[n-1] | Correta | 25 | 13.8 | 66 | 13.9 | 8 | 12.1 | 1 | FALSE | math | dynamic programming | memoization | |||||||||||||
16 | easy | https://leetcode.com/problems/remove-duplicates-from-sorted-list/ | 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: Input: head = [1,1,2] Output: [1,2] Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3] Constraints: The number of nodes in the list is in the range [0, 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order. | https://leetcode.com/problems/remove-duplicates-from-sorted-list/submissions/876905191/ | class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: current = head previous = None while current: if previous and previous.val == current.val: previous.next = current.next else: previous = current current = current.next return head | Correta | 41 | 13.8 | 101 | 13.9 | 22 | 13.1 | 1 | TRUE | linked list | |||||||||||||||
17 | easy | https://leetcode.com/problems/merge-sorted-array/ | 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: Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [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: Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1]. Example 3: Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [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. Constraints: nums1.length == m + n nums2.length == n 0 <= m, n <= 200 1 <= m + n <= 200 -109 <= nums1[i], nums2[j] <= 109 | https://leetcode.com/problems/merge-sorted-array/submissions/876907626/ | class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i = m - 1 j = n - 1 k = m + n - 1 while i >= 0 and j >= 0: if nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 while j >= 0: nums1[k] = nums2[j] j -= 1 k -= 1 | Correta | 46 | 13.9 | 89 | 14 | 19 | 13.5 | 1 | FALSE | array | two pointers | sorting | |||||||||||||
18 | easy | https://leetcode.com/problems/binary-tree-inorder-traversal/ | Given the root of a binary tree, return the inorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100 | https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/876909287/ | class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: result, stack = [], [] current = root while current or stack: while current: stack.append(current) current = current.left current = stack.pop() result.append(current.val) current = current.right return result | Correta | 39 | 13.7 | 68 | 13.9 | 12 | 13.5 | 1 | TRUE | stack | tree | depth-first search | binary tree | ||||||||||||
19 | easy | https://leetcode.com/problems/same-tree/ | 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: Input: p = [1,2,3], q = [1,2,3] Output: true Example 2: Input: p = [1,2], q = [1,null,2] Output: false Example 3: Input: p = [1,2,1], q = [1,1,2] Output: false Constraints: The number of nodes in both trees is in the range [0, 100]. -104 <= Node.val <= 104 | https://leetcode.com/problems/same-tree/submissions/876910472/ | class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: stack = [(p,q)] while stack: n1, n2 = stack.pop() if not n1 and not n2: continue if not n1 or not n2: return False if n1.val != n2.val: return False stack.append((n1.left,n2.left)) stack.append((n1.right,n2.right)) return True | Correta | 32 | 13.8 | 64 | 13.9 | 11 | 13.3 | 1 | TRUE | tree | depth-first search | breadth-first search | binary tree | ||||||||||||
20 | easy | https://leetcode.com/problems/symmetric-tree/ | Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Input: root = [1,2,2,3,4,4,3] Output: true Example 2: Input: root = [1,2,2,null,3,null,3] Output: false Constraints: The number of nodes in the tree is in the range [1, 1000]. -100 <= Node.val <= 100 | https://leetcode.com/problems/symmetric-tree/submissions/876916691/ | class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True stack = [(root.left, root.right)] while stack: left, right = stack.pop() if not left and not right: continue if not left or not right: return False if left.val != right.val: return False stack.append((left.left, right.right)) stack.append((left.right, right.left)) return True | Correta | 35 | 13.9 | 81 | 14 | 16 | 13.5 | 1 | TRUE | tree | depth-first search | breadth-first search | binary tree | ||||||||||||
21 | easy | https://leetcode.com/problems/path-sum/ | Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown. Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. Example 3: Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths. Constraints: The number of nodes in the tree is in the range [0, 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000 | https://leetcode.com/problems/path-sum/submissions/876913348/ | class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: if not root: return False stack = [(root, targetSum - root.val)] while stack: node, current_sum = stack.pop() if not node.left and not node.right and current_sum == 0: return True if node.left: stack.append((node.left, current_sum - node.left.val)) if node.right: stack.append((node.right, current_sum - node.right.val)) return False | Correta | 39 | 15 | 106 | 15.1 | 27 | 14.7 | 1 | TRUE | tree | depth-first search | breadth-first search | binary tree | ||||||||||||
22 | medium | https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/ | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]). The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i. A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes. Example 1: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd" Output: [2,1,1,1,1,1,1] Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree. Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself). Example 2: Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb" Output: [4,2,1,1] Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1. The sub-tree of node 3 contains only node 3, so the answer is 1. The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2. The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4. Example 3: Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab" Output: [3,2,1,1,1] Constraints: 1 <= n <= 105 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi labels.length == n labels is consisting of only of lowercase English letters. | https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/submissions/927189066/ | class Solution: def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: # Initialize frequency counts and visited array freq = [[0] * 26 for _ in range(n)] visited = [False] * n # Build adjacency list adj_list = [[] for _ in range(n)] for a, b in edges: adj_list[a].append(b) adj_list[b].append(a) # Define DFS function def dfs(node): visited[node] = True freq[node][ord(labels[node]) - ord('a')] += 1 for child in adj_list[node]: if not visited[child]: child_freq = dfs(child) for i in range(26): freq[node][i] += child_freq[i] return freq[node] # Start DFS from root node dfs(0) # Return frequency counts for all nodes return [freq[i][ord(labels[i]) - ord('a')] for i in range(n)] | Correta | 2402 | 211 | 3471 | 259 | 1434 | 147 | 2 | TRUE | hash table | tree | depth-first search | breadth-first search | counting | |||||||||||
23 | medium | https://leetcode.com/problems/add-two-numbers | 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: Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0], l2 = [0] Output: [0] Example 3: Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] Constraints: The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros. | https://leetcode.com/problems/add-two-numbers/submissions/872690828/ | class Solution(object): class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def addTwoNumbers(self, l1, l2): # create a dummy node to hold the result dummy = ListNode() curr = dummy carry = 0 # iterate until both linked lists are empty while l1 or l2 or carry: # add the values of the current nodes, or 0 if the list is empty val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry # update the carry for the next iteration carry = val // 10 # create a new node for the result and set its value to the ones digit of the sum curr.next = ListNode(val % 10) curr = curr.next # move to the next node in both lists, if they exist l1 = l1.next if l1 else None l2 = l2.next if l2 else None # return the next node after the dummy node, which is the head of the result linked list return dummy.next | Correta | 65 | 13.5 | 85 | 13.7 | 23 | 13.2 | 1 | TRUE | linked list | math | recursion | |||||||||||||
24 | medium | https://leetcode.com/problems/longest-substring-without-repeating-characters/ | Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 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. Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces. | https://leetcode.com/problems/longest-substring-without-repeating-characters/submissions/872734621/ | class Solution(object): def lengthOfLongestSubstring(self, s): # Edge case: if the input string is empty if not s: return 0 # Initialize the maximum length and the start and end indices max_length = 1 start = 0 end = 1 # Initialize a set to store the unique characters unique = set(s[start]) # Iterate through the string while end < len(s): # If the current character is not in the set, add it if s[end] not in unique: unique.add(s[end]) end += 1 max_length = max(max_length, end - start) # If the current character is in the set, remove the first character else: unique.remove(s[start]) start += 1 # Return the maximum length return max_length | Correta | 112 | 13.5 | 4569 | 15.1 | 44 | 12.9 | 1 | FALSE | hash table | string | sliding window | |||||||||||||
25 | medium | https://leetcode.com/problems/longest-palindromic-substring/ | Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters. | https://leetcode.com/problems/longest-palindromic-substring/submissions/872737799/ | class Solution(object): def longestPalindrome(self, s): # Edge case: if the input string is empty if not s: return "" # Initialize the start and end indices of the longest palindrome start = 0 end = 0 # Iterate through the string for i in range(len(s)): # Check for palindromes of odd length length1 = self.expandAroundCenter(s, i, i) # Check for palindromes of even length length2 = self.expandAroundCenter(s, i, i+1) # Update the start and end indices of the longest palindrome length = max(length1, length2) if length > end - start: start = i - (length - 1) // 2 end = i + length // 2 # Return the longest palindromic substring return s[start:end+1] def expandAroundCenter(self, s, left, right): # Expand the palindrome as long as the left and right indices are valid and the characters match while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 # Return the length of the palindrome return right - left - 1 | Correta | 1423 | 13.7 | 8073 | 22.2 | 72 | 12.8 | 1 | FALSE | string | dynamic programming | ||||||||||||||
26 | medium | https://leetcode.com/problems/zigzag-conversion/ | 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: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" Constraints: 1 <= s.length <= 1000 s consists of English letters (lower-case and upper-case), ',' and '.'. 1 <= numRows <= 1000 | https://leetcode.com/problems/zigzag-conversion/submissions/876922171/ | class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s result = [''] * numRows index, step = 0, 1 for char in s: result[index] += char if index == 0: step = 1 elif index == numRows - 1: step = -1 index += step return ''.join(result) | Correta | 52 | 13.9 | 1790 | 21.1 | 45 | 13.7 | 1 | FALSE | string | |||||||||||||||
27 | medium | https://leetcode.com/problems/reverse-integer/ | 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: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Constraints: -231 <= x <= 231 - 1 | https://leetcode.com/problems/reverse-integer/submissions/876923007/ | class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 sign = 1 if x > 0 else -1 x = abs(x) rev = 0 while x > 0: pop = x % 10 x //= 10 if rev > (2**31 - 1) // 10 or (rev == (2**31 - 1) // 10 and pop > 7): return 0 rev = rev * 10 + pop return sign * rev | Correta | 28 | 13.9 | 75 | 13.9 | 15 | 13.3 | 1 | FALSE | math | |||||||||||||||
28 | medium | https://leetcode.com/problems/string-to-integer-atoi/ | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. Return the integer as the final result. Note: Only the space character ' ' is considered a whitespace character. Do not ignore any characters other than the leading whitespace or the rest of the string after the digits. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in, 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) ^ The parsed integer is 42. Since 42 is in the range [-231, 231 - 1], the final result is 42. Example 2: Input: s = " -42" Output: -42 Explanation: Step 1: " -42" (leading whitespace is read and ignored) ^ Step 2: " -42" ('-' is read, so the result should be negative) ^ Step 3: " -42" ("42" is read in) ^ The parsed integer is -42. Since -42 is in the range [-231, 231 - 1], the final result is -42. Example 3: Input: s = "4193 with words" Output: 4193 Explanation: Step 1: "4193 with words" (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range [-231, 231 - 1], the final result is 4193. Constraints: 0 <= s.length <= 200 s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'. | https://leetcode.com/problems/string-to-integer-atoi/submissions/876923765/ | class Solution: def myAtoi(self, s: str) -> int: s = s.strip() if not s: return 0 sign = 1 if s[0] in ('-', '+'): if s[0] == '-': sign = -1 s = s[1:] result = 0 for char in s: if char.isdigit(): result = result * 10 + int(char) else: break result *= sign if result < -2**31: return -2**31 if result > 2**31-1: return 2**31-1 return result | Correta | 42 | 13.7 | 84 | 13.9 | 15 | 13.5 | 1 | FALSE | string | |||||||||||||||
29 | medium | https://leetcode.com/problems/container-with-most-water/ | 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: Input: height = [1,8,6,2,5,4,8,3,7] Output: 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: Input: height = [1,1] Output: 1 Constraints: n == height.length 2 <= n <= 105 0 <= height[i] <= 104 | https://leetcode.com/problems/container-with-most-water/submissions/876925727/ | class Solution: def maxArea(self, height: List[int]) -> int: left = 0 right = len(height) - 1 max_area = 0 while left < right: area = min(height[left], height[right]) * (right - left) max_area = max(max_area, area) if height[left] < height[right]: left += 1 else: right -= 1 return max_area | Correta | 803 | 27.3 | 2423 | 27.5 | 279 | 21.6 | 1 | TRUE | array | two pointers | greedy | |||||||||||||
30 | medium | https://leetcode.com/problems/integer-to-roman/ | 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 one's 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 an integer, convert it to a roman numeral. Example 1: Input: num = 3 Output: "III" Explanation: 3 is represented as 3 ones. Example 2: Input: num = 58 Output: "LVIII" Explanation: L = 50, V = 5, III = 3. Example 3: Input: num = 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. Constraints: 1 <= num <= 3999 | https://leetcode.com/problems/integer-to-roman/submissions/876926287/ | class Solution: def intToRoman(self, num: int) -> str: values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] symbols = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman = "" i = 0 while num > 0: while num >= values[i]: num -= values[i] roman += symbols[i] i += 1 return roman | Correta | 50 | 13.7 | 137 | 14 | 26 | 13.7 | 1 | FALSE | hash table | math | string | |||||||||||||
31 | medium | https://leetcode.com/problems/3sum/ | 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: Input: nums = [-1,0,1,2,-1,-4] Output: [[-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: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105 | https://leetcode.com/problems/3sum/submissions/876927262/ | class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() result = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue left = i + 1 right = len(nums) - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total == 0: result.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 elif total < 0: left += 1 else: right -= 1 return result | Correta | 1518 | 18.4 | 7804 | 19.4 | 229 | 13.5 | 1 | FALSE | array | two pointers | sorting | |||||||||||||
32 | medium | https://leetcode.com/problems/3sum-closest/ | 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: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 | https://leetcode.com/problems/3sum-closest/submissions/876953345/ | class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() closest_sum = float('inf') for i in range(len(nums) - 2): left, right = i + 1, len(nums) - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] if current_sum == target: return current_sum if abs(current_sum - target) < abs(closest_sum - target): closest_sum = current_sum if current_sum < target: left += 1 else: right -= 1 return closest_sum | Correta | 1063 | 13.8 | 4534 | 14 | 80 | 13.5 | 1 | FALSE | array | two pointers | sorting | |||||||||||||
33 | medium | https://leetcode.com/problems/letter-combinations-of-a-phone-number/ | 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: Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] Example 2: Input: digits = "" Output: [] Example 3: Input: digits = "2" Output: ["a","b","c"] Constraints: 0 <= digits.length <= 4 digits[i] is a digit in the range ['2', '9']. | https://leetcode.com/problems/letter-combinations-of-a-phone-number/submissions/876954515/ | class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] mapping = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} res = [] def backtrack(combination, next_digits): if not next_digits: res.append(combination) return for letter in mapping[next_digits[0]]: backtrack(combination + letter, next_digits[1:]) backtrack("", digits) return res | Correta | 32 | 13.9 | 68 | 13.9 | 14 | 13.6 | 1 | TRUE | hash table | string | backtracking | |||||||||||||
34 | medium | https://leetcode.com/problems/4sum/ | 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: Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] Example 2: Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]] Constraints: 1 <= nums.length <= 200 -109 <= nums[i] <= 109 -109 <= target <= 109 | https://leetcode.com/problems/4sum/submissions/876956193/ | class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() quadruplets = [] for i in range(len(nums) - 3): if i > 0 and nums[i] == nums[i - 1]: continue for j in range(i + 1, len(nums) - 2): if j > i + 1 and nums[j] == nums[j - 1]: continue left, right = j + 1, len(nums) - 1 while left < right: s = nums[i] + nums[j] + nums[left] + nums[right] if s == target: quadruplets.append([nums[i], nums[j], nums[left], nums[right]]) while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 elif s < target: left += 1 else: right -= 1 return quadruplets | Correta | 1005 | 13.9 | 5274 | 18.1 | 87 | 13.7 | 1 | FALSE | array | two pointers | sorting | |||||||||||||
35 | medium | https://leetcode.com/problems/remove-nth-node-from-end-of-list/ | Given the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Input: head = [1,2], n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz | https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/876957830/ | class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: first = second = head for _ in range(n): first = first.next if not first: return head.next while first.next: first = first.next second = second.next second.next = second.next.next return head | Correta | 35 | 13.8 | 76 | 13.9 | 15 | 13.5 | 1 | TRUE | linked list | two pointers | ||||||||||||||
36 | medium | https://leetcode.com/problems/maximum-ice-cream-bars/ | It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Note: The boy can buy the ice cream bars in any order. Return the maximum number of ice cream bars the boy can buy with coins coins. You must solve the problem by counting sort. Example 1: Input: costs = [1,3,2,4,1], coins = 7 Output: 4 Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. Example 2: Input: costs = [10,6,8,7,7,8], coins = 5 Output: 0 Explanation: The boy cannot afford any of the ice cream bars. Example 3: Input: costs = [1,6,3,1,2,5], coins = 20 Output: 6 Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. Constraints: costs.length == n 1 <= n <= 105 1 <= costs[i] <= 105 1 <= coins <= 108 | https://leetcode.com/problems/maximum-ice-cream-bars/submissions/872732256/ | class Solution(object): def maxIceCream(self, costs, coins): # Sort the prices in ascending order costs.sort() # Initialize a counter for the number of ice cream bars count = 0 # Iterate through the prices and add up the cost for price in costs: # If we have enough coins, buy another ice cream bar if coins >= price: count += 1 coins -= price # If we don't have enough coins, we're done else: break # Return the number of ice cream bars return count | Correta | 1739 | 25.3 | 2434 | 25.4 | 657 | 19.9 | 1 | FALSE | array | greedy | sorting | |||||||||||||
37 | hard | https://leetcode.com/problems/median-of-two-sorted-arrays/ | 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: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i], nums2[i] <= 106 | https://leetcode.com/problems/median-of-two-sorted-arrays/submissions/877035034/ | class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m, n = len(nums1), len(nums2) if m > n: nums1, nums2, m, n = nums2, nums1, n, m if n == 0: raise ValueError i_min, i_max, half_len = 0, m, (m + n + 1) // 2 while i_min <= i_max: i = (i_min + i_max) // 2 j = half_len - i if i < m and nums2[j-1] > nums1[i]: i_min = i + 1 elif i > 0 and nums1[i-1] > nums2[j]: i_max = i - 1 else: if i == 0: max_of_left = nums2[j-1] elif j == 0: max_of_left = nums1[i-1] else: max_of_left = max(nums1[i-1], nums2[j-1]) if (m + n) % 2 == 1: return max_of_left if i == m: min_of_right = nums2[j] elif j == n: min_of_right = nums1[i] else: min_of_right = min(nums1[i], nums2[j]) return (max_of_left + min_of_right) / 2 | Correta | 98 | 14.2 | 274 | 14.3 | 70 | 11 | 1 | FALSE | array | binary search | divide and conquer | |||||||||||||
38 | hard | https://leetcode.com/problems/regular-expression-matching/description/ | 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: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)". Constraints: 1 <= s.length <= 20 1 <= p.length <= 20 s contains only lowercase English letters. p contains only lowercase English letters, '.', and '*'. It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. | https://leetcode.com/problems/regular-expression-matching/submissions/872758023/ | class Solution(object): def isMatch(self, s, p): # Edge cases: if the pattern is empty if not p: return not s # Check if the first characters match first_match = bool(s) and p[0] in {s[0], '.'} # Check if the second character is '*' if len(p) >= 2 and p[1] == '*': # Check if the first character is repeated 0 times, or if the first characters match and the rest of the string and pattern match return self.isMatch(s, p[2:]) or (first_match and self.isMatch(s[1:], p)) else: # Check if the first characters match and the rest of the string and pattern match return first_match and self.isMatch(s[1:], p[1:]) | Correta | 2687 | 13.4 | 2687 | 13.9 | 22 | 13.1 | 1 | FALSE | string | dynamic programming | recursion | |||||||||||||
39 | hard | https://leetcode.com/problems/merge-k-sorted-lists/description/ | 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: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [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: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] Constraints: k == lists.length 0 <= k <= 104 0 <= lists[i].length <= 500 -104 <= lists[i][j] <= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104. | https://leetcode.com/problems/merge-k-sorted-lists/submissions/872754809/ | # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeKLists(self, lists): # Edge case: if the input list is empty if not lists: return None # Initialize a heap to store the nodes heap = [] # Add the first node of each linked list to the heap for i, lst in enumerate(lists): if lst: heap.append((lst.val, i)) # Build the heap heapq.heapify(heap) # Initialize the dummy node dummy = ListNode(0) curr = dummy # Repeat until the heap is empty while heap: # Pop the smallest node from the heap val, i = heapq.heappop(heap) curr.next = ListNode(val) curr = curr.next # Add the next node of the linked list to the heap lists[i] = lists[i].next if lists[i]: heapq.heappush(heap, (lists[i].val, i)) # Return the merged linked list return dummy.next | Correta | 186 | 19.5 | 6102 | 25 | 96 | 18.8 | 1 | FALSE | linked list | divide and conquer | heap | merge sort | ||||||||||||
40 | hard | https://leetcode.com/problems/reverse-nodes-in-k-group/description/ | 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: Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5] Example 2: Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 5000 0 <= Node.val <= 1000 | https://leetcode.com/problems/reverse-nodes-in-k-group/submissions/927207811/ | # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: # check if there are at least k nodes left count = 0 node = head while node and count < k: node = node.next count += 1 if count < k: return head # reverse the first k nodes prev = None curr = head for i in range(k): nxt = curr.next curr.next = prev prev = curr curr = nxt # recursively reverse the remaining part of the list head.next = self.reverseKGroup(curr, k) # return the new head of the reversed list return prev | Correta | 46 | 15.2 | 64 | 15.7 | 29 | 14.4 | 2 | TRUE | linked list | recursion | ||||||||||||||
41 | hard | https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/ | You are given a string s and an array of strings words. All the strings of words are of the same length. A concatenated substring in s is a substring that 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 substring because it is not the concatenation of any permutation of words. Return the starting indices of all the concatenated substrings in s. You can return the answer in any order. Example 1: Input: s = "barfoothefoobarman", words = ["foo","bar"] Output: [0,9] Explanation: Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6. 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. The output order does not matter. Returning [9,0] is fine too. Example 2: Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] Output: [] Explanation: Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16. There is no substring of length 16 is s that is equal to the concatenation of any permutation of words. We return an empty array. Example 3: Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] Output: [6,9,12] Explanation: Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9. The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"] which is a permutation of words. The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"] which is a permutation of words. The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"] which is a permutation of words. Constraints: 1 <= s.length <= 104 1 <= words.length <= 5000 1 <= words[i].length <= 30 s and words[i] consist of lowercase English letters. | https://leetcode.com/problems/substring-with-concatenation-of-all-words/submissions/872768725/ | from collections import Counter class Solution: def findSubstring(self, s, words): word_count = Counter(words) word_len = len(words[0]) total_len = word_len * len(words) result = [] for i in range(len(s) - total_len + 1): window = s[i:i+total_len] window_count = Counter([window[j:j+word_len] for j in range(0, total_len, word_len)]) if window_count == word_count: result.append(i) return result | Correta | 690 | 14.1 | 6364 | 15.4 | 90 | 14 | 2 | FALSE | hash table | string | sliding window | |||||||||||||
42 | hard | https://leetcode.com/problems/longest-valid-parentheses/ | Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring . Example 1: Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()". Example 2: Input: s = ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()". Example 3: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 3 * 104 s[i] is '(', or ')'. | https://leetcode.com/problems/longest-valid-parentheses/submissions/927210582/ | class Solution: def longestValidParentheses(self, s: str) -> int: stack = [-1] max_len = 0 for i in range(len(s)): if s[i] == '(': stack.append(i) else: stack.pop() if stack: max_len = max(max_len, i - stack[-1]) else: stack.append(i) return max_len | Correta | 43 | 14.6 | 77 | 15.8 | 23 | 13.7 | 2 | FALSE | string | dynamic programming | stack | |||||||||||||
43 | hard | https://leetcode.com/problems/sudoku-solver/description/ | 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: Input: 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"]] Output: [["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: Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit or '.'. It is guaranteed that the input board has only one solution. | https://leetcode.com/problems/sudoku-solver/submissions/872866188/ | class Solution: def solveSudoku(self, board): def is_valid(x, y, val): # check if val is a valid value for the given row and column for i in range(9): if board[x][i] == val: return False if board[i][y] == val: return False # check if val is a valid value for the given 3x3 sub-box x_start = (x // 3) * 3 y_start = (y // 3) * 3 for i in range(3): for j in range(3): if board[x_start + i][y_start + j] == val: return False return True def solve(board): for i in range(9): for j in range(9): if board[i][j] == '.': for k in range(1, 10): if is_valid(i, j, str(k)): board[i][j] = str(k) if solve(board): return True board[i][j] = '.' return False return True solve(board) | Correta | 574 | 13.9 | 2196 | 14.4 | 36 | 13.7 | 1 | TRUE | array | hash table | backtracking | matrix | ||||||||||||
44 | hard | https://leetcode.com/problems/first-missing-positive/ | Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space. Example 1: Input: nums = [1,2,0] Output: 3 Explanation: The numbers in the range [1,2] are all in the array. Example 2: Input: nums = [3,4,-1,1] Output: 2 Explanation: 1 is in the array but 2 is missing. Example 3: Input: nums = [7,8,9,11,12] Output: 1 Explanation: The smallest positive integer 1 is missing. Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 | https://leetcode.com/problems/first-missing-positive/submissions/877035818/ | class Solution: def firstMissingPositive(self, nums: List[int]) -> int: n = len(nums) for i in range(n): while 0 < nums[i] <= n and nums[nums[i]-1] != nums[i]: nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] for i in range(n): if nums[i] != i+1: return i+1 return n+1 | Correta | 304 | 27.2 | 1007 | 31.2 | 233 | 23.2 | 1 | FALSE | array | hash table | ||||||||||||||
45 | hard | https://leetcode.com/problems/trapping-rain-water/ | 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: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 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: Input: height = [4,2,0,3,2,5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 104 0 <= height[i] <= 105 | https://leetcode.com/problems/trapping-rain-water/submissions/877036618/ | class Solution: def trap(self, height: List[int]) -> int: left, right = 0, len(height) - 1 trapped_water = 0 left_max, right_max = 0, 0 while left < right: if height[left] < height[right]: if height[left] >= left_max: left_max = height[left] else: trapped_water += left_max - height[left] left += 1 else: if height[right] >= right_max: right_max = height[right] else: trapped_water += right_max - height[right] right -= 1 return trapped_water | Correta | 103 | 16 | 442 | 16.4 | 96 | 14.3 | 1 | TRUE | array | two pointers | dynamic programming | stack | monotonic stack | |||||||||||
46 | hard | https://leetcode.com/problems/wildcard-matching/ | 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: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb", p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Constraints: 0 <= s.length, p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters, '?' or '*'. | https://leetcode.com/problems/wildcard-matching/submissions/877038007/ | class Solution: def isMatch(self, s: str, p: str) -> bool: m, n = len(s), len(p) dp = [[False] * (n + 1) for _ in range(m + 1)] dp[0][0] = True for j in range(1, n + 1): if p[j - 1] == '*': dp[0][j] = dp[0][j - 1] for i in range(1, m + 1): for j in range(1, n + 1): if p[j - 1] == '*': dp[i][j] = dp[i][j - 1] or dp[i - 1][j] elif p[j - 1] == '?' or s[i - 1] == p[j - 1]: dp[i][j] = dp[i - 1][j - 1] return dp[m][n] | Correta | 786 | 22.4 | 2566 | 155.4 | 45 | 14.6 | 2 | FALSE | string | dynamic programming | greedy | recursion | ||||||||||||
47 | hard | https://leetcode.com/problems/n-queens/ | 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: Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Example 2: Input: n = 1 Output: [["Q"]] Constraints: 1 <= n <= 9 | https://leetcode.com/problems/n-queens/submissions/877039550/ | class Solution: def solveNQueens(self, n: int) -> List[List[str]]: def is_safe(board, row, col): for i in range(row): if board[i] == col or abs(board[i] - col) == abs(i - row): return False return True def backtrack(board, row): if row == n: result.append(["." * i + "Q" + "." * (n-i-1) for i in board]) else: for col in range(n): if is_safe(board, row, col): board[row] = col backtrack(board, row + 1) board[row] = -1 result = [] backtrack([-1] * n, 0) return result | Correta | 101 | 14.5 | 1107 | 14.7 | 39 | 12.9 | 1 | TRUE | array | backtracking | ||||||||||||||
48 | hard | https://leetcode.com/problems/n-queens-ii/ | 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: Input: n = 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown. Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 9 | https://leetcode.com/problems/n-queens-ii/submissions/877040453/ | class Solution: def totalNQueens(self, n: int) -> int: def is_safe(board, row, col): for i in range(row): if board[i] == col or abs(board[i] - col) == abs(i - row): return False return True def backtrack(board, row): if row == n: nonlocal result result += 1 else: for col in range(n): if is_safe(board, row, col): board[row] = col backtrack(board, row + 1) board[row] = -1 result = 0 backtrack([-1] * n, 0) return result | Correta | 88 | 13.8 | 661 | 14.2 | 23 | 13.6 | 1 | TRUE | backtracking | |||||||||||||||
49 | hard | https://leetcode.com/problems/permutation-sequence/ | 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: Input: n = 3, k = 3 Output: "213" Example 2: Input: n = 4, k = 9 Output: "2314" Example 3: Input: n = 3, k = 1 Output: "123" Constraints: 1 <= n <= 9 1 <= k <= n! | https://leetcode.com/problems/permutation-sequence/submissions/877096015/ | from math import factorial class Solution: def getPermutation(self, n: int, k: int) -> str: numbers = list(range(1, n+1)) permutation = "" k -= 1 while n > 0: n -= 1 index, k = divmod(k, factorial(n)) permutation += str(numbers[index]) numbers.remove(numbers[index]) return permutation | Correta | 31 | 13.8 | 5584 | 57.2 | 51 | 13.7 | 1 | FALSE | math | recursion | ||||||||||||||
50 | hard | https://leetcode.com/problems/valid-number/ | A valid number can be split up into these components (in order): A decimal number or an integer. (Optional) An 'e' or 'E', followed by an integer. A decimal number can be split up into these components (in order): (Optional) A sign character (either '+' or '-'). One of the following formats: One or more digits, followed by a dot '.'. One or more digits, followed by a dot '.', followed by one or more digits. A dot '.', followed by one or more digits. An integer can be split up into these components (in order): (Optional) A sign character (either '+' or '-'). One or more digits. 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"]. Given a string s, return true if s is a valid number. Example 1: Input: s = "0" Output: true Example 2: Input: s = "e" Output: false Example 3: Input: s = "." Output: false Constraints: 1 <= s.length <= 20 s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'. | https://leetcode.com/problems/valid-number/submissions/927221097/ | import re class Solution: def isNumber(self, s: str) -> bool: # Remove leading and trailing white spaces s = s.strip() # Define the regular expression pattern pattern = r'^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$' # Match the string against the regular expression pattern match = re.match(pattern, s) # If the string matches the pattern, return true, else return false return match is not None | Correta | 31 | 13.9 | 47 | 13.9 | 16 | 13.6 | 3 | FALSE | string | |||||||||||||||
51 | hard | https://leetcode.com/problems/text-justification/ | 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: Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 Output: [ "This is an", "example of text", "justification. " ] Example 2: Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 Output: [ "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: Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 Output: [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ] Constraints: 1 <= words.length <= 300 1 <= words[i].length <= 20 words[i] consists of only English letters and symbols. 1 <= maxWidth <= 100 words[i].length <= maxWidth | https://leetcode.com/problems/text-justification/submissions/877098343/ | class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: lines = [] line = [] line_length = 0 for word in words: if line_length + len(line) + len(word) > maxWidth: for i in range(maxWidth - line_length): line[i % (len(line) - 1 or 1)] += ' ' lines.append(''.join(line)) line = [] line_length = 0 line.append(word) line_length += len(word) lines.append(' '.join(line).ljust(maxWidth)) return lines | Correta | 31 | 13.8 | 71 | 14 | 14 | 13.7 | 1 | FALSE | array | string | simulation | |||||||||||||
52 | ||||||||||||||||||||||||||||||
53 | ||||||||||||||||||||||||||||||
54 | ||||||||||||||||||||||||||||||
55 | ||||||||||||||||||||||||||||||
56 | ||||||||||||||||||||||||||||||
57 | ||||||||||||||||||||||||||||||
58 | ||||||||||||||||||||||||||||||
59 | ||||||||||||||||||||||||||||||
60 | ||||||||||||||||||||||||||||||
61 | ||||||||||||||||||||||||||||||
62 | ||||||||||||||||||||||||||||||
63 | ||||||||||||||||||||||||||||||
64 | ||||||||||||||||||||||||||||||
65 | ||||||||||||||||||||||||||||||
66 | ||||||||||||||||||||||||||||||
67 | ||||||||||||||||||||||||||||||
68 | ||||||||||||||||||||||||||||||
69 | ||||||||||||||||||||||||||||||
70 | ||||||||||||||||||||||||||||||
71 | ||||||||||||||||||||||||||||||
72 | ||||||||||||||||||||||||||||||
73 | ||||||||||||||||||||||||||||||
74 | ||||||||||||||||||||||||||||||
75 | ||||||||||||||||||||||||||||||
76 | ||||||||||||||||||||||||||||||
77 | ||||||||||||||||||||||||||||||
78 | ||||||||||||||||||||||||||||||
79 | ||||||||||||||||||||||||||||||
80 | ||||||||||||||||||||||||||||||
81 | ||||||||||||||||||||||||||||||
82 | ||||||||||||||||||||||||||||||
83 | ||||||||||||||||||||||||||||||
84 | ||||||||||||||||||||||||||||||
85 | ||||||||||||||||||||||||||||||
86 | ||||||||||||||||||||||||||||||
87 | ||||||||||||||||||||||||||||||
88 | ||||||||||||||||||||||||||||||
89 | ||||||||||||||||||||||||||||||
90 | ||||||||||||||||||||||||||||||
91 | ||||||||||||||||||||||||||||||
92 | ||||||||||||||||||||||||||||||
93 | ||||||||||||||||||||||||||||||
94 | ||||||||||||||||||||||||||||||
95 | ||||||||||||||||||||||||||||||
96 | ||||||||||||||||||||||||||||||
97 | ||||||||||||||||||||||||||||||
98 | ||||||||||||||||||||||||||||||
99 | ||||||||||||||||||||||||||||||
100 |