├── Medium ├── 50. Pow(x,n).py ├── 80. Remove Duplicates from Sorted Array II.py ├── 452. Minimum Number of Arrows to Burst Balloons.py ├── 856. Score of Parentheses.py ├── 946. Validate Stack Sequences.py ├── 1029. Two City Scheduling.py ├── 991. Broken Calculator.py ├── 1094. Car Pooling.py ├── 1046. Last Stone Weight.py ├── 1291. Sequential Digits.py ├── 287. Find the Duplicate Number.py ├── 165. Compare Version Numbers.py ├── 11. Container With Most Water.py ├── 1584. Min Cost to Connect All Points.py ├── 230. Kth Smallest Element in a BST.py ├── 2186. Minimum Number of Steps to Make Two Strings Anagram II.py ├── 454. 4Sum II.py ├── 1288. Remove Covered Intervals.py ├── 382. Linked List Random Node.py ├── 39. Combination Sum.py ├── 1721. Swapping Nodes in a Linked List.py ├── 923. 3Sum With Multiplicity.py ├── 74. Search a 2D Matrix.py ├── 24. Swap Nodes in Pairs.py ├── 31. Next Permutation.py ├── 82. Remove Duplicates from Sorted List II.py ├── 567. Permutation in String.py ├── 701. Insert into a Binary Search Tree.py ├── 881. Boats to Save People.py ├── 525. Contiguous Array.py ├── 538. Convert BST to Greater Tree.py ├── 535. Encode and Decode TinyURL.py ├── 413. Arithmetic Slices.py ├── 59. Spiral Matrix II.py ├── 1631. Path With Minimum Effort.py ├── 1396. Design Underground System.py ├── 669. Trim a Binary Search Tree.py ├── 81. Search in Rotated Sorted Array II.py ├── 785. Is Graph Bipartite.py ├── 2177. Find Three Consecutive Integers That Sum to a Given Number.py ├── 189. Rotate Array.py ├── 8. String to Integer (atoi).py ├── 799. Champagne Tower.py ├── 173. Binary Search Tree Iterator.py ├── 438. Find All Anagrams in a String.py ├── 1305. All Elements in Two Binary Search Trees.py ├── 849. Maximum Distance to Closest Person.py ├── 532. K-diff Pairs in an Array.py ├── 1010. Pairs of Songs with Total durations divisible by 60.py ├── 78. Subsets.py ├── 421. Maximum XOR of Two Numbers in an Array.py ├── 662. Maximum Width of Binary Tree.py ├── 763. Partition Labels.py ├── 399. Evaluate Division.py ├── 148. Sort List.py ├── 740. Delete and Earn.py ├── 1007. Minimum Domino Rotations For Equal Row.py ├── 99. Recover Binary Search Tree.py ├── 1663. Smallest String With A Given Numeric Value.py ├── 131. Palindrome Partitioning.py ├── 1202. Smallest String With Swaps.py ├── 211. Design Add and Search Words Data Structure.py ├── 142. Linked List Cycle II.py ├── 284. Peeking Iterator.py ├── 560. Subarray Sum Equals K.py ├── 289. Game of Life.py ├── 133. Clone Graph.py ├── 402. Remove K Digits.py └── 1041. Robot Bounded In Circle.py ├── Easy ├── 709. To Lower Case.py ├── 1929. Concatenation of Array.py ├── 268. Missing Number.py ├── 1920. Build Array from Permutation.py ├── 383. Ransom Note.py ├── 2185. Counting Words With a Given Prefix.py ├── 202. Happy Number.py ├── 1342. Number of Steps to Reduce a Number to Zero.py ├── 1678. Goal Parser Interpretation.py ├── 1822. Sign of the Product of an Array.py ├── 104. Maximum Depth of Binary Tree.py ├── 1491. Average Salary Excluding the Minimum and Maximum Salary.py ├── 283. Move Zeroes.py ├── 136. Single Number.py ├── 242. Valid Anagram.py ├── 941. Valid Mountain Array.py ├── 2206. Divide Array Into Equal Pairs.py ├── 1009. Complement of Base 10 Integer.py ├── 1281. Subtract the Product and Sum of Digits of an Integer.py ├── 1356. Sort Integers by The Number of 1 Bits.py ├── 2169. Count Operations to Obtain Zero.py ├── 2180. Count Integers With Even Digit Sum.py ├── 412. Fizz Buzz.py ├── 605. Can Place Flowers.py ├── 566. Reshape the Matrix.py ├── 1480. Running Sum of 1d Array.py ├── 1502. Can Make Arithmetic Progression From Sequence.py ├── 700. Search in a Binary Search Tree.py ├── 141. Linked List Cycle.py ├── 680. Valid Palindrome II.py ├── 1779. Find Nearest Point That Has the Same X or Y Coordinate.py ├── 520. Detect Capital.py ├── 496. Next Greater Element I.py ├── 228. Summary Ranges.py ├── 1572. Matrix Diagonal Sum.py ├── 404. Sum of Left Leaves.py ├── 2160. Minimum Sum of Four Digit Number After Splitting Digits.py ├── 338. Counting Bits.py ├── 53. Maximum Subarray.py ├── 706. Design HashMap.py ├── 976. Largest Perimeter Triangle.py ├── 191. Number of 1 Bits.py ├── 35. Search Insert Position.py ├── 997. Find the Town Judge.py ├── 1523. Count Odd Numbers in an Interval Range.py ├── 724. Find Pivot Index.py ├── 303. Range Sum Query - Immutable.py ├── 1022. Sum of Root to Leaf Binary Numbers.py ├── 703. Kth Largest Element in a Stream.py ├── 1232. Check If It Is a Straight Line.py ├── 21. Merge Two Sorted Lists.py ├── 1588. Sum of All Odd Length Subarrays.py ├── 1672. Richest Customer Wealth.py ├── 953. Verifying an Alien Dictionary.py ├── 232. Implement Queue using Stacks.py ├── 897. Increasing Order Search Tree.py ├── 1337. The K Weakest Rows in a Matrix.py ├── 27. Remove Element.py ├── 705. Design HashSet.py ├── 1603. Design Parking System.py ├── 2176. Count Equal and Divisible Pairs in an Array.py ├── 2129. Capitalize the Title.py ├── 2164. Sort Even and Odd Indices Independently.py ├── 121. Best Time to Buy and Sell Stock.py ├── 389. Find the Difference.py ├── 290. Word Pattern.py ├── 392. Is Subsequence.py ├── 67. Add Binary.py ├── 1768. Merge Strings Alternately.py ├── 1290. Convert Binary Number in a Linked List to Integer.py ├── 344. Reverse String.py ├── 704. Binary Search.py ├── 876. Middle of the Linked List.py ├── 1. Two Sum.py ├── 26. Remove Duplicates from Sorted Array.py ├── 258. Add Digits.py ├── 589. N-ary Tree Preorder Traversal.py ├── 171. Excel Sheet Column Number.py ├── 1309. Decrypt String from Alphabet to Integer Mapping.py ├── 1790. Check if One String Swap Can Make Strings Equal.py ├── 9. Palindrome Number.py └── 169. Majority Element..py ├── Study Plan └── Data Structure I │ └── 217. Contains Duplicate.py ├── Hard ├── 84. Largest Rectangle in Histogram.py ├── 312. Burst Balloons.py ├── 1463. Cherry Pickup II.py ├── 23. Merge k Sorted Lists.py ├── 895. Maximum Frequency Stack.py ├── 1675. Minimize Deviation in Array.py ├── 1345. Jump Game IV.py ├── 127. Word Ladder.py ├── 1359. Count All Valid Pickup and Delivery Options.py ├── 410. Split Array Largest Sum.py └── 847. Shortest Path Visiting All Nodes.py └── README.md /Medium/50. Pow(x,n).py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/powx-n/ 2 | 3 | class Solution: 4 | def myPow(self, x: float, n: int) -> float: 5 | return x**n 6 | -------------------------------------------------------------------------------- /Easy/709. To Lower Case.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/to-lower-case/ 2 | 3 | class Solution: 4 | def toLowerCase(self, s: str) -> str: 5 | return s.lower() -------------------------------------------------------------------------------- /Easy/1929. Concatenation of Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/concatenation-of-array/ 2 | 3 | class Solution: 4 | def getConcatenation(self, nums: List[int]) -> List[int]: 5 | return nums*2 -------------------------------------------------------------------------------- /Easy/268. Missing Number.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://leetcode.com/problems/missing-number/ 2 | 3 | class Solution: 4 | def missingNumber(self, nums: List[int]) -> int: 5 | for i in range(len(nums)+1): 6 | if i in nums: 7 | pass 8 | else: 9 | return i -------------------------------------------------------------------------------- /Easy/1920. Build Array from Permutation.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/build-array-from-permutation/ 2 | 3 | class Solution: 4 | def buildArray(self, nums: List[int]) -> List[int]: 5 | num = nums 6 | arr = [] 7 | for i in range(len(num)): 8 | arr.append(num[num[i]]) 9 | return arr -------------------------------------------------------------------------------- /Easy/383. Ransom Note.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/ransom-note/ 2 | 3 | class Solution: 4 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 5 | for i in set(ransomNote): 6 | if ransomNote.count(i) > magazine.count(i): 7 | return False 8 | return True 9 | -------------------------------------------------------------------------------- /Easy/2185. Counting Words With a Given Prefix.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/counting-words-with-a-given-prefix/ 2 | 3 | class Solution: 4 | def prefixCount(self, words: List[str], pref: str) -> int: 5 | count = 0 6 | for word in words: 7 | if pref in word[:len(pref)]: 8 | count += 1 9 | return count -------------------------------------------------------------------------------- /Medium/80. Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 2 | 3 | class Solution: 4 | def removeDuplicates(self, nums): 5 | i = 0 6 | for n in nums: 7 | if i < 2 or n > nums[i-2]: 8 | nums[i] = n 9 | i += 1 10 | return i -------------------------------------------------------------------------------- /Study Plan/Data Structure I/217. Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://leetcode.com/problems/contains-duplicate/ 2 | class Solution: 3 | def containsDuplicate(self, nums): 4 | return (len(nums) > len(set(nums))) 5 | 6 | # Alternate Method 7 | class Solution: 8 | def containsDuplicate(self, nums: List[int]) -> bool: 9 | array = set(nums) 10 | return (len(array) != len(nums)) -------------------------------------------------------------------------------- /Medium/452. Minimum Number of Arrows to Burst Balloons.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ 2 | 3 | class Solution(object): 4 | def findMinArrowShots(self, points): 5 | points.sort(key=lambda p: p[1]) 6 | ans, arrow = 0, 0 7 | for [start, end] in points: 8 | if ans == 0 or start > arrow: 9 | ans, arrow = ans + 1, end 10 | return ans -------------------------------------------------------------------------------- /Easy/202. Happy Number.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/happy-number/ 2 | 3 | class Solution: 4 | def isHappy(self, n: int) -> bool: 5 | while(n > 6 and n!=1): 6 | squareSum = 0 7 | num = str(n) 8 | for i in range(len(num)): 9 | squareSum += int(num[i])**2 10 | n = squareSum 11 | 12 | if n == 1: 13 | return True 14 | return False -------------------------------------------------------------------------------- /Medium/856. Score of Parentheses.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/score-of-parentheses/ 2 | 3 | class Solution(object): 4 | def scoreOfParentheses(self, s): 5 | stack = [] 6 | answer = 0 7 | for c in s: 8 | if c == '(': 9 | stack.append(answer) 10 | answer = 0 11 | else: 12 | answer = stack.pop() + max(1, answer*2) 13 | return answer -------------------------------------------------------------------------------- /Easy/1342. Number of Steps to Reduce a Number to Zero.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ 2 | 3 | class Solution: 4 | def numberOfSteps(self, num: int) -> int: 5 | step = 0 6 | while(num != 0): 7 | if num%2 == 0: 8 | num //= 2 9 | step += 1 10 | else: 11 | num -= 1 12 | step += 1 13 | return step -------------------------------------------------------------------------------- /Easy/1678. Goal Parser Interpretation.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/goal-parser-interpretation/ 2 | 3 | class Solution: 4 | def interpret(self, s: str) -> str: 5 | dic = {"(al)":"al", "()":"o","G":"G"} 6 | tmp = "" 7 | result = "" 8 | for i in range(len(s)): 9 | tmp += s[i] 10 | if(tmp in dic): 11 | result += dic[tmp] 12 | tmp = "" 13 | return result -------------------------------------------------------------------------------- /Easy/1822. Sign of the Product of an Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sign-of-the-product-of-an-array/ 2 | 3 | class Solution: 4 | def arraySign(self, nums: List[int]) -> int: 5 | product = 1 6 | for i in range(len(nums)): 7 | product *= nums[i] 8 | 9 | if product == 0: 10 | return 0 11 | elif product > 0: 12 | return 1 13 | else: 14 | return -1 -------------------------------------------------------------------------------- /Medium/946. Validate Stack Sequences.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/validate-stack-sequences/ 2 | 3 | class Solution: 4 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: 5 | index, stack = 0, [] 6 | for p in pushed: 7 | stack.append(p) 8 | while stack and stack[-1] == popped[index]: 9 | stack.pop() 10 | index += 1 11 | return not stack -------------------------------------------------------------------------------- /Easy/104. Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def maxDepth(self, root): 11 | return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0 -------------------------------------------------------------------------------- /Easy/1491. Average Salary Excluding the Minimum and Maximum Salary.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/ 2 | 3 | class Solution: 4 | def average(self, salary: List[int]) -> float: 5 | minimum = min(salary) 6 | maximum = max(salary) 7 | salary.remove(minimum) 8 | salary.remove(maximum) 9 | 10 | average = sum(salary) / len(salary) 11 | 12 | return average -------------------------------------------------------------------------------- /Medium/1029. Two City Scheduling.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/two-city-scheduling/ 2 | 3 | class Solution: 4 | def twoCitySchedCost(self, costs: List[List[int]]) -> int: 5 | refund = [] 6 | N = len(costs)//2 7 | minCost = 0 8 | for A, B in costs: 9 | refund.append(B - A) 10 | minCost += A 11 | refund.sort() 12 | for i in range(N): 13 | minCost += refund[i] 14 | return minCost -------------------------------------------------------------------------------- /Easy/283. Move Zeroes.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/move-zeroes/ 2 | 3 | class Solution: 4 | def moveZeroes(self, nums: List[int]) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | last0 = 0 9 | for i in range(0,len(nums)): 10 | if (nums[i]!=0): 11 | nums[i],nums[last0] = nums[last0],nums[i] 12 | last0+=1 13 | #nums.sort(key=bool, reverse=True) -------------------------------------------------------------------------------- /Medium/991. Broken Calculator.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/broken-calculator/ 2 | 3 | class Solution: 4 | def brokenCalc(self, X, Y): 5 | if X > Y: return X - Y 6 | if X == Y: return 0 7 | if Y % 2 == 0: 8 | return self.brokenCalc(X, Y//2) + 1 9 | else: 10 | return self.brokenCalc(X, Y + 1) + 1 11 | 12 | #https://leetcode.com/problems/broken-calculator/discuss/1076046/Python-Greedy-solution-explained -------------------------------------------------------------------------------- /Easy/136. Single Number.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/single-number/ 2 | 3 | class Solution: 4 | def singleNumber(self, nums: List[int]) -> int: 5 | for num in nums: 6 | if nums.count(num) == 1: 7 | return num 8 | 9 | # Alternative Solution 10 | class Solution: 11 | def singleNumber(self, nums: List[int]) -> int: 12 | result = 0 13 | for i in range(len(nums)): 14 | result ^= nums[i] 15 | return result -------------------------------------------------------------------------------- /Easy/242. Valid Anagram.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/valid-anagram/ 2 | 3 | class Solution: 4 | def isAnagram(self, s, t): 5 | dic1, dic2 = {}, {} 6 | for item in s: 7 | dic1[item] = dic1.get(item, 0) + 1 8 | for item in t: 9 | dic2[item] = dic2.get(item, 0) + 1 10 | return dic1 == dic2 11 | 12 | # Alternate Solution 13 | class Solution: 14 | def isAnagram(self, s, t): 15 | return sorted(s) == sorted(t) -------------------------------------------------------------------------------- /Easy/941. Valid Mountain Array.py: -------------------------------------------------------------------------------- 1 | # problem Statement: https://leetcode.com/problems/valid-mountain-array/ 2 | 3 | class Solution: 4 | def validMountainArray(self, arr: List[int]) -> bool: 5 | if len(arr) < 3: return False 6 | left = 0 7 | right = len(arr) - 1 8 | while left + 1 < len(arr) - 1 and arr[left] < arr[left + 1]: 9 | left += 1 10 | while right - 1 > 0 and arr[right] < arr[right - 1]: 11 | right -= 1 12 | return left == right -------------------------------------------------------------------------------- /Easy/2206. Divide Array Into Equal Pairs.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/divide-array-into-equal-pairs/ 2 | 3 | class Solution: 4 | def divideArray(self, nums: List[int]) -> bool: 5 | #counting appearances 6 | count = collections.Counter(nums) 7 | #if a number has an odd frequency, it can't be split as the constraints require, so we can just return false 8 | for k, v in count.items(): 9 | if v % 2: 10 | return False 11 | return True -------------------------------------------------------------------------------- /Easy/1009. Complement of Base 10 Integer.py: -------------------------------------------------------------------------------- 1 | ## Problem Statement: https://leetcode.com/problems/complement-of-base-10-integer/ 2 | 3 | class Solution: 4 | def bitwiseComplement(self, n: int) -> int: 5 | if n == 0: 6 | return 1 7 | else: 8 | result = 0 9 | factor = 1 10 | 11 | while(n > 0): 12 | result += factor * (1 if n%2 == 0 else 0) 13 | factor *= 2 14 | n //= 2 15 | return result -------------------------------------------------------------------------------- /Easy/1281. Subtract the Product and Sum of Digits of an Integer.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ 2 | 3 | class Solution: 4 | def subtractProductAndSum(self, n: int) -> int: 5 | product_of_digits = 1 6 | sum_of_digits = 0 7 | n = str(n) 8 | for digit in n: 9 | product_of_digits *= int(digit) 10 | sum_of_digits += int(digit) 11 | 12 | return product_of_digits - sum_of_digits -------------------------------------------------------------------------------- /Easy/1356. Sort Integers by The Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ 2 | 3 | class Solution: 4 | def sortByBits(self, arr: List[int]) -> List[int]: 5 | arr.sort() 6 | brr=[] 7 | for i in arr: 8 | brr.append([i, bin(i).replace("0b","").count("1")]) 9 | brr.sort(key = lambda x: x[1]) 10 | ans=[] 11 | for element, bit_count in brr: 12 | ans.append(element) 13 | 14 | return ans -------------------------------------------------------------------------------- /Easy/2169. Count Operations to Obtain Zero.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/count-operations-to-obtain-zero/ 2 | 3 | class Solution: 4 | def countOperations(self, num1: int, num2: int) -> int: 5 | count = 0 6 | #while(num1 > 0 and num2 > 0): 7 | while(min(num1,num2) > 0): 8 | if num1 >= num2: 9 | num1 -= num2 10 | count += 1 11 | else: 12 | num2 -= num1 13 | count += 1 14 | return count -------------------------------------------------------------------------------- /Medium/1094. Car Pooling.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/car-pooling/ 2 | 3 | class Solution: 4 | def carPooling(self, trips: List[List[int]], capacity: int) -> bool: 5 | timestamp = [0] * 1001 6 | for number,start,end in trips: 7 | timestamp[start] += number 8 | timestamp[end] -= number 9 | size = 0 10 | for item in timestamp: 11 | size += item 12 | if size > capacity: 13 | return False 14 | return True -------------------------------------------------------------------------------- /Easy/2180. Count Integers With Even Digit Sum.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/count-integers-with-even-digit-sum/ 2 | 3 | class Solution: 4 | def countEven(self, num: int) -> int: 5 | count = 0 6 | for i in range(num+1): 7 | sum_of_digits = sum(int(digit) for digit in str(i)) 8 | if sum_of_digits % 2 == 0 and sum_of_digits != 0: 9 | count += 1 10 | return count 11 | #return sum(sum(int(x) for x in str(i)) % 2 == 0 for i in range(2, num + 1)) -------------------------------------------------------------------------------- /Easy/412. Fizz Buzz.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/fizz-buzz/ 2 | 3 | class Solution: 4 | def fizzBuzz(self, n: int) -> List[str]: 5 | ans = [] 6 | for i in range(1, n+1): 7 | if i % 3 == 0 and i % 5 == 0: 8 | ans.append("FizzBuzz") 9 | elif i % 3 == 0: 10 | ans.append("Fizz") 11 | elif i % 5 == 0: 12 | ans.append("Buzz") 13 | else: 14 | ans.append(str(i)) 15 | return ans 16 | -------------------------------------------------------------------------------- /Easy/605. Can Place Flowers.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/can-place-flowers/ 2 | 3 | class Solution(object): 4 | def canPlaceFlowers(self, flowerbed, n): 5 | if n == 0: return True 6 | for i in range(len(flowerbed)): 7 | if flowerbed[i] == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0): # can place? 8 | n -= 1 9 | if n == 0: return True 10 | flowerbed[i] = 1 # place! 11 | return False -------------------------------------------------------------------------------- /Easy/566. Reshape the Matrix.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/reshape-the-matrix/ 2 | 3 | class Solution: 4 | def matrixReshape(self,nums, r, c): 5 | flat_list = [] 6 | matrix = [] 7 | 8 | for sublist in nums: 9 | for item in sublist: 10 | flat_list.append(item) 11 | 12 | if len(flat_list) != r * c: 13 | return nums 14 | else: 15 | for i in range(0,len(flat_list),c): 16 | matrix.append(flat_list[i:i+c]) 17 | return matrix -------------------------------------------------------------------------------- /Easy/1480. Running Sum of 1d Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/running-sum-of-1d-array/ 2 | 3 | # Solution 1 4 | class Solution: 5 | def runningSum(self, nums: List[int]) -> List[int]: 6 | for i in range(1,len(nums)): 7 | nums[i] += nums[i-1] 8 | return nums 9 | 10 | #Solution 2 11 | class Solution: 12 | def runningSum(self, nums): 13 | result = [nums[0]] + [0] * (len(nums) - 1) 14 | for i, num in enumerate(nums[1:]): 15 | result[i + 1] += result[i] + num 16 | return result -------------------------------------------------------------------------------- /Easy/1502. Can Make Arithmetic Progression From Sequence.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ 2 | 3 | class Solution: 4 | def canMakeArithmeticProgression(self, arr: List[int]) -> bool: 5 | arr.sort() 6 | difference = arr[1] - arr[0] 7 | ans = False 8 | for i in range(len(arr)-1): 9 | if (arr[i+1] - arr[i]) == difference: 10 | ans = True 11 | else: 12 | ans = False 13 | return ans 14 | return ans -------------------------------------------------------------------------------- /Hard/84. Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | #Problem Statement: https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | 3 | class Solution: 4 | def largestRectangleArea(self, bars: List[int]) -> int: 5 | st, res = [], 0 6 | for bar in bars + [-1]: # add -1 to have an additional iteration 7 | step = 0 8 | while st and st[-1][1] >= bar: 9 | w, h = st.pop() 10 | step += w 11 | res = max(res, step * h) 12 | 13 | st.append((step + 1, bar)) 14 | 15 | return res -------------------------------------------------------------------------------- /Easy/700. Search in a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/search-in-a-binary-search-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 11 | while root: 12 | if val < root.val: root = root.left 13 | elif val > root.val: root = root.right 14 | else: return root 15 | return root -------------------------------------------------------------------------------- /Easy/141. Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/linked-list-cycle/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution: 10 | def hasCycle(self, head): 11 | try: 12 | slow = head 13 | fast = head.next 14 | while slow is not fast: 15 | slow = slow.next 16 | fast = fast.next.next 17 | return True 18 | except: 19 | return False -------------------------------------------------------------------------------- /Easy/680. Valid Palindrome II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/valid-palindrome-ii/ 2 | 3 | class Solution: 4 | def validPalindrome(self, s: str) -> bool: 5 | i = 0 6 | j = len(s)-1 7 | while i < j: 8 | if s[i] != s[j]: 9 | delete_i = s[i+1:j+1] 10 | delete_j = s[i:j] 11 | return self._isPalindrome(delete_i) or self._isPalindrome(delete_j) 12 | i += 1 13 | j -= 1 14 | return True 15 | 16 | def _isPalindrome(self, s): 17 | return s == s[::-1] -------------------------------------------------------------------------------- /Easy/1779. Find Nearest Point That Has the Same X or Y Coordinate.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/ 2 | 3 | class Solution: 4 | def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: 5 | m = 10000 6 | for i in points: 7 | if i[0] == x or i[1] == y: 8 | if m > abs(x-i[0]) + abs(y-i[1]): 9 | m = min(m,abs(x-i[0])+abs(y-i[1])) 10 | o = points.index(i) 11 | if m == 10000: 12 | return -1 13 | return o -------------------------------------------------------------------------------- /Easy/520. Detect Capital.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/detect-capital/ 2 | 3 | class Solution: 4 | def detectCapitalUse(self, word: str) -> bool: 5 | if word.isupper(): return True 6 | if word.islower(): return True 7 | if word[0].isupper() and word[1:].islower(): return True 8 | return False 9 | 10 | # Alternate Solution 11 | class Solution(object): 12 | def detectCapitalUse(self, word): 13 | return word.isupper() or word.islower() or word.istitle() 14 | 15 | # Post: https://leetcode.com/problems/detect-capital/discuss/1715987/Python-Easy -------------------------------------------------------------------------------- /Easy/496. Next Greater Element I.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/next-greater-element-i/ 2 | 3 | class Solution: 4 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 5 | greater_map = {x : -1 for x in nums1} 6 | stack = [] 7 | 8 | for num in nums2: 9 | while stack and stack[-1] < num: 10 | prev_num = stack.pop() 11 | if prev_num in greater_map: 12 | greater_map[prev_num] = num 13 | stack.append(num) 14 | 15 | return [greater_map[x] for x in nums1] -------------------------------------------------------------------------------- /Easy/228. Summary Ranges.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/summary-ranges/ 2 | 3 | class Solution: 4 | def summaryRanges(self, nums: List[int]) -> List[str]: 5 | start = 0 6 | end = 0 7 | result = [] 8 | while start < len(nums) and end'+str(nums[end])) 18 | start = end + 1 19 | end = end + 1 20 | return result -------------------------------------------------------------------------------- /Medium/1046. Last Stone Weight.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/last-stone-weight/ 2 | 3 | class Solution: 4 | def lastStoneWeight(self, stones: List[int]) -> int: 5 | sorted_stones = sorted(stones) 6 | while len(sorted_stones) > 1: 7 | stone1 = sorted_stones.pop() #highest 8 | stone2 = sorted_stones.pop() #second highest 9 | if stone2 != stone1: 10 | sorted_stones.append(stone1-stone2) 11 | sorted_stones = sorted(sorted_stones) 12 | if sorted_stones: 13 | return sorted_stones[0] 14 | return 0 -------------------------------------------------------------------------------- /Medium/1291. Sequential Digits.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sequential-digits/ 2 | 3 | class Solution: 4 | def sequentialDigits(self, low: int, high: int) -> List[int]: 5 | result = list() 6 | 7 | for window in range(floor(log10(low)) + 1, floor(log10(high)) + 2): 8 | for start in range(10 - window): 9 | number = 0 10 | for i in range(start, start + window): 11 | number = number * 10 + i + 1 12 | 13 | if low <= number <= high: 14 | result.append(number) 15 | 16 | return result -------------------------------------------------------------------------------- /Medium/287. Find the Duplicate Number.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-the-duplicate-number/ 2 | 3 | class Solution(object): 4 | def findDuplicate(self, nums): 5 | low = 0 6 | high = len(nums) - 1 7 | mid = (high + low) // 2 8 | while high - low > 1: 9 | count = 0 10 | for k in nums: 11 | if mid < k <= high: 12 | count += 1 13 | if count > high - mid: 14 | low = mid 15 | else: 16 | high = mid 17 | mid = (high + low) // 2 18 | return high -------------------------------------------------------------------------------- /Easy/1572. Matrix Diagonal Sum.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/matrix-diagonal-sum/ 2 | 3 | class Solution: 4 | def diagonalSum(self, mat: List[List[int]]) -> int: 5 | n = len(mat) 6 | mid = n // 2 7 | summation = 0 8 | for i in range(n): 9 | # primary diagonal 10 | summation += mat[i][i] 11 | # secondary diagonal 12 | summation += mat[n-1-i][i] 13 | if n % 2 == 1: 14 | # remove center element (repeated) on odd side-length case 15 | summation -= mat[mid][mid] 16 | 17 | return summation -------------------------------------------------------------------------------- /Medium/165. Compare Version Numbers.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/compare-version-numbers/ 2 | 3 | class Solution: 4 | def compareVersion(self, version1, version2): 5 | versions1 = [int(v) for v in version1.split(".")] 6 | versions2 = [int(v) for v in version2.split(".")] 7 | for i in range(max(len(versions1),len(versions2))): 8 | v1 = versions1[i] if i < len(versions1) else 0 9 | v2 = versions2[i] if i < len(versions2) else 0 10 | if v1 > v2: 11 | return 1 12 | elif v1 < v2: 13 | return -1 14 | return 0 -------------------------------------------------------------------------------- /Easy/404. Sum of Left Leaves.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sum-of-left-leaves/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution(object): 10 | def sumOfLeftLeaves(self, root): 11 | if not root: return 0 12 | if root.left and not root.left.left and not root.left.right: 13 | return root.left.val + self.sumOfLeftLeaves(root.right) 14 | return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) -------------------------------------------------------------------------------- /Medium/11. Container With Most Water.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/container-with-most-water/ 2 | 3 | class Solution(object): 4 | def maxArea(self, height): 5 | l, r, area = 0, len(height) - 1, 0 6 | while l < r: 7 | min_height=min(height[l], height[r]) 8 | area = max(area, (r - l) * min_height) 9 | if height[l] < height[r]: 10 | l+=1 11 | while height[l] int: 5 | x = [int(a) for a in str(num)] 6 | mini = min(x) 7 | x.remove(min(x)) 8 | smini = min(x) 9 | x.remove(min(x)) 10 | #print(mini,smini) 11 | #print(x) 12 | mini = str(mini) + str(x[0]) 13 | num1 = int(mini) 14 | #print(num1) 15 | smini = str(smini) + str(x[1]) 16 | num2 = int(smini) 17 | #print(num2) 18 | return num1 + num2 -------------------------------------------------------------------------------- /Easy/338. Counting Bits.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/counting-bits/ 2 | 3 | class Solution: 4 | def countBits(self, n: int) -> List[int]: 5 | def toBinary(num): 6 | return bin(num).replace("0b", "") 7 | 8 | binary_num = [] 9 | for i in range(n+1): 10 | num = toBinary(i) 11 | binary_num.append(str(num)) 12 | 13 | answer = [] 14 | for element in binary_num: 15 | count = 0 16 | for digit in element: 17 | if digit == '1': 18 | count += 1 19 | answer.append(count) 20 | return answer -------------------------------------------------------------------------------- /Easy/53. Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/maximum-subarray/ 2 | 3 | 4 | # Brute Force Solution : Complexity - O(n^2) 5 | class Solution: 6 | def maxSubArray(self, nums): 7 | dp = [[0]*len(nums) for i in range(2)] 8 | dp[0][0], dp[1][0] = nums[0], nums[0] 9 | for i in range(1, len(nums)): 10 | dp[1][i] = max(nums[i], nums[i] + dp[1][i-1]) 11 | dp[0][i] = max(dp[0][i-1], dp[1][i]) 12 | return dp[0][-1] 13 | 14 | """ https://leetcode.com/problems/maximum-subarray/discuss/1595195/C%2B%2BPython-7-Simple-Solutions-w-Explanation-or-Brute-Force-%2B-DP-%2B-Kadane-%2B-Divide-and-Conquer """ -------------------------------------------------------------------------------- /Hard/312. Burst Balloons.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/burst-balloons/ 2 | 3 | # Explaination: https://www.youtube.com/watch?v=uG_MtaCJIrM 4 | 5 | class Solution: 6 | def maxCoins(self, nums): 7 | nums, N = [1] + nums + [1], len(nums) + 2 #array with 1,1 balloons at the end and length as N 8 | dp = [[0] * N for _ in range(N)] # table full of zeros 9 | 10 | for left in range(N - 2, -1, -1): 11 | for right in range(left + 2, N): 12 | dp[left][right] = max(nums[left]*nums[i]*nums[right] + dp[left][i] + dp[i][right] for i in range(left + 1, right)) 13 | 14 | return dp[0][N-1] -------------------------------------------------------------------------------- /Medium/1584. Min Cost to Connect All Points.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/min-cost-to-connect-all-points/ 2 | 3 | class Solution: 4 | def minCostConnectPoints(self, points: List[List[int]]) -> int: 5 | d, res = {(x, y): float('inf') if i else 0 for i, (x, y) in enumerate(points)}, 0 6 | while d: 7 | x, y = min(d, key=d.get) # obtain the current minimum edge 8 | res += d.pop((x, y)) # and remove the corresponding point 9 | for x1, y1 in d: # for the rest of the points, update the minimum manhattan distance 10 | d[(x1, y1)] = min(d[(x1, y1)], abs(x-x1)+abs(y-y1)) 11 | return res -------------------------------------------------------------------------------- /Easy/706. Design HashMap.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/design-hashmap/ 2 | 3 | class MyHashMap: 4 | def __init__(self): 5 | self.data = [None] * 1000001 6 | 7 | def put(self, key: int, val: int) -> None: 8 | self.data[key] = val 9 | 10 | def get(self, key: int) -> int: 11 | val = self.data[key] 12 | return val if val != None else -1 13 | 14 | def remove(self, key: int) -> None: 15 | self.data[key] = None 16 | 17 | 18 | 19 | # Your MyHashMap object will be instantiated and called as such: 20 | # obj = MyHashMap() 21 | # obj.put(key,value) 22 | # param_2 = obj.get(key) 23 | # obj.remove(key) -------------------------------------------------------------------------------- /Easy/976. Largest Perimeter Triangle.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/largest-perimeter-triangle/ 2 | 3 | class Solution: 4 | def largestPerimeter(self, A: List[int]) -> int: 5 | A.sort(reverse = True) 6 | for i in range(3,len(A)+1): 7 | if(A[i-3] < A[i-2] + A[i-1]): 8 | return sum(A[i-3:i]) 9 | return 0 10 | 11 | ''' 12 | 1. Sort the List to get the top 3 lengths 13 | 2. Check if the largest length is less than sum of other two 14 | * If 2 is false, drop the max length take next 3 largest length and repeat 1-2 15 | * if 2 is true, return sum of all lengths 16 | 3. if loop ends, and no possible combination found, return 0 17 | ''' -------------------------------------------------------------------------------- /Easy/191. Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/number-of-1-bits/ 2 | 3 | class Solution: 4 | def hammingWeight(self, n: int) -> int: 5 | return bin(n).count('1') 6 | 7 | # Alternate Solution 8 | class Solution: 9 | def hammingWeight(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | c = 0 15 | while n: 16 | n &= n - 1 17 | c += 1 18 | return c 19 | 20 | ''' 21 | Using bit operation to cancel a 1 in each round 22 | 23 | Think of a number in binary n = XXXXXX1000, n - 1 is XXXXXX0111. n & (n - 1) will be XXXXXX0000 which is just remove the last significant 1 24 | ''' -------------------------------------------------------------------------------- /Medium/230. Kth Smallest Element in a BST.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def kthSmallest(self, root, k): 11 | stack = [] 12 | while root or stack: 13 | while root: 14 | stack.append(root) 15 | root = root.left 16 | root = stack.pop() 17 | k -= 1 18 | if k == 0: 19 | return root.val 20 | root = root.right -------------------------------------------------------------------------------- /Easy/35. Search Insert Position.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/search-insert-position/ 2 | 3 | # first try solution 4 | class Solution: 5 | def searchInsert(self, nums: List[int], target: int) -> int: 6 | for index, value in enumerate(nums): 7 | if value == target: 8 | return index 9 | else: 10 | for index, value in enumerate(nums): 11 | if value > target: 12 | return index 13 | else: 14 | return len(nums) 15 | 16 | """ to learn::-- https://leetcode.com/problems/search-insert-position/discuss/1596603/C%2B%2BPython-Simple-Solutions-w-Explanation-or-Recursive-and-Iterative-Binary-Search """ -------------------------------------------------------------------------------- /Hard/1463. Cherry Pickup II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/cherry-pickup-ii/ 2 | 3 | class Solution: 4 | def cherryPickup(self, grid: List[List[int]]) -> int: 5 | m, n = len(grid), len(grid[0]) 6 | 7 | @lru_cache(None) 8 | def dfs(r, c1, c2): 9 | if r == m: return 0 10 | cherries = grid[r][c1] if c1 == c2 else grid[r][c1] + grid[r][c2] 11 | ans = 0 12 | for nc1 in range(c1 - 1, c1 + 2): 13 | for nc2 in range(c2 - 1, c2 + 2): 14 | if 0 <= nc1 < n and 0 <= nc2 < n: 15 | ans = max(ans, dfs(r + 1, nc1, nc2)) 16 | return ans + cherries 17 | 18 | return dfs(0, 0, n - 1) -------------------------------------------------------------------------------- /Medium/2186. Minimum Number of Steps to Make Two Strings Anagram II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/ 2 | 3 | class Solution: 4 | def minSteps(self, s: str, t: str) -> int: 5 | count = 0 6 | char_count = [0] * 26 7 | for i in range(26): 8 | char_count[i] = 0 9 | for i in range(len(s)): 10 | char_count[ord(s[i]) - ord('a')] += 1 11 | for i in range(len(t)): 12 | char_count[ord(t[i]) - ord('a')] -= 1 13 | for i in range(26): 14 | if char_count[i] != 0: 15 | if char_count[i] != 0: 16 | count += abs(char_count[i]) 17 | return count -------------------------------------------------------------------------------- /Medium/454. 4Sum II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/4sum-ii/ 2 | 3 | class Solution: 4 | def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: 5 | 6 | # hashmap and final result count 7 | nums12, result = defaultdict(int), 0 8 | 9 | # storing all possible combinations of sum 10 | for num1 in nums1: 11 | for num2 in nums2: 12 | nums12[num1+num2] += 1 13 | 14 | # iterating the left out two array to find negation of same value 15 | for num3 in nums3: 16 | for num4 in nums4: 17 | result += nums12[-(num3+num4)] 18 | 19 | return result -------------------------------------------------------------------------------- /Easy/997. Find the Town Judge.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-the-town-judge/ 2 | 3 | class Solution: 4 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 5 | no_of_trust = [0] * (n+1) #because in trust numbers starts from 1 to N 6 | for a,b in trust: 7 | no_of_trust[a] -= 1 # a trusts b so a will become less 8 | no_of_trust[b] += 1 # a trusts b so b will become more trustworthy. 9 | 10 | for i in range(1,n+1): #because values are modified in range of 1 to N only 11 | if no_of_trust[i] == n-1: # n-1 is the higghest possible value if a judge is present 12 | return i #return the index where judge is found 13 | return -1 -------------------------------------------------------------------------------- /Easy/1523. Count Odd Numbers in an Interval Range.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ 2 | 3 | class Solution: 4 | def countOdds(self, low: int, high: int) -> int: 5 | # make the low and high variables even numbers so that the return value will be an integer 6 | if low % 2 == 1: 7 | low = low - 1 8 | if high % 2 == 1: 9 | high = high + 1 10 | return int((high-low)/2) 11 | 12 | # Alternate Solution 13 | ''' 14 | the count of odd numbers between 1 and low - 1 is low / 2 15 | the count of odd numbers between 1 and high is (high + 1 ) / 2 16 | ''' 17 | class Solution: 18 | def countOdds(self, low, high): 19 | return (high + 1) // 2 - low // 2 -------------------------------------------------------------------------------- /Easy/724. Find Pivot Index.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-pivot-index/ 2 | 3 | class Solution: 4 | def pivotIndex(self, nums: List[int]) -> int: 5 | leftSum, rightSum = 0,sum(nums) 6 | for index,num in enumerate(nums): 7 | rightSum -= num 8 | if rightSum == leftSum: 9 | return index 10 | leftSum += num 11 | return -1 12 | 13 | # Alternate Solution 14 | class Solution: 15 | def pivotIndex(self, nums: List[int]) -> int: 16 | leftsum = 0 17 | total_sum = sum(nums) 18 | for i in range(len(nums)): 19 | if leftsum == total_sum - leftsum - nums[i]: 20 | return i 21 | leftsum += nums[i] 22 | return -1 -------------------------------------------------------------------------------- /Medium/1288. Remove Covered Intervals.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/remove-covered-intervals/ 2 | 3 | class Solution: 4 | def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: 5 | start, end = 0, 1 6 | # Sort by left bound, and reversed right bound of interval 7 | intervals.sort(key = lambda segment:(segment[start], -segment[end]) ) 8 | # count of non-covered intervals 9 | count = 0 10 | # right bound so far 11 | right_bound = 0 12 | for interval in intervals: 13 | if right_bound < interval[end]: 14 | # previous interval can not cover current interval, update count 15 | count, right_bound = count + 1, interval[end] 16 | return count -------------------------------------------------------------------------------- /Easy/303. Range Sum Query - Immutable.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/range-sum-query-immutable/ 2 | 3 | class NumArray: 4 | 5 | def __init__(self, nums: List[int]): 6 | self.accu = [0] 7 | for num in nums: 8 | self.accu += self.accu[-1] + num, 9 | 10 | def sumRange(self, left: int, right: int) -> int: 11 | return self.accu[right + 1] - self.accu[left] 12 | 13 | 14 | # Your NumArray object will be instantiated and called as such: 15 | # obj = NumArray(nums) 16 | # param_1 = obj.sumRange(left,right) 17 | 18 | ''' 19 | create an array accu that stores the accumulated sum for nums such that accu[i] = nums[0] + ... + nums[i - 1] in the initializer of NumArray. Then just return accu[j + 1] - accu[i] in sumRange. 20 | ''' -------------------------------------------------------------------------------- /Medium/382. Linked List Random Node.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/linked-list-random-node/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | 9 | class Solution(object): 10 | def __init__(self, head): 11 | self.nodes = [] # convert linked list to a list, cost O(N) Space and O(N) Time 12 | while head: 13 | self.nodes.append(head.val) 14 | head = head.next 15 | 16 | def getRandom(self): # cost O(1) Time 17 | return random.choice(self.nodes) 18 | 19 | 20 | # Your Solution object will be instantiated and called as such: 21 | # obj = Solution(head) 22 | # param_1 = obj.getRandom() -------------------------------------------------------------------------------- /Easy/1022. Sum of Root to Leaf Binary Numbers.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: 11 | def dfs(node, path): 12 | if not node: return 0 13 | 14 | path = (path << 1) + node.val 15 | 16 | if not node.left and not node.right: 17 | return path 18 | 19 | return dfs(node.left, path) + dfs(node.right, path) 20 | 21 | return dfs(root, 0) -------------------------------------------------------------------------------- /Easy/703. Kth Largest Element in a Stream.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/kth-largest-element-in-a-stream/ 2 | 3 | class KthLargest(object): 4 | 5 | 6 | def __init__(self, k, nums): 7 | self.pool = nums 8 | self.k = k 9 | heapq.heapify(self.pool) 10 | while len(self.pool) > k: 11 | heapq.heappop(self.pool) 12 | 13 | 14 | def add(self, val): 15 | if len(self.pool) < self.k: 16 | heapq.heappush(self.pool, val) 17 | elif val > self.pool[0]: 18 | heapq.heapreplace(self.pool, val) 19 | return self.pool[0] 20 | 21 | 22 | 23 | # Your KthLargest object will be instantiated and called as such: 24 | # obj = KthLargest(k, nums) 25 | # param_1 = obj.add(val) -------------------------------------------------------------------------------- /Easy/1232. Check If It Is a Straight Line.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/check-if-it-is-a-straight-line/ 2 | 3 | class Solution: 4 | def checkStraightLine(self, coordinates: List[List[int]]) -> bool: 5 | (x1, y1), (x2, y2) = coordinates[:2] 6 | for i in range(2, len(coordinates)): 7 | (x, y) = coordinates[i] 8 | if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)): 9 | return False 10 | return True 11 | 12 | ''' 13 | The point is if we take points p1(x, y), p2(x1, y1), p3(x3, y3), slopes of any two pairs is same then p1, p2, p3 lies on same line. 14 | slope from p1 and p2 is y - y1 / x - x1 15 | slope from p2 and p3 is y2 - y1 / x2 - x1 16 | if these two slopes equal, then p1, p2, p3 lies on same line. 17 | ''' -------------------------------------------------------------------------------- /Easy/21. Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/merge-two-sorted-lists/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution: 9 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 10 | dummy = cur = ListNode(0) 11 | while list1 and list2: 12 | if list1.val < list2.val: 13 | cur.next = list1 14 | list1 = list1.next 15 | else: 16 | cur.next = list2 17 | list2 = list2.next 18 | cur = cur.next 19 | cur.next = list1 or list2 20 | return dummy.next -------------------------------------------------------------------------------- /Medium/39. Combination Sum.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/combination-sum/ 2 | 3 | class Solution: 4 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 5 | candidates.sort() # sort to terminate early when target < 0 6 | 7 | def backtracking(i, target, path): 8 | if target == 0: 9 | ans.append(path) 10 | return 11 | if i == len(candidates) or target < candidates[i]: 12 | return 13 | backtracking(i, target - candidates[i], path + [candidates[i]]) # Choose ith candidate 14 | backtracking(i + 1, target, path) # Skip ith candidate 15 | 16 | ans = [] 17 | backtracking(0, target, []) 18 | return ans -------------------------------------------------------------------------------- /Medium/1721. Swapping Nodes in a Linked List.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution: 9 | def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: 10 | # Find kth node from left 11 | l = r = head 12 | for _ in range(k-1): 13 | l = l.next 14 | # Find kth node from right 15 | # by finding tail node 16 | tail = l 17 | while tail.next: 18 | r, tail = r.next, tail.next 19 | # Swap values and return 20 | l.val, r.val = r.val, l.val 21 | return head -------------------------------------------------------------------------------- /Medium/923. 3Sum With Multiplicity.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/3sum-with-multiplicity/ 2 | 3 | class Solution: 4 | def threeSumMulti(self, A, T): 5 | nmap, third, ans = [0 for _ in range(101)], ceil(T / 3) - 1, 0 6 | for num in A: nmap[num] += 1 7 | for k in range(min(T,100), third, -1): 8 | rem = T - k 9 | half = ceil(rem / 2) - 1 10 | for j in range(min(rem, k), half, -1): 11 | i = rem - j 12 | x, y, z = nmap[i], nmap[j], nmap[k] 13 | if i == k: ans += x * (x-1) * (x-2) // 6 14 | elif i == j: ans += x * (x-1) // 2 * z 15 | elif j == k: ans += x * y * (y-1) // 2 16 | else: ans += x * y * z 17 | return ans % 1000000007 -------------------------------------------------------------------------------- /Easy/1588. Sum of All Odd Length Subarrays.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sum-of-all-odd-length-subarrays/ 2 | 3 | class Solution: 4 | def sumOddLengthSubarrays(self, A): 5 | n = len(A) 6 | res = 0 7 | for l in range(1, n + 1, 2): 8 | for i in range(n - l + 1): 9 | res += sum(A[i:i + l]) 10 | return res 11 | 12 | # Alternate Solution 13 | class Solution: 14 | def sumOddLengthSubarrays(self, arr: List[int]) -> int: 15 | res = 0; freq = 0; n = len(arr) 16 | for i in range(n): 17 | freq = freq-(i+1)//2+(n-i+1)//2 18 | res += freq*arr[i] 19 | return res 20 | # Explanation: https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/919521/python-3-99.78-faster-and-100-less-space -------------------------------------------------------------------------------- /Easy/1672. Richest Customer Wealth.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/richest-customer-wealth/ 2 | 3 | class Solution: 4 | def maximumWealth(self, accounts: List[List[int]]) -> int: 5 | max_wealth = [] 6 | for i in range(len(accounts)): 7 | wealth = 0 8 | for j in range(len(accounts[i])): 9 | wealth += accounts[i][j] 10 | max_wealth.append(wealth) 11 | return max(max_wealth) 12 | 13 | # return max(sum(acc) for acc in accounts) 14 | # return max(map(sum, accounts)) 15 | 16 | # Alternate Solution 17 | ''' 18 | def maximumWealth(self, accounts: List[List[int]]) -> int: 19 | wealth = [] 20 | for i in accounts: 21 | wealth.append(sum(i)) 22 | return max(wealth) 23 | ''' -------------------------------------------------------------------------------- /Medium/74. Search a 2D Matrix.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/search-a-2d-matrix/ 2 | 3 | class Solution: 4 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 5 | for i in range(len(matrix)): 6 | if target == matrix[i][0]: 7 | return True 8 | if target < matrix[i][0]: 9 | for j in range(len(matrix[i-1])): 10 | if target==matrix[i-1][j]: 11 | return True 12 | elif target == matrix[i][len(matrix[i])-1]: 13 | return True 14 | elif target <= matrix[i][len(matrix[i])-1]: 15 | for j in range(len(matrix[i])): 16 | if target==matrix[i][j]: 17 | return True 18 | return False -------------------------------------------------------------------------------- /Medium/24. Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/swap-nodes-in-pairs/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution(object): 9 | def swapPairs(self, head): 10 | if not head or not head.next: return head 11 | dummy = ListNode(0) 12 | dummy.next = head 13 | current = dummy 14 | 15 | while current.next and current.next.next: 16 | first = current.next 17 | second = current.next.next 18 | current.next = second 19 | first.next = second.next 20 | second.next = first 21 | current = current.next.next 22 | return dummy.next -------------------------------------------------------------------------------- /Medium/31. Next Permutation.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/next-permutation/ 2 | 3 | class Solution: 4 | def nextPermutation(self, nums): 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | i = j = len(nums)-1 9 | while i > 0 and nums[i-1] >= nums[i]: 10 | i -= 1 11 | if i == 0: # nums are in descending order 12 | nums.reverse() 13 | return 14 | k = i - 1 # find the last "ascending" position 15 | while nums[j] <= nums[k]: 16 | j -= 1 17 | nums[k], nums[j] = nums[j], nums[k] 18 | l, r = k+1, len(nums)-1 # reverse the second part 19 | while l < r: 20 | nums[l], nums[r] = nums[r], nums[l] 21 | l +=1 ; r -= 1 22 | -------------------------------------------------------------------------------- /Easy/953. Verifying an Alien Dictionary.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/verifying-an-alien-dictionary/ 2 | 3 | class Solution: 4 | def isAlienSorted(self, words: List[str], order: str) -> bool: 5 | 6 | for a, b in zip(words, words[1:]): 7 | i, j, A, B = 0, 0, len(a), len(b) 8 | 9 | while i < A and j < B: 10 | aOrderIdx = order.index(a[i]) 11 | bOrderIdx = order.index(b[i]) 12 | if aOrderIdx == bOrderIdx: 13 | i += 1 14 | j += 1 15 | elif aOrderIdx > bOrderIdx: 16 | return False 17 | else: 18 | break 19 | 20 | if i < A and j == B: 21 | return False 22 | 23 | return True -------------------------------------------------------------------------------- /Easy/232. Implement Queue using Stacks.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/implement-queue-using-stacks/ 2 | 3 | class MyQueue: 4 | def __init__(self): 5 | self.s1 = [] 6 | self.s2 = [] 7 | 8 | def push(self, x): 9 | self.s1.append(x) 10 | 11 | def pop(self): 12 | self.peek() 13 | return self.s2.pop() 14 | 15 | def peek(self): 16 | if not self.s2: 17 | while self.s1: 18 | self.s2.append(self.s1.pop()) 19 | return self.s2[-1] 20 | 21 | def empty(self): 22 | return not self.s1 and not self.s2 23 | 24 | 25 | # Your MyQueue object will be instantiated and called as such: 26 | # obj = MyQueue() 27 | # obj.push(x) 28 | # param_2 = obj.pop() 29 | # param_3 = obj.peek() 30 | # param_4 = obj.empty() -------------------------------------------------------------------------------- /Medium/82. Remove Duplicates from Sorted List II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution: 9 | def deleteDuplicates(self, head): 10 | dummy = pre = ListNode(0) 11 | dummy.next = head 12 | while head and head.next: 13 | if head.val == head.next.val: 14 | while head and head.next and head.val == head.next.val: 15 | head = head.next 16 | head = head.next 17 | pre.next = head 18 | else: 19 | pre = pre.next 20 | head = head.next 21 | return dummy.next -------------------------------------------------------------------------------- /Easy/897. Increasing Order Search Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/increasing-order-search-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def increasingBST(self, root): 11 | def dfs(node): 12 | l1, r2 = node, node 13 | 14 | if node.left: 15 | l1, l2 = dfs(node.left) 16 | l2.right = node 17 | 18 | if node.right: 19 | r1, r2 = dfs(node.right) 20 | node.right = r1 21 | 22 | node.left = None 23 | return (l1, r2) 24 | 25 | return dfs(root)[0] -------------------------------------------------------------------------------- /Medium/567. Permutation in String.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/permutation-in-string/ 2 | 3 | class Solution: 4 | def checkInclusion(self, s1: str, s2: str) -> bool: 5 | '''One string is a permutation of another if the two strings 6 | have the same character frequencies 7 | 8 | Hence: 9 | - find freq dict for s1 10 | - find freq dict for substrings of s2 (that are the same size as s1) 11 | 12 | runtime: O(n*k^2) 13 | ''' 14 | 15 | from collections import Counter 16 | d1 = Counter(s1) 17 | k = len(s1) 18 | for i in range(len(s2)): # ---- O(n) 19 | sub = s2[i:i+k] # ------ O(k) 20 | d2 = Counter(sub) # --- O(k) 21 | if d1 == d2: 22 | return True 23 | return False -------------------------------------------------------------------------------- /Medium/701. Insert into a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/insert-into-a-binary-search-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: 11 | if not root: return TreeNode(val) 12 | 13 | cur, next = None, root 14 | while next: 15 | cur = next 16 | next = cur.left if val < cur.val else cur.right 17 | 18 | if val < cur.val: 19 | cur.left = TreeNode(val) 20 | else: 21 | cur.right = TreeNode(val) 22 | 23 | return root -------------------------------------------------------------------------------- /Medium/881. Boats to Save People.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/boats-to-save-people/ 2 | 3 | class Solution: 4 | def numRescueBoats(self, people: List[int], limit: int) -> int: 5 | people.sort() 6 | left, right, result = 0, len(people) - 1, 0 7 | while left <= right: 8 | if people[left] + people[right] <= limit: 9 | left += 1 10 | result += 1 11 | right -= 1 12 | return result 13 | ''' 14 | Sort people. 15 | For the current heaviest person, we try to let him go with the lightest person. 16 | As all people need to get on the boat. 17 | If the sum of weight is over the limit, we have to let the heaviest go alone. 18 | No one can take the same boat with him. 19 | 20 | At the end of for loop, it may happend that i = j. 21 | But it won't change the result 22 | ''' -------------------------------------------------------------------------------- /Medium/525. Contiguous Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/contiguous-array/ 2 | 3 | class Solution: 4 | def findMaxLength(self, nums: List[int]) -> int: 5 | hashmap = {} 6 | max_len = 0 7 | suma = 0 8 | n = len(nums) 9 | for i in range(n): 10 | suma += -1 if nums[i] == 0 else 1 11 | if suma == 0: # max_len would be from start to ith index 12 | if max_len < i+1: 13 | max_len = i + 1 14 | elif suma in hashmap: # max_len would be ith index - previous value of that sum from hashmap 15 | if max_len < i-hashmap[suma]: 16 | max_len = i - hashmap[suma] 17 | else: 18 | hashmap[suma] = i # if sum not occured previously, add it in hashmap 19 | return max_len 20 | -------------------------------------------------------------------------------- /Easy/1337. The K Weakest Rows in a Matrix.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ 2 | 3 | class Solution: 4 | def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: 5 | m, n = len(mat), len(mat[0]) 6 | result = {} 7 | for j in range(n): 8 | for i in range(m): 9 | if mat[i][j] or i in result: continue 10 | result[i] = True 11 | k -= 1 12 | if not k: return result.keys() 13 | for i in range(m): 14 | if i not in result: 15 | result[i] = True 16 | k -= 1 17 | if not k: return result.keys() 18 | ''' 19 | traverse matrix vertically and add row index into ordered map when encounter a zero. 20 | If there are still rest of k, collect row from small index. 21 | ''' -------------------------------------------------------------------------------- /Hard/23. Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/merge-k-sorted-lists/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution(object): 9 | def mergeKLists(self, lists): 10 | if not lists: 11 | return None 12 | if len(lists) == 1: 13 | return lists[0] 14 | mid = len(lists) // 2 15 | l, r = self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:]) 16 | return self.merge(l, r) 17 | 18 | def merge(self, l, r): 19 | if not l or not r: 20 | return l or r 21 | if l.val< r.val: 22 | l.next = self.merge(l.next, r) 23 | return l 24 | r.next = self.merge(l, r.next) 25 | return r -------------------------------------------------------------------------------- /Easy/27. Remove Element.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/remove-element/ 2 | 3 | class Solution: 4 | def removeElement(self, nums: List[int], val: int) -> int: 5 | 6 | if len(nums) == 0: 7 | return 0 8 | else: 9 | lp = 0 10 | for rp in range(0,len(nums)): 11 | if nums[rp] != val: 12 | nums[lp] = nums[rp] 13 | lp += 1 14 | return lp 15 | 16 | ''' 17 | Similar to question 26. Remove duplicate element from sorted array 18 | Isme bas hume nums[rp-1] ki jagah us value se compare karna hai ki 19 | Kya hamara right pointer ki position wali value question ki value jisey remove karna hai usey different hai? 20 | Agar hai toh hum us different value ko left pointer ki jagah par store kardenge 21 | This will automatically remove question wali value. 22 | ''' -------------------------------------------------------------------------------- /Medium/538. Convert BST to Greater Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/convert-bst-to-greater-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def convertBST(self, root): 11 | def visit1(root): 12 | if root: 13 | visit1(root.left) 14 | vals.append(root.val) 15 | visit1(root.right) 16 | vals = [] 17 | visit1(root) 18 | 19 | self.s = 0 20 | def visit2(root): 21 | if root: 22 | visit2(root.right) 23 | self.s += vals.pop() 24 | root.val = self.s 25 | visit2(root.left) 26 | visit2(root) 27 | 28 | return root -------------------------------------------------------------------------------- /Easy/705. Design HashSet.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/design-hashset/ 2 | 3 | class MyHashSet: 4 | def eval_hash(self, key): 5 | return ((key*1031237) & (1<<20) - 1)>>5 6 | 7 | def __init__(self): 8 | self.arr = [[] for _ in range(1<<15)] 9 | 10 | def add(self, key: int) -> None: 11 | t = self.eval_hash(key) 12 | if key not in self.arr[t]: 13 | self.arr[t].append(key) 14 | 15 | def remove(self, key: int) -> None: 16 | t = self.eval_hash(key) 17 | if key in self.arr[t]: 18 | self.arr[t].remove(key) 19 | 20 | def contains(self, key: int) -> bool: 21 | t = self.eval_hash(key) 22 | return key in self.arr[t] 23 | 24 | 25 | 26 | # Your MyHashSet object will be instantiated and called as such: 27 | # obj = MyHashSet() 28 | # obj.add(key) 29 | # obj.remove(key) 30 | # param_3 = obj.contains(key) -------------------------------------------------------------------------------- /Medium/535. Encode and Decode TinyURL.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/encode-and-decode-tinyurl/ 2 | 3 | class Codec: 4 | codeDB, urlDB = defaultdict(), defaultdict() 5 | chars = string.ascii_letters + string.digits 6 | 7 | def getCode(self) -> str: 8 | code = ''.join(random.choice(self.chars) for i in range(6)) 9 | return "http://tinyurl.com/" + code 10 | 11 | def encode(self, longUrl: str) -> str: 12 | if longUrl in self.urlDB: return self.urlDB[longUrl] 13 | code = self.getCode() 14 | while code in self.codeDB: code = getCode() 15 | self.codeDB[code] = longUrl 16 | self.urlDB[longUrl] = code 17 | return code 18 | 19 | def decode(self, shortUrl: str) -> str: 20 | return self.codeDB[shortUrl] 21 | 22 | # Your Codec object will be instantiated and called as such: 23 | # codec = Codec() 24 | # codec.decode(codec.encode(url)) -------------------------------------------------------------------------------- /Easy/1603. Design Parking System.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/design-parking-system/ 2 | 3 | class ParkingSystem: 4 | 5 | def __init__(self, big: int, medium: int, small: int): 6 | self.vehicle = [big,medium,small] 7 | 8 | def addCar(self, carType: int) -> bool: 9 | if carType == 1 : 10 | if self.vehicle[0] > 0: 11 | self.vehicle[0] -= 1 12 | return True 13 | elif carType == 2: 14 | if self.vehicle[1] > 0: 15 | self.vehicle[1] -= 1 16 | return True 17 | elif carType == 3: 18 | if self.vehicle[2] > 0: 19 | self.vehicle[2] -= 1 20 | return True 21 | return False 22 | 23 | 24 | 25 | # Your ParkingSystem object will be instantiated and called as such: 26 | # obj = ParkingSystem(big, medium, small) 27 | # param_1 = obj.addCar(carType) -------------------------------------------------------------------------------- /Medium/413. Arithmetic Slices.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/arithmetic-slices/ 2 | 3 | class Solution: 4 | def numberOfArithmeticSlices(self, nums: List[int]) -> int: 5 | dp = [0] * len(nums) 6 | ans = 0 7 | for i in range(2, len(nums)): 8 | if nums[i-1] - nums[i-2] == nums[i] - nums[i-1]: 9 | dp[i] = dp[i-1] + 1 10 | ans += dp[i] 11 | return ans 12 | 13 | ''' 14 | Let dp[i] denote the number of arithmetic subarray ends at nums[i]. 15 | If if nums[i-1] - nums[i-2] == nums[i] - nums[i-1] then we can form the Arithmetic subarray ends at nums[i]. 16 | So dp[i] = dp[i-1] + 1. 17 | For example: nums = [1, 3, 5, 7, 9] 18 | dp[2] = 1 arithmetic subarrays are {1, 3, 5} 19 | dp[3] = dp[2] + 1 = 2, arithmetic subarrays are {1, 3, 5, 7}, {3, 5, 7} 20 | dp[4] = dp[3] + 1 = 3, arithmetic subarrays are {1, 3, 5, 7, 9}, {3, 5, 7, 9}, {5, 7, 9} 21 | ''' -------------------------------------------------------------------------------- /Easy/2176. Count Equal and Divisible Pairs in an Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/ 2 | 3 | class Solution: 4 | def countPairs(self, nums: List[int], k: int) -> int: 5 | PairCount = 0 6 | for i in range(len(nums)): 7 | for j in range(1,len(nums)): 8 | if 0 <= i < j < len(nums): 9 | if nums[i] == nums[j]: 10 | if (i*j) % k == 0: 11 | PairCount += 1 12 | return PairCount 13 | 14 | # Same solution in other way 15 | class Solution: 16 | def countPairs(self, nums: List[int], k: int) -> int: 17 | PairCount = 0 18 | for i in range(len(nums)-1): 19 | for j in range(i+1,len(nums)): 20 | if nums[i] == nums[j]: 21 | if (i*j) % k == 0: 22 | PairCount += 1 23 | return PairCount -------------------------------------------------------------------------------- /Medium/59. Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/spiral-matrix-ii/ 2 | 3 | class Solution: 4 | def generateMatrix(self, n: int) -> List[List[int]]: 5 | result = [[0] * n for _ in range(n)] 6 | 7 | def fill_circle(el, start, n): 8 | i, j = start, start 9 | for k in range(j, j + n): 10 | result[i][k], el = el, el + 1 11 | for k in range(i + 1, i + n): 12 | result[k][j + n - 1], el = el, el + 1 13 | for k in reversed(range(j, j + n - 1)): 14 | result[i + n - 1][k], el = el, el + 1 15 | for k in reversed(range(i + 1, i + n - 1)): 16 | result[k][j], el = el, el + 1 17 | 18 | el, start = 1, 0 19 | while n > 0: 20 | fill_circle(el, start, n) 21 | el = el + 4*(n - 1) 22 | n, start = n - 2, start + 1 23 | 24 | return result -------------------------------------------------------------------------------- /Easy/2129. Capitalize the Title.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/capitalize-the-title/ 2 | 3 | class Solution: 4 | def capitalizeTitle(self, title: str) -> str: 5 | title = title.split() 6 | word = "" 7 | for i in range(len(title)): 8 | if len(title[i]) < 3: 9 | word = word + title[i].lower() + " " 10 | else: 11 | word = word + title[i].capitalize() + " " 12 | return word[:-1] 13 | 14 | # Alternate Solution 15 | class Solution: 16 | def capitalizeTitle(self, title: str) -> str: 17 | title = title.split() 18 | word = [] 19 | for i in range(len(title)): 20 | if len(title[i]) < 3: 21 | word.append(title[i].lower()) 22 | else: 23 | word.append(title[i].capitalize()) 24 | return " ".join(word) 25 | 26 | # Post: https://leetcode.com/problems/capitalize-the-title/discuss/1716077/python-easy-solution -------------------------------------------------------------------------------- /Medium/1631. Path With Minimum Effort.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/path-with-minimum-effort/ 2 | 3 | class Solution: 4 | def minimumEffortPath(self, heights: List[List[int]]) -> int: 5 | if not heights: 6 | return 0 7 | 8 | r, c = len(heights), len(heights[0]) 9 | heap = [(0,0,0)] 10 | res = 0 11 | visited = set() 12 | 13 | while heap: 14 | # Always pop up the smaller abs distance 15 | d, x, y = heapq.heappop(heap) 16 | 17 | res = max(res, d) 18 | if (x, y) == (r-1, c-1): 19 | return res 20 | visited.add((x, y)) 21 | 22 | for nx, ny in (x+1, y), (x-1,y), (x, y+1), (x, y-1): 23 | if nx >= 0 and nx < r and ny >= 0 and ny < c and (nx, ny) not in visited: 24 | nd = abs(heights[nx][ny] - heights[x][y]) 25 | heapq.heappush(heap, (nd, nx, ny)) 26 | 27 | return res -------------------------------------------------------------------------------- /Medium/1396. Design Underground System.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/design-underground-system/ 2 | 3 | class UndergroundSystem: 4 | def __init__(self): 5 | self.ids = {} 6 | self.pairs = Counter() 7 | self.freqs = Counter() 8 | 9 | def checkIn(self, id, stationName, t): 10 | self.ids[id] = (stationName, t) 11 | 12 | def checkOut(self, id, stationName, t): 13 | Name2, t2 = self.ids.pop(id) 14 | self.pairs[(Name2, stationName)] += t-t2 15 | self.freqs[(Name2, stationName)] += 1 16 | 17 | def getAverageTime(self, startStation, endStation): 18 | return self.pairs[startStation, endStation]/self.freqs[startStation, endStation] 19 | 20 | 21 | 22 | # Your UndergroundSystem object will be instantiated and called as such: 23 | # obj = UndergroundSystem() 24 | # obj.checkIn(id,stationName,t) 25 | # obj.checkOut(id,stationName,t) 26 | # param_3 = obj.getAverageTime(startStation,endStation) -------------------------------------------------------------------------------- /Medium/669. Trim a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/trim-a-binary-search-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode(object): 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution(object): 10 | def trimBST(self, root, low, high): 11 | """ 12 | :type root: TreeNode 13 | :type low: int 14 | :type high: int 15 | :rtype: TreeNode 16 | """ 17 | def trim(node): 18 | if not node: 19 | return None 20 | elif node.val > high: 21 | return trim(node.left) 22 | elif node.val < low: 23 | return trim(node.right) 24 | else: 25 | node.left = trim(node.left) 26 | node.right = trim(node.right) 27 | return node 28 | 29 | return trim(root) -------------------------------------------------------------------------------- /Medium/81. Search in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ 2 | 3 | class Solution: 4 | def search(self, nums, target): 5 | l, r = 0, len(nums)-1 6 | while l <= r: 7 | mid = l + (r-l)//2 8 | if nums[mid] == target: 9 | return True 10 | while l < mid and nums[l] == nums[mid]: 11 | l += 1 12 | # the first half is ordered 13 | if nums[l] <= nums[mid]: 14 | # target is in the first half 15 | if nums[l] <= target < nums[mid]: 16 | r = mid - 1 17 | else: 18 | l = mid + 1 19 | # the second half is ordered 20 | else: 21 | # target is in the second half 22 | if nums[mid] < target <= nums[r]: 23 | l = mid + 1 24 | else: 25 | r = mid - 1 26 | return False -------------------------------------------------------------------------------- /Hard/895. Maximum Frequency Stack.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/maximum-frequency-stack/ 2 | 3 | class FreqStack: 4 | 5 | def __init__(self): 6 | self.heap = [] 7 | self.m = collections.defaultdict(int) 8 | self.counter = 0 9 | 10 | def push(self, val): 11 | self.m[val]+=1 12 | heapq.heappush(self.heap,(-self.m[val], -self.counter, val)) 13 | self.counter+=1 14 | 15 | def pop(self): 16 | toBeRemoved = heapq.heappop(self.heap) 17 | self.m[toBeRemoved[2]]-=1 18 | return toBeRemoved[2] 19 | 20 | ''' Heap will always keep the element with max count on top, and if two elements have same count, 21 | the second element (index) will be considered while doing pop operation. 22 | Also, the count map, is useful when the new occurence of the exisiting element is pushed.''' 23 | 24 | # Your FreqStack object will be instantiated and called as such: 25 | # obj = FreqStack() 26 | # obj.push(val) 27 | # param_2 = obj.pop() -------------------------------------------------------------------------------- /Medium/785. Is Graph Bipartite.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/is-graph-bipartite/ 2 | 3 | class Solution: 4 | def isBipartite(self, graph: List[List[int]]) -> bool: 5 | def checkBipartite(vertex): 6 | nonlocal color 7 | nonlocal q 8 | 9 | q.append(vertex) 10 | color[vertex] = 1 11 | 12 | while(q): 13 | curr = q.popleft() 14 | 15 | for i in graph[curr]: 16 | if color[i] == -1: 17 | color[i] = 1-color[curr] 18 | q.append(i) 19 | else: 20 | if color[i] == color[curr]: 21 | return False 22 | return True 23 | color = [-1]*len(graph) 24 | q = collections.deque() 25 | for i in range(len(graph)): 26 | if color[i] == -1: 27 | if not checkBipartite(i): 28 | return False 29 | return True 30 | -------------------------------------------------------------------------------- /Easy/2164. Sort Even and Odd Indices Independently.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sort-even-and-odd-indices-independently/ 2 | 3 | class Solution: 4 | def sortEvenOdd(self, nums: List[int]) -> List[int]: 5 | if len(nums) == 2: 6 | return nums 7 | else: 8 | evensorted = [] 9 | oddsorted = [] 10 | for i in range(len(nums)): 11 | if i%2 == 0: 12 | evensorted.append(nums[i]) 13 | else: 14 | oddsorted.append(nums[i]) 15 | evensorted.sort() 16 | oddsorted.sort(reverse=True) 17 | 18 | evenindex = 0 19 | oddindex = 0 20 | for i in range(len(nums)): 21 | if i%2==0: 22 | nums[i] = evensorted[evenindex] 23 | evenindex += 1 24 | else: 25 | nums[i] = oddsorted[oddindex] 26 | oddindex += 1 27 | return nums -------------------------------------------------------------------------------- /Easy/121. Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | class Solution: 4 | def maxProfit(self, prices: List[int]) -> int: 5 | buy = 0 6 | sell = 1 7 | max_profit = 0 8 | while sell < len(prices): 9 | currentProfit = prices[sell] - prices[buy] 10 | if prices[buy] < prices[sell]: 11 | max_profit = max(currentProfit,max_profit) 12 | else: 13 | buy = sell 14 | sell += 1 15 | return max_profit 16 | 17 | # Alternate Solution 18 | ''' 19 | class Solution: 20 | def maxProfit(self, prices: List[int]) -> int: 21 | bestProfit = 0 22 | 23 | minBuy = float('inf') 24 | 25 | for price in prices: 26 | if price < minBuy: 27 | minBuy = price 28 | elif price - minBuy > bestProfit: 29 | bestProfit = price - minBuy 30 | 31 | return bestProfit 32 | ''' -------------------------------------------------------------------------------- /Easy/389. Find the Difference.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-the-difference/ 2 | 3 | class Solution: 4 | def findTheDifference(self, s: str, t: str) -> str: 5 | for letter in t: 6 | if t.count(letter) != s.count(letter): 7 | return letter 8 | 9 | # Alternate Solution 1 10 | class Solution: 11 | def findTheDifference(self, s: str, t: str) -> str: 12 | if len(s) == 0: 13 | return t 14 | 15 | s = sorted(s) 16 | t = sorted(t) 17 | 18 | for index, s_val in enumerate(s): 19 | if t[index] != s_val: 20 | return t[index] 21 | 22 | return t[-1] 23 | 24 | #Alternate Solution 2 25 | from collections import Counter 26 | class Solution: 27 | def findTheDifference(self, s: str, t: str) -> str: 28 | s_counts = Counter(s) 29 | t_counts = Counter(t) 30 | for i in t_counts: 31 | if t_counts[i] > s_counts[i]: 32 | return i 33 | 34 | -------------------------------------------------------------------------------- /Easy/290. Word Pattern.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/word-pattern/ 2 | 3 | class Solution: 4 | def wordPattern(self, pattern: str, s: str) -> bool: 5 | d = {} # word - key, and letter - value 6 | d2 = {} # to keep track of all the letters we are going to use 7 | 8 | words = s.split() 9 | # base case 10 | if len(words) != len(pattern): return False # no. of words should be equal to no. of characters in the string pattern 11 | 12 | i = 0 13 | while i < len(words): 14 | if words[i] not in d and pattern[i] not in d2: # if words[i] is not in hashmap/dictionary 15 | d[words[i]] = pattern[i] # add in hashmap/dictionary 16 | d2[pattern[i]] = True 17 | elif d.get(words[i]) != pattern[i]: return False # if it doesn't exists then get method will return None. This is to remove key value error 18 | i += 1 19 | return True 20 | 21 | # Post: https://leetcode.com/problems/word-pattern/discuss/1697674/Python-Solution -------------------------------------------------------------------------------- /Easy/392. Is Subsequence.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/is-subsequence/ 2 | 3 | class Solution: 4 | def isSubsequence(self, s: str, t: str) -> bool: 5 | if len(s) > len(t):return False #if len of s is greater than len of t, return false because s cant be a subsequence of t 6 | if len(s) == 0:return True 7 | subsequence=0 8 | for i in range(0,len(t)): 9 | if subsequence <= len(s) -1: #if it is matching, increment subsequence 10 | print(s[subsequence]) 11 | if s[subsequence]==t[i]: 12 | 13 | subsequence+=1 14 | return subsequence == len(s) 15 | 16 | # Alternate Solution 17 | class Solution: 18 | def isSubsequence(self, s, t): 19 | for c in s: 20 | i = t.find(c) 21 | if i == -1: 22 | return False 23 | else: 24 | t = t[i+1:] 25 | return True 26 | ''' 27 | If current char is not in t, then we return False 28 | Else, we take the substring of t and start from there 29 | ''' -------------------------------------------------------------------------------- /Easy/67. Add Binary.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/add-binary/ 2 | 3 | class Solution: 4 | def addBinary(self, a: str, b: str) -> str: 5 | max_len = max(len(a), len(b)) 6 | # zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length 7 | a = a.zfill(max_len) 8 | b = b.zfill(max_len) 9 | result = '' 10 | 11 | carry = 0 12 | 13 | # Traversing string 14 | for i in range(max_len - 1, -1, -1): 15 | r = carry 16 | if a[i] == '1': 17 | r += 1 18 | else: 19 | r += 0 20 | if b[i] == '1': 21 | r += 1 22 | else: 23 | r += 0 24 | if r % 2 == 1: 25 | result = '1' + result 26 | else: 27 | result = '0' + result 28 | 29 | 30 | # Computing carry. 31 | carry = 0 if r < 2 else 1 32 | 33 | if carry != 0: 34 | result = '1' + result 35 | return result -------------------------------------------------------------------------------- /Easy/1768. Merge Strings Alternately.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/merge-strings-alternately/ 2 | 3 | class Solution: 4 | def mergeAlternately(self, word1: str, word2: str) -> str: 5 | ans = "" 6 | if len(word1) == len(word2): 7 | for i in range(len(word1)): 8 | ans = ans + word1[i] + word2[i] 9 | return ans 10 | elif len(word1) < len(word2): 11 | for i in range(len(word1)): 12 | ans = ans + word1[i] + word2[i] 13 | ans = ans + word2[i+1:] 14 | return ans 15 | else: 16 | for i in range(len(word2)): 17 | ans = ans + word1[i] + word2[i] 18 | ans = ans + word1[i+1:] 19 | return ans 20 | 21 | # Alternate Solution 22 | class Solution: 23 | def mergeAlternately(self, word1: str, word2: str) -> str: 24 | mergedString = '' 25 | for i in range(min(len(word1),len(word2))): 26 | mergedString += word1[i] + word2[i] 27 | 28 | return mergedString + word1[i+1:] + word2[i+1:] -------------------------------------------------------------------------------- /Medium/2177. Find Three Consecutive Integers That Sum to a Given Number.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/ 2 | 3 | class Solution: 4 | def sumOfThree(self, num: int) -> List[int]: 5 | n = (num - 3) // 3 6 | if 3*n + 3 == num: 7 | return [n, n+1, n+2] 8 | return [] 9 | 10 | # Alternate Solution 11 | class Solution: 12 | def sumOfThree(self, num: int) -> List[int]: 13 | if num % 3 != 0: 14 | return [] 15 | return [num // 3 - 1, num//3, num//3 + 1] 16 | 17 | 18 | ''' 19 | Observe the following: 20 | 21 | For num=2. No triplet is possible. 22 | For num=3. Our answer would be: [0, 1, 2]. 23 | For num=4. No triplet is possible. 24 | For num=6. Our answer would be: [1, 2, 3]. 25 | For num=9. Our answer would be: [2, 3, 4]. 26 | Thus, we can say that: 27 | 28 | If a number is divisible by 3, then only an answer exists. 29 | If a number is divisible by 3, then it's answer array would have three elements: 30 | i. num/3 31 | ii. num/3 + 1 32 | iii. num/3 - 1 33 | 34 | ''' -------------------------------------------------------------------------------- /Medium/189. Rotate Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/rotate-array/ 2 | 3 | class Solution: 4 | def rotate(self, nums: List[int], k: int) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | k = k % len(nums) 9 | nums[:] = nums[-k:] + nums[:-k] 10 | 11 | # Alternate Solution 12 | ''' 13 | class Solution: 14 | def reverse (self, nums, i, j) : 15 | li = i 16 | ri = j 17 | 18 | while li < ri: 19 | temp = nums[li] 20 | nums[li] = nums[ri] 21 | nums[ri] = temp 22 | 23 | li += 1 24 | ri -= 1 25 | def rotate(self, nums: List[int], k: int) -> None: 26 | """ 27 | Do not return anything, modify nums in-place instead. 28 | """ 29 | k = k % len(nums) 30 | if k < 0 : 31 | k += len(nums) 32 | 33 | self.reverse(nums, 0, len(nums) - k - 1); 34 | self.reverse(nums, len(nums) - k, len(nums) - 1); 35 | self.reverse(nums, 0, len(nums) - 1); 36 | ''' -------------------------------------------------------------------------------- /Medium/8. String to Integer (atoi).py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/string-to-integer-atoi/ 2 | 3 | class Solution(object): 4 | def myAtoi(self, s): 5 | MIN, MAX = -2 ** 31, 2 ** 31 - 1 6 | n, empty, sign = 0, True, 1 # empty denotes we have not seen any number, sign is -1 or 1 7 | for c in s: 8 | if empty: 9 | if c == ' ': continue # ignore the leading whitespace 10 | elif c == '-': sign = -1 # final answer is a negative number 11 | elif c.isdigit(): n = int(c) # the first digit of number 12 | elif c != '+': return 0 # the first char is not a digit and not in (' ', '+', '-'), so s is invalid 13 | empty = False # the first char is a digit or '+' or '-', valid number starts 14 | else: 15 | if c.isdigit(): 16 | n = n * 10 + int(c) 17 | if sign * n > MAX: return MAX 18 | elif sign * n < MIN: return MIN 19 | else: break # end of valid number 20 | return sign * n # sign is 1 or -1 -------------------------------------------------------------------------------- /Easy/1290. Convert Binary Number in a Linked List to Integer.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution: 9 | def getDecimalValue(self, head: ListNode) -> int: 10 | # Read the binary number from MSB to LSB 11 | answer = 0 12 | while head: 13 | answer = 2 * answer + head.val 14 | head = head.next 15 | return answer 16 | 17 | 18 | ''' 19 | For Example: 20 | 1101 -> 13 21 | 22 | Binary View 23 | 0000 * 2 # shift left 24 | 0000 + 1 # add bit 25 | 26 | 0001 * 2 # shift left 27 | 0010 + 1 # add bit 28 | 29 | 0011 * 2 # shift left 30 | 0110 + 0 # add bit 31 | 32 | 0110 * 2 # shift left 33 | 1100 + 1 # add bit 34 | 35 | 1101 # 13 36 | 37 | Decimal View 38 | 0 * 2 # x2 39 | 0 + 1 # add bit 40 | 41 | 1 * 2 # x2 42 | 2 + 1 # add bit 43 | 44 | 3 * 2 # x2 45 | 6 + 0 # add bit 46 | 47 | 6 * 2 # x2 48 | 12 + 1 # add bit 49 | 50 | 13 # Answer 51 | ''' -------------------------------------------------------------------------------- /Medium/799. Champagne Tower.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/champagne-tower/ 2 | 3 | class Solution: 4 | def champagneTower(self, poured, query_row, query_glass): 5 | l = [poured] 6 | for _ in range(query_row): 7 | l_new = [0] * (len(l) + 1) 8 | for i in range(len(l)): 9 | pour = (l[i] - 1)/2 10 | if pour > 0: 11 | l_new[i] += pour 12 | l_new[i+1] += pour 13 | 14 | l = l_new 15 | 16 | return min(1, l[query_glass]) 17 | 18 | ''' 19 | What we need to do in this problem is to simulate our pouring process: imagine, that we have 6 cups of water arrived at some place, then one full cup is left on this place and 2.5 cups go to the right bottom and left bottom cups. What we need to do now is to simulate this process! 20 | 21 | 1. We start with l = [poured] - top layer 22 | 2. Then we process full current layer to create next layer. We need to check if we have enough champagne: if we have less than 1, this cup is dead-end. If it has more than 1, then we add values to bottom layer. 23 | ''' -------------------------------------------------------------------------------- /Easy/344. Reverse String.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/reverse-string/ 2 | 3 | # Method 1 4 | class Solution: 5 | def reverseString(self, s: List[str]) -> None: 6 | """ 7 | Do not return anything, modify s in-place instead. 8 | """ 9 | start = 0 10 | end = len(s) - 1 11 | 12 | while start < end: 13 | s[start], s[end] = s[end], s[start] 14 | 15 | start += 1 16 | end -= 1 17 | return s 18 | 19 | # Method 2 20 | class Solution: 21 | def reverseString(self, s: List[str]) -> None: 22 | s[:] = s[::-1] 23 | 24 | # Method 3 25 | class Solution: 26 | def reverseString(self, s: List[str]) -> None: 27 | s.reverse() 28 | 29 | # Method 4 (similar to method 1) 30 | class Solution: 31 | def reverseString(self, s: List[str]) -> None: 32 | start = 0 33 | end = len(s) - 1 34 | 35 | while start < end: 36 | temp = s[start] 37 | s[start] = s[end] 38 | s[end] = temp 39 | 40 | start += 1 41 | end -= 1 42 | return s -------------------------------------------------------------------------------- /Medium/173. Binary Search Tree Iterator.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/binary-search-tree-iterator/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class BSTIterator: 10 | # @param root, a binary search tree's root node 11 | def __init__(self, root): 12 | self.stack = list() 13 | self.pushAll(root) 14 | 15 | # @return a boolean, whether we have a next smallest number 16 | def hasNext(self): 17 | return self.stack 18 | 19 | # @return an integer, the next smallest number 20 | def next(self): 21 | tmpNode = self.stack.pop() 22 | self.pushAll(tmpNode.right) 23 | return tmpNode.val 24 | 25 | def pushAll(self, node): 26 | while node is not None: 27 | self.stack.append(node) 28 | node = node.left 29 | 30 | 31 | # Your BSTIterator object will be instantiated and called as such: 32 | # obj = BSTIterator(root) 33 | # param_1 = obj.next() 34 | # param_2 = obj.hasNext() -------------------------------------------------------------------------------- /Easy/704. Binary Search.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/binary-search/ 2 | 3 | class Solution(object): 4 | def search(self, nums, target): 5 | """ 6 | :type nums: List[int] 7 | :type target: int 8 | :rtype: int 9 | """ 10 | #corner case: nums is empty 11 | if not nums or len(nums) == 0: 12 | return -1 13 | left, right = 0, len(nums) - 1 14 | #corner case: target value is out of the list's value range 15 | if target < nums[left] or target > nums[right]: 16 | return -1 17 | #lock the target in left, right and mid three numbers. 18 | while left + 1 < right: 19 | mid = left + (right - left) // 2 20 | if nums[mid] > target: 21 | right = mid 22 | elif nums[mid] < target: 23 | left = mid 24 | else: 25 | return mid 26 | #if the target is not the mid, check the right and left 27 | if nums[right] == target: 28 | return right 29 | if nums[left] == target: 30 | return left 31 | return -1 -------------------------------------------------------------------------------- /Hard/1675. Minimize Deviation in Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/minimize-deviation-in-array/ 2 | 3 | class Solution: 4 | def minimumDeviation(self, A): 5 | pq = [] 6 | for a in A: 7 | heapq.heappush(pq, [a / (a & -a), a]) 8 | res = float('inf') 9 | ma = max(a for a, a0 in pq) 10 | while len(pq) == len(A): 11 | a, a0 = heapq.heappop(pq) 12 | res = min(res, ma - a) 13 | if a % 2 == 1 or a < a0: 14 | ma = max(ma, a * 2) 15 | heapq.heappush(pq, [a * 2, a0]) 16 | return int(res) 17 | 18 | ''' 19 | For each a in A, 20 | divide a by 2 until it is an odd. 21 | Push divided a and its original value in to the pq. 22 | 23 | The current max value in pq is noted as ma. 24 | We iterate from the smallest value in pq, 25 | Update res = min(res, ma - a), 26 | then we check we can get a * 2. 27 | 28 | If a is an odd, we can get a * 2, 29 | If a < a0, which is its original value, we can also get a*2. 30 | 31 | If we can, we push [a*2,a0] back to the pq and continue this process. 32 | ''' -------------------------------------------------------------------------------- /Easy/876. Middle of the Linked List.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/middle-of-the-linked-list/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | 9 | class Solution(object): 10 | def middleNode(self, head): 11 | # While slow moves one step forward, fast moves two steps forward. 12 | # Finally, when fast reaches the end, slow happens to be in the middle of the linked list. 13 | slow = fast = head 14 | while fast and fast.next: 15 | slow = slow.next 16 | fast = fast.next.next 17 | return slow 18 | 19 | ''' 20 | While slow moves one step forward, fast moves two steps forward. 21 | Finally, when fast reaches the end, slow happens to be in the middle of the linked list. 22 | For example, head = [1, 2, 3, 4, 5]. 23 | step 0: slow: [1, 2, 3, 4, 5], fast: [1, 2, 3, 4, 5] 24 | step 1: slow: [1, 2, 3, 4, 5], fast: [1, 2, 3, 4, 5] 25 | step 2: slow: [1, 2, 3, 4, 5], fast: [1, 2, 3, 4, 5] 26 | end because fast cannot move forward anymore and return [3, 4, 5] 27 | ''' -------------------------------------------------------------------------------- /Medium/438. Find All Anagrams in a String.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/find-all-anagrams-in-a-string/ 2 | 3 | class Solution: 4 | def findAnagrams(self, s: str, p: str) -> List[int]: 5 | # take counter of first n elements in s_dict with n = len(p) - 1 6 | s_dict = collections.Counter(s[:len(p)-1]) 7 | # counter of p, this should not be changed 8 | p_dict = collections.Counter(p) 9 | start = 0 10 | # final result list 11 | result = [] 12 | # We iterate over the string s, and in each step we check if s_dict and p_dict match 13 | for i in range(len(p)-1, len(s)): 14 | # updating the counter & adding the character 15 | s_dict[s[i]] += 1 16 | # checking if counters match 17 | if s_dict == p_dict: 18 | result.append(start) 19 | # remove the first element from counter 20 | s_dict[s[start]] -= 1 21 | #if element count = 0, pop it from the counter 22 | if s_dict[s[start]] == 0: 23 | del s_dict[s[start]] 24 | start += 1 25 | 26 | return result -------------------------------------------------------------------------------- /Easy/1. Two Sum.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/two-sum/ 2 | 3 | # General Solution : Complexity - O(n^2) 4 | class Solution: 5 | def twoSum(self, nums: List[int], target: int) -> List[int]: 6 | for i in range(len(nums)): 7 | for j in range(i+1,len(nums)): 8 | if nums[i] + nums[j] == target: 9 | return i,j 10 | 11 | class Solution: 12 | def twoSum(self, nums: List[int], target: int) -> List[int]: 13 | d = {} 14 | for index, value in enumerate(nums): 15 | required_num = target - nums[index] 16 | if required_num in d: 17 | return [d[required_num],index] 18 | else: 19 | d[value] = index 20 | 21 | ''' 22 | Hum ek empty dictionary banayenge, 23 | phir enumerate se index and values ajayegi nums array ki 24 | then hum check karenge ki target - index or target - nums[index] kya hai 25 | That is required number. Agar woh already dictionary me hai then we will return it 26 | warna we will put (eg) d[2] = 0 matlab 2:0 27 | Phir jab iske sath ka target hoga then we will return d[2] i.e 0 and index means 28 | us time ka present index ie. 1 29 | ''' -------------------------------------------------------------------------------- /Medium/1305. All Elements in Two Binary Search Trees.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: 11 | st1, st2 = [], [] 12 | res = [] 13 | 14 | while root1 != None or root2 != None or len(st1) > 0 or len(st2) > 0: 15 | while root1 != None: 16 | st1.append(root1) 17 | root1 = root1.left 18 | while root2 != None: 19 | st2.append(root2) 20 | root2 = root2.left 21 | if len(st2) == 0 or (len(st1) > 0 and st1[-1].val <= st2[-1].val): 22 | root1 = st1.pop() 23 | res.append(root1.val) 24 | root1 = root1.right 25 | else: 26 | root2 = st2.pop() 27 | res.append(root2.val) 28 | root2 = root2.right 29 | return res -------------------------------------------------------------------------------- /Medium/849. Maximum Distance to Closest Person.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/maximize-distance-to-closest-person/ 2 | 3 | class Solution: 4 | def maxDistToClosest(self, seats: List[int]) -> int: 5 | distance = -1 6 | Maximum_Distance = 0 7 | for i in range(len(seats)): 8 | if seats[i] == 1: # if seat is 0 that means it is empty we won't perform any action 9 | if distance == -1: # if we are encounting the first seated person 10 | Maximum_Distance = i 11 | 12 | else: 13 | Maximum_Distance = max(Maximum_Distance,((i - distance) // 2)) 14 | # if we have encounted any seated person before then we will compare for the maximum distance till now to the current distance possible 15 | 16 | distance = i 17 | 18 | if seats[-1] == 0: # if end seat is empty 19 | Maximum_Distance = max(Maximum_Distance, (len(seats) - 1 - distance)) 20 | return Maximum_Distance 21 | 22 | # Post: https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1694631/Python-O(n)-Solution-with-comments -------------------------------------------------------------------------------- /Medium/532. K-diff Pairs in an Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/k-diff-pairs-in-an-array/ 2 | 3 | from collections import Counter 4 | class Solution: 5 | def findPairs(self, nums: List[int], k: int) -> int: 6 | #If k is less than 0, then the result is 0 since we are looking fpr pairs with an ABSOLUTE difference of k. 7 | if k < 0: 8 | return 0 9 | 10 | count = Counter(nums) 11 | pairs = set([]) 12 | 13 | for num in count.keys(): 14 | #Special case: If k == 0, then there needs to be at least two occurences of a particular num in nums 15 | #in order for there to be a pair (num, num). 16 | if k == 0: 17 | if count[num] > 1: 18 | pairs.add((num, num)) 19 | 20 | #Regular case: k != 0. Simply check if num + k is a member of the array nums. 21 | #Insert the pair into the set of pairs (smallerNum, largerNum) so that there are no duplicate pairs. 22 | else: 23 | otherNum = num + k 24 | if otherNum in count: 25 | pairs.add((num, otherNum) if num <= otherNum else (otherNum, num)) 26 | 27 | return len(pairs) -------------------------------------------------------------------------------- /Medium/1010. Pairs of Songs with Total durations divisible by 60.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ 2 | 3 | # Brute Force : Complexity - O(n^2) 4 | class Solution: 5 | def numPairsDivisibleBy60(self, time: List[int]) -> int: 6 | count = 0 7 | for i in range(0,len(time)-1): 8 | for j in range(i+1,len(time)): 9 | if (time[i] + time[j]) % 60 == 0: 10 | count += 1 11 | return count 12 | 13 | # Using HashMap i.e dictionary : Complexity - O(n) 14 | class Solution: 15 | def numPairsDivisibleBy60(self, time: List[int]) -> int: 16 | HashMap = {} 17 | pairs = 0 18 | 19 | for t in time: 20 | numMod = t % 60 21 | 22 | if numMod == 0: 23 | if 0 in HashMap: 24 | pairs += HashMap[0] 25 | elif (60 - numMod) in HashMap: 26 | pairs += HashMap[60 - numMod] 27 | 28 | if numMod in HashMap: 29 | HashMap[numMod] += 1 30 | else: 31 | HashMap[numMod] = 1 32 | 33 | return pairs 34 | -------------------------------------------------------------------------------- /Medium/78. Subsets.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/subsets/ 2 | 3 | class Solution(object): 4 | def subsets(self, nums): 5 | result = [[]] 6 | for n in nums: 7 | for i in range(len(result)): 8 | result.append(result[i]+[n]) 9 | return result 10 | 11 | ''' 12 | # the set to iterate over/generate the power set for 13 | input_set = [1, 2, 3] 14 | 15 | # subset initially only has the empty set (empty list), [] 16 | subset = [[]] 17 | 18 | # in each iteration, concatenate each element/list in subset with the list [n], then extend the results into subset 19 | # element -> subset list after each iteration 20 | 21 | # in the first iteration, subset's only element is [] 22 | # [ [] + [1] ] = [ [1] ] 23 | num = 1 -> [[], [1]] 24 | 25 | # in the second iteration, we concatenate [] with [2] and [1] with [2] 26 | # [ [] + [2] ] = [ [2] ], [ [1] + [2] ] = [ [1, 2] ] 27 | num = 2 -> [[], [1], [2], [1, 2]] 28 | 29 | # in the third iteration, we concatenate [3] with each element in subset 30 | # [ [] + [3] ] = [ [3] ], [ [1] + [3] ] = [ [1, 3] ], [ [2] + [3] ] = [ [2, 3] ], [ [1, 2] + [3] ] = [ [1, 2, 3] ] 31 | num = 3 -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] 32 | ''' -------------------------------------------------------------------------------- /Medium/421. Maximum XOR of Two Numbers in an Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ 2 | 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | def findMaximumXOR(self, nums: List[int]) -> int: 8 | """ 9 | let ni and nj be the numbers such that xor between them produces maximum 10 | value among other pairs. let m be the max value. 11 | 12 | m = ni ^ nj 13 | => m ^ nj = (ni ^ nj) ^ nj 14 | => = ni ^ (nj ^ nj) # xor is associative 15 | => = ni ^ 0 16 | => = ni 17 | 18 | so, m ^ nj = ni 19 | 20 | We note that m is 31-bit integer so we guess bits of m and and with each nj, 21 | we check if the combination of m and nj will produce ni. 22 | 23 | So time complexity becomes O(32N) = O(N) 24 | :param nums: 25 | :return: 26 | """ 27 | m, mask = 0, 0 28 | 29 | for i in range(32)[::-1]: 30 | mask |= 1 << i 31 | prefixes = {n & mask for n in nums} 32 | 33 | tmp = m | (1 << i) 34 | 35 | if any(prefix ^ tmp in prefixes for prefix in prefixes): 36 | m = tmp 37 | 38 | return m -------------------------------------------------------------------------------- /Medium/662. Maximum Width of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/maximum-width-of-binary-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def widthOfBinaryTree(self, root): 11 | if not root: return [] 12 | width, level = 0, [(root, 1)] 13 | # Keep going untill current level has some nodes. 14 | while len(level): 15 | # Put all children of current level in next_level. 16 | width = max(width, level[-1][1] - level[0][1] + 1) 17 | next_level = [] 18 | for item, num in level: 19 | if item.left: # Make sure to not put the Null nodes 20 | next_level.append((item.left, num*2)) 21 | if item.right: 22 | next_level.append((item.right, num*2+1)) 23 | level = next_level 24 | return width 25 | 26 | ''' 27 | That's numbering nodes (and nulls) like this: 28 | 29 | 1 30 | 2 3 31 | 4 5 6 7 32 | 8 9 ... 33 | ''' -------------------------------------------------------------------------------- /Easy/26. Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | # Problem Statement:https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | 3 | class Solution: 4 | def removeDuplicates(self, nums: List[int]) -> int: 5 | if len(nums) == 0: 6 | return 0 7 | else: 8 | lp = 1 #left pointer 9 | for rp in range(1,len(nums)): #right pointer 10 | if nums[rp] != nums[rp-1]: 11 | nums[lp] = nums[rp] 12 | lp += 1 13 | return lp 14 | ''' 15 | Isme hum 2 pointers lenge left and right aur dono ko 1st index par rakhenge 16 | Because unique element ka count chahiye so 1st element will always be unique 17 | Then for loop se right pointer increment hota jayega jabtak ki hume dusri unique value nhi milti 18 | Matlab ki jabtak nums[1] == nums[0] tab tak right pointer will just increase 19 | Jaise hi nums[rp or 2] != nums[rp-1 or 1] matlab ki different / unique value 20 | Tab hum us unique value ko first unique value ke baad wali position par store kardenge 21 | Matlab ki jaha par hamara left pointer tha 22 | Because left pointer 1st position par hai starting me toh second unique value waha par hi ayegi after 0 position. 23 | And then end me hum left pointer ko isiliye return kar rhe hai kyuki uska count = total unique elements. 24 | ''' -------------------------------------------------------------------------------- /Hard/1345. Jump Game IV.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/jump-game-iv/ 2 | 3 | class Solution: 4 | def minJumps(self, arr: List[int]) -> int: 5 | visited = set() 6 | xs = defaultdict(list) 7 | for i, v in enumerate(arr): 8 | xs[v].append(i) 9 | 10 | N = len(arr) 11 | if N == 1: 12 | return 0 13 | 14 | 15 | num_steps = 1 16 | level = [N-1] 17 | visited.add(N-1) 18 | 19 | while level: 20 | next_level = set() 21 | # print(level, num_steps) 22 | 23 | for i in level: 24 | if i == 1: 25 | return num_steps 26 | 27 | if i-1 not in visited: 28 | visited.add(i-1) 29 | next_level.add(i-1) 30 | if i != N-1 and i+1 not in visited: 31 | visited.add(i+1) 32 | next_level.add(i+1) 33 | 34 | for ni in xs[arr[i]]: 35 | if ni == 0: 36 | return num_steps 37 | if ni not in visited: 38 | visited.add(ni) 39 | next_level.add(ni) 40 | 41 | num_steps += 1 42 | level = next_level -------------------------------------------------------------------------------- /Easy/258. Add Digits.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/add-digits/ 2 | 3 | class Solution: 4 | def addDigits(self, num: int) -> int: 5 | if num == 0: 6 | return 0 7 | if num % 9 == 0: 8 | return 9 9 | else: 10 | return(num % 9) 11 | 12 | # Alternate Solution 1 13 | ''' 14 | def Sum(a): 15 | ans = 0 16 | for i in str(a): 17 | ans += int(i) 18 | return ans 19 | 20 | class Solution: 21 | def addDigits(self, num: int) -> int: 22 | sum = Sum(num) 23 | if len(str(sum)) == 1: 24 | return sum 25 | while len(str((sum))) != 1: 26 | sum = Sum(sum) 27 | if len(str(sum)) == 1: 28 | return sum 29 | ''' 30 | 31 | # Alternate Solution 2 32 | 33 | ''' 34 | class Solution: 35 | def addDigits(self, num: int) -> int: 36 | if num//10 == 0: 37 | return num 38 | 39 | sum = 0 40 | while num > 0: 41 | sum += num%10 42 | num = num//10 43 | 44 | return self.addDigits(sum) 45 | 46 | # OR THIS WAY 47 | while(num >= 10): 48 | temp = 0 49 | while(num > 0): 50 | temp += num % 10 51 | num = num // 10 52 | num = temp 53 | return num 54 | ''' -------------------------------------------------------------------------------- /Easy/589. N-ary Tree Preorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/n-ary-tree-preorder-traversal/ 2 | 3 | """ 4 | # Definition for a Node. 5 | class Node(object): 6 | def __init__(self, val=None, children=None): 7 | self.val = val 8 | self.children = children 9 | """ 10 | 11 | class Solution(object): 12 | def preorder(self, root): 13 | """ 14 | :type root: Node 15 | :rtype: List[int] 16 | """ 17 | if root is None: 18 | return [] 19 | 20 | stack = [root] 21 | output = [] 22 | 23 | # Till there is element in stack the loop runs. 24 | while stack: 25 | 26 | #pop the last element from the stack and store it into temp. 27 | temp = stack.pop() 28 | 29 | # append. the value of temp to output 30 | output.append(temp.val) 31 | 32 | #add the children of the temp into the stack in reverse order. 33 | # children of 1 = [3,2,4], if not reveresed then 4 will be popped out first from the stack. 34 | # if reversed then stack = [4,2,3]. Here 3 will pop out first. 35 | # This continues till the stack is empty. 36 | stack.extend(temp.children[::-1]) 37 | 38 | #return the output 39 | return output -------------------------------------------------------------------------------- /Hard/127. Word Ladder.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/word-ladder/ 2 | 3 | class Solution: 4 | def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: 5 | visited = set([beginWord]) 6 | wordSet = set(wordList) 7 | startSet, endSet = set([beginWord]), set([endWord]) 8 | if endWord not in wordSet: 9 | return 0 10 | return self.bfs(startSet, endSet, visited, wordSet) 11 | 12 | def bfs(self, startSet, endSet, visited, wordSet): 13 | steps = 1 14 | while startSet and endSet: 15 | if len(startSet) > len(endSet): 16 | startSet, endSet = endSet, startSet 17 | steps += 1 18 | nextSet = set() 19 | for word in startSet: 20 | for i in range(len(word)): 21 | for ch in "abcdefghijklmnopqrstuvwxyz": 22 | newWord = word[:i] + ch + word[i+1:] 23 | if newWord in endSet: 24 | return steps 25 | if newWord in wordSet and newWord not in visited: 26 | nextSet.add(newWord) 27 | wordSet.remove(newWord) 28 | visited.add(newWord) 29 | startSet = nextSet 30 | 31 | return 0 -------------------------------------------------------------------------------- /Medium/763. Partition Labels.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/partition-labels/ 2 | 3 | class Solution: 4 | def partitionLabels(self, s: str) -> List[int]: 5 | 6 | last = {s[i]: i for i in range(len(s))} # last appearance of the letter 7 | i, ans = 0, [] 8 | while i < len(s): 9 | end, j = last[s[i]], i + 1 10 | while j < end: # validation of the part [i, end] 11 | if last[s[j]] > end: 12 | end = last[s[j]] # extend the part 13 | j += 1 14 | 15 | ans.append(end - i + 1) 16 | i = end + 1 17 | 18 | return ans 19 | 20 | ''' 21 | Since each letter can appear only in one part, we cannot form a part shorter than the 22 | index of the last appearance of a letter subtracted by an index of the first appearance. 23 | For example here (absfab) the lengths of the first part are limited by the positions of the letter a. 24 | So it's important to know at what index each letter appears in the string last time. 25 | We can create a hash map and fill it with the last indexes for letters. 26 | 27 | Also, we have to validate a candidate part. 28 | For the same example (absfab) we see that letter a cannot form a border for the first part 29 | because of a nasty letter b inside. So we need to expand the range of the initial part. 30 | ''' -------------------------------------------------------------------------------- /Easy/171. Excel Sheet Column Number.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/excel-sheet-column-number/ 2 | 3 | class Solution: 4 | def titleToNumber(self, columnTitle: str) -> int: 5 | answer = 0 6 | for char in columnTitle: 7 | answer = answer*26 + ord(char)-ord('A')+1 8 | return answer 9 | 10 | 11 | # Alternate Solution 12 | class Solution: 13 | def titleToNumber(self, columnTitle: str) -> int: 14 | ans, pos = 0, 0 15 | for letter in reversed(columnTitle): 16 | digit = ord(letter)-64 17 | ans += digit * 26**pos 18 | pos += 1 19 | 20 | return ans 21 | 22 | ''' 23 | Essentially, what we asked to do here is to convert a number in the base 26 numeral system 24 | to a decimal number. This is a standard algorithm, where we iterate over the digits from 25 | right to left and multiply them by the base to the power of the position of the digit. 26 | To translate a letter to a number we use the Python method ord which returns the Unicode code of the letter. 27 | By subtracting the code by 64, we can map letters to the numbers from 1 to 26. 28 | 29 | 26**pos because: 30 | eg: number = '2539' 31 | ans = ans + 9 * 10**0 32 | ans = ans + 3 * 10**1 33 | ans = ans + 5 * 10**2 34 | ans = ans + 2 * 10**3 35 | ans = 2539 36 | For base 26 we do absolutely the same but instead of 10 we use 26. 37 | ''' -------------------------------------------------------------------------------- /Medium/399. Evaluate Division.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/evaluate-division/ 2 | 3 | class Solution: 4 | def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: 5 | # Step 1. Build the Graph 6 | graph = collections.defaultdict(dict) 7 | for (x, y), val in zip(equations, values): 8 | graph[x][y] = val 9 | graph[y][x] = 1.0 / val 10 | print(graph) 11 | 12 | # Step 2. DFS function 13 | def dfs(x, y, visited): 14 | # neither x not y exists 15 | if x not in graph or y not in graph: 16 | return -1.0 17 | 18 | # x points to y 19 | if y in graph[x]: 20 | return graph[x][y] 21 | 22 | # x maybe connected to y through other nodes 23 | # use dfs to see if there is a path from x to y 24 | for i in graph[x]: 25 | if i not in visited: 26 | visited.add(i) 27 | temp = dfs(i, y, visited) 28 | if temp == -1: 29 | continue 30 | else: 31 | return graph[x][i] * temp 32 | return -1 33 | 34 | # go through each of the queries and find the value 35 | res = [] 36 | for query in queries: 37 | res.append(dfs(query[0], query[1], set())) 38 | return res 39 | -------------------------------------------------------------------------------- /Medium/148. Sort List.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/sort-list/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution(object): 9 | def merge(self, h1, h2): 10 | dummy = tail = ListNode(None) 11 | while h1 and h2: 12 | if h1.val < h2.val: 13 | tail.next, h1 = h1, h1.next 14 | else: 15 | tail.next, h2 = h2, h2.next 16 | tail = tail.next 17 | 18 | tail.next = h1 or h2 19 | return dummy.next 20 | 21 | def sortList(self, head): 22 | if not head or not head.next: 23 | return head 24 | 25 | pre, slow, fast = None, head, head 26 | while fast and fast.next: 27 | pre, slow, fast = slow, slow.next, fast.next.next 28 | pre.next = None 29 | 30 | return self.merge(*map(self.sortList, (head, slow))) 31 | 32 | # Alternate Solution 33 | class Solution(object): 34 | def sortList(self, head): 35 | if not head: 36 | return None 37 | values = [] 38 | node = head 39 | while node: 40 | values.append(node.val) 41 | node = node.next 42 | values.sort() 43 | #print(values) 44 | node = head 45 | for n in values: 46 | node.val = n 47 | node = node.next 48 | return head -------------------------------------------------------------------------------- /Easy/1309. Decrypt String from Alphabet to Integer Mapping.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ 2 | 3 | class Solution: 4 | def freqAlphabets(self, s: str) -> str: 5 | dic = {'1':'a','2':'b','3':'c','4':'d','5':'e','6':'f','7':'g','8':'h','9':'i','10':'j','11':'k','12':'l','13':'m','14':'n','15':'o','16':'p','17':'q','18':'r','19':'s','20':'t','21':'u','22':'v','23':'w','24':'x','25':'y','26':'z'} 6 | len_s, i, ans = len(s), 0, '' 7 | while i < len_s: 8 | # Each number between 10 and 26 is followed by # character. 9 | # So, If s[i+2] is equal to #, then the number ( e.g. s[i:i+1] ) is between 10 and 26; 10 | # otherwise, the number ( e.g. s[i] ) is between 1 and 9. 11 | if i + 2 < len_s and s[i+2] == '#': 12 | ans += dic[s[i:i+2]] 13 | i += 3 14 | else: 15 | ans += dic[s[i]] 16 | i += 1 17 | return ans 18 | 19 | # Alternate Solution 20 | class Solution: 21 | def freqAlphabets(self, s: str) -> str: 22 | i = 0 23 | ans = [] 24 | length = len(s) 25 | 26 | while i < length: 27 | if i+2 < length and s[i+2] == '#': 28 | ans.append(chr(96+int(s[i:i+2]))) 29 | i += 3 30 | else: 31 | ans.append(chr(96+int(s[i]))) 32 | i += 1 33 | 34 | return ''.join(ans) -------------------------------------------------------------------------------- /Medium/740. Delete and Earn.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/delete-and-earn/ 2 | 3 | class Solution: 4 | def deleteAndEarn(self, nums: List[int]) -> int: 5 | 6 | # score is the storage to collect all the copies of distinct integers in input array 7 | score = [0] * (max(nums)+1) 8 | 9 | # score[i] save all the copies of corresponding number in input array 10 | for number in nums: 11 | score[number]+= number 12 | 13 | 14 | # Reduce to the House Robbery Problem I 15 | # Leetcode #198: https://leetcode.com/problems/house-robber/ 16 | size = len(score) 17 | 18 | if size <= 2: 19 | return max(score) 20 | 21 | max_points = [0 for _ in range(size)] 22 | max_points[0] = score[0] 23 | max_points[1] = max(score[0], score[1]) 24 | 25 | for i in range(2, size): 26 | 27 | take_integer_i = max_points[i-2] + score[i] 28 | not_to_take_integer_i = max_points[i-1] + 0 29 | 30 | max_points[i] = max( take_integer_i, not_to_take_integer_i) 31 | 32 | return max_points[-1] 33 | 34 | ''' 35 | Given nums = [2,2,3,3,3,4] 36 | 37 | reduce it to House Robbery problem 38 | 39 | score = [0, 0, 2+2, 3+3+3, 4] = [0, 0, 4, 9, 4] 40 | 41 | Max points of Delete and Eran with [2,2,3,3,3,4] 42 | = Max value of Leetcode 198: House Robbery with [0, 0, 4, 9, 4] 43 | = 9 44 | ''' -------------------------------------------------------------------------------- /Medium/1007. Minimum Domino Rotations For Equal Row.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ 2 | 3 | from collections import defaultdict 4 | 5 | class Solution: 6 | def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: 7 | counterT = defaultdict(int) #count of the occurences of numbers in tops 8 | counterB = defaultdict(int) #count of the occurences of numbers in buttoms 9 | same = 0 #counting the same occurences in top & bottom 10 | 11 | for i in range(len(tops)): 12 | counterT[tops[i]] += 1 13 | counterB[bottoms[i]] += 1 14 | 15 | if tops[i] == bottoms[i]: 16 | same += 1 17 | 18 | for num in range(1,7): 19 | if (counterT[num] + counterB[num] - same) == len(tops): 20 | return len(tops) - max(counterT[num],counterB[num]) 21 | 22 | return -1 23 | 24 | ''' 25 | If we can make number i in a whole row it should satisfy that counterT[i] + counterB[i] - same == len(top) or len(bottom) 26 | 27 | eg in the first test Case: 28 | tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2] 29 | faceA[2] = 4 , as tops[0] = tops[2] = tops[4] = tops[5] 30 | faceB[2] = 3, as bottoms[1] = bottoms[3] = bottoms[5] 31 | same[2] = 1, as tops[5] = bottoms[5] 32 | Therefore we have faceA[2] + faceB[2] - same[2] = 6, (size of arr) 33 | Therfore we can make 2 in a whole row. 34 | ''' -------------------------------------------------------------------------------- /Medium/99. Recover Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/recover-binary-search-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution(object): 10 | def recoverTree(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: None Do not return anything, modify root in-place instead. 14 | """ 15 | self.first, self.second, self.prevNode = None, None, None # Create three nodes. 16 | self.inOrder(root) # Calling the function 17 | self.first.val, self.second.val = self.second.val, self.first.val 18 | # Swapping the two elements needed to be swapped 19 | 20 | def inOrder(self, root): 21 | if not root: 22 | return 23 | self.inOrder(root.left) 24 | 25 | if self.prevNode: # To handle the case of first node, because we make it prev to begin with 26 | if self.prevNode.val > root.val: # Check property violation 27 | if not self.first: 28 | self.first = self.prevNode # Found first pair 29 | self.second = root # If the second pair is found then simply assign the smaller element of the pair as the second guy, it works for single pair easily, as it wont get updated again in that case. 30 | 31 | self.prevNode = root 32 | 33 | self.inOrder(root.right) -------------------------------------------------------------------------------- /Medium/1663. Smallest String With A Given Numeric Value.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/" 2 | 3 | # Time Limit Exceeded 4 | class Solution: 5 | def getSmallestString(self, n: int, k: int) -> str: 6 | alphabets = ['','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'] 7 | output = '' 8 | for i in range(n,0,-1): 9 | value = k - (i - 1) 10 | if value >= 26: 11 | output = alphabets[26] + output 12 | k -= 26 13 | else: 14 | output = alphabets[value] + output 15 | k -= value 16 | return output 17 | 18 | 19 | # Accepted 20 | class Solution: 21 | def getSmallestString(self, n: int, k: int) -> str: 22 | output = ['a'] * n #Since we are forming the lexicographically smallest string, we just simply fill our result with 'a' 23 | # But, that result will not necessarily have the required score n 24 | # we can add some 'z' to the back of the result until the score reaches the required value. 25 | # if we are missing less than 26 to the required score, we add something that is less than 'z'. 26 | k = k - n 27 | i = n - 1 28 | while k: 29 | k += 1 30 | if k//26 >= 1: 31 | output[i] = 'z' 32 | k = k - 26 33 | i -= 1 34 | else: 35 | output[i] = chr(k + 96) 36 | k = 0 37 | 38 | return ''.join(output) 39 | -------------------------------------------------------------------------------- /Medium/131. Palindrome Partitioning.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/palindrome-partitioning/ 2 | 3 | class Solution: 4 | def partition(self, s: str) -> List[List[str]]: 5 | result = [] # will store all posible partitions 6 | partition = [] # current partition 7 | 8 | # function for backtracking 9 | def dfs(i): # i is the index of the character we are currently at 10 | if i >= len(s): # checking base case 11 | result.append(partition.copy()) 12 | ''' because there is only 1 partition variable and we will keep updating/changing it 13 | so we need to copy it everytime we append to result ''' 14 | return 15 | for j in range(i,len(s)): # generating every single possible substring 16 | if self.isPalindrome(s,i,j): # checking is the substring is palindrome 17 | partition.append(s[i:j+1]) 18 | dfs(j + 1) # recursively continue our dfs 19 | partition.pop() 20 | # if a substring is not a palindrome, we just skip it 21 | dfs(0) 22 | return result 23 | 24 | # function for palindrome checking 25 | def isPalindrome(self,s,left,right): 26 | while left < right: 27 | if s[left] != s[right]: # if character at left position doesnot equal character at left position 28 | return False # substring is not palindrom 29 | left,right = left+1,right-1 # if they are equal we update left and right pointers 30 | return True # substring is palindrome -------------------------------------------------------------------------------- /Easy/1790. Check if One String Swap Can Make Strings Equal.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/ 2 | 3 | class Solution: 4 | def areAlmostEqual(self, s1: str, s2: str) -> bool: 5 | count = 0 6 | for ch1, ch2 in zip(s1, s2): 7 | if ch1 != ch2: count += 1 8 | return (Counter(s1) == Counter(s2)) and (count == 0 or count == 2) 9 | 10 | 11 | # Alternate Solution 12 | class Solution: 13 | def areAlmostEqual(self, s1: str, s2: str) -> bool: 14 | bad = [] # list of bad indices 15 | if s1 == s2 : return True 16 | 17 | for i in range(len(s1)): 18 | if s1[i] != s2[i]: 19 | bad.append(i) 20 | 21 | if not (len(bad) == 2): return False 22 | 23 | s1 = list(s1) 24 | s1[bad[0]], s1[bad[1]] = s1[bad[1]], s1[bad[0]] 25 | res = "" 26 | 27 | for char in s1: 28 | res += char 29 | 30 | return (res == s2) 31 | ''' 32 | This solution just chooses one string (the first one) and then counts how many "bad" characters exist. 33 | A "bad" character is a character that doesn't match it's corresponding character in the second string. 34 | If there are more than 2 bad indices, one swap is not enough to make them equal. 35 | (In fact, if there are any odd number of bad indices, no swaps can make the two strings equal). 36 | We only care about the case where we have 2 bad indices. We can then make an array of the characters in the string 37 | to then swap the two bad ones, and finally re-create the string to then compare it to our goal string. 38 | ''' -------------------------------------------------------------------------------- /Hard/1359. Count All Valid Pickup and Delivery Options.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: 1359. Count All Valid Pickup and Delivery Options 2 | 3 | from functools import reduce 4 | from operator import mul 5 | class Solution: 6 | def countOrders(self, n: int) -> int: 7 | cap = 10**9 + 7 8 | pickup_permutation = math.factorial(n) % cap 9 | delivery_permutation = reduce(mul, range(1, 2*n, 2), 1) % cap 10 | return pickup_permutation * delivery_permutation % cap 11 | 12 | ''' 13 | Denote pickup 1, pickup 2, pickup 3, ... as A, B, C, ... 14 | Denote delivery 1, delivery 2, delivery 3, ... as a, b, c, ... 15 | We need to ensure a is behind A, b is behind B, ... 16 | 17 | This solution involves 2 stages. 18 | 19 | - Stage 1 20 | We decide the order of all the pickups. It is trivial to tell there are n! possibilities 21 | - Stage 2 22 | Given one possibility. Let's say the pickups are ordered like this A B C 23 | We can now insert the corresponding deliveries one by one. 24 | We start with the last pickup we made, namely, insert c, and there is only 1 valid slot. 25 | A B C c 26 | We continue with the second last pickup we made, namely, insert b, and there are 3 valid slots. 27 | A B x C x c x (where x denotes the location of valid slots for b) 28 | Let's only consider one case A B C c b. We continue with the third last pickup we made, namely, insert a, and there are 5 valid slots. 29 | A x B x C x c x b x, (where x denotes the location of valid slots for a) 30 | In conclusion. we have in total 1 * 3 * 5 * ... * (2n-1) possibilities 31 | Thus, the final solution is n! * (1 * 3 * 5 * ... * (2n-1)) % 1000000007 32 | ''' -------------------------------------------------------------------------------- /Medium/1202. Smallest String With Swaps.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/smallest-string-with-swaps/ 2 | 3 | class Solution: 4 | def smallestStringWithSwaps(self, s, pairs): 5 | d = defaultdict(list) 6 | for a,b in pairs: 7 | d[a].append(b) 8 | d[b].append(a) 9 | 10 | def dfs(x,A): 11 | if x in d: 12 | A.append(x) 13 | for y in d.pop(x): 14 | dfs(y,A) 15 | 16 | s = list(s) 17 | while d: 18 | x = next(iter(d)) 19 | A = [] 20 | dfs(x,A) 21 | A = sorted(A) 22 | B = sorted([ s[i] for i in A ]) 23 | for i,b in enumerate(B): 24 | s[A[i]] = b 25 | return ''.join(s) 26 | 27 | ''' 28 | 1. The initial idea is that each pair of swappable letters in "pairs" can be treated as an edge in a (undirected) graph. This works because, in the limit case, we could do bubble sort across connected letters. 29 | 30 | 2. We then go one step further and treat each index s[i] as a node, and convert the array "pairs" into a dictionary "d" of connected nodes. 31 | 32 | 3. While our dictionary "d" has entries, we choose one element in "d" and visit all connected nodes, returning a list of detected points. We sort this list, and place the results back in our final string/array. Since each node can only be visited once, this process has a linear time complexity of O(E), where E is the number of edges in our graph ( E = len(pairs) ). 33 | 34 | 4. Once all nodes have been visited, we exit our function and return the final string, with all its connected sections sorted . 35 | ''' -------------------------------------------------------------------------------- /Medium/211. Design Add and Search Words Data Structure.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/design-add-and-search-words-data-structure/ 2 | 3 | class WordDictionary(object): 4 | 5 | def __init__(self): 6 | self.dict, self.len2word = defaultdict(set), defaultdict(set) 7 | 8 | def addWord(self, word): 9 | # self.dict: key is combination of index and character, value is a word set whose i-th letter is c 10 | for i, c in enumerate(word): self.dict[(i, c)].add(word) 11 | # self.len2word: key is length of word, value is a word set whose length is equal to key 12 | self.len2word[len(word)].add(word) 13 | 14 | def search(self, word): 15 | ans = copy.deepcopy(self.len2word[len(word)]) 16 | for i, c in enumerate(word): 17 | if c != '.': ans &= self.dict[(i, c)] 18 | return True if len(ans) else False 19 | 20 | # Alternate Solution 21 | ''' 22 | class WordDictionary: 23 | 24 | def __init__(self): 25 | self.d = collections.defaultdict(list) 26 | 27 | 28 | def addWord(self, word: str) -> None: 29 | self.d[len(word)] += [word] 30 | 31 | 32 | def search(self, word: str) -> bool: 33 | if '.' not in word: 34 | return word in self.d[len(word)] 35 | for x in self.d[len(word)]: 36 | for i in range(len(word)): 37 | if word[i] != x[i] and word[i] != '.': 38 | break 39 | else: 40 | return True 41 | return False 42 | ''' 43 | 44 | # Your WordDictionary object will be instantiated and called as such: 45 | # obj = WordDictionary() 46 | # obj.addWord(word) 47 | # param_2 = obj.search(word) -------------------------------------------------------------------------------- /Medium/142. Linked List Cycle II.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/linked-list-cycle-ii/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution: 10 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 11 | slow = fast = head 12 | while fast and fast.next: 13 | slow, fast = slow.next, fast.next.next 14 | if slow == fast: break 15 | else: return None # if not (fast and fast.next): return None 16 | while head != slow: 17 | head, slow = head.next, slow.next 18 | return head 19 | 20 | ''' 21 | slow moves 1 step at a time, fast moves 2 steps at a time. 22 | when slow and fast meet each other, they must be on the cycle 23 | x denotes the length of the linked list before starting the circle 24 | y denotes the distance from the start of the cycle to where slow and fast met 25 | C denotes the length of the cycle 26 | when they meet, slow traveled (x + y) steps while fast traveled 2 * (x + y) steps, and the extra distance (x + y) must be a multiple of the circle length C 27 | note that x, y, C are all lengths or the number of steps need to move. 28 | head, slow, fast are pointers. 29 | head moves x steps and arrives at the start of the cycle. 30 | so we have x + y = N * C, let slow continue to travel from y and after x more steps, slow will return to the start of the cycle. 31 | At the same time, according to the definition of x, head will also reach the start of the cycle after moving x steps. 32 | so if head and slow start to move at the same time, they will meet at the start of the cycle, that is the answer. 33 | ''' -------------------------------------------------------------------------------- /Easy/9. Palindrome Number.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/palindrome-number/ 2 | 3 | class Solution: 4 | def isPalindrome(self, x: int) -> bool: 5 | if x < 0: 6 | return False 7 | 8 | return str(x) == str(x)[::-1] 9 | 10 | # Alternate Solution 1 11 | class Solution: 12 | def isPalindrome(self, x: int) -> bool: 13 | if x < 0: 14 | return False 15 | 16 | inputNum = x 17 | newNum = 0 18 | while x > 0: 19 | newNum = newNum * 10 + x % 10 20 | x = x // 10 21 | return newNum == inputNum 22 | 23 | # Alternate Solution 2 24 | class Solution: 25 | def isPalindrome(self, x: int) -> bool: 26 | if x < 0 or (x > 0 and x%10 == 0): # if x is negative, return False. if x is positive and last digit is 0, that also cannot form a palindrome, return False. 27 | return False 28 | 29 | result = 0 30 | while x > result: 31 | result = result * 10 + x % 10 32 | x = x // 10 33 | 34 | return True if (x == result or x == result // 10) else False 35 | 36 | ''' 37 | Instead of reversing the whole integer, let's convert half of the integer and then check if it's palindrome. 38 | But we don't know when is that half going to come. 39 | 40 | Example, if x = 15951, then let's create reverse of x in loop. Initially, x = 15951, revX = 0 41 | 42 | x = 1595, revX = 1 43 | x = 159, revX = 15 44 | x = 15, revX = 159 45 | We see that revX > x after 3 loops and we crossed the half way in the integer bcoz it's an odd length integer. 46 | If it's an even length integer, our loop stops exactly in the middle. 47 | 48 | Now we can compare x and revX, if even length, or x and revX//10 if odd length and return True if they match. 49 | ''' -------------------------------------------------------------------------------- /Medium/284. Peeking Iterator.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/peeking-iterator/ 2 | 3 | # Below is the interface for Iterator, which is already defined for you. 4 | # 5 | # class Iterator: 6 | # def __init__(self, nums): 7 | # """ 8 | # Initializes an iterator object to the beginning of a list. 9 | # :type nums: List[int] 10 | # """ 11 | # 12 | # def hasNext(self): 13 | # """ 14 | # Returns true if the iteration has more elements. 15 | # :rtype: bool 16 | # """ 17 | # 18 | # def next(self): 19 | # """ 20 | # Returns the next element in the iteration. 21 | # :rtype: int 22 | # """ 23 | 24 | class PeekingIterator(object): 25 | def __init__(self, iterator): 26 | """ 27 | Initialize your data structure here. 28 | :type iterator: Iterator 29 | """ 30 | self.iter = iterator 31 | self.temp = self.iter.next() if self.iter.hasNext() else None 32 | 33 | def peek(self): 34 | """ 35 | Returns the next element in the iteration without advancing the iterator. 36 | :rtype: int 37 | """ 38 | return self.temp 39 | 40 | def next(self): 41 | """ 42 | :rtype: int 43 | """ 44 | ret = self.temp 45 | self.temp = self.iter.next() if self.iter.hasNext() else None 46 | return ret 47 | 48 | def hasNext(self): 49 | """ 50 | :rtype: bool 51 | """ 52 | return self.temp is not None 53 | 54 | 55 | # Your PeekingIterator object will be instantiated and called as such: 56 | # iter = PeekingIterator(Iterator(nums)) 57 | # while iter.hasNext(): 58 | # val = iter.peek() # Get the next element but not advance the iterator. 59 | # iter.next() # Should return the same value as [val]. -------------------------------------------------------------------------------- /Medium/560. Subarray Sum Equals K.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/subarray-sum-equals-k/ 2 | 3 | # Solution 1 - Complexity: O(n^2) [Time Limit Exceeded] 4 | class Solution: 5 | def subarraySum(self, nums: List[int], k: int) -> int: 6 | count = 0 7 | for i in range(len(nums)): 8 | for j in range(i,len(nums)): 9 | if sum(nums[i:j+1]) == k: 10 | count += 1 11 | return count 12 | 13 | # Solution 2 - Complexity: O(n) [Accepted] 14 | class Solution: 15 | def subarraySum(self, nums: List[int], k: int) -> int: 16 | d = {} 17 | d[0] = 1 18 | s = 0 19 | count = 0 20 | for i in range(len(nums)): 21 | s += nums[i] 22 | if s-k in d: # --- I 23 | count += d[s-k] 24 | # or return True 25 | # or return indicies 26 | 27 | # add sum to frq dict 28 | if s in d: 29 | d[s] += 1 # --- II 30 | else: 31 | d[s] = 1 32 | 33 | return count 34 | 35 | 36 | # COMMENT -- I 37 | # --------------- 38 | # Single scan. Given the current sum and the k, we check if (sum-k) existed as previous sum at an earlier stage ( aka smaller window size) 39 | # Keep expanding the sum while checking whether we have seen (sum - k) before 40 | 41 | 42 | 43 | # COMMENT -- II 44 | # --------------- 45 | # It's possible that the freq of a sum could be greater than 1 only when the nums list conatins a zero 46 | # ex: nums = [1,2,3,0,4] 47 | # because sum will be the same for two consecutive iterations. 48 | # it's important to capture this edge case in order to return the correct number of subarrays that 49 | # add up to target. 50 | # if we are guaranteed that the list nums has no zeros, then we can replace the prefix dict with a prefix set -------------------------------------------------------------------------------- /Medium/289. Game of Life.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/game-of-life/ 2 | 3 | class Solution: 4 | def gameOfLife(self, board: List[List[int]]) -> None: 5 | """ 6 | Do not return anything, modify board in-place instead. 7 | """ 8 | # Populating the directions array 9 | # Corresponding to [N, NE, E, SE, S, SW, W, NW] 10 | directions = [[-1,0], [-1,1], [0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] 11 | 12 | m = len(board) 13 | n = len(board[0]) 14 | 15 | for i in range(m): 16 | for j in range(n): 17 | # Maintaining a counter of live cells in the original matrix 18 | livecount = 0 19 | 20 | for direction in directions: 21 | # Determining what our new row would be after taking a direction 22 | nr = i + direction[0] 23 | 24 | # Determining what our new column would be after taking a direction 25 | nc = j + direction[1] 26 | 27 | # Ensuring that our new_row and new_column 28 | # are within the bounds of the matrix 29 | if 0 <= nr < m and 0 <= nc < n and abs(board[nr][nc])==1: 30 | livecount += 1 31 | 32 | if board[i][j] == 1: 33 | # case where live cell dies from under/over population 34 | if livecount<2 or livecount>3: 35 | board[i][j] = -1 36 | else: 37 | # case of dead cell resurrection 38 | if livecount==3: 39 | board[i][j] = 2 40 | 41 | for i in range(m): 42 | for j in range(n): 43 | if board[i][j] == -1: 44 | board[i][j] = 0 45 | elif board[i][j] == 2: 46 | board[i][j] = 1 -------------------------------------------------------------------------------- /Easy/169. Majority Element..py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/majority-element/ 2 | 3 | class Solution: 4 | def majorityElement(self, nums: List[int]) -> int: 5 | maximum = nums[0] 6 | count = 1 7 | for i in range(1,len(nums)): 8 | if count == 0: 9 | count += 1 10 | maximum = nums[i] 11 | elif maximum == nums[i]: 12 | count += 1 13 | else: 14 | count -= 1 15 | return maximum 16 | 17 | # Alternate Solution 18 | class Solution: 19 | def majorityElement(self, nums: List[int]) -> int: 20 | nums.sort() 21 | return nums[len(nums)//2] 22 | 23 | ''' 24 | def majorityElement(self, nums): 25 | 26 | # Boyer's Moore Algorithm --> O(1) Space 27 | 28 | # We first assume that our first num is the majority element 29 | # So the count here is 1 as we have seen it 1 times, if the 30 | # count in the end is greater than 0 we are sure that this is majority element 31 | # as if you take count of majority element and subtract sum of all counts of non 32 | # Majority element, if that count is still positive that it proves that is 33 | # majority element. We do not need to check count in end over here as we are 34 | # sure that there exists a majority element. 35 | count = 1 36 | 37 | # Our Initial guess that this is the majority element 38 | result = nums[0] 39 | 40 | for num in nums[1:]: 41 | # If the next number is not same as prev 42 | # and count becomes 0 make this number as majority element and initialize 43 | # count to 1 again else just decrease the count 44 | if num != result: 45 | # decrease count by 1 46 | count -= 1 47 | # Make this element as majority element 48 | if count == 0: 49 | result = num 50 | count = 1 51 | else: 52 | # This is same element as previous one. 53 | count += 1 54 | 55 | return result 56 | 57 | ''' -------------------------------------------------------------------------------- /Medium/133. Clone Graph.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/clone-graph/ 2 | 3 | """ 4 | # Definition for a Node. 5 | class Node: 6 | def __init__(self, val = 0, neighbors = None): 7 | self.val = val 8 | self.neighbors = neighbors if neighbors is not None else [] 9 | """ 10 | 11 | class Solution: 12 | # BFS 13 | def cloneGraph(self, node: 'Node') -> 'Node': 14 | if not node: 15 | return 16 | nodeCopy = Node(node.val, []) 17 | dic = {node: nodeCopy} 18 | queue = collections.deque([node]) 19 | while queue: 20 | node = queue.popleft() 21 | for neighbor in node.neighbors: 22 | if neighbor not in dic: # neighbor is not visited 23 | neighborCopy = Node(neighbor.val, []) 24 | dic[neighbor] = neighborCopy 25 | dic[node].neighbors.append(neighborCopy) 26 | queue.append(neighbor) 27 | else: 28 | dic[node].neighbors.append(dic[neighbor]) 29 | return nodeCopy 30 | # DFS iteratively 31 | def cloneGraph(self, node): 32 | if not node: 33 | return 34 | nodeCopy = Node(node.val, []) 35 | dic = {node: nodeCopy} 36 | stack = [node] 37 | while stack: 38 | node = stack.pop() 39 | for neighbor in node.neighbors: 40 | if neighbor not in dic: 41 | neighborCopy = Node(neighbor.val, []) 42 | dic[neighbor] = neighborCopy 43 | dic[node].neighbors.append(neighborCopy) 44 | stack.append(neighbor) 45 | else: 46 | dic[node].neighbors.append(dic[neighbor]) 47 | return nodeCopy 48 | # DFS recursively 49 | def cloneGraph(self, node): 50 | if not node: 51 | return 52 | nodeCopy = Node(node.val, []) 53 | dic = {node: nodeCopy} 54 | self.dfs(node, dic) 55 | return nodeCopy 56 | 57 | def dfs(self, node, dic): 58 | for neighbor in node.neighbors: 59 | if neighbor not in dic: 60 | neighborCopy = Node(neighbor.val, []) 61 | dic[neighbor] = neighborCopy 62 | dic[node].neighbors.append(neighborCopy) 63 | self.dfs(neighbor, dic) 64 | else: 65 | dic[node].neighbors.append(dic[neighbor]) -------------------------------------------------------------------------------- /Medium/402. Remove K Digits.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/remove-k-digits/ 2 | 3 | class Solution: 4 | def removeKdigits(self, num: str, k: int) -> str: 5 | stack = [] 6 | for digit in num: 7 | while k > 0 and len(stack) > 0 and stack[-1] > digit: 8 | k -= 1 9 | stack.pop() 10 | stack.append(digit) 11 | if k > 0: 12 | stack = stack[:-k] 13 | return "".join(stack).lstrip("0") or "0" 14 | 15 | 16 | ''' 17 | Suppose If we have num 1543, k = 2 18 | Traverse through each digit in num, 19 | if you found, previous digit is greater than the current digit, delete it. 20 | 21 | DIGITS = 1, 5, 6, 3 K = 2 res = "" 22 | current_digit = 1, So, res = 1 23 | current_digit = 5, So, res = 15 24 | current_digit = 6, So, res = 156 25 | current_digit = 3, 26 | Now, previous digit (6) greater than current digit (3). 27 | So, del previous digit. 28 | res = 15 K = 1 29 | Still previous digit(5) is greater than current digit (3) 30 | res = 1, K = 0 31 | Now, K becomes 0 32 | and add remaining digits to res. 33 | res = 13 34 | So, smallest number is 13. 35 | 36 | -> From this, we can understand if last digit of 37 | result greater than the current_digit, then we need to delete it 38 | to get smallest number. 39 | -> By using this point, let's develop 40 | an algorithm to solve this problem. 41 | 42 | Suppose given num = 14329 and k = 2 43 | Do the following steps to get least number:- 44 | 1. Traverse through each digit in num 45 | 2. Now, pop stack 46 | while k > 0 top of the stack is greater than current digit. 47 | this is beacuse if stack has 1 4 48 | then, current digit is 3, then 4 > 3 so, pop 4. 49 | because, the number starting with 13 is smaller than 14. 50 | That's why we need to pop stack while top is 51 | greater than current digit. 52 | 3. After traversing through all the digits, 53 | then stack looks like this = 1 2 9 54 | if k > 0 55 | pop k times 56 | because we need to delete k digits from the number. 57 | 4. Now, create a string variable, 58 | then insert every digit in stack at the beginning. 59 | This is because, 60 | while popping stack 9 will first come out, then 2, and then 1. 61 | So, add digits in reverse. 62 | Here, I am adding digits at starting position. 63 | So, 64 | when 9 is popped, str = 9 65 | when 2 is popped str = 29 66 | when 1 is popped str = 129. 67 | that's how we will get number in reverse order. 68 | 5. Now, Del any leading zeros are in string. 69 | 6. return smallest string. 70 | ''' -------------------------------------------------------------------------------- /Medium/1041. Robot Bounded In Circle.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/robot-bounded-in-circle/ 2 | 3 | class Solution: 4 | def isRobotBounded(self, instructions: str) -> bool: 5 | x,y,dx,dy = 0,0,0,1 6 | for i in instructions: 7 | if i == 'G': 8 | x,y = x+dx,y+dy 9 | if i == 'L': 10 | dx,dy = -dy, dx 11 | if i == 'R': 12 | dx,dy = dy, -dx 13 | return (x,y) == (0,0) or (dx,dy) != (0,1) 14 | 15 | ''' 16 | Let's say the robot starts with facing up. It moves [dx, dy] by executing the instructions once. 17 | If the robot starts with facing 18 | right, it moves [dy, -dx]; 19 | left, it moves [-dy, dx]; 20 | down, it moves [-dx, -dy] 21 | 22 | If the robot faces right (clockwise 90 degree) after executing the instructions once, 23 | the direction sequence of executing the instructions repeatedly will be up -> right -> down -> left -> up 24 | The resulting move is [dx, dy] + [dy, -dx] + [-dx, -dy] + [-dy, dx] = [0, 0] (back to the original starting point) 25 | 26 | All other possible direction sequences: 27 | up -> left -> down -> right -> up. The resulting move is [dx, dy] + [-dy, dx] + [-dx, -dy] + [dy, -dx] = [0, 0] 28 | up -> down -> up. The resulting move is [dx, dy] + [-dx, -dy] = [0, 0] 29 | up -> up. The resulting move is [dx, dy] 30 | ''' 31 | 32 | # https://i.imgur.com/asL4A1g.png (direction photo) 33 | 34 | # Another Solution 35 | class Solution: 36 | def isRobotBounded(self, instructions: str) -> bool: 37 | rotation = 0 38 | position = [0,0] 39 | normal = [0,1] 40 | for i in instructions: 41 | if i == "G": 42 | position[0]+=normal[0] 43 | position[1]+=normal[1] 44 | continue 45 | elif i == "L": 46 | if rotation == 0: 47 | rotation = 270 48 | else: 49 | rotation -=90 50 | else: 51 | if rotation == 270: 52 | rotation = 0 53 | else: 54 | rotation +=90 55 | if rotation == 0: 56 | normal = [0,1] 57 | continue 58 | elif rotation == 90: 59 | normal = [1,0] 60 | continue 61 | elif rotation == 180: 62 | normal = [0,-1] 63 | continue 64 | else: 65 | normal = [-1,0] 66 | continue 67 | # after for loop 68 | if (not position == [0,0]) and normal == [0,1]: 69 | return False 70 | return True -------------------------------------------------------------------------------- /Hard/410. Split Array Largest Sum.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/split-array-largest-sum/ 2 | 3 | class Solution: 4 | def splitArray(self, nums: List[int], m: int) -> int: 5 | # First, understand WHAT we are binary searching over 6 | # we are doing a binary search over the *search space of possible results* 7 | # What is the search space, aka what are all possible results? 8 | # For this, we need to know the minimum and maximum possible result 9 | ## minimum possible result - largest element in array. Since each element needs 10 | # to be part of some subarray, the smallest we can go is by taking the largest element 11 | # in a subarray by itself 12 | ## maximum possible result - sum of all elements in the array since we cannot form 13 | # a subarray larger than the array itself 14 | # Compute minResult and maxResult boundaries 15 | minResult, maxResult = 0,0 16 | for num in nums: 17 | maxResult += num 18 | if num > minResult: 19 | minResult = num 20 | 21 | # now that we have our minResult and maxResult boundaries, we can begin searching within this space 22 | # What are we searching for? 23 | # The smallest value within this space such that we can form m subarrays from nums and none of their sums exceed that value 24 | finalResult = float('inf') 25 | while minResult <= maxResult: 26 | # Start by checking if the value in the middle of the search space satisfies this desired outcome 27 | # If it does, we can discard all values to the right of this in our search space since we have 28 | # something better than those already. We only need to search values to the left to see if 29 | # we can find something better 30 | # If not, we only need to search values higher than mid 31 | mid = (minResult + maxResult) // 2 32 | if self.isPossibility(mid, nums, m): 33 | finalResult = mid 34 | maxResult = mid-1 35 | else: 36 | minResult = mid+1 37 | return finalResult 38 | 39 | # Checks to see if x is a valid possibility given the constraint of m subarrays 40 | def isPossibility(self, x, nums, m): 41 | numSubarrays = 1 42 | subarraySum = 0 43 | for num in nums: 44 | # Greedily try to add this element to the current subarray as long as the subarray's sum doesn't exceed our upper limit x 45 | if (num + subarraySum) <= x: 46 | subarraySum += num 47 | # If sum would be exceeded by adding the current element, we need to start a new subarray and put this element into that 48 | else: 49 | numSubarrays += 1 50 | subarraySum = num 51 | 52 | return (numSubarrays <= m) -------------------------------------------------------------------------------- /Hard/847. Shortest Path Visiting All Nodes.py: -------------------------------------------------------------------------------- 1 | # Problem Statement: https://leetcode.com/problems/shortest-path-visiting-all-nodes/ 2 | 3 | from math import inf 4 | from collections import deque 5 | 6 | class Solution: 7 | def shortestPathLength(self, graph): 8 | # 1 <= graph.length <= 12 9 | # 0 <= graph[i].length < graph.length 10 | 11 | nodeCount = len(graph) 12 | 13 | # NOTE 14 | # We are using BFS here because it's better suited for 'shortest path' 15 | # types of problems. DFS solution is also viable though. 16 | 17 | # Thoughts: 18 | # 1. start at each node, do BFS to try reaching all other nodes. 19 | # 2. Must keep track of visited nodes, else infinite loop may happen. 20 | # 3. But each node may have to be visited multiple times, as described in the problem 21 | # statement. So we cannot be too strict in limiting searches 22 | # 4. We must describe the state during a search, we need: 23 | # - The current node we are on 24 | # - Nodes we have visited (Notice the order does not matter in this case, that's a key) 25 | 26 | # each search is described by (currentNode, visited) 27 | # same search does _not_ have to be repeated, since if re-visited with 28 | # the same state, it would yield the same result. 29 | # NOTE this does not prevent revisiting the same node again, 30 | # it just prevents revisiting it with the same STATE! 31 | 32 | # Since the input size is restricted, we can use a number to encode 33 | # which nodes have been visited -- the i-th bit is on iff node i has been visited 34 | 35 | # conceptually masks[k] indicates that only node k has been visited 36 | masks = [1 << i for i in range(nodeCount)] 37 | # used to check whether all nodes have been visited (11111...111) 38 | allVisited = (1 << nodeCount) - 1 39 | queue = deque([(i, masks[i]) for i in range(nodeCount)]) 40 | steps = 0 41 | 42 | # encoded_visited in visited_states[node] iff 43 | # (node, encoded_visited) has been pushed onto the queue 44 | visited_states = [{masks[i]} for i in range(nodeCount)] 45 | # states in visited_states will never be pushed onto queue again 46 | 47 | while queue: 48 | # number of nodes to be popped off for current steps size 49 | # this avoids having to store steps along with the state 50 | # which consumes both time and memory 51 | count = len(queue) 52 | 53 | while count: 54 | currentNode, visited = queue.popleft() 55 | if visited == allVisited: 56 | return steps 57 | 58 | # start bfs from each neighbor 59 | for nb in graph[currentNode]: 60 | new_visited = visited | masks[nb] 61 | # pre-check here to for efficiency, as each steps increment may results 62 | # in huge # of nodes being added into queue 63 | if new_visited == allVisited: 64 | return steps + 1 65 | if new_visited not in visited_states[nb]: 66 | visited_states[nb].add(new_visited) 67 | queue.append((nb, new_visited)) 68 | 69 | count -= 1 70 | steps += 1 71 | # no path which explores every node 72 | return inf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |



