LEETCODE LEGENDARY SET
53. Maximum Subarray Given an integer array nums, find the subarray with the largest sum, and returnits sum. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6.
class Solution: def maxSubArray(self, nums: List[int]) -> int: maxSum = max(nums) curSum = 0 for num in nums: if curSum < 0: curSum = 0 curSum += num maxSum = max(curSum, maxSum) return maxSum - go through the array and add to your curSum - if your current sum falls below zero, reset your current sum to zero - if not, consider it for your new max
33. Search in Rotated Sorted Array
class Solution: def search(self, nums: List[int], target: int) -> int: l = 0 r = len(nums) - 1 while l <= r: m = (l + r) // 2 if nums[m] == target: return m if nums[m] >= nums[l]: if target < nums[l] or nums[m] < target: l = m +1 else: r = m -1 else: if target > nums[r] or target < nums[m]: r = m - 1 else: l = m +1 return -1
1. Two Sum (return the index) 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. Ex: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
class Solution(object): def twoSum(self, nums, target): dict = {} for i in range(len(nums)): targetSum = target - nums[i] if targetSum in dict: return[dict[targetSum], i] dict[nums[i]] = i - have a dictionary - calculate the targetSum - if the target number is in the dictionary, return dict[targetSum] and that will give you the index of the target number and i is the index of the other number you need - if not, add dict[nums[i]] = i to assign the value you are at to its index in the dictionary
217. Contains Duplicate Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() for i in range(len(nums)): if nums[i] in seen: return True seen.add(nums[i]) return False -create a set loop through the nums and see if the num is in the set - if not, add to set and once the loop finishes return False if a duplicate is not found
153. Find Minimum in Rotated Sorted Array Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5] rotated 3 times.
class Solution: def findMin(self, nums: List[int]) -> int: res = nums[0] l = 0 r = len(nums) -1 while l<= r: if nums[l] < nums[r]: res = min(nums[l], res) break m = (l + r) // 2 res = min(res, nums[m]) if nums[m] >= nums[l]: l = m +1 else: r = m - 1 return res - start a left pointer at the beginning of the list and a right pointer at the end of the list - if nums[l] is less than nums[r], because this is a rotated array, than we know we've found out minimum if not, we do binary search and we calculate the middle and see if that can be our new minimum - then we check if the value at m is bigger than l, if it is then we know that our minimum is to the right of m and we adjust l, if this is not true then we know our minimum is to the left of middle so we adjust r - if middle is our minimum at some point, the code will terminate when r is eventually less than l
152. Maximum Product Subarray Given an integer array nums, find a subarray that has the largest product, and returnthe product. The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
class Solution: def maxProduct(self, nums: List[int]) -> int: maxNum = 1 minNum = 1 theMax = max(nums) for i in nums: if i == 0: maxNum = 1 minNum = 1 continue tmp = maxNum maxNum = max(maxNum * i, minNum *i, i) minNum = min(minNum *i, tmp*i, i) theMax = max(theMax, maxNum) return theMax - because there are negative numbers involved, we need to keep track of the max and the min - loop through the numbers and keep track of the new max and new min at all times - if there is a zero, reset the maxNum and minNum to 1
121. Best Time to Buy and Sell Stock You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. Ex: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
class Solution: def maxProfit(self, prices: List[int]) -> int: max_Profit = 0 l = 0 for r in range(1, len(prices)): current_Profit = prices[r] - prices[l] if current_Profit < 0: l = r else: max_Profit = max(current_Profit, max_Profit) return max_Profit - start by initializing a maxProfit at 0 - left pointer at 0 and a right pointer start at 1 and goes to the end of prices - calculate the currentProfit which is the r price - l price - if the profit is below 0, then we adjust l to equal r while r move each iteration - if the profit is not negative, we consider for our max and finally return max
1768. Merge Strings Alternately You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. Ex: Input: word1 = "abc", word2 = "pqr" Output: "apbqcr" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: res = '' for i in range(min(len(word1),len(word2))): res += word1[i] + word2[i] return res + word1[i+1:] + word2[i+1:] - start with an empty string - loop through the minimum length of the two given strings and add to res - return res + the excess of the string if they are not the same length
238. Product of Array Except Itself Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6]
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: res = [1]* len(nums) prefix = 1 for i in range(len(nums)): res[i] = prefix prefix *= nums[i] postfix = 1 for i in range(len(nums)-1, -1, -1): res[i] *= postfix postfix *= nums[i] return res - think prefix and postfix and store this in the original array
15. 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.
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for i in range(len(nums)): if i>0 and nums[i] == nums[i-1]: continue l,r = i+1, len(nums) -1 while l<r: threeSum = nums[i] + nums[l] + nums[r] if threeSum >0: r -= 1 elif threeSum <0: l+=1 else: res.append([nums[i],nums[l],nums[r]]) l += 1 while nums[l] == nums[l-1] and l<r: l+=1 return res
1. Two Sum (return the values)
def twoNumberSum(array, target): seen = set() for num in array: targetSum = target - num if targetSum in seen: return targetSum, num seen.add(num) return [] - create a set - loop through the array and cacluate the targetSum - if the targetSum is in seen, return the targetSum, num - if not add to the set