├── 93.RestoreIPAddresses.py ├── BinaryTreePreorderTraversal.py ├── DeleteColumns2MakeSorted.py ├── MinimumRoundsToCompleteAllTasks.py ├── Problems ├── 0001.-0100. │ ├── 0002._Add_Two_Numbers │ │ ├── AddTwoNumbers0.py │ │ └── AddTwoNumbers1.py │ ├── 0006._Zigzag_Conversion │ │ └── ZigzagConversion0.py │ ├── 0007._Reverse_Integer │ │ ├── ReverseInteger0.py │ │ ├── ReverseInteger1.py │ │ ├── ReverseInteger2.py │ │ └── ReverseInteger3.py │ ├── 0009._Palindrome_Number │ │ ├── PalindromeNumber0.py │ │ ├── PalindromeNumber1.py │ │ └── PalindromeNumber2.py │ ├── 0014._Longest_Common_Prefix │ │ └── LongestCommonPrefix0.py │ ├── 0021._Merge_Two_Sorted_Lists │ │ ├── MergeTwoSortedLists0.py │ │ └── MergeTwoSortedLists1.py │ ├── 0024._Swap_Nodes_in_Pairs │ │ └── SwapNodesInPairs0.py │ ├── 0026._Remove_Duplicates_from_Sorted_Array │ │ ├── RemoveDuplicatesFromSortedArray0.java │ │ ├── RemoveDuplicatesFromSortedArray0.py │ │ ├── RemoveDuplicatesFromSortedArray1.py │ │ └── RemoveDuplicatesFromSortedArray2.py │ ├── 0027._Remove_Element │ │ ├── RemoveElement0.java │ │ ├── RemoveElement0.py │ │ └── RemoveElement1.py │ ├── 0028._Find_the_Index_of_the_First_Occurence_in_a_String │ │ ├── FindtheIndexoftheFirstOccurenceinaString0.java │ │ ├── FindtheIndexoftheFirstOccurenceinaString0.py │ │ ├── FindtheIndexoftheFirstOccurenceinaString1.py │ │ └── FindtheIndexoftheFirstOccurenceinaString2.py │ ├── 0061._Rotate_List │ │ ├── RotateList0.py │ │ ├── RotateList1.py │ │ └── RotateList2.py │ ├── 0066._Plus_One │ │ ├── PlusOne0.py │ │ └── PlusOne1.py │ ├── 0067._Add_Binary │ │ ├── AddBinary0.java │ │ ├── AddBinary0.py │ │ ├── AddBinary1.py │ │ └── AddBinary2.py │ ├── 0070._Climbing_Stairs │ │ ├── ClimbingStairs0.py │ │ └── ClimbingStairs1.py │ ├── 0075._Sort_Colors │ │ ├── SortColors0.py │ │ ├── SortColors1.py │ │ └── SortColors2.py │ └── 0118._Pascal's_Triangle_I │ │ ├── PascalsTriangleI0.py │ │ └── PascalsTriangleI1.py ├── 0101.-0200. │ ├── 0119._Pascal's_Triangle_II │ │ ├── PascalsTriangleII0.java │ │ ├── PascalsTriangleII0.py │ │ ├── PascalsTriangleII1.java │ │ ├── PascalsTriangleII1.py │ │ ├── PascalsTriangleII2.py │ │ └── PascalsTriangleII3.py │ ├── 0125._Valid_Palindrome │ │ ├── ValidPalindrome0.py │ │ ├── ValidPalindrome1.py │ │ └── ValidPalindrome2.py │ ├── 0142._Linked_List_Cycle_II │ │ ├── LinkedListCycleII0.py │ │ └── LinkedListCycleII1.py │ ├── 0160._Intersection_of_Two_Linked_Lists │ │ ├── IntersectionOf2LinkedLists0.py │ │ └── IntersectionOf2LinkedLists1.py │ └── 0189._Rotate_Array │ │ ├── RotateArray0.java │ │ ├── RotateArray0.py │ │ ├── RotateArray1.java │ │ ├── RotateArray1.py │ │ └── RotateArray2.java ├── 0201.-0300. │ ├── 0203._Remove_Linked_List_Elements │ │ ├── RemoveLinkedListElements0.py │ │ └── RemoveLinkedListElements1.py │ ├── 0206._Reverse_Linked_List │ │ ├── ReverseLinkedList0.py │ │ └── ReverseLinkedList1.py │ ├── 0232._Implement_Queue_using_Stacks │ │ ├── ImplementQueueFromStacks0.py │ │ └── ImplementQueueFromStacks1.py │ ├── 0234._Palindrome_Linked_List │ │ ├── PalindromeLinkedList0.py │ │ ├── PalindromeLinkedList1.py │ │ └── PalindromeLinkedList2.py │ ├── 0242._Valid_Anagram │ │ ├── ValidAnagram0.java │ │ ├── ValidAnagram0.py │ │ ├── ValidAnagram1.py │ │ ├── ValidAnagram2.py │ │ └── ValidAnagram3.py │ └── 0290._Word_Pattern │ │ ├── WordPattern0.py │ │ └── WordPattern1.py ├── 0301.-0400. │ ├── 0328._Odd_Even_Linked_List │ │ └── OddEvenLinkedList0.py │ ├── 0344._Reverse_String │ │ ├── ReverseString0.java │ │ ├── ReverseString0.py │ │ ├── ReverseString1.java │ │ ├── ReverseString1.py │ │ ├── ReverseString2.py │ │ ├── ReverseString3.py │ │ ├── ReverseString4.py │ │ ├── ReverseString5.py │ │ ├── ReverseString6.py │ │ └── ReverseString7.py │ └── 350._Intersection_of_Two_Arrays_II │ │ └── IntersectionOfTwoArraysII0.py ├── 0401.-0500. │ ├── 0414._Third_Maximum_Number │ │ ├── ThirdMaximumNumber0.py │ │ └── ThirdMaximumNumber1.py │ └── 0451._Sort_Characters_By_Frequency │ │ ├── SortCharsByFrequency0.py │ │ └── SortCharsByFrequency1.py ├── 0501.-0600. │ ├── 0520._Detect_Capital │ │ ├── DetectCapital0.py │ │ ├── DetectCapital1.py │ │ └── DetectCapital2.py │ └── 0561._Array_Partition │ │ ├── ArrayPartition0.java │ │ ├── ArrayPartition0.py │ │ ├── ArrayPartition1.java │ │ ├── ArrayPartition1.py │ │ ├── ArrayPartition2.java │ │ ├── ArrayPartition2.py │ │ ├── ArrayPartition3.py │ │ ├── ArrayPartition4.py │ │ └── ArrayPartition5.py ├── 0601.-0700. │ ├── 0633._Sum_of_Squared_Numbers │ │ └── SumOfSquaredNumbers0.py │ ├── 0654._Set_Mismatch │ │ ├── SetMismatch0.py │ │ ├── SetMismatch1.py │ │ └── SetMismatch2.py │ └── 700._Search_in_a_Binary_Search_Tree │ │ ├── SearchInBinarySearchTree0.py │ │ ├── SearchInBinarySearchTree1.py │ │ ├── SearchInBinarySearchTree2.py │ │ └── SearchInBinarySearchTree3.py ├── 0701.-0800. │ └── 0747._Largest_Number_At_Least_Twice_of_Others │ │ └── LargestNumberAtLeastTwiceofOthers0.py ├── 0901.-1000. │ ├── 0905._Sort_Array_By_Parity │ │ ├── SortArrayByParity0.java │ │ ├── SortArrayByParity0.py │ │ ├── SortArrayByParity1.java │ │ ├── SortArrayByParity1.py │ │ ├── SortArrayByParity2.py │ │ └── SortArrayByParity3.py │ ├── 0941._Valid_Mountain_Array │ │ ├── ValidMountainArray0.java │ │ ├── ValidMountainArray0.py │ │ ├── ValidMountainArray1.java │ │ ├── ValidMountainArray1.py │ │ ├── ValidMountainArray2.java │ │ └── ValidMountainArray2.py │ ├── 0976._Largest_Perimeter_Triangle │ │ ├── LargestPerimeterTriangle0.java │ │ ├── LargestPerimeterTriangle0.py │ │ └── LargestPerimeterTriangle1.py │ └── 938._Range_Sum_of_BST │ │ └── RangeSumOfBst0.py ├── 1001.-1100. │ ├── 1051._Height_Checker │ │ ├── HeightChecker0.java │ │ ├── HeightChecker0.py │ │ ├── HeightChecker1.java │ │ ├── HeightChecker1.py │ │ ├── HeightChecker2.java │ │ ├── HeightChecker2.py │ │ └── HeightChecker3.java │ └── 1089._Duplicate_Zeros │ │ ├── DuplicateZeros0.java │ │ └── DuplicateZeros0.py ├── 1101.-1200. │ └── 1122._Relative_Sort_Array │ │ └── RelativeSortArray0.py ├── 1201.-1300. │ ├── 1207._Unique_Number_of_Occurences │ │ ├── UniqueNumberOfOccurences0.py │ │ └── UniqueNumberOfOccurences1.py │ └── 1299._Replace_Elements_with_Greatest_Element_on_Right_Side │ │ ├── ReplaceElementsWithGreatestElementOnRightSide0.java │ │ └── ReplaceElementsWithGreatestElementOnRightSide0.py ├── 1301.-1400. │ └── 1346._Check_If_N_and_Its_Double_Exist │ │ ├── CheckIfNandItsDoubleExist0.java │ │ ├── CheckIfNandItsDoubleExist0.py │ │ └── CheckIfNandItsDoubleExist1.py ├── 1601.-1700. │ └── 1636._Sort_Array_by_Increasing_Frequency │ │ ├── SortArrayByIncreasingFrequency0.py │ │ └── SortArrayByIncreasingFrequency1.py ├── 1701.-1800. │ ├── 1704._Determine_if_String_Halves_Are_Alike │ │ ├── AlikeStringHalves0.py │ │ ├── AlikeStringHalves1.py │ │ ├── AlikeStringHalves2.py │ │ └── AlikeStringHalves3.py │ └── 1779._Find_Nearest_Point_That_Has_The_Same_X_or_Y_coordinate │ │ └── FindNearestPointThatHasTheSameXorYcoordinate0.py ├── 1801.-1900. │ └── 1833._Maximum_Ice_Cream_Bars │ │ └── MaximumIceCreamBars0.py ├── 2101.-2200. │ └── 2125._Number_of_Laser_Beams_in_a_Bank │ │ ├── NumberOfLaserBeamsInABank0.py │ │ ├── NumberOfLaserBeamsInABank1.py │ │ └── NumberOfLaserBeamsInABank2.py ├── 2201.-2300. │ ├── 2225._Find_Players_With_Zero_or_One_Losses │ │ └── FindPlayersWithZeroOrOneLosses0.py │ └── 2235._Add_Two_Integers │ │ ├── Add2Integers0.java │ │ ├── Add2Integers0.py │ │ ├── Add2Integers1.py │ │ ├── Add2Integers2.py │ │ ├── Add2Integers3.py │ │ ├── Add2Integers4.py │ │ ├── Add2Integers5.py │ │ ├── Add2Integers6.py │ │ └── Add2Integers7.py ├── 2401.-2500. │ └── 2418._Sort_the_People │ │ ├── SortThePeople0.py │ │ ├── SortThePeople1.py │ │ └── SortThePeople2.py ├── 2601.-2700. │ └── 2610._Convert_an_Array_Into_a_2D_Array_With_Conditions │ │ └── Convert1DArrayTo2DArrayWithConds0.py ├── 2801.-2900. │ └── 2870._Minimum_Number_of_Operations_to_Make_Array_Empty │ │ ├── MinNumberOfOperationsToMakeArrayEmpty0.py │ │ └── MinNumberOfOperationsToMakeArrayEmpty1.py └── 2901.-3000. │ └── 2966._Divide_Array_Into_Arrays_With_Max_Difference │ └── DivideArrayIntoArraysWithMaxDiff0.py ├── README.md └── echo.sh /93.RestoreIPAddresses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreIpAddresses(self, s: str) -> List[str]: 3 | n = len(s); 4 | if n < 4 or n > 12: 5 | return [] 6 | elif n == 4: 7 | return ['.'.join(list(s))] 8 | elif n == 12: 9 | lst = [] 10 | for i in range(0,12,12//4): 11 | if s[i] != '0': 12 | if int(s[i:i+3]) <= 255: 13 | lst += [s[i:i+3]] 14 | else: 15 | break 16 | return ['.'.join([num for num in lst])] if len(lst) == 4 else [] 17 | else: # 5,6,7,8,9,10,11 18 | lst1 = [] 19 | x = lambda s: s == str(int(s)) and int(s) <= 255 20 | for i in range(1,n): 21 | for j in range(i+1,n): 22 | for k in range(j+1,n): 23 | a, b, c, d = s[:i], s[i:j], s[j:k], s[k:] 24 | if x(a) and x(b) and x(c) and x(d): 25 | lst1.append(a + '.' + b + '.' + c + '.' + d) 26 | return lst1 27 | -------------------------------------------------------------------------------- /BinaryTreePreorderTraversal.py: -------------------------------------------------------------------------------- 1 | # 144. Binary Tree Preorder Traversal 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, val=0, left=None, right=None): 5 | # self.val = val 6 | # self.left = left 7 | # self.right = right 8 | class Solution: 9 | def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 10 | return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) if (root) else [] 11 | -------------------------------------------------------------------------------- /DeleteColumns2MakeSorted.py: -------------------------------------------------------------------------------- 1 | # 944. Delete Columns to Make Sorted 2 | class Solution: 3 | def minDeletionSize(self, strs: List[str]) -> int: 4 | if len(strs[0]) == 0: 5 | return 0 6 | elif len(strs[0]) == 1: 7 | for i in range(len(strs)-1): 8 | if strs[i] > strs[i+1]: 9 | return 1 10 | else: 11 | return 0 12 | else: 13 | elem = lambda x, i, j: x[i][j] 14 | lst2 = [] 15 | for k in range(len(strs[0])): 16 | lst = [] 17 | for j in range(len(strs)): 18 | lst.append(elem(strs,j,k)) 19 | lst2 += [lst] 20 | things = map(''.join,lst2) 21 | count = 0 22 | for chars in things: 23 | chars_sort = ''.join(sorted(chars)) 24 | if chars != chars_sort: 25 | count += 1 26 | return count 27 | -------------------------------------------------------------------------------- /MinimumRoundsToCompleteAllTasks.py: -------------------------------------------------------------------------------- 1 | # 2244. Minimum Rounds to Complete All Tasks 2 | def minimumRounds(self, tasks: List[int]) -> int: 3 | def twosThrees(n: int): 4 | # determines the numbers of 2s & 3s that adds up to make a number 5 | # n = 2*a + 3*b 6 | a, b = 0, 0 7 | if n % 3 == 0: # multiple of 3 8 | b = n //3 9 | else: # not a multiple of 3 10 | b = n // 3 11 | a = 0 12 | if n % 3 == 1: 13 | a += 2 14 | b -= 1 15 | elif n % 3 == 2: 16 | a += 1 17 | return a+b if n != 1 else 0 18 | frequencies = Counter(tasks) 19 | rounds = 0 20 | for freq in frequencies.values(): 21 | if freq == 1: 22 | return -1 23 | else: 24 | rounds += twosThrees(freq) 25 | return rounds 26 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0002._Add_Two_Numbers/AddTwoNumbers0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 2. Add Two Numbers 3 | 4 | # Definition for singly-linked list. 5 | class ListNode(object): 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution: 11 | # def List2Num(self, l: list) -> int: 12 | # number = 0 13 | # for i in range(0, len(l), +1): 14 | # number += (10**i)*l[i] 15 | # return number 16 | 17 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 18 | # Edge case: Both linked lists have a single node with value of 0 19 | if (l1.val == 0 and l2.val == 0 and l1.next is None and l2.next is None): 20 | return l1 21 | else: 22 | curr1, curr2 = l1, l2 23 | num1 = [] 24 | while (curr1): 25 | num1 = [curr1.val] + num1 # Hold linked list 1 node values in reverse 26 | curr1 = curr1.next 27 | 28 | num2 = [] 29 | while (curr2): 30 | num2 = [curr2.val] + num2 # Hold linked list 2 node values in reverse 31 | curr2 = curr2.next 32 | 33 | n1 = int(''.join(map(str, num1))) # n1 = self.reverseList2Num(num1) 34 | n2 = int(''.join(map(str, num2))) # n2 = self.reverseList2Num(num2) 35 | n = n1 + n2 36 | final_list = [] 37 | 38 | while (n): 39 | final_list.append(ListNode(n % 10)) 40 | n //= 10 41 | 42 | for i in range(len(final_list)-1): 43 | final_list[i].next = final_list[i+1] 44 | 45 | return final_list[0] 46 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0002._Add_Two_Numbers/AddTwoNumbers1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | # Definition for singly-linked list. 4 | class ListNode(object): 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | class Solution: 10 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 11 | # Edge case: Both linked lists have a single node with value of 0 12 | if (l1.val == 0 and l2.val == 0 and l1.next is None and l2.next is None): 13 | return l1 14 | else: 15 | curr1, curr2 = l1, l2 16 | number1, i = 0, 0 17 | 18 | while (curr1): 19 | number1 += (curr1.val)*(10**i) # Convert linked list 1 node values to an integer 20 | i += 1 21 | curr1 = curr1.next 22 | 23 | number2, j = 0, 0 24 | while (curr2): 25 | number2 += (curr2.val)*(10**j) # Convert linked list 2 node values to an integer 26 | j += 1 27 | curr2 = curr2.next 28 | 29 | number = number1 + number2 30 | l3 = list() 31 | 32 | while (number): 33 | l3 += [ListNode(number % 10)] # Create a Node object with the last digit 34 | number //= 10 # Remove the last digit 35 | 36 | for i in range(len(l3)-1): 37 | l3[i].next = l3[i+1] 38 | 39 | head_node = l3.pop(0) # Get the head of the new singly linked list 40 | 41 | return head_node 42 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0006._Zigzag_Conversion/ZigzagConversion0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | # simulate and add each character to the corresponding row 5 | # go down -> reach bottom -> go up -> reach top -> go down ... 6 | def convert(self, s: str, n: int) -> str: 7 | # edge case 8 | if (n == 1): return s 9 | rows = ['' for _ in range(n)] 10 | # j is the index to track which rows a character should be added to 11 | # d is the direction: -1 means go up, 1 means go down 12 | j, d = 0, 1 13 | for i in range(len(s)): 14 | # add the current character to corresponding row 15 | rows[j] += s[i] 16 | # if it reaches to the last row, we need to go up 17 | if j == n - 1: d = -1 18 | # if it reaches to the first row, we need to go down 19 | elif j == 0: d = 1 20 | # move j pointer 21 | j += d; 22 | # rows would look like below in the first example 23 | # ['PAHN', 'APLSIIG', 'YIR'] 24 | # we use join to build the final answer 25 | return ''.join(rows) 26 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0007._Reverse_Integer/ReverseInteger0.py: -------------------------------------------------------------------------------- 1 | # 7. Reverse Integer 2 | def reverse(self, x: int) -> int: 3 | if (-9 <= x <= 9): 4 | return x 5 | 6 | str_int = str(x) 7 | if (str_int[0] == '-'): 8 | minus = '-' 9 | str_int = str_int[1:][::-1] 10 | while (str_int[0] == '0'): 11 | str_int = str_int[1:] 12 | str_int = minus + str_int 13 | else: 14 | str_int = str_int[::-1] 15 | while (str_int[0] == '0'): 16 | str_int = str_int[1:] 17 | ans = int(str_int) if (-2**31 <= int(str_int) <= 2**31-1) else 0 18 | return ans 19 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0007._Reverse_Integer/ReverseInteger1.py: -------------------------------------------------------------------------------- 1 | # 7. Reverse Integer 2 | class Solution: 3 | def reverse(self, x: int) -> int: 4 | def cal(x: int): 5 | x = str(x) 6 | if (x[0] == '-'): 7 | k = x[1:(len(x)+1)] 8 | return 0 - int(k[::-1]) 9 | else: 10 | return int(x[::-1]) 11 | 12 | def cond(x): # Check for Overflow 13 | return (x > -2**31 and x < 2**31-1) 14 | 15 | if cond(x): 16 | c = cal(x) 17 | if cond(c): 18 | return c 19 | else: 20 | return 0 21 | else: 22 | return 0 23 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0007._Reverse_Integer/ReverseInteger2.py: -------------------------------------------------------------------------------- 1 | # 7. Reverse Integer 2 | class Solution: 3 | def reverse(self, x: int) -> int: 4 | sign = [1, -1][x < 0] # if x = 0: sign = -1 5 | rev = sign * int(''.join(reversed(str(abs(x))))) 6 | return [0, rev][-2**31 <= rev <= 2**31-1] 7 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0007._Reverse_Integer/ReverseInteger3.py: -------------------------------------------------------------------------------- 1 | # 7. Reverse Integer 2 | import math 3 | 4 | class Solution: 5 | def reverse(self, x: int) -> int: 6 | MIN_INT, MAX_INT = -2**31, 2**31-1 7 | reverse = 0 8 | 9 | while (x != 0): 10 | digit = [(x % -10), x % 10][x > 0] # (x % 10) if (x > 10) else (x % -10) 11 | reverse = reverse * 10 + digit 12 | x = math.trunc(x / 10) # x //= 10 13 | 14 | return 0 if (reverse.bit_length() > 31) else reverse 15 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0009._Palindrome_Number/PalindromeNumber0.py: -------------------------------------------------------------------------------- 1 | # 9. Palindrome Number 2 | class Solution: 3 | def isPalindrome(self, x: int) -> bool: 4 | return str(x) == str(x)[::-1] 5 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0009._Palindrome_Number/PalindromeNumber1.py: -------------------------------------------------------------------------------- 1 | # 9. Palindrome Number 2 | class Solution: 3 | def isPalindrome(self, x: int) -> bool: 4 | # Reverse the input number 5 | if (x < 0): return False 6 | else: # x > 0 7 | # Reverse the input number 8 | original_num, reverse_num = x, 0 9 | 10 | while (x): 11 | digit = x % 10 # Get last digit 12 | reverse_num = reverse_num*10 + digit # Shift by 1 order of magnitude 13 | x //= 10 # Go to next higher place value digit 14 | return (original_num == reverse_num) 15 | 16 | ''' 17 | def signum(self, x: int) -> int: 18 | """ 19 | Return the sign of x 20 | """ 21 | return (-1 if (x < 0) else (0 if (x == 0) else 1)) 22 | ''' 23 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0009._Palindrome_Number/PalindromeNumber2.py: -------------------------------------------------------------------------------- 1 | # 9. Palindrome Number 2 | class Solution: 3 | def isPalindrome(self, x: int) -> bool: 4 | return str(x) == ''.join(reversed(str(x))) 5 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0014._Longest_Common_Prefix/LongestCommonPrefix0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def longestCommonPrefix(self, strs: list) -> str: 4 | common_str = ""; m = len(strs); lst_common = [] 5 | # If there's only one element in the list, return that entry 6 | if m == 1: 7 | return strs[0] 8 | 9 | # For at least 2 elements 10 | for i in range(m-1): 11 | # For more than 1 element (compare 2 strings) 12 | common_str = str() 13 | smaller = min(len(strs[i]), len(strs[i+1])) 14 | 15 | # Check for the common string between i-th & j-th elements 16 | for k in range(smaller): 17 | if strs[i][k] == strs[i+1][k]: 18 | common_str += str(strs[i][k]) # or str(strs[i+1][k]) 19 | else: # if there's an element mismatch, exit loop 20 | break 21 | # Append this common string to a list of strings of adjacent elements 22 | lst_common.append(common_str) 23 | return min(lst_common) 24 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0021._Merge_Two_Sorted_Lists/MergeTwoSortedLists0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 21. Merge Two Sorted Lists 3 | 4 | # Definition for singly-linked list. 5 | class ListNode: 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution(object): 11 | def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode: 12 | if (not list1 and not list2): 13 | return None 14 | elif (not list1): 15 | return list2 16 | elif (not list2): 17 | return list1 18 | else: 19 | l1, l2 = [], [] 20 | curr1, curr2 = list1, list2 21 | 22 | while (curr1): 23 | l1 += [curr1.val] 24 | curr1 = curr1.next 25 | 26 | while (curr2): 27 | l2 += [curr2.val] 28 | curr2 = curr2.next 29 | 30 | _list_ = [*map(ListNode, sorted(l1 + l2))] 31 | 32 | for i in range(0, len(_list_)-1): 33 | _list_[i].next = _list_[i+1] 34 | 35 | return _list_[0] 36 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0021._Merge_Two_Sorted_Lists/MergeTwoSortedLists1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | sys.setrecursionlimit(100) 5 | 6 | # Definition for singly-linked list. 7 | class ListNode: 8 | def __init__(self, val=0, next=None): 9 | self.val = val 10 | self.next = next 11 | 12 | class Solution: 13 | def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode: 14 | if (list1 is None and list2 is None): return None 15 | elif (list1 is None): return list2 16 | elif (list2 is None): return list1 17 | else: 18 | if (list2.val > list1.val): 19 | return ListNode(list1.val, self.mergeTwoLists(list1.next, list2)) 20 | else: # (list1.val > list2.val) 21 | return ListNode(list2.val, self.mergeTwoLists(list2.next, list1)) 22 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0024._Swap_Nodes_in_Pairs/SwapNodesInPairs0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 24. Swap Nodes in Pairs 3 | 4 | # Definition for singly-linked list. 5 | class ListNode: 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution: 11 | def swapPairs(self, head: ListNode) -> ListNode: 12 | # Iterative approach 13 | curr = head 14 | length = 0 15 | l = [] 16 | 17 | while (curr): 18 | l += [curr.val] 19 | curr = curr.next 20 | length += 1 21 | 22 | if (not head or length == 0): # empty linked list 23 | return head 24 | elif (length == 1): # 1-node in linked list 25 | return head 26 | else: # 2-nodes or more in linked list 27 | if (length % 2 == 0): # even number of nodes 28 | for i in range(0, length, 2): 29 | l[i], l[i+1] = l[i+1], l[i] # swap 30 | 31 | else: # odd number of nodes 32 | for j in range(0, length-1, 2): 33 | l[j], l[j+1] = l[j+1], l[j] # swap 34 | 35 | nodes = list(map(ListNode, l)) 36 | 37 | for k in range(length-1): 38 | nodes[k].next = nodes[k+1] 39 | 40 | head_node = nodes.pop(0) 41 | 42 | return head_node 43 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0026._Remove_Duplicates_from_Sorted_Array/RemoveDuplicatesFromSortedArray0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public int removeDuplicates(int[] nums) { 4 | int i, len = nums.length; 5 | 6 | for (i = 0; i < len-1; ++i) { 7 | if (nums[i] == nums[i+1]) { // Check that no 2 elements are equal; if 8 | // they're then there's a duplicate 9 | int j = i; 10 | while (j < len-1) { 11 | nums[j] = nums[j+1]; 12 | ++j; 13 | } 14 | len--; i--; // decrease the overall length 15 | } 16 | } 17 | return len; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0026._Remove_Duplicates_from_Sorted_Array/RemoveDuplicatesFromSortedArray0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def removeDuplicates(self, nums: List[int]) -> int: 5 | i = 0 6 | while (0 <= i < len(nums)): 7 | if nums.count(nums[i]) > 1: 8 | nums.remove(nums[i]) 9 | i -= 1 10 | i += 1 11 | return len(nums) 12 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0026._Remove_Duplicates_from_Sorted_Array/RemoveDuplicatesFromSortedArray1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def removeDuplicates(self, nums: List[int]) -> int: 4 | length = len(nums) 5 | i = 0 6 | while (i < length-1): 7 | if (nums[i] == nums[i+1]): # Check that no 2 elements are equal; 8 | # if they're then there's a duplicate 9 | j = i; 10 | while (j < length-1): 11 | nums[j] = nums[j+1] 12 | j += 1 13 | length -= 1 # decrease the overall length 14 | i -= 1 15 | i += 1 16 | return length 17 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0026._Remove_Duplicates_from_Sorted_Array/RemoveDuplicatesFromSortedArray2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution(object): 3 | def removeDuplicates(self, nums): 4 | i = 0 5 | j = 1 6 | while i<= j and j < len(nums): 7 | if nums[i] != nums[j]: 8 | nums[i+1] = nums[j] 9 | i += 1 10 | j += 1 11 | return i + 1 12 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0027._Remove_Element/RemoveElement0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public int removeElement(int[] nums, int val) { 5 | int len, i; 6 | len = nums.length; 7 | i = 0; 8 | 9 | while (0 <= i && i < len) { 10 | if (nums[i] == val) { 11 | for (int j = i; j < len-1; j++) { 12 | nums[j] = nums[j+1]; // loop to move elements left 13 | } 14 | len -= 1; 15 | i -= 1; 16 | } 17 | i += 1; 18 | } 19 | return len; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0027._Remove_Element/RemoveElement0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def removeElement(self, nums: List[int], val: int) -> int: 4 | while val in nums: 5 | nums.remove(val) 6 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0027._Remove_Element/RemoveElement1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def removeElement(self, nums: list, val: int) -> int: 5 | i = 0; length = len(nums) 6 | 7 | while (0 <= i < length): 8 | if (nums[i] == val): 9 | for j in range(i, length-1): 10 | nums[j] = nums[j+1] 11 | length -= 1 12 | i -= 1 # In case of duplicate 13 | i += 1 14 | return length 15 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0028._Find_the_Index_of_the_First_Occurence_in_a_String/FindtheIndexoftheFirstOccurenceinaString0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public int strStr(String haystack, String needle) { 5 | // Variable to hold the length of the needle 6 | int m = needle.length(); 7 | int[] ind = new int[]{-1}; 8 | int i = 0; 9 | 10 | while (i < haystack.length()-m+1) { 11 | if ((haystack.substring(i,i+m)).equals(needle)) { 12 | ind[0] = i; 13 | break; 14 | } 15 | i += 1; 16 | } 17 | 18 | if (ind[0] >= 0) { 19 | return ind[0]; 20 | } else { 21 | return ind[0]; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0028._Find_the_Index_of_the_First_Occurence_in_a_String/FindtheIndexoftheFirstOccurenceinaString0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | # Convert each to a list 4 | # lst1 = list(haystack) 5 | # lst2 = list(needle) 6 | 7 | # Create a variable to hold the length of the needle word 8 | n = len(needle) 9 | lst = [] 10 | i = 0 11 | if needle in haystack: 12 | while i < len(haystack)- n and lst == []: 13 | if haystack[i:i+n] == needle: 14 | lst.append(i) 15 | break 16 | i += 1 17 | return i 18 | else: 19 | return -1 20 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0028._Find_the_Index_of_the_First_Occurence_in_a_String/FindtheIndexoftheFirstOccurenceinaString1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def strStr(self, haystack: str, needle: str) -> int: 5 | return haystack.find(needle) 6 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0028._Find_the_Index_of_the_First_Occurence_in_a_String/FindtheIndexoftheFirstOccurenceinaString2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def strStr(self, haystack: str, needle: str) -> int: 5 | n = len(needle) 6 | 7 | ind = [i for i in range(len(haystack)-n+1) if haystack[i:i+n] == needle] 8 | 9 | return ind[0] if ind != [] else -1 10 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0061._Rotate_List/RotateList0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 61. Rotate List 3 | 4 | # Definition for singly-linked list. 5 | class ListNode: 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution: 11 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 12 | if (not head): # empty linked list 13 | return None 14 | elif (head and k == 0): # No rotations! 15 | return head 16 | else: 17 | curr = head 18 | length = 0 19 | node_vals = list() 20 | 21 | while (curr): 22 | node_vals.append(ListNode(curr.val)) 23 | length += 1 24 | curr = curr.next 25 | 26 | k %= length # get smallest amount of rotations for same results 27 | 28 | new = [] 29 | for i in range(k): 30 | new = [node_vals.pop(-1)] + new 31 | 32 | new += node_vals 33 | for j in range(length-1): 34 | new[j].next = new[j+1] 35 | 36 | return new[0] 37 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0061._Rotate_List/RotateList1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for singly-linked list. 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | class Solution: 10 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 11 | if (head is None): # empty linked list 12 | return head 13 | elif (head is not None and k == 0): # No rotations! 14 | return head 15 | else: 16 | size = 0 17 | node_data = [] 18 | 19 | while (head): 20 | node_data += [head.val] 21 | head = head.next 22 | size += 1 23 | 24 | k = pow(k, 1, size) # k (mod size) 25 | 26 | post_nodes = node_data[0:size-k] 27 | pre_nodes = node_data[size-k:] 28 | rotated_nodes_data = pre_nodes + post_nodes 29 | rotated_nodes = [*map(ListNode, rotated_nodes_data)] 30 | 31 | for l in range(0, size-1, 1): 32 | rotated_nodes[l].next = rotated_nodes[l+1] 33 | 34 | rotated_head = rotated_nodes.pop(-size) 35 | return rotated_head 36 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0061._Rotate_List/RotateList2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 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: 10 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 11 | if (not head or k == 0): 12 | return head 13 | 14 | # Get number of nodes in the linked list 15 | curr1 = head 16 | length = 0 17 | while (curr1): 18 | curr1 = curr1.next 19 | length += 1 20 | 21 | if (k == length): # rotate back to original 22 | return head 23 | 24 | k %= length 25 | if (k == 0): # No rotation 26 | return head 27 | 28 | # (0 < k < length) 29 | i = 0 # node position 30 | while (i < length-k-1): 31 | lead = lead.next 32 | i += 1 33 | 34 | lead2 = lead.next 35 | lead.next = None 36 | 37 | if (length == 1): return head # 1 node in the linked list 38 | 39 | tail = lead2 40 | while (tail.next): 41 | tail = tail.next 42 | 43 | tail.next = head 44 | return lead2 45 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0066._Plus_One/PlusOne0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | return [*map(int,list(str(int(''.join([*map(str,digits)])) + 1)))] 4 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0066._Plus_One/PlusOne1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | # Store the length of the array 4 | n = len(digits) 5 | # Get the integer from the array 6 | numFromDigits = 0 7 | for i in range(n-1,-1,-1): 8 | numFromDigits += digits[i]*(10**(n-i-1)) 9 | # Increment this integer by 1 (or You could have also declared numFromDigits to be 1 & skip this step) 10 | numFromDigits += 1 11 | # Initialize array to hold each new digit 12 | new_digits = [] 13 | 14 | while (numFromDigits): 15 | n = numFromDigits % 10 16 | new_digits = [n] + new_digits 17 | numFromDigits //= 10 18 | return new_digits 19 | 20 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0067._Add_Binary/AddBinary0.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String addBinary(String a, String b) { 3 | int m = a.length(); int n = b.length(); 4 | 5 | // If a or b is empty 6 | if (m == 0) 7 | return b; 8 | if (n == 0) 9 | return a; 10 | // String to hold sum 11 | String s = ""; 12 | int carry = 0; 13 | 14 | // Initialize indexes 15 | int i = m-1; 16 | int j = n-1; 17 | 18 | // Get char arrays 19 | char[] a_c = a.toCharArray(); 20 | char[] b_c = b.toCharArray(); 21 | 22 | while (i >= 0 || j >= 0 || carry > 0) { 23 | if (i >= 0) { 24 | carry += Integer.parseInt("" + a_c[i]); 25 | i -= 1; 26 | } 27 | if (j >= 0) { 28 | carry += Integer.parseInt("" + b_c[j]); 29 | j -= 1; 30 | } 31 | s = "" + carry%2 + "" + s; 32 | carry /= 2; 33 | } 34 | return s; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0067._Add_Binary/AddBinary0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | a, b = [*map(self.bin2Decimal, [a, b])] 4 | c = a + b; bits = "" 5 | if c == 0: 6 | return str(c) 7 | while c: 8 | bits += str(c % 2) 9 | c //= 2 10 | return bits[::-1] 11 | 12 | def bin2Decimal(self, x: str) -> int: 13 | num_x = 0 14 | for i in range(len(x)): 15 | num_x += int(x[-(i+1)])*(2**i) 16 | return num_x 17 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0067._Add_Binary/AddBinary1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | a, b = [*map(self.bin2Decimal, [a, b])] 4 | c = a + b; bits = [] 5 | if c == 0: 6 | return str(c) 7 | while c: 8 | bits += [str(c % 2)] 9 | c >>= 1 10 | return ''.join(bits[::-1]) 11 | 12 | def bin2Decimal(self, x: str) -> int: 13 | num_x = 0 14 | for i in range(len(x)): 15 | num_x += int(x[-(i+1)])*(2**i) 16 | return num_x 17 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0067._Add_Binary/AddBinary2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | return bin(int(a, 2) + int(b, 2))[2:] 4 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0070._Climbing_Stairs/ClimbingStairs0.py: -------------------------------------------------------------------------------- 1 | # 70. Climbing Stairs 2 | 3 | class Solution: 4 | def climbStairs(self, n: int) -> int: 5 | if (n == 1): return n 6 | else: 7 | a, b = 1, 2 # n = 1 or n = 2 steps 8 | lst = [0]*n 9 | lst[0] = a; lst[1] = b 10 | 11 | for i in range(len(lst)-2): 12 | lst[i+2] = lst[i] + lst[i+1] 13 | return lst[n-1] 14 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0070._Climbing_Stairs/ClimbingStairs1.py: -------------------------------------------------------------------------------- 1 | # 70. Climbing Stairs 2 | 3 | class Solution: 4 | def climbStairs(self, n: int) -> int: 5 | current_step, next_step = 1, 2 6 | for i in range(2, n+1): 7 | next_step, current_step = next_step + current_step, next_step 8 | return current_step 9 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0075._Sort_Colors/SortColors0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 75. Sort Colors 3 | 4 | class Solution: 5 | def sortColors(self, nums: int) -> None: 6 | n = len(nums) 7 | for i in range(n): 8 | for j in range(i + 1, n): 9 | if (nums[i] > nums[j]): 10 | # Swap nums[i] and nums[j] 11 | nums[i], nums[j] = nums[j], nums[i] 12 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0075._Sort_Colors/SortColors1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def sortColors(self, nums: list) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | nums.sort() 9 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0075._Sort_Colors/SortColors2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def sortColors(self, nums: list) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | nums.sort(reverse = False) 9 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0118._Pascal's_Triangle_I/PascalsTriangleI0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def generate(self, numRows: int) -> List[List[int]]: 4 | lst2 = [] 5 | for i in range(numRows): 6 | lst = [] 7 | for j in range(i+1): 8 | lst.append(math.comb(i,j)) 9 | lst2.append(lst) 10 | return lst2 11 | -------------------------------------------------------------------------------- /Problems/0001.-0100./0118._Pascal's_Triangle_I/PascalsTriangleI1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def generate(self, numRows: int) -> List[List[int]]: 4 | triangle = [[1], [1,1]] 5 | # Pascal's Triangle for n <= 2 6 | if (numRows <= 2): 7 | return triangle[:numRows] 8 | else: 9 | # Iterate through each i-th row, considering the fact that we already have [[1],[1,1]] 10 | for i in range(2,numRows): 11 | row = [1] # j = 0 12 | # may need to iterate through each j-th element in the i-th row 13 | for j in range(1,i): # numRows also represenets the number of elements in a row 14 | row += [triangle[i-1][j-1] + triangle[i-1][j]] 15 | triangle.append(row + [1]) # Put 1 at the end 16 | return triangle 17 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0119._Pascal's_Triangle_II/PascalsTriangleII0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public List getRow(int rowIndex) { 5 | List> arr = new ArrayList>(); 6 | ArrayList s0 = new ArrayList<>(); 7 | s0.add(1); 8 | arr.add(s0); 9 | 10 | ArrayList s1 = new ArrayList<>(); 11 | s1.add(1); 12 | s1.add(1); 13 | arr.add(s1); 14 | 15 | for (int i = 2; i < rowIndex+1; i++) { 16 | ArrayList si = new ArrayList(); 17 | si.add(1); // [1, ...] 18 | int len = arr.get(i-1).size(); 19 | for (int j = 1; j < len; j++) { 20 | int num = arr.get(i-1).get(j-1) + arr.get(i-1).get(j); 21 | si.add(num); 22 | } 23 | si.add(1); // [..., 1] 24 | arr.add(si); 25 | } 26 | return arr.get(rowIndex); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0119._Pascal's_Triangle_II/PascalsTriangleII0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def getRow(self, rowIndex: int) -> List[int]: 5 | if (rowIndex < 1): 6 | return [1]*(rowIndex+1) 7 | else: 8 | lst = [[1]] 9 | for i in range(1,rowIndex+1): 10 | lst2 = [1] + [0 for _ in range(1,i)] + [1] 11 | for j in range(1,len(lst)): 12 | lst2[j] = lst[i-1][j-1] + lst[i-1][j] 13 | lst += [lst2] 14 | return lst[rowIndex] 15 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0119._Pascal's_Triangle_II/PascalsTriangleII1.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | import java.lang.Math; 3 | 4 | class Solution { 5 | public List getRow(int rowIndex) { 6 | // Create a new array for each Binomial coefficient 7 | ArrayList coeffs = new ArrayList(); 8 | 9 | for (int i = 0; i <= rowIndex; i++) { 10 | coeffs.add(combination(rowIndex, i)); 11 | } 12 | return coeffs; 13 | } 14 | 15 | public static int combination(int n, int r) { 16 | // Compute nCr = n!/[r!(n-r)!] 17 | return (int) Math.round(factorial(n) /(factorial(r) * factorial(n-r))); 18 | } 19 | 20 | public static double factorial(int z) { 21 | // Computes z! = z x (z-1) x (z-2) x ... x 2 x 1 22 | double fac = 1; 23 | for (double i = 1; i <= z; i++) 24 | fac *= i; 25 | return fac; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0119._Pascal's_Triangle_II/PascalsTriangleII1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import math; 3 | 4 | class Solution: 5 | def getRow(self, rowIndex: int) -> list: 6 | lst2 = [] 7 | for i in range(rowIndex+1): 8 | lst = [] 9 | for j in range(i+1): 10 | lst.append(math.comb(i,j)) 11 | lst2 += [lst] 12 | return lst2[rowIndex] 13 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0119._Pascal's_Triangle_II/PascalsTriangleII2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | from math import comb as nCr; 3 | 4 | class Solution: 5 | def getRow(self, rowIndex: int) -> list: 6 | return [[nCr(i,j) for j in range(rowIndex+1)] for i in range(rowIndex+1)][rowIndex] 7 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0119._Pascal's_Triangle_II/PascalsTriangleII3.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution(object): 4 | def getRow(self, rowIndex: int) -> list[int]: 5 | if (rowIndex == 0): # Base Case 1 6 | return list((1,)) 7 | elif (rowIndex == 1): # Base Case 2 8 | return list((1,1,)) 9 | else: # Recursive 10 | current_row = [self.getRow(0)[0]] # i.e. l = [1] 11 | previous_row = self.getRow(rowIndex-1) 12 | 13 | for i in range(rowIndex-1): 14 | current_row.append(previous_row[i] + previous_row[i+1]) 15 | current_row += [1] 16 | 17 | return (current_row) 18 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0125._Valid_Palindrome/ValidPalindrome0.py: -------------------------------------------------------------------------------- 1 | # 125. Valid Palindrome 2 | class Solution: 3 | def isPalindrome(self, s: str) -> bool: 4 | s = s.strip() 5 | lst = [] 6 | for char in s: 7 | if char.isalnum(): 8 | lst += [char.lower()] 9 | word = ''.join(lst) 10 | return word == word[::-1] 11 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0125._Valid_Palindrome/ValidPalindrome1.py: -------------------------------------------------------------------------------- 1 | # 125. Valid Palindrome 2 | import re 3 | 4 | class Solution(object): 5 | def isPalindrome(self, s): 6 | new_s = re.sub(r"[^a-zA-Z0-9\\s+]", "", s).lower() 7 | return new_s == new_s[::-1] 8 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0125._Valid_Palindrome/ValidPalindrome2.py: -------------------------------------------------------------------------------- 1 | # 125. Valid Palindrome 2 | class Solution: 3 | def isPalindrome(self, s: str) -> bool: 4 | return ("".join([char.lower() for char in s.strip() if char.isalnum()]) == "".join([char.lower() for char in s.strip() if char.isalnum()])[::-1]) 5 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0142._Linked_List_Cycle_II/LinkedListCycleII0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 142. Linked List Cycle II 3 | 4 | # Definition for singly-linked list. 5 | class ListNode(object): 6 | def __init__(self, x): 7 | self.val = x 8 | self.next = None 9 | 10 | class Solution: 11 | def detectCycle(self, head: ListNode) -> ListNode: 12 | if (not head): # Empty Linked List has no cycle 13 | return None 14 | else: 15 | linkedListNodes = list() 16 | 17 | while (head): 18 | if (head not in linkedListNodes): 19 | linkedListNodes.append(head) 20 | else: 21 | break 22 | head = head.next 23 | 24 | ans = [node for node in linkedListNodes if (node == head)] 25 | return ans[0] if (len(ans) != 0) else None 26 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0142._Linked_List_Cycle_II/LinkedListCycleII1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for singly-linked list. 3 | class ListNode: 4 | def __init__(self, x): 5 | self.val = x 6 | self.next = None 7 | 8 | class Solution: 9 | def detectCycle(self, head: ListNode) -> ListNode: 10 | if (not head): # Empty Linked List has no cycle 11 | return None 12 | else: 13 | nodes = set() # More efficient than using a list 14 | 15 | while (head is not None): 16 | if (head in nodes): 17 | return head 18 | nodes.add(head) 19 | head = head.next 20 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0160._Intersection_of_Two_Linked_Lists/IntersectionOf2LinkedLists0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 3 | # 160. Intersection of Two Linked Lists 4 | # 5 | # Definition for singly-linked list. 6 | class ListNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.next = None 10 | 11 | class Solution: 12 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 13 | currA, currB = headA, headB 14 | sizeA, sizeB = 0, 0 15 | 16 | while (currA): 17 | sizeA += 1 18 | currA = currA.next 19 | 20 | while (currB): 21 | sizeB += 1 22 | currB = currB.next 23 | 24 | if (sizeA > sizeB): # LinkedListA has (sizeA - sizeB) more elements than LinkedListB 25 | for _ in range(sizeA - sizeB): 26 | headA = headA.next 27 | 28 | while (headA and headB): 29 | if (headA is headB and headA.val == headB.val): 30 | return headA 31 | headA = headA.next 32 | headB = headB.next 33 | 34 | elif (sizeA < sizeB): # LinkedListB has (sizeB - sizeA) more elements than LinkedListA 35 | for _ in range(sizeB - sizeA): 36 | headB = headB.next 37 | 38 | while (headA and headB): 39 | if (headA is headB and headA.val == headB.val): 40 | return headB 41 | headA = headA.next 42 | headB = headB.next 43 | 44 | elif (sizeA == sizeB): # LinkedListA is LinkedListB 45 | while (headA and headB): 46 | if (headA is headB): 47 | return headA 48 | headA = headA.next 49 | headB = headB.next 50 | 51 | return None # No intersection 52 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0160._Intersection_of_Two_Linked_Lists/IntersectionOf2LinkedLists1.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | class Solution: 8 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 9 | # Hashtable for the Linked Lists: ID of head & values 10 | nodes = dict() 11 | 12 | while (headA is not None): 13 | nodes[id(headA)] = headA.val 14 | headA = headA.next 15 | 16 | # Check for node with the same thing in Linked List B 17 | while (headB): 18 | if id(headB) in nodes: 19 | return headB 20 | headB = headB. next 21 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0189._Rotate_Array/RotateArray0.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | 3 | class Solution { 4 | public void rotate(int[] nums, int k) { 5 | k %= nums.length; 6 | if (nums.length > k) { 7 | // create a new array to hold elements from the kth index (behind) to the end 8 | // nums arr 9 | // [1, 2, 3, 4, 5, 6, 7] -> [5, 6, 7] if k = 3 10 | // (length-k to length-1) 11 | int[] arr = new int[k]; 12 | int[] arr1 = new int[nums.length-k]; 13 | 14 | for (int i = k-1; i >= 0; i--) 15 | arr[i] = nums[nums.length-(k-i)]; 16 | 17 | for (int j = 0; j < nums.length-k;j++) 18 | arr1[j] = nums[j]; 19 | 20 | for (int m = 0; m < nums.length; m++) { 21 | if (m < k) nums[m] = arr[m]; 22 | else nums[m] = arr1[m-k]; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0189._Rotate_Array/RotateArray0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def rotate(self, nums: list, k: int) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | k %= len(nums) 9 | if (len(nums) > k): 10 | arr = nums[:len(nums)-k] 11 | arr1 = nums[len(nums)-k:] 12 | for i in range(len(nums)): 13 | nums[i] = arr1[i] if (i < k) else arr[i-k] 14 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0189._Rotate_Array/RotateArray1.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | 3 | class Solution { 4 | public void rotate(int[] nums, int k) { 5 | k %= nums.length; 6 | if (nums.length > k) { 7 | /* create a new array to hold elements from the kth index (behind) to the end 8 | * nums arr 9 | * [1, 2, 3, 4, 5, 6, 7] -> [5, 6, 7] if k = 3 10 | * (length-k to length-1) 11 | */ 12 | int[] arr = new int[k]; 13 | int[] arr1 = new int[nums.length-k]; 14 | 15 | for (int i = k-1; i >= 0; i--) 16 | arr[i] = nums[nums.length-(k-i)]; 17 | 18 | for (int j = 0; j < nums.length-k;j++) 19 | arr1[j] = nums[j]; 20 | 21 | for (int m = 0; m < nums.length; m++){ 22 | nums[m] = (m < k) ? arr[m] : arr1[m-k]; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0189._Rotate_Array/RotateArray1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 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 | n = len(nums); k %= n 9 | if (n > k): 10 | ''' 11 | create a new array to hold elements from the kth index (behind) to the end 12 | nums arr 13 | [1, 2, 3, 4, 5, 6, 7] -> [5, 6, 7] if k = 3 14 | (length-k to length-1) 15 | ''' 16 | arr = [0]*k 17 | arr1 = [0]*(n-k) 18 | for i in range(k-1,-1,-1): 19 | arr[i] = nums[n-k+i] 20 | 21 | for j in range(n-k): 22 | arr1[j] = nums[j] 23 | 24 | for m in range(n): 25 | nums[m] = arr[m] if (m < k) else arr1[m-k] 26 | -------------------------------------------------------------------------------- /Problems/0101.-0200./0189._Rotate_Array/RotateArray2.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public void rotate(int[] nums, int k) { 5 | int n = nums.length; 6 | 7 | if (n > k) { 8 | int arr[] = new int[k]; 9 | for (int i = n-1; i >= n-k; i--) 10 | arr[k-n+i] = nums[i]; 11 | 12 | int j = 0, l = n-k-1; 13 | while (n-- > 0) { 14 | if (l >= 0) { 15 | nums[l+k] = nums[l]; 16 | l--; 17 | } else { 18 | nums[j] = arr[j]; 19 | j++; 20 | } 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0203._Remove_Linked_List_Elements/RemoveLinkedListElements0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 203. Remove Linked List Elements 3 | 4 | # Definition for singly-linked list. 5 | class ListNode(object): 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution: 11 | def removeElements(self, head: ListNode, val: int) -> ListNode: 12 | ll_size = 0 13 | curr = head 14 | 15 | while (curr): # Count the number of nodes in the Singly Linked List 16 | ll_size += 1 17 | curr = curr.next 18 | 19 | if (not head and ll_size == 0): # Empty Linked List 20 | return head 21 | elif (ll_size == 1): # Linked List with 1 node 22 | if (head.val == val): 23 | return None 24 | else: 25 | return head 26 | else: # Linked List with 2 or more nodes 27 | dummy = ListNode(-1, head) # dummy.next = head 28 | prev = dummy 29 | 30 | while (head): 31 | if (head.val == val): 32 | prev.next = head.next 33 | else: 34 | prev = head 35 | 36 | head = head.next 37 | return dummy.next 38 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0203._Remove_Linked_List_Elements/RemoveLinkedListElements1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 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: 10 | def removeElements(self, head: ListNode, val: int) -> ListNode: 11 | if (not head): # empty linked list 12 | return head 13 | else: 14 | length = 0 15 | curr = head 16 | _list_ = [] 17 | 18 | while (curr): # Count number of nodes 19 | length += 1 20 | _list_.append(curr.val) 21 | curr = curr.next 22 | 23 | re = 0 24 | while (0 <= re < length): 25 | if (_list_[re] == val): 26 | del _list_[re] # remove element 27 | re -= 1 # Shift pointer left 28 | length -= 1 # reduce size of linked list 29 | re += 1 30 | 31 | final_linked_list = list(map(ListNode, _list_)) 32 | 33 | for i in range(len(final_linked_list)-1): 34 | final_linked_list[i].next = final_linked_list[i+1] 35 | 36 | new_head = final_linked_list[0] if (len(final_linked_list) != 0) else None 37 | return new_head 38 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0206._Reverse_Linked_List/ReverseLinkedList0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 206. Reverse Linked List 3 | 4 | # Definition for singly-linked list. 5 | class ListNode(object): 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution: 11 | def reverseList(self, head: ListNode) -> ListNode: 12 | if (head is None): # Empty Linked List: _ -> NULL 13 | return None 14 | elif (head.next is None): # Unary Linked List: x -> NULL 15 | return head 16 | else: # Binary Linked List & others: x -> y -> NULL 17 | curr = head 18 | prev = None 19 | 20 | while (curr): 21 | temp = curr.next 22 | curr.next = prev 23 | prev = curr 24 | curr = temp 25 | return prev 26 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0206._Reverse_Linked_List/ReverseLinkedList1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 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: 10 | def reverseList(self, head: ListNode]) -> ListNode: 11 | if (head is None or not head.next): 12 | return head 13 | else: 14 | llist = list() 15 | curr = head 16 | 17 | while (curr is not None): 18 | llist = [curr.val] + llist # Store the node values in reverse 19 | curr = curr.next 20 | 21 | nodes = [*map(ListNode, llist)] # Create node objects from the values 22 | 23 | for i in range(len(llist)-1): # Link the node objects to create the singly linked list 24 | nodes[i].next = nodes[i+1] 25 | 26 | headNode = nodes.pop(0) 27 | return (headNode) 28 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0232._Implement_Queue_using_Stacks/ImplementQueueFromStacks0.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | def __init__(self): 3 | """Initialize the queue using a list object""" 4 | self.Q = list() # self.Q = [] 5 | 6 | def push(self, x: int) -> None: 7 | """Push element x to the back of the queue""" 8 | self.Q.append(x) # self.Q += [x] 9 | 10 | def pop(self) -> int: 11 | """Remove the element from the front of the queue 12 | and return it""" 13 | elementOne = self.Q.pop(0) # elementOne = self.Q[0]; del elementOne; return elementOne 14 | return elementOne 15 | 16 | def peek(self) -> int: 17 | """Returns the element at the front of the queue""" 18 | return self.Q[0] 19 | 20 | def empty(self) -> bool: 21 | """Returns 'true' if the queue is empty, 'false' otherwise""" 22 | return (len(self.Q) == 0) 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() 31 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0232._Implement_Queue_using_Stacks/ImplementQueueFromStacks1.py: -------------------------------------------------------------------------------- 1 | class MyQueue(object): 2 | def __init__(self): 3 | """Initialize the queue using a list object""" 4 | self.stack = [] 5 | 6 | def push(self, x: int) -> None: 7 | """Push element x to the back of the queue""" 8 | self.stack += [x] 9 | 10 | def pop(self) -> int: 11 | """Remove the element from the front of the queue 12 | and return it""" 13 | elementOne = self.stack[0] 14 | del self.stack[0] 15 | return elementOne 16 | 17 | def peek(self) -> int: 18 | """Returns the element at the front of the queue""" 19 | return self.stack[-len(self.stack)] 20 | 21 | def empty(self) -> bool: 22 | """Returns 'true' if the queue is empty, 'false' otherwise""" 23 | return True if (len(self.stack) == 0) else False 24 | 25 | 26 | # Your MyQueue object will be instantiated and called as such: 27 | # obj = MyQueue() 28 | # obj.push(x) 29 | # param_2 = obj.pop() 30 | # param_3 = obj.peek() 31 | # param_4 = obj.empty() 32 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0234._Palindrome_Linked_List/PalindromeLinkedList0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 234. Palindrome Linked List 3 | 4 | # Definition for singly-linked list. 5 | class ListNode: 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution(object): 11 | def isPalindrome(self, head: ListNode) -> bool: 12 | llist = [] 13 | curr = head 14 | 15 | while (curr): 16 | llist += [curr.val] 17 | curr = curr.next 18 | 19 | return (llist == llist[::-1]) 20 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0234._Palindrome_Linked_List/PalindromeLinkedList1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 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 isPalindrome(self, head: ListNode) -> bool: 11 | nodesData = list() 12 | 13 | while (head is not None): 14 | nodesData.append(head.val) 15 | head = head.next 16 | 17 | return 1 if ([*reversed(nodesData)] == nodesData) else 0 18 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0234._Palindrome_Linked_List/PalindromeLinkedList2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for singly-linked list. 3 | # Code works but gives Time Limit Exceeded (TLE) error for huge linked lists with ~ 10⁵ nodes 4 | 5 | class ListNode: 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution: 11 | def isPalindrome(self, head: ListNode) -> bool: 12 | forward_nodes, backward_nodes = [], [] 13 | 14 | while (head != None): 15 | forward_nodes += [head.val] 16 | backward_nodes = [head.val] + backward_nodes 17 | head = head.next 18 | 19 | if (forward_nodes == backward_nodes): 20 | return True 21 | else: 22 | return False 23 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0242._Valid_Anagram/ValidAnagram0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | import java.util.HashMap; 3 | 4 | class Solution { 5 | public boolean isAnagram(String s, String t) { 6 | // Create HashMap object to hold characters and frequencies 7 | HashMap dict_s = new HashMap(); 8 | int count_s = 0; 9 | 10 | for (int i = 0; i < s.length(); i++) { 11 | if (dict_s.get(s.charAt(i)) == null) { 12 | dict_s.put(s.charAt(i), 0); 13 | } else { 14 | count_s++; 15 | dict_s.put(s.charAt(i), count_s); 16 | } 17 | } 18 | 19 | HashMap dict_t = new HashMap(); 20 | int count_t = 0; 21 | 22 | for (int j = 0; j < t.length(); j++) { 23 | if (dict_t.get(t.charAt(j)) == null) { 24 | dict_t.put(t.charAt(j), 0); 25 | } else { 26 | count_t++; 27 | dict_t.put(t.charAt(j), count_t); 28 | } 29 | } 30 | 31 | return dict_t.equals(dict_s); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0242._Valid_Anagram/ValidAnagram0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def isAnagram(self, s: str, t: str) -> bool: 4 | # Dictionary to hold chars in s 5 | dict_s = {} 6 | 7 | for char in s: 8 | if char not in dict.keys(dict_s): 9 | dict_s[char] = 0 10 | else: 11 | dict_s[char] += 1 12 | 13 | # Dictionary to hold chars in t 14 | dict_t = {} 15 | 16 | for char in t: 17 | if char not in dict.keys(dict_t): 18 | dict_t[char] = 0 19 | else: 20 | dict_t[char] += 1 21 | return dict_s == dict_t 22 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0242._Valid_Anagram/ValidAnagram1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | from collections import Counter 3 | 4 | class Solution: 5 | def isAnagram(self, s: str, t: str) -> bool: 6 | # Use a Counter object to get the frequenices of characters in each string 7 | char_count_s = Counter(s) 8 | char_count_t = Counter(t) 9 | 10 | return char_count_s == char_count_t 11 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0242._Valid_Anagram/ValidAnagram2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import collections 3 | 4 | class Solution: 5 | def isAnagram(self, s: str, t: str) -> bool: 6 | return collections.Counter(s) == collections.Counter(t) 7 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0242._Valid_Anagram/ValidAnagram3.py: -------------------------------------------------------------------------------- 1 | # 242. Valid Anagram 2 | 3 | class Solution: 4 | def isAnagram(self, s: str, t: str) -> bool: 5 | dict_s, dict_t = [dict() for _ in range(2)] 6 | 7 | for char in s: 8 | dict_s[char] = dict_s.get(char, 0) + 1 9 | 10 | for char in t: 11 | dict_t[char] = dict_t.get(char, 0) + 1 12 | 13 | return (dict_s == dict_t) 14 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0290._Word_Pattern/WordPattern0.py: -------------------------------------------------------------------------------- 1 | # 290. Word Pattern 2 | class Solution: 3 | def wordPattern(self, pattern: str, s: str) -> bool: 4 | s = s.split(' ') 5 | if len(pattern) == len(s): 6 | chars1 = list(set(pattern)) 7 | chars2 = list(set(s)) 8 | pattern = tuple(pattern) 9 | lst = [] 10 | for i, j in zip(pattern, s): 11 | lst.append((i,j)) 12 | if len(chars1) == len(chars2) and len(chars1) == len(set(lst)): 13 | return True 14 | else: 15 | return False 16 | else: 17 | return False 18 | -------------------------------------------------------------------------------- /Problems/0201.-0300./0290._Word_Pattern/WordPattern1.py: -------------------------------------------------------------------------------- 1 | # 290. Word Pattern 2 | class Solution: 3 | def wordPattern(self, pattern: str, s: str) -> bool: 4 | s = s.split() 5 | if (len(pattern) == len(s)): 6 | chars1, chars2 = map(list, [set(pattern), set(s)]) 7 | pattern = tuple(pattern) 8 | lst = [(i, j) for i, j in zip(pattern, s)] 9 | return len(chars1) == len(chars2) and len(chars1) == len(set(lst)) 10 | else: 11 | return 0 12 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0328._Odd_Even_Linked_List/OddEvenLinkedList0.py: -------------------------------------------------------------------------------- 1 | # 328. Odd Even Linked List 2 | 3 | # Definition for singly-linked list. 4 | class ListNode(object): 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | class Solution: 10 | def oddEvenList(self, head: ListNode) -> ListNode: 11 | if (not head): 12 | return head 13 | else: 14 | odd_indices, even_indices = [], [] 15 | curr1, curr2 = head, head 16 | ll_size = 0 17 | 18 | while (curr1): # Get the number of nodes 19 | ll_size += 1 20 | curr1 = curr1.next 21 | 22 | count = 1 # Tracing index 23 | while (curr2 and (count <= ll_size)): 24 | if (count % 2 == 1): # even numbered node 25 | odd_indices += [ListNode(curr2.val)] 26 | elif (count % 2 == 0): # odd numbered node 27 | even_indices += [ListNode(curr2.val)] 28 | count += 1 29 | curr2 = curr2.next 30 | 31 | odd_indices.extend(even_indices) # Merge odd & even numbered nodes 32 | 33 | for k in range(len(odd_indices)-1): 34 | odd_indices[k].next = odd_indices[k+1] 35 | 36 | return odd_indices.pop(0) 37 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString0.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | class Solution { 3 | public void reverseString(char[] s) { 4 | /* Python3 code 5 | # 2-pointer approach 6 | i = 0; j = len(s)-1 7 | 8 | while (i < len(s)//2): 9 | temp = s[j] 10 | s[j] = s[i] 11 | s[i] = temp 12 | i += 1 13 | j -= 1 14 | */ 15 | // 2-pointer approach 16 | int i = 0; 17 | int j = s.length-1; 18 | char temp; // declare dummy variable for swapping 19 | 20 | while (i < s.length/2) { 21 | temp = s[j]; 22 | s[j] = s[i]; 23 | s[i] = temp; 24 | i++; 25 | j--; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def reverseString(self, s: List[str]) -> None: 4 | """ 5 | Do not return anything, modify s in-place instead. 6 | """ 7 | # 2-pointer approach 8 | i = 0; j = len(s)-1 9 | 10 | while (i < len(s)//2): 11 | temp = s[j] 12 | s[j] = s[i] 13 | s[i] = temp 14 | i += 1 15 | j -= 1 16 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString1.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | class Solution { 3 | public void reverseString(char[] s) { 4 | /* 5 | # 1-pointer approach 6 | i = 0 7 | 8 | while (i < len(s)//2): 9 | temp = s[len(s)-i-1] 10 | s[len(s)-i-1] = s[i] 11 | s[i] = temp 12 | i += 1 13 | */ 14 | // 1-pointer approach 15 | int i = 0; 16 | char temp; // declare dummy variable for swapping 17 | 18 | while (i < s.length/2) { 19 | temp = s[s.length-i-1]; 20 | s[s.length-i-1] = s[i]; 21 | s[i] = temp; 22 | i++; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def reverseString(self, s: List[str]) -> None: 4 | """ 5 | Do not return anything, modify s in-place instead. 6 | """ 7 | # 1-pointer approach 8 | i = 0; 9 | 10 | while (i < len(s)//2): 11 | temp = s[len(s)-i-1] 12 | s[len(s)-i-1] = s[i] 13 | s[i] = temp 14 | i += 1 15 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def reverseString(self, s: List[str]) -> None: 5 | """ 6 | Do not return anything, modify s in-place instead. 7 | """ 8 | # Base cases 9 | if (len(s) == 0): # empty string: "" 10 | return [''] 11 | elif (len(s) == 0): # unary string: "a" 12 | return [s[0]] 13 | else: # binary strings or more: "ab", "abc", ... 14 | i, j = 0, len(s)-1 # 2-pointer recursive approach 15 | 16 | if (len(s) % 2 == 1): # odd number of characters 17 | while (i != j): 18 | s[i], s[j] = s[j], s[i] # swap 19 | i += 1 20 | j -= 1 21 | else: # even number of characters 22 | while (i < len(s)//2): 23 | s[i], s[j] = s[j], s[i] # swap 24 | i += 1 25 | j -= 1 26 | return self.reverseString(s[i:j]) 27 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString3.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution(object): 4 | def reverseString(self, s: list[str]) -> None: 5 | """ 6 | Do not return anything, modify s in-place instead. 7 | """ 8 | n = len(s) 9 | 10 | # Base cases 11 | if (n == 0): # empty string: "" 12 | return [''] 13 | elif (n == 0): # unary string: "a" 14 | return [s[0]] 15 | else: # binary strings or more: "ab", "abc", ... 16 | i = 0 # 1-pointer recursive approach 17 | 18 | if (n % 2): # odd number of characters 19 | while (i != n-i-1): 20 | s[i], s[n-i-1] = s[n-i-1], s[i] # swap 21 | i += 1 22 | else: # even number of characters 23 | while (i < int(n/2)): 24 | s[i], s[n-i-1] = s[n-i-1], s[i] # swap 25 | i += 1 26 | return self.reverseString(s[i:n-i-1]) 27 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString4.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def reverseString(self, s: list[str]) -> None: 5 | """ 6 | Do not return anything, modify s in-place instead. 7 | """ 8 | s[:] = s[::-1] 9 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString5.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def reverseString(self, s: list[str]) -> None: 5 | """ 6 | Do not return anything, modify s in-place instead. 7 | """ 8 | s[:] = reversed(s) 9 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString6.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def reverseString(self, s: list) -> None: 5 | """ 6 | Do not return anything, modify s in-place instead. 7 | """ 8 | s.reverse() 9 | 10 | -------------------------------------------------------------------------------- /Problems/0301.-0400./0344._Reverse_String/ReverseString7.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution(object): 4 | def reverseString(self, s: list[str]) -> None: 5 | """ 6 | Do not return anything, modify s in-place instead. 7 | """ 8 | s[:] = s[len(s)::-1] 9 | -------------------------------------------------------------------------------- /Problems/0301.-0400./350._Intersection_of_Two_Arrays_II/IntersectionOfTwoArraysII0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 350. Intersection of Two Arrays II 3 | 4 | class Solution: 5 | def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]: 6 | nums1, nums2 = map(sorted, [nums1, nums2]) 7 | lst = [] 8 | i, j = 0, 0 9 | while (i < len(nums1) and j < len(nums2)): 10 | if nums1[i] == nums2[j]: 11 | lst += [nums1[i]] 12 | j += 1 13 | i += 1 14 | elif nums1[i] < nums2[j]: 15 | i += 1 16 | else: 17 | j += 1 18 | return lst 19 | -------------------------------------------------------------------------------- /Problems/0401.-0500./0414._Third_Maximum_Number/ThirdMaximumNumber0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 414. Third Maximum Number 3 | 4 | class Solution: 5 | def thirdMax(self, nums: List[int]) -> int: 6 | # Get the 1st unique maximum 7 | first_max = -10**10-7; i = 0 8 | while (i < len(nums)): 9 | if (nums[i] > first_max): 10 | first_max = nums[i] 11 | i += 1 12 | 13 | # Get the 2nd unique maximum number 14 | second_max = -10**10-8; j = 0 15 | while (j < len(nums)): 16 | if (nums[j] > second_max and nums[j] < first_max): 17 | second_max = nums[j] 18 | j += 1 19 | 20 | # Get the 3rd unique maximum number 21 | third_max = -10**10-9; k = 0 22 | while (k < len(nums)): 23 | if (nums[k] > third_max and nums[k] < second_max): 24 | third_max = nums[k] 25 | k += 1 26 | return (third_max if (third_max != -10**10-9) else first_max) 27 | -------------------------------------------------------------------------------- /Problems/0401.-0500./0414._Third_Maximum_Number/ThirdMaximumNumber1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def thirdMax(self, nums: List[int]) -> int: 3 | nums = set(nums) 4 | if (len(nums) <= 2): 5 | return max(nums) 6 | else: 7 | return sorted(nums, reverse=True)[2] 8 | -------------------------------------------------------------------------------- /Problems/0401.-0500./0451._Sort_Characters_By_Frequency/SortCharsByFrequency0.py: -------------------------------------------------------------------------------- 1 | # 451. Sort Characters By Frequency 2 | 3 | class Solution: 4 | def frequencySort(self, s: str) -> str: 5 | freqs = {} 6 | 7 | # Count the frequencies of each character 8 | for char in s: 9 | if char not in freqs: 10 | freqs[char] = 1 11 | else: 12 | freqs[char] += 1 13 | 14 | sorted_string = str() 15 | item_counts = sorted(freqs.items(), key = lambda x: x[1], reverse = True) 16 | 17 | # Empty string for output 18 | for char, count in item_counts: 19 | sorted_string += char*count 20 | return sorted_string 21 | -------------------------------------------------------------------------------- /Problems/0401.-0500./0451._Sort_Characters_By_Frequency/SortCharsByFrequency1.py: -------------------------------------------------------------------------------- 1 | # 451. Sort Characters By Frequency 2 | 3 | class Solution: 4 | def frequencySort(self, s: str) -> str: 5 | char_count = dict() 6 | 7 | # Count the frequencies of each character 8 | for char in s: 9 | char_count[char] = char_count.get(char,0) + 1 10 | 11 | final_string = "" 12 | maps = list(char_count.items()) 13 | maps.sort(key = lambda x: x[1]) 14 | 15 | for i, _ in maps: 16 | final_string += i *char_count[i] 17 | return final_string[::-1] 18 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0520._Detect_Capital/DetectCapital0.py: -------------------------------------------------------------------------------- 1 | # 520. Detect Capital 2 | class Solution: 3 | def detectCapitalUse(self, word: str) -> bool: 4 | if len(word) == 1 or len(word) == 0: 5 | return True 6 | else: 7 | lst = [] 8 | for i in range(1,len(word)): 9 | lst += [word[i].isupper()] 10 | if word[0].isupper(): 11 | if all(lst): 12 | return True 13 | elif any(lst): 14 | return False 15 | else: 16 | return True 17 | else: 18 | if any(lst): 19 | return False 20 | elif all(lst): 21 | return False 22 | else: 23 | return True 24 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0520._Detect_Capital/DetectCapital1.py: -------------------------------------------------------------------------------- 1 | # 520. Detect Capital 2 | class Solution: 3 | def detectCapitalUse(self, word: str) -> bool: 4 | n = len(word) 5 | upper_count = 0 6 | 7 | for char in word: 8 | if ("A" <= char <= "Z"): 9 | upper_count += 1 10 | 11 | if (0 < upper_count < n): 12 | if (upper_count > 1): 13 | return False 14 | if not ("A" <= word[0] <= "Z"): 15 | return False 16 | return True 17 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0520._Detect_Capital/DetectCapital2.py: -------------------------------------------------------------------------------- 1 | # 520. Detect Capital 2 | class Solution: 3 | def detectCapitalUse(self, word: str) -> bool: 4 | if word.isupper(): # All letters in this word are capitals 5 | return 1 6 | elif word.islower(): # All letters in this word are not capitals 7 | return 1 8 | elif word[0].isupper() and word[1:].islower(): # Only the 1st letter is capital 9 | return 1 10 | else: 11 | return 0 12 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition0.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | class Solution { 3 | public int arrayPairSum(int[] nums) { 4 | /* Python3 code 5 | n = len(nums) 6 | 7 | # To maximize the sum of pairs sort the array 8 | for i in range(n): 9 | for j in range(i+1,n): 10 | if (nums[j] < nums[i]): 11 | temp = nums[i] 12 | nums[i] = nums[j] 13 | nums[j] = temp 14 | else: 15 | continue 16 | 17 | k = n-1; 18 | max_sum = 0 19 | while (k >= 0): 20 | max_sum += min(nums[k],nums[k-1]) 21 | k -= 2 22 | return max_sum 23 | */ 24 | int n = nums.length; 25 | int swap_num; 26 | 27 | // To maximize the sum of pairs sort the array 28 | Arrays.sort(nums); 29 | /* 30 | for (int i = 0; i < n; i++) { 31 | for (int j = i+1; j < n; j++) { 32 | if (nums[j] < nums[i]) { 33 | swap_num = nums[i]; 34 | nums[i] = nums[j]; 35 | nums[j] = swap_num; 36 | } 37 | } 38 | } 39 | */ 40 | 41 | // Index for going over the minimum of pairs 42 | n--; 43 | int max_sum = 0; 44 | while (n >= 1) { 45 | max_sum += Math.min(nums[n-1], nums[n]); 46 | n -= 2; 47 | } 48 | return max_sum; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def arrayPairSum(self, nums: list) -> int: 4 | """ 5 | return the maximized sum for an integer array of even length 6 | """ 7 | n = len(nums) 8 | 9 | # To maximize the sum of pairs sort the array 10 | nums.sort(reverse = False); 11 | 12 | k = n-1; 13 | max_sum = 0 14 | while (k >= 0): 15 | max_sum += min(nums[k], nums[k-1]) 16 | k -= 2 17 | return max_sum 18 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition1.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | class Solution { 3 | public int arrayPairSum(int[] nums) { 4 | // Sort the array 5 | Arrays.sort(nums); 6 | 7 | // Hold the maximum sum 8 | int max_sum = 0; 9 | for (int i = nums.length-1; i > -1; i -= 2) { 10 | max_sum += Math.min(nums[i-1], nums[i]); 11 | } 12 | return max_sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def arrayPairSum(self, nums: List[int]) -> int: 4 | n = len(nums) 5 | 6 | # To maximize the sum of pairs sort the array 7 | nums = sorted(nums, reverse = 0) 8 | 9 | n -= 1; 10 | max_sum = 0 11 | while (n >= 0): 12 | max_sum += min(nums[n], nums[n-1]) 13 | n -= 2 14 | return max_sum 15 | 16 | 17 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition2.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | import java.util.ArrayList; 3 | 4 | class Solution { 5 | public int arrayPairSum(int[] nums) { 6 | // Sort the array 7 | Arrays.sort(nums); 8 | 9 | // Hold the maximum sum 10 | int max_sum = 0; 11 | 12 | // Store all the minimums of pairs 13 | List mins = new ArrayList<>(0); 14 | 15 | // Loop through pairs 16 | for (int j = nums.length-1; j > -1; j -= 2) 17 | mins.add(Math.min(nums[j-1], nums[j])); 18 | 19 | // Sum the items in the arraylist collection 20 | for (int m : mins) 21 | max_sum += m; 22 | 23 | return max_sum; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayPairSum(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | 5 | # To maximize the sum of pairs sort the array 6 | nums = sorted(nums, key = lambda x: x) 7 | 8 | n -= 1 9 | max_sum = 0 10 | for i in range(n,-1,-2): 11 | max_sum += min(nums[i], nums[i-1]) 12 | return max_sum 13 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition3.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def arrayPairSum(self, nums: List[int]) -> int: 4 | """ 5 | return the maximized sum for an integer array of even length 6 | """ 7 | n = len(nums) 8 | 9 | # To maximize the sum of pairs sort the array 10 | nums.sort() 11 | return sum([min(nums[i], nums[i-1]) for i in range(n-1,-1,-2)]) 12 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition4.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | from functools import reduce 3 | 4 | class Solution: 5 | def arrayPairSum(self, nums: List[int]) -> int: 6 | """ 7 | return the maximized sum for an integer array of even length 8 | """ 9 | # To maximize the sum of pairs sort the array 10 | nums.sort() 11 | return reduce(lambda a, b: a + b, [min(nums[i], nums[i-1]) for i in range(len(nums)-1,-1,-2)]) 12 | -------------------------------------------------------------------------------- /Problems/0501.-0600./0561._Array_Partition/ArrayPartition5.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | from itertools import accumulate 3 | 4 | class Solution: 5 | def arrayPairSum(self, nums: List[int]) -> int: 6 | """ 7 | return the maximized sum for an integer array of even length 8 | """ 9 | # To maximize the sum of pairs sort the array 10 | nums = sorted(nums) 11 | return [*accumulate([min(nums[i], nums[i-1]) for i in range(len(nums)-1,-1,-2)], lambda a, b: a + b)][-1] 12 | -------------------------------------------------------------------------------- /Problems/0601.-0700./0633._Sum_of_Squared_Numbers/SumOfSquaredNumbers0.py: -------------------------------------------------------------------------------- 1 | # 633. Sum of Squared Numbers 2 | 3 | class Solution: 4 | def judgeSquareSum(self, c: int) -> bool: 5 | div = 2 # Smallest prime number 6 | while (div * div <= c): 7 | if (c % div == 0): # div is a factor of c 8 | expCount = 0 9 | 10 | while (c % div == 0): # increment the exponent of div 11 | expCount += 1 12 | c /= div 13 | 14 | if (div % 4 == 3) and (expCount % 2 != 0): # check power of prime factor 15 | return False 16 | div += 1 17 | return (c % 4 != 3) 18 | -------------------------------------------------------------------------------- /Problems/0601.-0700./0654._Set_Mismatch/SetMismatch0.py: -------------------------------------------------------------------------------- 1 | # 654. Set Mismatch 2 | class Solution: 3 | def findErrorNums(self, nums: list) -> list: 4 | duplicate = sum(nums) - sum(set(nums)) 5 | n = len(nums) 6 | missing = (n*(n+1))//2 - sum(set(nums)) 7 | return [duplicate, missing] 8 | -------------------------------------------------------------------------------- /Problems/0601.-0700./0654._Set_Mismatch/SetMismatch1.py: -------------------------------------------------------------------------------- 1 | # 654. Set Mismatch 2 | class Solution: 3 | def findErrorNums(self, nums: List[int]) -> List[int]: 4 | duplicate = sum(nums) - sum(set(nums)) 5 | s = {i for i in range(1, len(nums)+1)} 6 | return [duplicate] + list(set(nums) ^ s) 7 | -------------------------------------------------------------------------------- /Problems/0601.-0700./0654._Set_Mismatch/SetMismatch2.py: -------------------------------------------------------------------------------- 1 | # 654. Set Mismatch 2 | class Solution: 3 | def findErrorNums(self, nums: list]) -> list]: 4 | min_num, max_num = 1, len(nums) 5 | s = [i for i in range(min_num, max_num+1)] # [1, 2, 3, ..., n] 6 | output = {j for j in s if j not in nums} # get the missing element 7 | 8 | duplicate = set() 9 | for k in nums: 10 | if (nums.count(k) == 2): 11 | duplicate.add(k) 12 | else: 13 | del k 14 | return list(duplicate) + list(output) 15 | 16 | ''' 17 | ----------------------------------------------------- 18 | Works for all testcases except #49 19 | Gives "Time Limit Exceeded" error but the code works! 20 | ----------------------------------------------------- 21 | ''' 22 | -------------------------------------------------------------------------------- /Problems/0601.-0700./700._Search_in_a_Binary_Search_Tree/SearchInBinarySearchTree0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 700. Search in a Binary Search Tree 3 | 4 | # Definition for a binary tree node. 5 | class TreeNode: 6 | def __init__(self, val=0, left=None, right=None): 7 | self.val = val 8 | self.left = left 9 | self.right = right 10 | 11 | class Solution: 12 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 13 | if (not root): # Empty Binary Search Tree: 14 | return None 15 | elif (root.val == val): 16 | return root 17 | elif (root.val > val): # Left substree of Binary Search Tree 18 | return self.searchBST(root.left, val) 19 | elif (root.val < val): # Right subtree of Binary Search Tree 20 | return self.searchBST(root.right, val) 21 | -------------------------------------------------------------------------------- /Problems/0601.-0700./700._Search_in_a_Binary_Search_Tree/SearchInBinarySearchTree1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for a binary tree node. 3 | class TreeNode: 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution: 10 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 11 | if (root is None or root.val == val): 12 | return root 13 | elif (root.val > val): 14 | return self.searchBST(root.left, val) 15 | else: 16 | return self.searchBST(root.right, val) 17 | -------------------------------------------------------------------------------- /Problems/0601.-0700./700._Search_in_a_Binary_Search_Tree/SearchInBinarySearchTree2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for a binary tree node. 3 | class TreeNode: 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution: 10 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 11 | return root if (not root or root.val == val) else (self.searchBST(root.left, val) if (root.val > val) else self.searchBST(root.right, val)) 12 | -------------------------------------------------------------------------------- /Problems/0601.-0700./700._Search_in_a_Binary_Search_Tree/SearchInBinarySearchTree3.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for a binary tree node. 3 | class TreeNode: 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution(object): 10 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 11 | while (root): 12 | if (root.val == val): 13 | return root 14 | elif (root.val > val): 15 | root = root.left 16 | elif (root.val < val): 17 | root = root.right 18 | return root 19 | -------------------------------------------------------------------------------- /Problems/0701.-0800./0747._Largest_Number_At_Least_Twice_of_Others/LargestNumberAtLeastTwiceofOthers0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dominantIndex(self, nums: List[int]) -> int: 3 | dummy_num = nums.copy() 4 | max_num = max(nums) 5 | nums.remove(max_num) 6 | 7 | if max_num >= 2*max(nums): 8 | return dummy_num.index(max_num) 9 | else: 10 | return -1 11 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0905._Sort_Array_By_Parity/SortArrayByParity0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | import java.util.ArrayList; 3 | 4 | class Solution { 5 | public int[] sortArrayByParity(int[] nums) { 6 | ArrayList evenNumbers = new ArrayList<>(); 7 | ArrayList oddNumbers = new ArrayList<>(); 8 | 9 | // Check if each element is EVEN or ODD 10 | for (int i = 0; i < nums.length; i++) { 11 | if (nums[i] % 2 == 1) oddNumbers.add(nums[i]); // odd #s 12 | else evenNumbers.add(nums[i]); // even #s 13 | } 14 | 15 | // Combine even & odd number ArrayLists 16 | evenNumbers.addAll(oddNumbers); 17 | 18 | // Convert ArrayList to int[] array 19 | int[] ints = evenNumbers.stream().mapToInt(Integer::intValue).toArray(); 20 | return ints; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0905._Sort_Array_By_Parity/SortArrayByParity0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def sortArrayByParity(self, nums: list) -> list: 5 | """ 6 | Move all the even integers at the beginning of the array 7 | followed by all the odd integers. 8 | """ 9 | lsteven = [] 10 | lstodd = [] 11 | for i in nums: 12 | if i % 2: # odd 13 | lstodd += [i] 14 | else: 15 | lsteven += [i] 16 | return lsteven + lstodd 17 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0905._Sort_Array_By_Parity/SortArrayByParity1.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public int[] sortArrayByParity(int[] nums) { 4 | int[] lst = new int[nums.length]; 5 | int i = 0, countEven = 1; 6 | int j = 0, countOdd = 1; 7 | 8 | while (i < nums.length) { 9 | if (nums[i] % 2 == 0) { 10 | lst[countEven-1] = nums[i]; 11 | countEven++; 12 | } 13 | i++; 14 | } 15 | while (j < nums.length) { 16 | if (nums[j] % 2 == 1) { 17 | lst[countEven+countOdd-2] = nums[j]; 18 | countOdd++; 19 | } 20 | j++; 21 | } 22 | return lst; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0905._Sort_Array_By_Parity/SortArrayByParity1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def sortArrayByParity(self, nums: list) -> list: 4 | return [i for i in nums if i % 2 == 0] + [j for j in nums if j % 2] 5 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0905._Sort_Array_By_Parity/SortArrayByParity2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def sortArrayByParity(self, nums: list) -> list: 4 | """ 5 | Move all the even integers at the beginning of 6 | the array followed by all the odd integers 7 | """ 8 | evens = [e for e in nums if e % 2 == 0] 9 | odds = [o for o in nums if o % 2] 10 | evens.extend(odds) 11 | return evens 12 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0905._Sort_Array_By_Parity/SortArrayByParity3.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def sortArrayByParity(self, nums: list) -> list: 5 | lst = list() 6 | i = 0 7 | 8 | while (i < len(nums)): # Insert all EVEN #s first 9 | if (nums[i] % 2 == 0): 10 | lst += [nums[i]] 11 | i += 1 12 | 13 | j = 0 14 | while (j < len(nums)): # Then, insert all ODD #s 15 | if (nums[j] % 2): 16 | lst += [nums[j]] 17 | j += 1 18 | return lst 19 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0941._Valid_Mountain_Array/ValidMountainArray0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public boolean validMountainArray(int[] arr) { 4 | int i, j, count, n = arr.length; 5 | 6 | // If the array has at most 2 elements 7 | if (n <= 2) return false; 8 | 9 | i = 0; 10 | count = 1; // Count elements in arr 11 | // Loop while strictly INCREASING 12 | while (i < n-1) { 13 | if (arr[i+1] > arr[i]) { 14 | i++; 15 | count++; 16 | } else {break;} 17 | } 18 | // When count = 1, arr is sorted in DESCENDING order 19 | // When count = n, arr is sorted in ASCENDING order 20 | if (count == 1 || count == n) return false; 21 | 22 | j = i; 23 | // Loop while strictly DECREASING 24 | while (j < n-1) { 25 | if (arr[j+1] < arr[j]) { 26 | j++; 27 | count++; 28 | } else {break;} 29 | } 30 | return (count == n) ? true : false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0941._Valid_Mountain_Array/ValidMountainArray0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def validMountainArray(self, arr: list) -> bool: 4 | n = len(arr) 5 | 6 | # If the array has at most 2 elements 7 | if (n <= 2): 8 | return False 9 | 10 | i = 0 11 | count = 1 # count elements in arr 12 | 13 | # Loop while strictly INCREASING 14 | while (i < n-1): 15 | if (arr[i+1] > arr[i]): 16 | i += 1 17 | count += 1 18 | else: 19 | break 20 | # When count = 1, arr is sorted in DESCENDING order 21 | # When count = n, arr is sorted in ASCENDING order 22 | if (count == 1 or count == n): 23 | return False 24 | 25 | j = i 26 | # Loop while strictly DECREASING 27 | while (j < n-1): 28 | if (arr[j+1] < arr[j]): 29 | j += 1 30 | count += 1 31 | else: 32 | break 33 | return count == n 34 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0941._Valid_Mountain_Array/ValidMountainArray1.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public boolean validMountainArray(int[] arr) { 4 | int n = arr.length, i = 0, j = n-1; 5 | 6 | // Strictly INCREASING loop 7 | while (i < n-1 && arr[i] < arr[i+1]) 8 | i++; 9 | 10 | // Strictly DECREASING loop 11 | while (j > 0 && arr[j-1] > arr[j]) 12 | j--; 13 | 14 | /* 15 | * If the array is a VALID MOUNTAIN array, i and j meet 16 | * at the same index 17 | */ 18 | return (i > 0 && i == j && j < n-1); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0941._Valid_Mountain_Array/ValidMountainArray1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution(object): 3 | def validMountainArray(self, arr: list) -> bool: 4 | i, j = 0, len(arr)-1 5 | # Strictly INCREASING loop 6 | while (i < len(arr)-1 and arr[i] < arr[i+1]): 7 | i += 1 8 | # Strictly DECREASING loop 9 | while (j > 0 and arr[j-1] > arr[j]): 10 | j -= 1 11 | ''' 12 | If the array is a VALID MOUNTAIN, i and j meet 13 | at the same index 14 | ''' 15 | return (i > 0 and i == j and j < len(arr)-1) 16 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0941._Valid_Mountain_Array/ValidMountainArray2.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public boolean validMountainArray(int[] arr) { 4 | int n = arr.length, i = 0, j = n-1, k = 0; 5 | 6 | // Loop over the entire array 7 | while (k < n) { 8 | if (i < n-1 && arr[i+1] > arr[i]) // Strictly INCREASING 9 | ++i; 10 | if (j > 0 && arr[j] < arr[j-1]) // Strictly DECREASING 11 | --j; 12 | k++; 13 | } 14 | return (i > 0 && i == j && j < n-1); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0941._Valid_Mountain_Array/ValidMountainArray2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def validMountainArray(self, arr: list) -> bool: 4 | i, j, k = 0, len(arr)-1, 0 5 | 6 | # Loop over the entire array 7 | while (k < len(arr)): 8 | if (i < len(arr)-1 and arr[i+1] > arr[i]): # Strictly INCREASING 9 | i += 1 10 | if (j > 0 and arr[j] < arr[j-1]): # Strictly DECREASING 11 | j -= 1 12 | k += 1 13 | return (i > 0 and i == j and j < len(arr)-1) 14 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0976._Largest_Perimeter_Triangle/LargestPerimeterTriangle0.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int largestPerimeter(int[] nums) { 3 | Arrays.sort(nums); 4 | 5 | for (int i = nums.length-3; i >= 0; i--) { 6 | if (nums[i] + nums[i+1] > nums[i+2]) { 7 | return nums[i] + nums[i+1] + nums[i+2]; 8 | } 9 | } 10 | return 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0976._Largest_Perimeter_Triangle/LargestPerimeterTriangle0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums: List[int]) -> int: 3 | # Sort the #s in the list, then check every triple using 4 | # the triangle inequality 5 | nums = sorted(nums, reverse=False) 6 | m = 3 7 | lst = [] 8 | for i in range(len(nums)-m+1): 9 | a = nums[i]; b = nums[i+1]; c = nums[i+2] 10 | if a + b > c and a + c > b and b + c > a: 11 | # Store all possible perimeters 12 | lst.append(a + b + c) 13 | return sorted(lst)[-1] if lst else 0 14 | -------------------------------------------------------------------------------- /Problems/0901.-1000./0976._Largest_Perimeter_Triangle/LargestPerimeterTriangle1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums: List[int]) -> int: 3 | nums.sort() 4 | for i in range(len(nums)-1,1,-1): 5 | if nums[i-2] + nums[i-1] > nums[i]: 6 | return nums[i-2] + nums[i-1] + nums[i] 7 | return 0 8 | -------------------------------------------------------------------------------- /Problems/0901.-1000./938._Range_Sum_of_BST/RangeSumOfBst0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # Definition for a binary tree node. 3 | class TreeNode: 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution: 10 | def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: 11 | sum_val = 0 12 | 13 | if (root is None): return sum_val 14 | 15 | if (root.val < low): 16 | return self.rangeSumBST(root.right, low, high) 17 | elif (root.val > high): 18 | return self.rangeSumBST(root.left, low, high) 19 | else: 20 | sum_val += root.val 21 | sum_val += (self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)) 22 | return sum_val 23 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public int heightChecker(int[] heights) { 5 | // Initialize the expected array 6 | int[] expected = new int[heights.length]; 7 | 8 | // Copy the heights array 9 | for (int e = 0; e < heights.length; e++) 10 | expected[e] = heights[e]; 11 | 12 | int temp; 13 | // Sort the heights array 14 | for (int i = 0; i < expected.length; i++) { 15 | for (int j = i+1; j < expected.length; j++) { 16 | if (expected[j] < expected[i]) { 17 | temp = expected[j]; 18 | expected[j] = expected[i]; 19 | expected[i] = temp; 20 | } 21 | } 22 | } 23 | 24 | int count = 0; 25 | for (int k = 0; k < heights.length; k++) { 26 | if (heights[k] != expected[k]) count++; 27 | } 28 | 29 | return count; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def heightChecker(self, heights: list) -> int: 5 | # expected[] is the ascending order of heights 6 | # Hence, sort the heights[] array 7 | expected = sorted(heights) 8 | n = len(heights) 9 | return len([i for i in range(n) if heights[i] != expected[i]]) 10 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker1.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | import java.util.Arrays; 3 | 4 | class Solution { 5 | public int heightChecker(int[] heights) { 6 | // Initialize the expected array 7 | int[] expected = new int[heights.length]; 8 | 9 | // Copy the heights array 10 | for (int i = 0; i < heights.length; i++) 11 | expected[i] = heights[i]; 12 | 13 | // Sort the heights array 14 | Arrays.sort(expected); 15 | 16 | int count = 0; 17 | for (int j = 0; j < heights.length; j++) 18 | if (heights[j] != expected[j]) count++; 19 | 20 | return count; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def heightChecker(self, heights: list) -> int: 5 | return len([i for i in range(len(heights)) if heights[i] != sorted(heights)[i]]) 6 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker2.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public int heightChecker(int[] heights) { 5 | int total = 0; 6 | int clone[] = heights.clone(); 7 | Arrays.sort(clone); 8 | 9 | for (int i = 0; i < heights.length; i++){ 10 | if (heights[i] != clone[i]) { 11 | total++; 12 | } 13 | } 14 | return total; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def heightChecker(self, heights: list) -> int: 5 | return sum([heights[i] != sorted(heights)[i] for i in range(len(heights))]) 6 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1051._Height_Checker/HeightChecker3.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | import java.util.Arrays; 3 | 4 | class Solution { 5 | public int heightChecker(int[] heights) { 6 | int count = 0; 7 | int[] arr = new int[heights.length]; // Initialize expected array 8 | 9 | for (int e : heights){ 10 | arr[count] = e; 11 | count++; 12 | } 13 | 14 | count = 0; 15 | Arrays.sort(arr); // Sort the heights array 16 | 17 | for (int i = 0; i < heights.length; i++) { 18 | if (heights[i] != arr[i]) { 19 | count++; 20 | } 21 | } 22 | return count; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1089._Duplicate_Zeros/DuplicateZeros0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public void duplicateZeros(int[] arr) { 4 | // Number of elements in arr[] 5 | int n = arr.length; 6 | 7 | for (int j = 0; j < n-1; j++) { 8 | // Check if the element is 0 9 | if (arr[j] == 0) { 10 | // Move elements 1 place to the right 11 | for (int i = n-2; i >= j; i--) { 12 | arr[i + 1] = arr[i]; 13 | } 14 | arr[j+1] = 0; 15 | ++j; 16 | } 17 | } 18 | // return arr; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Problems/1001.-1100./1089._Duplicate_Zeros/DuplicateZeros0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def duplicateZeros(self, arr: list) -> None: 4 | """ 5 | Do not return anything, modify arr in-place instead. 6 | """ 7 | # Number of elements in arr 8 | n = len(arr); j = 0 9 | 10 | while (0 <= j < n-1): 11 | # Check if the element is 0 12 | if (arr[j] == 0): 13 | for i in range(n-2, j, -1): 14 | arr[i+1] = arr[i] 15 | # Insert 0 16 | arr[j+1] = 0 17 | j += 1 # Skip to the next element 18 | # Loop variable 19 | j += 1 20 | -------------------------------------------------------------------------------- /Problems/1101.-1200./1122._Relative_Sort_Array/RelativeSortArray0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 1122. Relative Sort Array 3 | 4 | class Solution: 5 | def relativeSortArray(self, arr1: list, arr2: list) -> list: 6 | arr3, arr4 = [], [] 7 | 8 | # Dynamic array to hold all elements that match those in arr2 9 | for j in range(0, len(arr2)): 10 | for i in range(0, len(arr1)): 11 | if (arr1[i] in arr2 and arr1[i] == arr2[j]): 12 | arr3.append(arr1[i]) 13 | # Capture elements that don't appear in arr2 14 | elif (j == 0 and arr1[i] not in arr2): 15 | arr4 += [arr1[i]] 16 | 17 | # Sort elements not in arr2 18 | arr4.sort(reverse = False) 19 | arr3.extend(arr4) 20 | return arr3 21 | -------------------------------------------------------------------------------- /Problems/1201.-1300./1207._Unique_Number_of_Occurences/UniqueNumberOfOccurences0.py: -------------------------------------------------------------------------------- 1 | # 1207. Unique Number of Occurences 2 | class Solution: 3 | def uniqueOccurrences(self, arr: List[int]) -> bool: 4 | dict_arr = {} 5 | 6 | for num in arr: 7 | dict_arr[num] = dict_arr.get(num, 0) + 1 8 | 9 | freqs, nums = [*set(dict_arr.values())], list(dict.keys(dict_arr)) 10 | 11 | return len(freqs) == len(nums) 12 | -------------------------------------------------------------------------------- /Problems/1201.-1300./1207._Unique_Number_of_Occurences/UniqueNumberOfOccurences1.py: -------------------------------------------------------------------------------- 1 | # 1207. Unique Number of Occurences 2 | from collections import Counter 3 | 4 | class Solution: 5 | def uniqueOccurrences(self, arr: list) -> bool: 6 | return len(set(Counter(arr).values())) == len(Counter(arr).keys()) 7 | -------------------------------------------------------------------------------- /Problems/1201.-1300./1299._Replace_Elements_with_Greatest_Element_on_Right_Side/ReplaceElementsWithGreatestElementOnRightSide0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | 3 | class Solution { 4 | public int[] replaceElements(int[] arr) { 5 | if (arr.length == 1) return new int[]{-1}; 6 | 7 | // Replace the last element with -1 8 | int temp = arr[arr.length-1]; 9 | arr[arr.length-1] = -1; 10 | 11 | // Replace the 2nd last elements with last element 12 | int maxVal = Math.max(temp,arr[arr.length-2]); 13 | arr[arr.length-2] = temp; 14 | 15 | // Continue with loop 16 | for (int i = arr.length-3; i >= 0; i--) { 17 | temp = arr[i]; 18 | arr[i] = maxVal; 19 | maxVal = Math.max(temp,maxVal); 20 | } 21 | return arr; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Problems/1201.-1300./1299._Replace_Elements_with_Greatest_Element_on_Right_Side/ReplaceElementsWithGreatestElementOnRightSide0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceElements(self, arr: List[int]) -> List[int]: 3 | n = len(arr) 4 | if (n == 1): return [-1] 5 | 6 | # Replace the last element with -1 7 | temp = arr[n-1]; arr[n-1] = -1 8 | 9 | # Replace the 2nd last element with the last one 10 | max_value = max(temp, arr[n-2]) 11 | arr[n-2] = temp 12 | 13 | # Continue with loop 14 | for i in range(n-3,-1,-1): 15 | temp = arr[i] 16 | arr[i] = max_value 17 | max_value = max(temp, max_value) 18 | return arr 19 | -------------------------------------------------------------------------------- /Problems/1301.-1400./1346._Check_If_N_and_Its_Double_Exist/CheckIfNandItsDoubleExist0.java: -------------------------------------------------------------------------------- 1 | //!/bin/java 2 | class Solution { 3 | public boolean checkIfExist(int[] arr) { 4 | boolean logic = false; 5 | for (int i = 0; i < arr.length-1; ++i) { 6 | for (int j = i+1; j < arr.length; ++j) { 7 | if (arr[i] == 2*arr[j] || arr[i]*2 == arr[j]) { 8 | logic = true; 9 | break; 10 | } 11 | } 12 | } 13 | return logic; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Problems/1301.-1400./1346._Check_If_N_and_Its_Double_Exist/CheckIfNandItsDoubleExist0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def checkIfExist(self, arr: List[int]) -> bool: 4 | ''' 5 | Check if there exists any 2 elements in arr, such 6 | that one is double the other 7 | ''' 8 | logic = False 9 | length = len(arr) 10 | for i in range(0,length-1): 11 | for j in range(i+1,length): 12 | if (arr[i] == 2*arr[j] or arr[i]*2 == arr[j]): 13 | logic = True 14 | return logic 15 | -------------------------------------------------------------------------------- /Problems/1301.-1400./1346._Check_If_N_and_Its_Double_Exist/CheckIfNandItsDoubleExist1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def checkIfExist(self, arr: List[int]) -> bool: 4 | seen = set() 5 | for i in range(len(arr)): 6 | # Check if element's Double is in arr 7 | if 2 * arr[i] in seen: 8 | return True 9 | # Check Double is even and exists 10 | elif arr[i] % 2 == 0 and arr[i] / 2 in seen: 11 | return True 12 | else: 13 | seen.add(arr[i]) 14 | return False 15 | -------------------------------------------------------------------------------- /Problems/1601.-1700./1636._Sort_Array_by_Increasing_Frequency/SortArrayByIncreasingFrequency0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 1636. Sort Array by Increasing Frequency 3 | 4 | class Solution: 5 | def frequencySort(self, nums: list[int]) -> list[int]: 6 | unique_nums = [*set(nums)] # Get unique numbers in nums 7 | lists = [] 8 | 9 | for num in unique_nums: # Store numbers & their frequencies as an ordered pair: (num, freq) 10 | lists += [(num, nums.count(num))] 11 | 12 | sorted_nums_with_freqs = sorted(lists, key = lambda x: (x[1], -x[0])) 13 | 14 | sorted_nums = list() 15 | 16 | for i, j in sorted_nums_with_freqs: 17 | sorted_nums.extend([i] * j) 18 | 19 | return sorted_nums 20 | -------------------------------------------------------------------------------- /Problems/1601.-1700./1636._Sort_Array_by_Increasing_Frequency/SortArrayByIncreasingFrequency1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import collections as clt 4 | 5 | class Solution(object): 6 | def frequencySort(self, nums: list[int]) -> list[int]: 7 | numFreqs = clt.Counter(nums) 8 | return sorted(nums, key = lambda x: (numFreqs[x], -x)) 9 | -------------------------------------------------------------------------------- /Problems/1701.-1800./1704._Determine_if_String_Halves_Are_Alike/AlikeStringHalves0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | firstHalf = s[:len(s)//2] 4 | secondHalf = s[len(s)//2:] 5 | return self.vowelCounter(firstHalf) == self.vowelCounter(secondHalf) 6 | 7 | def vowelCounter(self, s: str) -> int: 8 | dictVowels, countVowel = {}, 1 9 | vowels = ['a','e','i','o','u','A','E','I','O','U'] 10 | 11 | for i in range(len(s)): 12 | if s[i] in vowels: 13 | countVowel += 1 14 | return countVowel 15 | -------------------------------------------------------------------------------- /Problems/1701.-1800./1704._Determine_if_String_Halves_Are_Alike/AlikeStringHalves1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | vowels = "aeiouAEIOU" 4 | return sum(i in vowels for i in s[:len(s)//2]) == sum(j in vowels for j in s[len(s)//2:]) 5 | -------------------------------------------------------------------------------- /Problems/1701.-1800./1704._Determine_if_String_Halves_Are_Alike/AlikeStringHalves2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | s = s.lower() 4 | half = int(len(s)/2) 5 | left, right = s[0:half], s[half:len(s)] 6 | vowels = 'aeiouAEIOU' 7 | count_left, count_right = 0, 0 8 | 9 | for char1 in left: 10 | if char1 in vowels: 11 | count_left += 1 12 | 13 | for char2 in right: 14 | if char2 in vowels: 15 | count_right += 1 16 | 17 | return (True if (count_left == count_right) else False) 18 | -------------------------------------------------------------------------------- /Problems/1701.-1800./1704._Determine_if_String_Halves_Are_Alike/AlikeStringHalves3.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | return (len([i for i in s[:len(s)//2] if i in 'aeiouAEIOU']) == len([j for j in s[len(s)//2:] if j in 'aeiouAEIOU'])) 4 | -------------------------------------------------------------------------------- /Problems/1701.-1800./1779._Find_Nearest_Point_That_Has_The_Same_X_or_Y_coordinate/FindNearestPointThatHasTheSameXorYcoordinate0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | class Solution: 3 | def nearestValidPoint(self, x: int, y: int, points: list[list[int]]) -> int: 4 | valid_points = [point for point in points if point[0] == x or point[1] == y] 5 | manhattan_dist = lambda a: abs(x - a[0]) + abs(y - a[1]) 6 | all_valids = list(map(manhattan_dist, valid_points)) 7 | 8 | lst = [] 9 | for j in range(len(valid_points)): 10 | if all_valids[j] == min(all_valids): 11 | lst += [points.index(valid_points[j])] 12 | return min(lst) if lst else -1 13 | -------------------------------------------------------------------------------- /Problems/1801.-1900./1833._Maximum_Ice_Cream_Bars/MaximumIceCreamBars0.py: -------------------------------------------------------------------------------- 1 | # 1833. Maximum Ice Cream Bars 2 | 3 | class Solution: 4 | def maxIceCream(self, costs: List[int], coins: int) -> int: 5 | costs = sorted(costs) 6 | n, ice_cream = len(costs), 0 7 | 8 | while (ice_cream < n and costs[ice_cream] <= coins): 9 | coins -= costs[ice_cream] 10 | ice_cream += 1 11 | return ice_cream 12 | -------------------------------------------------------------------------------- /Problems/2101.-2200./2125._Number_of_Laser_Beams_in_a_Bank/NumberOfLaserBeamsInABank0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def numberOfBeams(self, bank: List[str]) -> int: 5 | bank_floor = list(map(self.countOne, bank)) 6 | sec_devices = self.removeZeros(bank_floor) 7 | 8 | laser_beam = 0 9 | if len(sec_devices) == 1: 10 | return laser_beam 11 | else: 12 | for i in range(0, len(sec_devices)-1): 13 | laser_beam += (sec_devices[i]*sec_devices[i+1]) 14 | return laser_beam 15 | 16 | # Remove rows with no security device 17 | def removeZeros(self, list_num: list) -> list: 18 | while 0 in list_num: 19 | list_num.remove(0) 20 | return list_num 21 | 22 | # Number of security devices 23 | def countOne(self, bin_string: str) -> int: 24 | return sum([1 for _ in bin_string if _ == "1"]) 25 | -------------------------------------------------------------------------------- /Problems/2101.-2200./2125._Number_of_Laser_Beams_in_a_Bank/NumberOfLaserBeamsInABank1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def numberOfBeams(self, bank: List[str]) -> int: 5 | bank_floor, total_lasers = [], 0 6 | 7 | for cell in bank: 8 | num_devices = cell.count("1") 9 | if (num_devices > 0): 10 | bank_floor += [num_devices] 11 | 12 | for i in range(len(bank_floor)-1): 13 | total_lasers += bank_floor[i]*bank_floor[i+1] 14 | return total_lasers 15 | -------------------------------------------------------------------------------- /Problems/2101.-2200./2125._Number_of_Laser_Beams_in_a_Bank/NumberOfLaserBeamsInABank2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def numberOfBeams(self, bank: List[str]) -> int: 5 | bank_floor = list() 6 | 7 | for cell in bank: 8 | num_devices = cell.count("1") 9 | if num_devices != 0: 10 | bank_floor.append(num_devices) 11 | 12 | i, laser_beams = 0, 0 13 | while (i < len(bank_floor)-1): 14 | laser_beams += bank_floor[i]*bank_floor[i+1] 15 | i += 1 16 | return laser_beams 17 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2225._Find_Players_With_Zero_or_One_Losses/FindPlayersWithZeroOrOneLosses0.py: -------------------------------------------------------------------------------- 1 | # 2225. Find Players With Zero or One Losses 2 | 3 | class Solution: 4 | def findWinners(self, matches: list) -> list: 5 | losses = dict() 6 | 7 | for match in matches: 8 | winner, loser = match 9 | 10 | losses[winner] = losses.get(winner, 0) + 0 11 | 12 | losses[loser] = losses.get(loser, 0) + 1 13 | 14 | no_losers, losers_of_1 = [], list() 15 | 16 | for players in list(losses.items()): 17 | if (losses[players[0]] == 0): # if a player hasn't LOST any matches 18 | no_losers += [players[0]] 19 | elif (losses[players[0]] == 1): # if a player has lost ONE match 20 | losers_of_1.append(players[0]) 21 | 22 | return [sorted(no_losers), sorted(losers_of_1)] 23 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers0.java: -------------------------------------------------------------------------------- 1 | //#!/bin/java 2 | 3 | class Solution { 4 | public int sum(int num1, int num2) { 5 | return num1 + num2; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers0.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sum(self, num1: int, num2: int) -> int: 3 | return num1 + num2 4 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sum(self, num1: int, num2: int) -> int: 3 | return list(accumulate([num1, num2], lambda a, b: a + b))[-1] 4 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers2.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | class Solution: 4 | def sum(self, num1: int, num2: int) -> int: 5 | return operator.add(num1, num2) 6 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers3.py: -------------------------------------------------------------------------------- 1 | import operator 2 | from itertools import accumulate 3 | 4 | class Solution: 5 | def sum(self, num1: int, num2: int) -> int: 6 | return list(accumulate([num1, num2], operator.add))[-1] 7 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers4.py: -------------------------------------------------------------------------------- 1 | import operator 2 | from functools import reduce 3 | 4 | class Solution: 5 | def sum(self, num1: int, num2: int) -> int: 6 | return reduce(operator.add, [num1, num2]) 7 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers5.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | class Solution: 4 | def sum(self, num1: int, num2: int) -> int: 5 | return reduce(lambda a, b: a + b, [num1, num2]) 6 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers6.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sum(self, num1: int, num2: int) -> int: 3 | return sum((num1, num2)) 4 | -------------------------------------------------------------------------------- /Problems/2201.-2300./2235._Add_Two_Integers/Add2Integers7.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | sum = add 3 | -------------------------------------------------------------------------------- /Problems/2401.-2500./2418._Sort_the_People/SortThePeople0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 2418. Sort the people 3 | 4 | class Solution: 5 | def sortPeople(self, names: list[str], heights: list[int]) -> list[str]: 6 | names_heights = [(i, j) for i, j in zip(names, heights)] 7 | sorted_names_heights = sorted(names_heights, key = lambda x: x[1], reverse = True) 8 | return [name for name, _ in sorted_names_heights] 9 | -------------------------------------------------------------------------------- /Problems/2401.-2500./2418._Sort_the_People/SortThePeople1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution(object): 4 | def sortPeople(self, names: list[str], heights: list[int]) -> list[str]: 5 | n = len(names) 6 | namesHeights = list() 7 | for i in range(0, n): 8 | namesHeights += [(names[i], heights[i])] 9 | 10 | for j in range(n-1): 11 | for k in range(j+1,n): 12 | if (namesHeights[k][1] > namesHeights[j][1]): # Check for heights 13 | namesHeights[k], namesHeights[j] = namesHeights[j], namesHeights[k] # swap name & height pairs 14 | 15 | descendingHeights = [person[0] for person in namesHeights] 16 | return descendingHeights 17 | -------------------------------------------------------------------------------- /Problems/2401.-2500./2418._Sort_the_People/SortThePeople2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def sortPeople(self, names: list[str], heights: list[int]) -> list[str]: 5 | return [n for n, h in sorted(zip(names, heights), key = lambda a: a[1])][::-1] 6 | -------------------------------------------------------------------------------- /Problems/2601.-2700./2610._Convert_an_Array_Into_a_2D_Array_With_Conditions/Convert1DArrayTo2DArrayWithConds0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def findMatrix(self, nums: list) -> list: 5 | main_list = list() 6 | 7 | # Dictionary to count the frequency of each number 8 | freqs = {} 9 | 10 | for num in nums: 11 | if num not in freqs: # freqs[num] = freqs.get(num, 0) + 1 12 | freqs[num] = 1 13 | else: 14 | freqs[num] += 1 15 | # The number with the most occurences is the number of rows 16 | # in the 2D array (run a loop that many times) 17 | m = max(freqs.values()) 18 | 19 | for _ in range(m): 20 | sub_list = []; i = 0 21 | while (i < len(nums)): 22 | if nums[i] not in sub_list: 23 | sub_list += [nums[i]] # append 24 | del nums[i] 25 | else: # if the number is in the sublist (move forward) 26 | i += 1 27 | main_list.append(sub_list) 28 | return main_list 29 | -------------------------------------------------------------------------------- /Problems/2801.-2900./2870._Minimum_Number_of_Operations_to_Make_Array_Empty/MinNumberOfOperationsToMakeArrayEmpty0.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | class Solution: 4 | def minOperations(self, nums: List[int]) -> int: 5 | # Store the frequencies of the numbers 6 | freqs = dict() 7 | 8 | for num in nums: 9 | freqs[num] = freqs.get(num,0) + 1 10 | 11 | if list(freqs.values()).__contains__(1): 12 | return -1 13 | else: # Hashmap does not have any 1s 14 | min_ops = 0 15 | for i in list(freqs.values()): 16 | if i % 3 == 0: # multiple of 3 17 | min_ops += (i // 3) 18 | elif i % 3 == 1: # remainder of 1 19 | min_ops += math.ceil(i / 3) 20 | elif i % 3 == 2: # remainder of 2 21 | min_ops += ((i+1)//3) 22 | return min_ops 23 | -------------------------------------------------------------------------------- /Problems/2801.-2900./2870._Minimum_Number_of_Operations_to_Make_Array_Empty/MinNumberOfOperationsToMakeArrayEmpty1.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import math 3 | from collections import Counter 4 | 5 | class Solution: 6 | def minOperations(self, nums: List[int]) -> int: 7 | num_count, ops = Counter(nums), 0 8 | 9 | for val in num_count.values(): 10 | if (val == 1): 11 | return -1 12 | else: 13 | ops += math.ceil(val / 3) 14 | return ops 15 | -------------------------------------------------------------------------------- /Problems/2901.-3000./2966._Divide_Array_Into_Arrays_With_Max_Difference/DivideArrayIntoArraysWithMaxDiff0.py: -------------------------------------------------------------------------------- 1 | # 2966. Divide Array Into Arrays With Max Difference 2 | 3 | class Solution: 4 | def divideArray(self, nums: list, k: int) -> list: 5 | n = len(nums) # array size 6 | nums.sort(reverse=False) # Sort the array 7 | arr, i = [], 0 8 | 9 | while (i <= n - 3): 10 | sub_arr = [] 11 | if ((nums[i+1] - nums[i]) <= k) and ((nums[i+2] - nums[i]) <= k): 12 | sub_arr += [nums[i], nums[i+1], nums[i+2]] 13 | arr.append(sub_arr) 14 | i += 3 15 | else: 16 | i += 1 17 | 18 | # Check that output array has a length: n/3 19 | if (n > len(arr)*3): 20 | return [] 21 | else: 22 | return arr 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | - Solutions to programming challenges covering Data Strucutures & Algorithms, Databases, and Problem-solving overall using 3 | Python, Java, C++, JavaScript, and Shell. 4 | 5 | https://leetcode.com/problemset/ 6 | -------------------------------------------------------------------------------- /echo.sh: -------------------------------------------------------------------------------- 1 | echo HELLO 2 | --------------------------------------------------------------------------------