3 | 4 | 5 | [![Solved](https://img.shields.io/badge/Solved-191/2255-337ab7.svg?style=flat)](https://github.com/yashitanamdeo/leetcode) 6 | [![Easy](https://img.shields.io/badge/Easy-80-5cb85c.svg?style=flat)](https://github.com/yashitanamdeo/leetcode/tree/main/Easy) 7 | [![Medium](https://img.shields.io/badge/Medium-56-f0ad4e.svg?style=flat)](https://github.com/yashitanamdeo/leetcode/tree/main/Medium) 8 | [![Hard](https://img.shields.io/badge/Hard-12-d9534f.svg?style=flat)](https://github.com/yashitanamdeo/leetcode/tree/main/Hard) 9 |
10 | [![Languages](https://img.shields.io/badge/Languages-Python-red.svg?style=flat)](https://github.com/yashitanamdeo/leetcode) 11 | [![Author](https://img.shields.io/badge/Author-Yashita%20Namdeo-blue.svg?style=flat)](https://leetcode.com/yashitanamdeo/) 12 | 13 |

14 | [Python](https://github.com/yashitanamdeo/leetcode) full list to be updated...(Readme is in progress) + SQL/Database questions 15 | 16 | | # | Title | Solution | Difficulty | 17 | | --- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------- | 18 | | 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/1.%20Two%20Sum.py) | Easy | 19 | | 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers) | [Python]() | Medium | 20 | | 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/26.%20Remove%20Duplicates%20from%20Sorted%20Array.py) | Easy | 21 | | 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/27.%20Remove%20Element.py) | Easy | 22 | | 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/35.%20Search%20Insert%20Position.py) | Easy | 23 | | 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/53.%20Maximum%20Subarray.py) | Easy | 24 | | 67 | [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/67.%20Add%20Binary.py) | Easy | 25 | | 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | [Python](https://github.com/yashitanamdeo/leetcode/blob/main/Easy/121.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock.py) | Easy | 26 | | | []() | []() | | 27 | | | []() | []() | | 28 | | | []() | []() | | 29 | | | []() | []() | | 30 | | | []() | []() | | 31 | | | []() | []() | | 32 | | | []() | []() | | 33 | | | []() | []() | | 34 | | | []() | []() | | 35 | | | []() | []() | | 36 | | | []() | []() | | 37 | | | []() | []() | | 38 | | | []() | []() | | 39 | | | []() | []() | | 40 | | | []() | []() | | 41 | | | []() | []() | | 42 | | | []() | []() | | 43 | | | []() | []() | | 44 | | | []() | []() | | 45 | | | []() | []() | | 46 | | | []() | []() | | 47 | | | []() | []() | | 48 | | | []() | []() | | 49 | | | []() | []() | | 50 | | | []() | []() | | 51 | | | []() | []() | | 52 | | | []() | []() | | 53 | | | []() | []() | | 54 | | | []() | []() | | 55 | | | []() | []() | | 56 | | | []() | []() | | 57 | 58 |
59 | --------------------------------------------------------------------------------