├── README.md ├── Python_ ├── LinkedList │ └── single_linked_list │ │ ├── __pycache__ │ │ └── linked_list.cpython-38.pyc │ │ └── merge_to_list.py ├── 1_Recursion │ ├── recursion.py │ ├── fibonacci_numbers.py │ ├── l1_intro.py │ ├── interview_question2.py │ ├── interview_question1.py │ ├── interview_question4.py │ ├── interview_question3.py │ ├── l2.py │ └── palindrome_partitioning.py ├── DataStructure │ ├── sprialMatrix_2.py │ ├── addStrings.py │ ├── containsDuplicates.py │ ├── firstUniqueCharacterInaString.py │ ├── subarryaSumEqualsK.py │ ├── PascalTriangle.py │ ├── maximunSubarray.py │ ├── isSubsequence.py │ ├── pascalsTriangle_2.py │ ├── topKFrequentElements.py │ ├── lognestPalindrome.py │ ├── findTheDifference.py │ ├── productOfArrayExceptSelf.py │ ├── twoSum.py │ ├── singleNumber.py │ ├── validParentheses.py │ ├── incresingTripletSubsequence.py │ ├── wordPattern.py │ ├── symmetricTree.py │ ├── invertBinaryTree.py │ ├── majorityElement.py │ ├── partitionLabels.py │ ├── consturctBinaryTreeFromPreorderAndInorderTraversal.py │ ├── nonOverlappingIntervals.py │ ├── threeSum.py │ ├── MaximunDepthOfBinaryTree.py │ ├── RansomNote.py │ ├── binaryTreeLevelOrderTravesal.py │ ├── groupAnagrams.py │ ├── sortColors.py │ ├── ValidateBinarySearchTree.py │ ├── treeTraversal.py │ ├── kClosestPointsToOrigin.py │ ├── minimumRemoveToMakeValidParentheses.py │ ├── sortCharactersByFrequency.py │ ├── minStack.py │ ├── reverseLinkedList.py │ └── convertSortedArrayToBinarySearchTree.py ├── pattern_ │ ├── containsDuplicate.py │ ├── single_numbers.py │ ├── max_depth_bt.py │ ├── missing_number.py │ ├── min_depthBT.py │ ├── diameter_of_bt.py │ └── avg_of_levels.py ├── Questions │ ├── subSet.py │ ├── reverseWordsInAstring.py │ ├── complemetOfBase10Integer.py │ ├── reverseString.py │ ├── subSet(II).py │ ├── AddDigits.py │ ├── ClimbingStairs.py │ ├── twoSum.py │ ├── combinations.py │ ├── searchInsertPosition.py │ ├── validParentheses.py │ ├── longestPalindromicSubstring.py │ ├── stack │ │ ├── validParenthesis.py │ │ └── largestRectangleInHistogram.py │ ├── rotate_matrix.py │ ├── AllPathsFromSourceToTarget.py │ ├── jumpGame2.py │ ├── backspaceStringCompare.py │ ├── binarySearch.py │ ├── easy │ │ ├── maximunSubarray.py │ │ └── validAnagram.py │ ├── longestIncreasingSubsequence.py │ ├── squareOfSortedArray.py │ ├── 01Matrix.py │ ├── lognestSubstringWithoutRepeatingCharacters.py │ ├── rotateArray.py │ ├── 3Sum.py │ ├── mergeTwoSortedList.py │ ├── premutationInString.py │ ├── findPeakElement.py │ ├── letterCombinationsOfAPhoneNumber.py │ ├── bestTimeToBuyAndSellStock.py │ ├── happyNumber.py │ ├── moveZeros.py │ ├── Permutations_second.py │ ├── contiguousArray.py │ ├── houseRobber2.py │ ├── NumberOfProvinces.py │ ├── findMinimunInRotatedSortedArray.py │ ├── numberOfIslands.py │ ├── searchInRotatedSortedArray.py │ ├── populatingNextRightPointersInEachNode.py │ └── CombinationSum.py ├── qus │ ├── duplicateFind.py │ ├── bubble_sort.py │ ├── topKFrequentElemets.py │ ├── selection_sort.py │ ├── groupAnagrams.py │ ├── validParentheses.py │ ├── lognestSubStringWithoutRepeatingCharacters.py │ ├── binarySearch.py │ ├── searcha2Dmatrix.py │ ├── constructBinaryTreeFromPreAndInorderTree.py │ ├── invertBinaryTree.py │ ├── bestTimeTobuyAndSell.py │ ├── containerWithMostWater.py │ ├── 3sum.py │ ├── binaryTreeLevelOrderTraversal.py │ ├── validateBinarySearchTree.py │ ├── heightBalanceTree.py │ ├── numberOfIslands.py │ ├── kthSmallestElementinABSt.py │ ├── subtreeOfAnotherTree.py │ ├── uniquePath.py │ └── searchInRoatedSortedArray.py ├── blind75 │ ├── 3_longestPalindromicSubString.py │ ├── 1_twosum.py │ ├── 2_longestSubstringWithRepeatingCharacters.py │ ├── 7_validParentheses.py │ ├── 11_maximumSubarray.py │ ├── 10_mergeIntervals.py │ ├── 4_containerWithMostWater.py │ ├── 13_maximumDepthofBinaryTree.py │ ├── 12_binaryTreeLevelOrderTraversal.py │ ├── 8_3sum.py │ ├── 14_bestTimeToBuyAndSellStock.py │ └── 15_numberOfIslands.py ├── sorting │ ├── bubble_sort.py │ └── selection_sort.py ├── leetCode75 │ ├── runningSumof1dArray.py │ ├── subSequence.py │ ├── isomorphic_strings.py │ ├── merge_two_llist.py │ └── findPivotIndex.py ├── dp │ ├── riverSize.py │ ├── climbingStairs.py │ ├── palindromicSubstrings.py │ ├── coinChange.py │ ├── grid_uniquePath.py │ ├── lognestPalindromicSubstring.py │ ├── 2houseRobber.py │ └── sneakThroughGrid.py ├── Binary_tree │ └── bfs.py ├── stack │ ├── validParenthesis.py │ ├── GenerateParentheses.py │ ├── stackPythonList_withoutLimt.py │ ├── largestRectangleInHistogram.py │ ├── linkedlistStack.py │ └── stackPythonList_withlimit.py ├── Graphs │ ├── makeGraph.py │ ├── 01Matix.py │ ├── basic.py │ ├── numbersOfProvinces.py │ ├── numberOfIslands.py │ ├── minimunJumpsToReachHome.py │ └── numberOfOperationsToMakeNetworkConnected.py └── stacks │ ├── stackPythonList_withoutLimt.py │ ├── linkedlistStack.py │ └── stackPythonList_withlimit.py ├── Go └── Basics │ ├── if-else-if.go │ ├── loops.go │ └── functions.go ├── hackerRank ├── mini-max-sum.py └── diagonalDifference.py ├── JavaScript_ ├── Graphs │ ├── largestComponent.js │ ├── hasPath.js │ └── makeGraph.js ├── Questions │ ├── container_with_most.js │ └── reverseLinkedList.js ├── Dynamic Programming │ ├── tabulationFib.js │ ├── waysToGetSum.js │ ├── tableHowSum.js │ ├── palindromicSubstrings.js │ ├── 01_first.js │ ├── tableCunSum.js │ ├── gridTraveler.js │ ├── allConstruct.js │ ├── tableCanConstruct.js │ └── countConstruct.js └── BinaryTree │ ├── bfs.js │ └── dfs.js ├── .github └── workflows │ └── python-app.yml └── noOfIsland.py /README.md: -------------------------------------------------------------------------------- 1 | # Coding-Interview-Preparation 2 | 3 | - Important Data Struture Question for coding interviews 4 | - Practice Questions 5 | - Brief explanation 6 | - important question.. 7 | -------------------------------------------------------------------------------- /Python_/LinkedList/single_linked_list/__pycache__/linked_list.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamhimanshu0/Coding-Interview-Preparation/HEAD/Python_/LinkedList/single_linked_list/__pycache__/linked_list.cpython-38.pyc -------------------------------------------------------------------------------- /Python_/1_Recursion/recursion.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | assert n >= 0 and int(n) == n, "The number must be positve integer only!" 3 | if n == 0 or n == 1: 4 | return 1 5 | return n * factorial(n-1) 6 | 7 | 8 | print(factorial(5)) 9 | -------------------------------------------------------------------------------- /Go/Basics/if-else-if.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func ifWithAssignment() { 6 | if num := 10; num%2 == 0 { 7 | fmt.Println("Number is even") 8 | } else { 9 | fmt.Println("Number is odd") 10 | } 11 | } 12 | 13 | func main() { 14 | ifWithAssignment() 15 | } 16 | -------------------------------------------------------------------------------- /Python_/1_Recursion/fibonacci_numbers.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def fibonacci(n): 4 | assert n >= 0 and int(n) == n, "Should be an integer number!" 5 | if n == 0 or n == 1: 6 | return n 7 | else: 8 | return fibonacci(n-1) + fibonacci(n-2) 9 | 10 | 11 | print(fibonacci(7)) 12 | -------------------------------------------------------------------------------- /hackerRank/mini-max-sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | # hackerrank.com/challenges/mini-max-sum/problem?isFullScreen=true 3 | """ 4 | 5 | arr = [1,3,5,7,9] 6 | 7 | def minMaxSum(arr): 8 | arr.sort() 9 | minSum = sum(arr[:-1]) 10 | maxSum = sum(arr[1:]) 11 | 12 | print(minSum, maxSum) 13 | 14 | print( 15 | minMaxSum(arr) 16 | ) 17 | -------------------------------------------------------------------------------- /JavaScript_/Graphs/largestComponent.js: -------------------------------------------------------------------------------- 1 | /* 2 | 5 3 | | \ 4 | 1 -> 0 -> 8 5 | 6 | 4 -> 2 7 | \/ 8 | 3 9 | 10 | */ 11 | 12 | const graph1 = { 13 | 0 : [8,1,5], 14 | 1 : [0], 15 | 5 : [0,8], 16 | 8 : [0,5], 17 | 2 : [3,4], 18 | 3 : [2,4], 19 | 4 : [3,2] 20 | } 21 | 22 | const largest = (graph) =>{ 23 | // first traversal and get component 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Python_/DataStructure/sprialMatrix_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/spiral-matrix-ii/ 3 | 4 | Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. 5 | 6 | Input: n = 3 7 | Output: [[1,2,3],[8,9,4],[7,6,5]] 8 | 9 | Input: n = 1 10 | Output: [[1]] 11 | """ 12 | 13 | n = 3 14 | 15 | def generateMatrix(n): 16 | return n 17 | 18 | print( 19 | generateMatrix(n) 20 | ) -------------------------------------------------------------------------------- /JavaScript_/Questions/container_with_most.js: -------------------------------------------------------------------------------- 1 | var maxArea = function (height) { 2 | var left = 0; 3 | var right = height.length - 1; 4 | var res = 0; 5 | var ans = 0; 6 | 7 | while (left < right) { 8 | ans = (right - left) * Math.min(height[left], height[right]); 9 | res = Math.max(res, ans); 10 | 11 | if (height[left] < height[right]) { 12 | left++; 13 | } else { 14 | right--; 15 | } 16 | } 17 | return res; 18 | }; 19 | 20 | height = [1, 8, 6, 2, 5, 4, 8, 3, 7]; 21 | console.log(maxArea(height)); 22 | -------------------------------------------------------------------------------- /Python_/1_Recursion/l1_intro.py: -------------------------------------------------------------------------------- 1 | 2 | def print_n_time(n): 3 | if n <= 0: 4 | return 5 | print_n_time(n-1) 6 | print(n) 7 | 8 | def sum_of_first_n(n,value=0): 9 | if n <= 0: 10 | return value 11 | return sum_of_first_n(n-1,n+value) 12 | 13 | def fact_of_number(n): 14 | if n==1: 15 | return 1 16 | return n * fact_of_number(n-1) 17 | 18 | # 1,1,2,3,5,8 19 | def fibonacci(n): 20 | if n ==1 or n==2: 21 | return 1 22 | return fibonacci(n-1) + fibonacci(n-2) 23 | 24 | print( 25 | fibonacci(6) 26 | ) 27 | 28 | -------------------------------------------------------------------------------- /Python_/1_Recursion/interview_question2.py: -------------------------------------------------------------------------------- 1 | # How to calculate power of a number using recursion? 2 | 3 | # Step 1 : Recursive Case - the flow 4 | # x^n = n * x^n-1 5 | 6 | # Step 2 : Base case - the stopping criterion 7 | 8 | # Step 3 : Unintentional case - the constraint 9 | 10 | 11 | def powerOfNumber(number, power): 12 | assert power >= 0 and int(power) == power "Please add only positive number for Power" 13 | if power == 0: 14 | return 1 15 | if power == 1: 16 | return number 17 | else: 18 | return number * powerOfNumber(number, power-1) 19 | 20 | print(powerOfNumber(3,1)) -------------------------------------------------------------------------------- /Python_/pattern_/containsDuplicate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 3 | 4 | Input: nums = [1,2,3,1] 5 | Output: true 6 | 7 | Input: nums = [1,2,3,4] 8 | Output: false 9 | 10 | Input: nums = [1,1,1,3,3,4,3,2,4,2] 11 | Output: true 12 | """ 13 | 14 | 15 | def duplicated(nums): 16 | nums.sort() 17 | 18 | for i in range(len(nums)-1): 19 | if nums[i] == nums[i+1]: 20 | return True 21 | return False 22 | 23 | 24 | print( 25 | duplicated([1,1,1,3,3,4,3,2,4,2]) 26 | ) 27 | -------------------------------------------------------------------------------- /Python_/Questions/subSet.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums of unique elements, return all possible subsets (the power set). 3 | 4 | The solution set must not contain duplicate subsets. Return the solution in any order. 5 | 6 | Input: nums = [1,2,3] 7 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 8 | 9 | Input: nums = [0] 10 | Output: [[],[0]] 11 | """ 12 | 13 | nums = [1,2,3] 14 | 15 | def subsets(nums): 16 | n = len(nums) 17 | output = [[]] 18 | 19 | for num in nums: 20 | output += [curr + [num] for curr in output] 21 | 22 | return output 23 | 24 | 25 | print( 26 | subsets(nums) 27 | ) -------------------------------------------------------------------------------- /Python_/Questions/reverseWordsInAstring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 3 | 4 | Input: s = "Let's take LeetCode contest" 5 | Output: "s'teL ekat edoCteeL tsetnoc" 6 | 7 | Input: s = "God Ding" 8 | Output: "doG gniD" 9 | 10 | # https://leetcode.com/problems/reverse-words-in-a-string-iii/ 11 | """ 12 | 13 | s = "Let's take LeetCode contest" 14 | 15 | def reverseWords(s): 16 | new = "" 17 | for i in s.split(" "): 18 | new+=i[::-1]+" " 19 | 20 | return new.rstrip() 21 | print(reverseWords(s)) -------------------------------------------------------------------------------- /Python_/qus/duplicateFind.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 3 | 4 | There is only one repeated number in nums, return this repeated number. 5 | 6 | You must solve the problem without modifying the array nums and uses only constant extra space. 7 | 8 | Input: nums = [1,3,4,2,2] 9 | Output: 2 10 | 11 | Input: nums = [3,1,3,4,2] 12 | Output: 3 13 | """ 14 | 15 | nums = [1,3,4,2,2] 16 | 17 | def duplicate(nums): 18 | check = {} 19 | for i in nums: 20 | if i in check: 21 | return i 22 | else: 23 | check[i] = 1 24 | 25 | print(duplicate(nums)) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/tabulationFib.js: -------------------------------------------------------------------------------- 1 | /* 2 | write a function that takes in a number as an argument, the function should return the n-th number of the Fibonacci sequence. 3 | 4 | The 0th number of the sequence is 0 5 | The 1th number of the sequence is 1 6 | 7 | */ 8 | 9 | // TC :- O(N) 10 | // SC :- O(N) 11 | const tabluationFib = (n) => { 12 | let dp = Array(n + 1).fill(0); 13 | dp[1] = 1; 14 | for (let i = 2; i <= n; i++) { 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | } 17 | 18 | return dp[n]; 19 | }; 20 | 21 | console.log(tabluationFib(5)); 22 | console.log(tabluationFib(7)); 23 | console.log(tabluationFib(8)); 24 | console.log(tabluationFib(50)); 25 | -------------------------------------------------------------------------------- /JavaScript_/Graphs/hasPath.js: -------------------------------------------------------------------------------- 1 | // if path is exist between src node and destination node 2 | 3 | const hasPath = (graph, src, dst) => { 4 | const stack = [src] 5 | 6 | while(stack.length > 0){ 7 | const current = stack.pop(); 8 | 9 | console.log(current) 10 | for(let neighbor of graph[current]){ 11 | stack.push(neighbor) 12 | } 13 | } 14 | 15 | }; 16 | 17 | const graph = { 18 | f : ["g","i"], 19 | g : ["h"], 20 | h : [], 21 | i : ["g", "k"], 22 | j : ["i"], 23 | k : [] 24 | }; 25 | 26 | /* 27 | f > g > h 28 | | / 29 | i > j 30 | | 31 | k 32 | */ 33 | 34 | console.log(hasPath(graph, "f", "j")) 35 | -------------------------------------------------------------------------------- /Python_/DataStructure/addStrings.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/add-strings/ 3 | 4 | Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. 5 | 6 | You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. 7 | 8 | Input: num1 = "11", num2 = "123" 9 | Output: "134" 10 | 11 | Input: num1 = "456", num2 = "77" 12 | Output: "533" 13 | 14 | Input: num1 = "0", num2 = "0" 15 | Output: "0" 16 | """ 17 | num1 = "11"; num2 = "123" 18 | 19 | def addStrings(num1, num2): 20 | return str(int(num1)+int(num2)) 21 | 22 | 23 | print(addStrings(num1, num2)) -------------------------------------------------------------------------------- /Python_/DataStructure/containsDuplicates.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/contains-duplicate/ 3 | 4 | Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 5 | 6 | Input: nums = [1,2,3,1] 7 | Output: true 8 | 9 | Input: nums = [1,2,3,4] 10 | Output: false 11 | 12 | Input: nums = [1,1,1,3,3,4,3,2,4,2] 13 | Output: true 14 | 15 | """ 16 | 17 | nums = [1,2,3,1] 18 | 19 | def containsDuplicate(nums): 20 | check = {} 21 | for n in range(len(nums)): 22 | if nums[n] in check: 23 | return True 24 | else: 25 | check[nums[n]] = 1 26 | 27 | return False 28 | 29 | print(containsDuplicate(nums)) -------------------------------------------------------------------------------- /Python_/DataStructure/firstUniqueCharacterInaString.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/first-unique-character-in-a-string/ 3 | 4 | Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. 5 | 6 | Input: s = "leetcode" 7 | Output: 0 8 | 9 | Input: s = "loveleetcode" 10 | Output: 2 11 | 12 | Input: s = "aabb" 13 | Output: -1 14 | 15 | """ 16 | import collections 17 | 18 | 19 | s = "loveleetcode" 20 | 21 | def firstUniqChar(s): 22 | count = collections.Counter(s) 23 | 24 | # find the index 25 | for idx, ch in enumerate(s): 26 | if count[ch] == 1: 27 | return idx 28 | return -1 29 | 30 | print( 31 | firstUniqChar(s) 32 | ) 33 | -------------------------------------------------------------------------------- /Python_/Questions/complemetOfBase10Integer.py: -------------------------------------------------------------------------------- 1 | """ 2 | The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. 3 | 4 | For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. 5 | Given an integer n, return its complement. 6 | 7 | Input: n = 5 8 | Output: 2 9 | Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. 10 | 11 | Input: n = 7 12 | Output: 0 13 | Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. 14 | """ 15 | 16 | n = 5 17 | 18 | def changeBin(n): 19 | return bin(n)[2:] 20 | 21 | 22 | print( 23 | int(changeBin(n)).reverse() 24 | ) -------------------------------------------------------------------------------- /Python_/1_Recursion/interview_question1.py: -------------------------------------------------------------------------------- 1 | # How to find the sum of digits of a positive integer number using recursion? 2 | 3 | # Step 1 : Recursive Case - the flow 4 | 5 | # 10 10/10 = 1 and Remainder = 0 6 | # 54 54/10 = 5 and Remainder = 4 7 | 8 | # 112 112/10 = 11 and Remainder = 2 9 | # 11 11/10 = 1 and Remainder = 1 10 | 11 | # idea = f(n) = n%10 + f(n/10) 12 | 13 | # Step 2 : Base case - the stopping criterion 14 | 15 | # Step 3 : Unintentional case - the constraint 16 | 17 | 18 | def sumOfDigites(n): 19 | assert n >= 0 and int(n) == n, "Enter Positive Number Please!" 20 | if n == 0: 21 | return 0 22 | else: 23 | return int(n % 10) + sumOfDigites(int(n/10)) 24 | 25 | 26 | print(sumOfDigites(23)) 27 | -------------------------------------------------------------------------------- /Python_/DataStructure/subarryaSumEqualsK.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/subarray-sum-equals-k/ 3 | 4 | Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 5 | 6 | Input: nums = [1,1,1], k = 2 7 | Output: 2 8 | 9 | Input: nums = [1,2,3], k = 3 10 | Output: 2 11 | 12 | """ 13 | 14 | nums = [1,1,1]; k = 2 15 | 16 | def subarraySum(nums,k): 17 | ans, n = 0, len(nums) 18 | preSum = [nums[0]] 19 | dic = {} 20 | dic[0] = 1 21 | for i in nums[1:]: 22 | preSum.append(i+preSum[-1]) 23 | for i in preSum: 24 | if i-k in dic: 25 | ans+=dic[i-k] 26 | dic[i] = dic.get(i,0) + 1 27 | return ans 28 | 29 | 30 | print(subarraySum(nums,k)) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/waysToGetSum.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given 3 numbers {1, 3, 5}, we need to tell 3 | the total number of ways we can form a number 'N' 4 | using the sum of the given three numbers. 5 | */ 6 | 7 | // brute force 8 | // const getSum = (number) => { 9 | // if (number < 0) return 0; 10 | // if (number == 0) return 1; 11 | 12 | // return getSum(number - 1) + getSum(number - 3) + getSum(number - 5); 13 | // }; 14 | 15 | // memo 16 | const getSum = (number, memo = {}) => { 17 | if (number in memo) return memo[number]; 18 | if (number < 0) return 0; 19 | if (number == 0) return 1; 20 | 21 | memo[number] = getSum(number - 1) + getSum(number - 3) + getSum(number - 5); 22 | return memo[number]; 23 | }; 24 | 25 | console.log(getSum(40)); 26 | -------------------------------------------------------------------------------- /Python_/DataStructure/PascalTriangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/pascals-triangle/ 3 | 4 | Given an integer numRows, return the first numRows of Pascal's triangle. 5 | 6 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 7 | 8 | Input: numRows = 5 9 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 10 | 11 | Input: numRows = 1 12 | Output: [[1]] 13 | """ 14 | numRows = 5 15 | 16 | def generate(numRows): 17 | res = [[1]] 18 | 19 | for i in range(numRows-1): 20 | temp = [0] + res[-1] + [0] 21 | row = [] 22 | for j in range(len(res[-1])+1): 23 | row.append(temp[j]+ temp[j+1]) 24 | 25 | res.append(row) 26 | return res 27 | 28 | print(generate(numRows)) -------------------------------------------------------------------------------- /Python_/DataStructure/maximunSubarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | A subarray is a contiguous part of an array. 5 | 6 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 7 | Output: 6 8 | Explanation: [4,-1,2,1] has the largest sum = 6. 9 | 10 | Input: nums = [1] 11 | Output: 1 12 | 13 | Input: nums = [5,4,-1,7,8] 14 | Output: 23 15 | """ 16 | 17 | nums = [-2,1,-3,4,-1,2,1,-5,4] 18 | 19 | def maxSubArray(nums): 20 | 21 | curSum, largestSum = 0, nums[0] 22 | 23 | for c in nums: 24 | curSum = max(c, curSum+c) 25 | largestSum = max(largestSum, curSum) 26 | 27 | return largestSum 28 | 29 | print( 30 | maxSubArray(nums) 31 | ) -------------------------------------------------------------------------------- /Python_/Questions/reverseString.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that reverses a string. The input string is given as an array of characters s. 3 | 4 | You must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | Input: s = ["h","e","l","l","o"] 7 | Output: ["o","l","l","e","h"] 8 | 9 | Input: s = ["H","a","n","n","a","h"] 10 | Output: ["h","a","n","n","a","H"] 11 | 12 | # https://leetcode.com/problems/reverse-string/ 13 | """ 14 | 15 | # s = ["H","a","n","n","a","h"] 16 | s = ["h","e","l","l","o"] 17 | 18 | 19 | def reverseString(s): 20 | # return s[::-1] 21 | l , r = 0, len(s)-1 22 | 23 | while l <= r: 24 | s[l], s[r] = s[r], s[l] 25 | l,r = l+1, r-1 26 | return s 27 | 28 | print(reverseString(s)) -------------------------------------------------------------------------------- /Python_/DataStructure/isSubsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s and t, return true if s is a subsequence of t, or false otherwise. 3 | 4 | A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). 5 | 6 | Input: s = "abc", t = "ahbgdc" 7 | Output: true 8 | 9 | Input: s = "axc", t = "ahbgdc" 10 | Output: false 11 | """ 12 | 13 | s = "abc"; t = "ahbgdc" 14 | 15 | def isSubsequence(s, t): 16 | remainder_of_t = iter(t) 17 | for letter in s: 18 | if letter not in remainder_of_t: 19 | return False 20 | return True 21 | 22 | 23 | print(isSubsequence(s,t)) -------------------------------------------------------------------------------- /Python_/blind75/3_longestPalindromicSubString.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, return the longest palindromic substring in s. 3 | 4 | Input: s = "babad" 5 | Output: "bab" 6 | Explanation: "aba" is also a valid answer. 7 | 8 | Input: s = "cbbd" 9 | Output: "bb" 10 | """ 11 | 12 | 13 | def longestPalindrome(self, s): 14 | self.maxlen = 0 15 | self.start = 0 16 | 17 | for i in range(len(s)): 18 | self.expandFromCenter(s,i,i) 19 | self.expandFromCenter(s,i,i+1) 20 | return s[self.start:self.start+self.maxlen] 21 | 22 | 23 | def expandFromCenter(self,s,l,r): 24 | while l > -1 and r < len(s) and s[l] ==s[r]: 25 | l -= 1 26 | r += 1 27 | 28 | if self.maxlen < r-l-1: 29 | self.maxlen = r-l-1 30 | self.start = l + 1 31 | -------------------------------------------------------------------------------- /Python_/qus/bubble_sort.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | bubble sort is also refreed as sinking sort 4 | we repeatedly compare each pair of adjacent items and swap them 5 | if needed 6 | """ 7 | 8 | def bubble(list): 9 | for i in range(len(list)): 10 | for j in range(len(list)): 11 | if list[i] < list[j]: 12 | list[i], list[j] = list[j], list[i] 13 | 14 | return list 15 | 16 | 17 | a = [5,3,1,2,8,4,7,6,9] 18 | 19 | print(bubble(a)) 20 | 21 | """ 22 | # time complexity = O(N^2) 23 | # space complexity = O(1) 24 | 25 | # when to use 26 | # - when the input is already sorted 27 | # - space is a concern 28 | # - Easy to implment 29 | 30 | 31 | # when to avoid 32 | # - Average time complexity is poor 33 | """ -------------------------------------------------------------------------------- /Python_/sorting/bubble_sort.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | bubble sort is also refreed as sinking sort 4 | we repeatedly compare each pair of adjacent items and swap them 5 | if needed 6 | """ 7 | 8 | def bubble(list): 9 | for i in range(len(list)): 10 | for j in range(len(list)): 11 | if list[i] < list[j]: 12 | list[i], list[j] = list[j], list[i] 13 | 14 | return list 15 | 16 | 17 | a = [5,3,1,2,8,4,7,6,9] 18 | 19 | print(bubble(a)) 20 | 21 | """ 22 | # time complexity = O(N^2) 23 | # space complexity = O(1) 24 | 25 | # when to use 26 | # - when the input is already sorted 27 | # - space is a concern 28 | # - Easy to implment 29 | 30 | 31 | # when to avoid 32 | # - Average time complexity is poor 33 | """ -------------------------------------------------------------------------------- /Python_/Questions/subSet(II).py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/subsets-ii/ 3 | 4 | Given an integer array nums that may contain duplicates, return all possible subsets (the power set). 5 | 6 | The solution set must not contain duplicate subsets. Return the solution in any order. 7 | 8 | Input: nums = [1,2,2] 9 | Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] 10 | 11 | Input: nums = [0] 12 | Output: [[],[0]] 13 | """ 14 | 15 | S = [1,2,2] 16 | 17 | def subSetWithDuplicates(S): 18 | res = [[]] 19 | S.sort() 20 | for i in range(len(S)): 21 | if i == 0 or S[i] != S[i - 1]: 22 | l = len(res) 23 | for j in range(len(res) - l, len(res)): 24 | res.append(res[j] + [S[i]]) 25 | return res 26 | 27 | print( 28 | subSetWithDuplicates(S) 29 | ) -------------------------------------------------------------------------------- /Python_/Questions/AddDigits.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/add-digits/ 3 | 4 | Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. 5 | 6 | Input: num = 38 7 | Output: 2 8 | Explanation: The process is 9 | 38 --> 3 + 8 --> 11 10 | 11 --> 1 + 1 --> 2 11 | Since 2 has only one digit, return it. 12 | 13 | Input: num = 0 14 | Output: 0 15 | """ 16 | num = 38 17 | 18 | def addDigits(num): 19 | 20 | def helper(nums): 21 | 22 | while True: 23 | number = nums%10 + nums//10 24 | # print(number) 25 | if len(str(number)) <= 1: 26 | return number 27 | 28 | nums = number 29 | 30 | return helper(num) 31 | 32 | 33 | 34 | print(addDigits(num)) -------------------------------------------------------------------------------- /Python_/leetCode75/runningSumof1dArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 3 | 4 | Return the running sum of nums. 5 | 6 | Input: nums = [1,2,3,4] 7 | Output: [1,3,6,10] 8 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 9 | 10 | Input: nums = [1,1,1,1,1] 11 | Output: [1,2,3,4,5] 12 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 13 | 14 | Input: nums = [3,1,2,10,1] 15 | Output: [3,4,6,16,17] 16 | """ 17 | 18 | 19 | def runningSum(nums): 20 | # result = [0]*len(nums) 21 | # result[0] = nums[0] 22 | for i in range(1, len(nums)): 23 | nums[i] += nums[i-1] 24 | 25 | return nums 26 | 27 | 28 | print( 29 | runningSum([1, 2, 3, 4]) 30 | ) 31 | -------------------------------------------------------------------------------- /Python_/leetCode75/subSequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s and t, return true if s is a subsequence of t, or false otherwise. 3 | 4 | A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). 5 | 6 | Input: s = "abc", t = "ahbgdc" 7 | Output: true 8 | 9 | Input: s = "axc", t = "ahbgdc" 10 | Output: false 11 | """ 12 | 13 | 14 | def isSubsequence(s, t): 15 | i, j = 0, 0 16 | 17 | while i < len(s) and j < len(t): 18 | if s[i] == t[j]: 19 | i += 1 20 | j += 1 21 | 22 | return i == len(s) 23 | 24 | 25 | print( 26 | isSubsequence("abc", "ahbgdc") 27 | ) 28 | -------------------------------------------------------------------------------- /Python_/Questions/ClimbingStairs.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/climbing-stairs/ 3 | 4 | You are climbing a staircase. It takes n steps to reach the top. 5 | 6 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 7 | 8 | Input: n = 2 9 | Output: 2 10 | Explanation: There are two ways to climb to the top. 11 | 1. 1 step + 1 step 12 | 2. 2 steps 13 | 14 | Input: n = 3 15 | Output: 3 16 | Explanation: There are three ways to climb to the top. 17 | 1. 1 step + 1 step + 1 step 18 | 2. 1 step + 2 steps 19 | 3. 2 steps + 1 step 20 | """ 21 | n = 2 22 | 23 | def climbStairs(n): 24 | if n == 1: 25 | return 1 26 | a, b = 1, 2 27 | for i in range(2, n): 28 | tmp = b 29 | b = a+b 30 | a = tmp 31 | return b 32 | 33 | print( 34 | climbStairs(n) 35 | ) -------------------------------------------------------------------------------- /Python_/qus/topKFrequentElemets.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums and an integer k, 3 | return the k most frequent elements. You may return the answer in any order. 4 | 5 | Input: nums = [1,1,1,2,2,3], k = 2 6 | Output: [1,2] 7 | 8 | Input: nums = [1], k = 1 9 | Output: [1] 10 | """ 11 | 12 | nums = [3,0,1,0] 13 | k = 1 14 | 15 | def topKFrequentElemet(nums, k): 16 | count = {} 17 | 18 | for i in range(len(nums)): 19 | if nums[i] not in count: 20 | count[nums[i]] = 1 21 | else: 22 | count[nums[i]] +=1 23 | count = {k:v for k, v in sorted(count.items(), key=lambda item: item[1], reverse=True)} 24 | 25 | ans = [] 26 | for key, _ in count.items(): 27 | ans.append(key) 28 | 29 | return ans[:k] 30 | 31 | 32 | print( 33 | topKFrequentElemet(nums,1) 34 | ) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/tableHowSum.js: -------------------------------------------------------------------------------- 1 | /* 2 | The function should return an array containing any combination of elements that add up to exactly the targetSum. 3 | 4 | If there is no combination that adds up to the targetSum, then return null. 5 | 6 | If there are multiple combinations possible, you may return any single one. 7 | 8 | */ 9 | // m = targetSum 10 | // n = numbers.length 11 | // TC = O(n*m^2) 12 | // SC = O(m^2) 13 | const howSum = (targetSum, numbers) => { 14 | table = Array(targetSum + 1).fill(null); 15 | 16 | table[0] = []; 17 | 18 | for (let i = 0; i <= targetSum; i++) { 19 | if (table[i] != null) { 20 | for (let num of numbers) { 21 | table[i + num] = [...table[i], num]; 22 | } 23 | } 24 | } 25 | return table[targetSum]; 26 | }; 27 | 28 | console.log(howSum(7, [5, 3, 4])); 29 | -------------------------------------------------------------------------------- /Python_/qus/selection_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | in case of selection sort we repeatedly find the minimun element and 3 | move it to the sorted part of array to make unsorted part sorted. 4 | """ 5 | 6 | def selection(list): 7 | for i in range(len(list)): 8 | min_value = i 9 | for j in range(i+1,len(list)): 10 | if list[min_value] > list[j]: 11 | min_value = j 12 | 13 | list[i], list[min_value] = list[min_value], list[i] 14 | 15 | return list 16 | 17 | a = [5,3,1,2,8,4,7,6,9] 18 | 19 | print(selection(a)) 20 | 21 | 22 | """ 23 | # time complexity = O(N^2) 24 | # space complexity = O(1) 25 | 26 | # when to use 27 | # - when we have insufficient memory 28 | # - Easy to implment 29 | 30 | 31 | # when to avoid 32 | # - when time is a concern 33 | """ -------------------------------------------------------------------------------- /Python_/sorting/selection_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | in case of selection sort we repeatedly find the minimun element and 3 | move it to the sorted part of array to make unsorted part sorted. 4 | """ 5 | 6 | def selection(list): 7 | for i in range(len(list)): 8 | min_value = i 9 | for j in range(i+1,len(list)): 10 | if list[min_value] > list[j]: 11 | min_value = j 12 | 13 | list[i], list[min_value] = list[min_value], list[i] 14 | 15 | return list 16 | 17 | a = [5,3,1,2,8,4,7,6,9] 18 | 19 | print(selection(a)) 20 | 21 | 22 | """ 23 | # time complexity = O(N^2) 24 | # space complexity = O(1) 25 | 26 | # when to use 27 | # - when we have insufficient memory 28 | # - Easy to implment 29 | 30 | 31 | # when to avoid 32 | # - when time is a concern 33 | """ -------------------------------------------------------------------------------- /Python_/DataStructure/pascalsTriangle_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/pascals-triangle-ii/ 3 | 4 | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. 5 | 6 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 7 | 8 | Input: rowIndex = 3 9 | Output: [1,3,3,1] 10 | 11 | Input: rowIndex = 0 12 | Output: [1] 13 | 14 | Input: rowIndex = 1 15 | Output: [1,1] 16 | """ 17 | 18 | rowIndex = 3 19 | 20 | def getRow(rowIndex): 21 | result = [[1]] 22 | 23 | for _ in range(rowIndex): 24 | previous = [0] + result[-1] + [0] 25 | row = [] 26 | for j in range(len(result[-1])+1): 27 | row.append(previous[j] + previous[j+1]) 28 | 29 | result.append(row) 30 | 31 | return result[-1] 32 | 33 | print( 34 | getRow(rowIndex) 35 | ) -------------------------------------------------------------------------------- /Python_/pattern_/single_numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 3 | 4 | You must implement a solution with a linear runtime complexity and use only constant extra space. 5 | 6 | Input: nums = [2,2,1] 7 | Output: 1 8 | 9 | Input: nums = [4,1,2,1,2] 10 | Output: 4 11 | 12 | Input: nums = [1] 13 | Output: 1 14 | """ 15 | 16 | 17 | def singleNumber(nums): 18 | count = {} 19 | for i in range(len(nums)): 20 | if nums[i] in count: 21 | count[nums[i]] += 1 22 | else: 23 | count[nums[i]] = 1 24 | 25 | for key, value in count.items(): 26 | if value == 1: 27 | return key 28 | 29 | 30 | print( 31 | singleNumber([4, 1, 2, 1, 2]), 32 | singleNumber([2, 2, 1]), 33 | singleNumber([4]) 34 | 35 | ) 36 | -------------------------------------------------------------------------------- /Python_/1_Recursion/interview_question4.py: -------------------------------------------------------------------------------- 1 | # How to covert a number from Decimal to Binary using Recursion 2 | 3 | # Step 1 : Recursive Case - the flow 4 | # - Divide the number by 2 5 | # - Get the integer quotient for the next iteration 6 | # - Get the remainder for the binary digit 7 | # - Repeat the steps until the quotient is equal to 0 8 | 9 | # f(n) = remainder + 10 * (divided/2) 10 | # f(n) = n mod 2 + 10 * (f/2) 11 | 12 | 13 | # Step 2 : Base case - the stopping criterion 14 | # -if n == 0 (quotient == 0) 15 | 16 | # Step 3 : Unintentional case - the constraint 17 | 18 | 19 | def decimalToBinary(n): 20 | assert int(n) == n , "Please Enter Positive Value!" 21 | if n == 0: 22 | return 0 23 | else: 24 | return n % 2 + 10 * decimalToBinary(int(n/2)) 25 | 26 | 27 | 28 | print(decimalToBinary(10)) -------------------------------------------------------------------------------- /Go/Basics/loops.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func simpleLoop() { 6 | for i := 1; i <= 10; i++ { 7 | fmt.Println(i) 8 | } 9 | } 10 | 11 | func loopBreak() { 12 | for i := 1; i <= 10; i++ { 13 | if i > 5 { 14 | break 15 | } 16 | fmt.Println(i) 17 | } 18 | fmt.Println("Line After loop") 19 | } 20 | 21 | func loopContinue() { 22 | for i := 1; i <= 10; i++ { 23 | if i%2 == 0 { 24 | continue 25 | } 26 | fmt.Println(i) 27 | } 28 | 29 | } 30 | 31 | func loopNested() { 32 | n := 5 33 | for i := 0; i < n; i++ { 34 | for j := 0; j <= i; j++ { 35 | fmt.Print("*") 36 | } 37 | fmt.Println() 38 | } 39 | } 40 | 41 | func loopInfinite() { 42 | for { 43 | fmt.Printf("Welcome to infinity loop") 44 | } 45 | } 46 | 47 | func main() { 48 | // simpleLoop() 49 | // loopBreak() 50 | // loopContinue() 51 | loopNested() 52 | } 53 | -------------------------------------------------------------------------------- /Python_/DataStructure/topKFrequentElements.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/top-k-frequent-elements/ 3 | 4 | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 5 | 6 | Input: nums = [1,1,1,2,2,3], k = 2 7 | Output: [1,2] 8 | 9 | Input: nums = [1], k = 1 10 | Output: [1] 11 | """ 12 | 13 | nums = [1, 2]; k = 2 14 | # nums = [1,1,1,2,2,3]; k = 2 15 | 16 | def topKFrequent(nums, k): 17 | if k == len(nums): 18 | return nums 19 | check = {} 20 | 21 | for i in range(len(nums)): 22 | if nums[i] not in check: 23 | check[nums[i]] =1 24 | else: 25 | check[nums[i]] +=1 26 | result = {k:v for k,v in sorted(check.items(), key=lambda item:item[1])} 27 | 28 | return list(result.values())[:k] 29 | 30 | print( 31 | topKFrequent(nums, k) 32 | ) -------------------------------------------------------------------------------- /Python_/DataStructure/lognestPalindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. 3 | 4 | Letters are case sensitive, for example, "Aa" is not considered a palindrome here. 5 | 6 | Input: s = "abccccdd" 7 | Output: 7 8 | Explanation: 9 | One longest palindrome that can be built is "dccaccd", whose length is 7. 10 | 11 | Input: s = "a" 12 | Output: 1 13 | 14 | Input: s = "bb" 15 | Output: 2 16 | """ 17 | s = "abccccdd" 18 | 19 | def longestPalindrome(s): 20 | hash = set() 21 | 22 | for c in s: 23 | if c not in hash: 24 | hash.add(c) 25 | else: 26 | hash.remove(c) 27 | 28 | # print(hash) 29 | if len(hash) >0: 30 | return len(s) - len(hash)+1 31 | else: 32 | len(s) 33 | 34 | print(longestPalindrome(s)) -------------------------------------------------------------------------------- /Python_/blind75/1_twosum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | You can return the answer in any order. 7 | 8 | Input: nums = [2,7,11,15], target = 9 9 | Output: [0,1] 10 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 11 | 12 | Input: nums = [3,2,4], target = 6 13 | Output: [1,2] 14 | 15 | Input: nums = [3,3], target = 6 16 | Output: [0,1] 17 | """ 18 | nums = [2,7,11,15] 19 | 20 | def solution(nums, target): 21 | d = {} 22 | for i, n in enumerate(nums): 23 | print(d) 24 | m = target - n 25 | if m in d: 26 | return [d[m],i] 27 | else: 28 | d[n] = i 29 | 30 | 31 | print(solution(nums, 26)) -------------------------------------------------------------------------------- /Python_/dp/riverSize.py: -------------------------------------------------------------------------------- 1 | 2 | def riverSize(matrix): 3 | row, col = len(matrix), len(matrix[0]) 4 | visited = set() 5 | result = [] 6 | 7 | def getSize(i, j): 8 | if i < 0 or j < 0 or j >= col or i >= row or (i, j) in visited or matrix[i][j] != 1: 9 | return 0 10 | visited.add((i, j)) 11 | 12 | return 1 + getSize(i-1, j) + getSize(i+1, j) + \ 13 | getSize(i, j-1) + getSize(i, j+1) 14 | 15 | for i in range(row): 16 | for j in range(col): 17 | if matrix[i][j] == 1: 18 | size = getSize(i, j) 19 | if size != 0: 20 | result.append(size) 21 | 22 | return (result) 23 | 24 | 25 | matrix = [[0, 0, 0, 1, 1], 26 | [1, 1, 0, 0, 1], 27 | [0, 0, 0, 1, 1], 28 | [1, 0, 0, 1, 0]] 29 | 30 | print( 31 | riverSize(matrix) 32 | ) 33 | -------------------------------------------------------------------------------- /Python_/dp/climbingStairs.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are climbing a staircase. It takes n steps to reach the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | 6 | Input: n = 2 7 | Output: 2 8 | Explanation: There are two ways to climb to the top. 9 | 1. 1 step + 1 step 10 | 2. 2 steps 11 | 12 | Input: n = 3 13 | Output: 3 14 | Explanation: There are three ways to climb to the top. 15 | 1. 1 step + 1 step + 1 step 16 | 2. 1 step + 2 steps 17 | 3. 2 steps + 1 step 18 | 19 | https://www.geeksforgeeks.org/count-ways-reach-nth-stair/ 20 | """ 21 | n = 5 22 | def fib(n, memo = {}): 23 | if n in memo: 24 | return memo[n] 25 | if n <=1: 26 | return n 27 | memo[n] = fib(n-1, memo) + fib(n-2, memo) 28 | return memo[n] 29 | 30 | def climb_stairs(n): 31 | return fib(n+1) 32 | 33 | 34 | 35 | print(climb_stairs(n)) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/palindromicSubstrings.js: -------------------------------------------------------------------------------- 1 | const countSubstrings = (s) => { 2 | let count = 0; 3 | let matrix = []; 4 | 5 | for (let char of s) { 6 | matrix.push(Array(s.length).fill(0)); 7 | } 8 | 9 | for (let i = 0; i < s.length; i++) { 10 | matrix[i][i] = 1; 11 | count++; 12 | } 13 | 14 | for (let col = 1; col < s.length; col++) { 15 | for (let row = 0; row < col; row++) { 16 | // this check palindrom for string length <=2 17 | if (row === col - 1 && s[col] === s[row]) { 18 | matrix[row][col] = 1; 19 | count++; 20 | } 21 | // this checks for string length 3 or more and inner string palindrom 22 | else if (matrix[row + 1][col - 1] === 1 && s[col] === s[row]) { 23 | matrix[row][col] = 1; 24 | count++; 25 | } 26 | } 27 | } 28 | return count; 29 | }; 30 | 31 | console.log(countSubstrings("aaa")); 32 | -------------------------------------------------------------------------------- /Python_/DataStructure/findTheDifference.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/find-the-difference/ 3 | 4 | You are given two strings s and t. 5 | 6 | String t is generated by random shuffling string s and then add one more letter at a random position. 7 | 8 | Return the letter that was added to t. 9 | 10 | Input: s = "abcd", t = "abcde" 11 | Output: "e" 12 | Explanation: 'e' is the letter that was added. 13 | 14 | Input: s = "", t = "y" 15 | Output: "y" 16 | """ 17 | 18 | from typing import Counter 19 | from markupsafe import re 20 | 21 | 22 | s = "abcd" 23 | t = "abcde" 24 | 25 | def findTheDifference(s, t): 26 | # s_cnt, t_cnt = Counter(s), Counter(t) 27 | # for letter in t_cnt: 28 | # if not s_cnt[letter] == t_cnt[letter]: 29 | # return letter 30 | for i in t: 31 | if s.count(i) != t.count(i): 32 | return i 33 | 34 | print( 35 | findTheDifference(s, t) 36 | ) -------------------------------------------------------------------------------- /Python_/qus/groupAnagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/group-anagrams/ 3 | 4 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 5 | 6 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 7 | 8 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 9 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 10 | 11 | Input: strs = [""] 12 | Output: [[""]] 13 | 14 | Input: strs = ["a"] 15 | Output: [["a"]] 16 | 17 | """ 18 | strs = ["eat","tea","tan","ate","nat","bat"] 19 | 20 | def groupAnagrams(strs): 21 | hist = {} 22 | 23 | for c in strs: 24 | key = "".join(sorted(c)) 25 | if key not in hist: 26 | hist[key] = [c] 27 | else: 28 | hist[key] += [c] 29 | 30 | return hist.values() 31 | 32 | print(groupAnagrams(strs)) -------------------------------------------------------------------------------- /Python_/Questions/twoSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | You can return the answer in any order. 7 | 8 | Input: nums = [2,7,11,15], target = 9 9 | Output: [0,1] 10 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 11 | 12 | Input: nums = [3,2,4], target = 6 13 | Output: [1,2] 14 | 15 | Input: nums = [3,3], target = 6 16 | Output: [0,1] 17 | 18 | """ 19 | # nums = [2,7,11,15] 20 | # target = 9 21 | nums = [3,2,4] 22 | target = 6 23 | 24 | def twoSum(nums, target): 25 | d = {} 26 | for i, n in enumerate(nums): 27 | m = target - n 28 | if m in d: 29 | return [d[m], i] 30 | else: 31 | d[n] = i 32 | 33 | 34 | 35 | 36 | print( 37 | twoSum(nums, target) 38 | ) -------------------------------------------------------------------------------- /Python_/blind75/2_longestSubstringWithRepeatingCharacters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, find the length of the longest substring without repeating characters. 3 | 4 | Input: s = "abcabcbb" 5 | Output: 3 6 | Explanation: The answer is "abc", with the length of 3. 7 | 8 | Input: s = "bbbbb" 9 | Output: 1 10 | Explanation: The answer is "b", with the length of 1. 11 | 12 | Input: s = "pwwkew" 13 | Output: 3 14 | Explanation: The answer is "wke", with the length of 3. 15 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 16 | """ 17 | s = "abcabcbb" 18 | 19 | def lengthOfLongestSubstring(s): 20 | charset = set() 21 | l =0 22 | result = 0 23 | for i in range(len(s)): 24 | while s[i] in charset: 25 | charset.remove(s[i]) 26 | l+=1 27 | charset.add(s[i]) 28 | result = max(result, i-l+1) 29 | return result 30 | 31 | print(lengthOfLongestSubstring(s)) 32 | -------------------------------------------------------------------------------- /Python_/DataStructure/productOfArrayExceptSelf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 5 | 6 | You must write an algorithm that runs in O(n) time and without using the division operation. 7 | 8 | Input: nums = [1,2,3,4] 9 | Output: [24,12,8,6] 10 | 11 | Input: nums = [-1,1,0,-3,3] 12 | Output: [0,0,9,0,0] 13 | """ 14 | 15 | 16 | 17 | nums = [-1,1,0,-3,3] 18 | 19 | def productExceptSelf(nums): 20 | res = [1]* len(nums) 21 | prefix = 1 22 | for i in range(len(nums)): 23 | res[i] = prefix 24 | prefix *= nums[i] 25 | 26 | postfix = 1 27 | for i in range(len(nums)-1,-1,-1): 28 | res[i] *= postfix 29 | postfix *= nums[i] 30 | 31 | return res 32 | 33 | 34 | print( 35 | productExceptSelf(nums) 36 | ) -------------------------------------------------------------------------------- /Python_/qus/validParentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | 9 | Input: s = "()" 10 | Output: true 11 | 12 | Input: s = "()[]{}" 13 | Output: true 14 | 15 | Input: s = "(]" 16 | Output: false 17 | """ 18 | s = "()[]{}" 19 | 20 | def isValid(s): 21 | stack = [] 22 | check = { 23 | "}":"{", 24 | "]":"[", 25 | ")":"(" 26 | } 27 | 28 | for c in s: 29 | if c in check: 30 | if stack and stack[-1] == check[c]: 31 | return True 32 | else: 33 | return False 34 | else: 35 | stack.append(c) 36 | 37 | return True if not stack else False 38 | 39 | print( 40 | isValid(s) 41 | ) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/01_first.js: -------------------------------------------------------------------------------- 1 | console.log("Dynamic Programming"); 2 | 3 | // Memoization 4 | // Tabulation 5 | 6 | /* 7 | fibonacci Sequence 8 | 9 | 1,1,2,3,5,8,13,21,34,.... 10 | */ 11 | 12 | // const Classicalfib = (n) => { 13 | // if (n <= 2) return 1; 14 | // return fib(n - 1) + fib(n - 2); 15 | // }; 16 | 17 | // console.log(Classicalfib(6)); 18 | // console.log(Classicalfib(7)); 19 | // console.log(Classicalfib(80)); // not going to work 20 | 21 | // memoization 22 | // keys will be args to fn, value will be the return value 23 | 24 | const memoFib = (n, memo = {}) => { 25 | // return value if alredy in memo 26 | if (n in memo) return memo[n]; 27 | if (n <= 2) return 1; 28 | // if not then add value in memo 29 | memo[n] = memoFib(n - 1, memo) + memoFib(n - 2, memo); 30 | return memo[n]; 31 | }; 32 | 33 | console.log(memoFib(50)); 34 | console.log(memoFib(135)); 35 | console.log(memoFib(55)); 36 | console.log(memoFib(51)); 37 | -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/tableCunSum.js: -------------------------------------------------------------------------------- 1 | /* 2 | write a function that takes in a targetSum and an array of numbers as arguments. 3 | 4 | The function should return a boolean indicating whether 5 | or not it is possible to generate the tragetSum using number 6 | from the array. 7 | 8 | You may use an element of the array as many times as needed. 9 | You may assume that all input numbers are nonegative. 10 | */ 11 | 12 | // m = targetSum 13 | // n = numbers.length 14 | // TC = O(nm) 15 | // SC = O(m) 16 | 17 | const canSum = (targetSum, numbers) => { 18 | const table = Array(targetSum + 1).fill(false); 19 | table[0] = true; 20 | 21 | for (let i = 0; i <= targetSum; i++) { 22 | if (table[i] === true) { 23 | // look ahead (if true) 24 | for (let num of numbers) { 25 | table[i + num] = true; 26 | } 27 | } 28 | } 29 | return table[targetSum]; 30 | }; 31 | 32 | console.log(canSum(7, [5, 3, 4, 7])); 33 | -------------------------------------------------------------------------------- /Python_/Binary_tree/bfs.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class Node: 5 | def __init__(self, value): 6 | self.val = value 7 | self.left = None 8 | self.right = None 9 | 10 | 11 | def breadth_first_values(root): 12 | if not root: 13 | return [] 14 | 15 | queue = deque([root]) 16 | values = [] 17 | 18 | while queue: 19 | node = queue.popleft() 20 | 21 | values.append(node.val) 22 | 23 | if node.left: 24 | queue.append(node.left) 25 | 26 | if node.right: 27 | queue.append(node.right) 28 | 29 | return values 30 | 31 | 32 | root = Node(1) 33 | root.left = Node(2) 34 | root.right = Node(3) 35 | 36 | root.left.left = Node(4) 37 | root.left.right = Node(5) 38 | 39 | root.right.left = Node(6) 40 | root.right.right = Node(7) 41 | 42 | 43 | # 1 44 | # / \ 45 | # 2 3 46 | # / \ / \ 47 | # 4 5 6 7 48 | 49 | print(breadth_first_values(root)) 50 | -------------------------------------------------------------------------------- /hackerRank/diagonalDifference.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a square matrix, calculate the absolute difference between the sums of its diagonals. 3 | 4 | For example, the square matrix is shown below: 5 | 6 | 1 2 3 7 | 4 5 6 8 | 9 8 9 9 | The left-to-right diagonal = 1+5+9=15. 10 | The right to left diagonal = 3+5+9=17. 11 | Their absolute difference is |15-17| = 2 12 | """ 13 | 14 | arr= [ 15 | [1,2,3], 16 | [4,5,6], 17 | [9,8,9] 18 | ] 19 | 20 | 21 | def diagonalDifference(arr): 22 | left_to_right = [] 23 | right_to_left = [] 24 | 25 | r,c = len(arr), len(arr[0]) 26 | value = 0 27 | for i in range(r): 28 | left_to_right.append(arr[i][value]) 29 | value+=1 30 | 31 | value = r 32 | for j in range(c): 33 | right_to_left.append(arr[j][value-1]) 34 | value -=1 35 | 36 | return abs(sum(right_to_left)- sum(left_to_right)) 37 | 38 | 39 | print( 40 | diagonalDifference(arr) 41 | ) 42 | 43 | -------------------------------------------------------------------------------- /Python_/Questions/combinations.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/combinations/ 3 | Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. 4 | 5 | You may return the answer in any order. 6 | Input: n = 4, k = 2 7 | Output: 8 | [ 9 | [2,4], 10 | [3,4], 11 | [2,3], 12 | [1,2], 13 | [1,3], 14 | [1,4], 15 | ] 16 | 17 | Input: n = 1, k = 1 18 | Output: [[1]] 19 | """ 20 | 21 | def combine(n, k): 22 | res = [] 23 | 24 | def backtrack(start, comb): 25 | if len(comb) == k: 26 | res.append(comb.copy()) 27 | return 28 | 29 | for i in range(start,n+1 ): 30 | comb.append(i) 31 | backtrack(i+1, comb) 32 | comb.pop() 33 | 34 | backtrack(1,[]) 35 | 36 | n ,k = 4, 2 37 | print(combine(n,k)) 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Python_/qus/lognestSubStringWithoutRepeatingCharacters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, find the length of the longest substring without repeating characters. 3 | 4 | Input: s = "abcabcbb" 5 | Output: 3 6 | Explanation: The answer is "abc", with the length of 3. 7 | 8 | Input: s = "bbbbb" 9 | Output: 1 10 | Explanation: The answer is "b", with the length of 1. 11 | 12 | Input: s = "pwwkew" 13 | Output: 3 14 | Explanation: The answer is "wke", with the length of 3. 15 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 16 | """ 17 | 18 | s = "pwwkew" 19 | # s = "abcabcbb" 20 | 21 | def lengthOfLongestSubstring(s): 22 | charSet = set() 23 | l = 0 24 | result = 0 25 | for i in range(len(s)): 26 | while s[i] in charSet: 27 | charSet.remove(s[l]) 28 | l+=1 29 | charSet.add(s[i]) 30 | result = max(result, i-l+1) 31 | return result 32 | 33 | 34 | print( 35 | lengthOfLongestSubstring(s) 36 | ) -------------------------------------------------------------------------------- /Python_/DataStructure/twoSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/two-sum/ 3 | 4 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 5 | 6 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 7 | 8 | You can return the answer in any order. 9 | 10 | Input: nums = [2,7,11,15], target = 9 11 | Output: [0,1] 12 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 13 | 14 | Input: nums = [3,2,4], target = 6 15 | Output: [1,2] 16 | 17 | Input: nums = [3,3], target = 6 18 | Output: [0,1] 19 | """ 20 | 21 | nums = [7,4,15] 22 | target = 11 23 | 24 | 25 | def twoSum(nums, target): 26 | d = {} 27 | for i , n in enumerate(nums): 28 | value = target - n 29 | if value in d: 30 | return [d[value], i] 31 | else: 32 | d[n] = i 33 | 34 | # return nums 35 | 36 | 37 | print( 38 | twoSum(nums, target) 39 | ) -------------------------------------------------------------------------------- /Python_/stack/validParenthesis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | # https://leetcode.com/problems/valid-parentheses/ 9 | 10 | Input: s = "()" 11 | Output: true 12 | 13 | Input: s = "()[]{}" 14 | Output: true 15 | 16 | Input: s = "(]" 17 | Output: false 18 | """ 19 | s = "()[]{}" 20 | 21 | def isValid(s): 22 | stack = [] 23 | closeToOpen = { 24 | ")":"(", 25 | "}":"{", 26 | "]":"[" 27 | } 28 | 29 | for c in s: 30 | if c in closeToOpen: 31 | if stack and stack[-1] == closeToOpen[c]: 32 | stack.pop() 33 | else: 34 | return False 35 | else: 36 | stack.append(c) 37 | return True if not stack else False 38 | 39 | print(isValid(s)) -------------------------------------------------------------------------------- /Python_/Questions/searchInsertPosition.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | 6 | Input: nums = [1,3,5,6], target = 5 7 | Output: 2 8 | 9 | Input: nums = [1,3,5,6], target = 2 10 | Output: 1 11 | 12 | Input: nums = [1,3,5,6], target = 7 13 | Output: 4 14 | 15 | https://leetcode.com/problems/search-insert-position/ 16 | """ 17 | 18 | def serachInset(nums, target): 19 | l ,r = 0, len(nums)-1 20 | 21 | while l <= r: 22 | mid = (l+r)//2 23 | 24 | if nums[mid] == target: 25 | return mid 26 | 27 | if nums[mid] > target: 28 | r = mid - 1 29 | else: 30 | l = mid +1 31 | 32 | return l 33 | 34 | nums = [1,3,5,6] 35 | target = 2 36 | 37 | print(serachInset(nums, target)) 38 | -------------------------------------------------------------------------------- /Python_/Questions/validParentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | # https://leetcode.com/problems/valid-parentheses/ 9 | 10 | Input: s = "()" 11 | Output: true 12 | 13 | Input: s = "()[]{}" 14 | Output: true 15 | 16 | Input: s = "(]" 17 | Output: false 18 | """ 19 | s = "()[]{}" 20 | 21 | def isValid(s): 22 | stack = [] 23 | closeToOpen = { 24 | ")":"(", 25 | "}":"{", 26 | "]":"[" 27 | } 28 | 29 | for c in s: 30 | if c in closeToOpen: 31 | if stack and stack[-1] == closeToOpen[c]: 32 | stack.pop() 33 | else: 34 | return False 35 | else: 36 | stack.append(c) 37 | return True if not stack else False 38 | 39 | print(isValid(s)) -------------------------------------------------------------------------------- /Python_/Questions/longestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, return the longest palindromic substring in s. 3 | 4 | Input: s = "babad" 5 | Output: "bab" 6 | Explanation: "aba" is also a valid answer. 7 | 8 | Input: s = "cbbd" 9 | Output: "bb" 10 | """ 11 | 12 | s = "babad" 13 | 14 | def longestPalindrome(s): 15 | res = "" 16 | resLen = 0 17 | 18 | for i in range(len(s)): 19 | # odd length 20 | l,r = i ,i 21 | while l >=0 and r resLen: 23 | res = s[l:r+1] 24 | resLen = r - 1 +1 25 | l-=1 26 | r +=1 27 | 28 | # even length 29 | l,r = i, i+1 30 | while l >=0 and r resLen: 32 | res = s[l:r+1] 33 | resLen = r - 1 +1 34 | l-=1 35 | r +=1 36 | 37 | return res 38 | 39 | 40 | print( 41 | longestPalindrome(s) 42 | ) -------------------------------------------------------------------------------- /Python_/Questions/stack/validParenthesis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | # https://leetcode.com/problems/valid-parentheses/ 9 | 10 | Input: s = "()" 11 | Output: true 12 | 13 | Input: s = "()[]{}" 14 | Output: true 15 | 16 | Input: s = "(]" 17 | Output: false 18 | """ 19 | s = "()[]{}" 20 | 21 | def isValid(s): 22 | stack = [] 23 | closeToOpen = { 24 | ")":"(", 25 | "}":"{", 26 | "]":"[" 27 | } 28 | 29 | for c in s: 30 | if c in closeToOpen: 31 | if stack and stack[-1] == closeToOpen[c]: 32 | stack.pop() 33 | else: 34 | return False 35 | else: 36 | stack.append(c) 37 | return True if not stack else False 38 | 39 | print(isValid(s)) -------------------------------------------------------------------------------- /Python_/DataStructure/singleNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/single-number/ 3 | 4 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 5 | 6 | You must implement a solution with a linear runtime complexity and use only constant extra space. 7 | 8 | Input: nums = [2,2,1] 9 | Output: 1 10 | 11 | Input: nums = [4,1,2,1,2] 12 | Output: 4 13 | 14 | Input: nums = [1] 15 | Output: 1 16 | """ 17 | 18 | nums = [4,1,2,1,2] 19 | 20 | def singleNumber(nums): 21 | check = {} 22 | 23 | for n in nums: 24 | if n in check: 25 | check[n] +=1 26 | else: 27 | check[n] = 1 28 | 29 | for key, value in check.items(): 30 | if value == 1: 31 | return key 32 | else: 33 | continue 34 | 35 | # only using constant space 36 | def singleNumber2(nums): 37 | res = 0 38 | for num in nums: 39 | res ^= num 40 | return res 41 | 42 | print( 43 | singleNumber2(nums) 44 | ) -------------------------------------------------------------------------------- /Python_/blind75/7_validParentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/valid-parentheses/ 3 | 4 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | 6 | An input string is valid if: 7 | 8 | Open brackets must be closed by the same type of brackets. 9 | Open brackets must be closed in the correct order. 10 | 11 | Input: s = "()" 12 | Output: true 13 | 14 | Input: s = "()[]{}" 15 | Output: true 16 | 17 | Input: s = "(]" 18 | Output: false 19 | """ 20 | # s = "()[]{}" 21 | s = "]" 22 | 23 | def isValid(s): 24 | stack = [] 25 | check = { 26 | ")":"(", 27 | "}":"{", 28 | "]":"[" 29 | } 30 | 31 | for c in s: 32 | if c in check: 33 | if stack and stack[-1] == check[c]: 34 | stack.pop() 35 | else: 36 | return False 37 | else: 38 | stack.append(c) 39 | 40 | return True if not stack else False 41 | 42 | print(isValid(s)) -------------------------------------------------------------------------------- /Python_/Questions/rotate_matrix.py: -------------------------------------------------------------------------------- 1 | # Rotate matrix - 2 | # Given an image represented by a NxN matrix 3 | # write a method to rotate the image by 90 degrees. 4 | 5 | import numpy as np 6 | 7 | arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) 8 | print(arr) 9 | print("*"*30) 10 | def rotate_matrix(matrix): 11 | no_of_rows = len(matrix) 12 | 13 | for layer in range(no_of_rows//2): 14 | first = layer 15 | last = no_of_rows - layer -1 16 | for i in range(first, last): 17 | # save top element 18 | top = matrix[layer][i] 19 | # move left element to top 20 | matrix[layer][i] = matrix[-i-1][layer] 21 | # move bottom element to left 22 | matrix[-i-1][layer] = matrix[-layer-1][-i-1] 23 | # move right element to the bottom 24 | matrix[-layer-1][-i-1] = matrix[i][-layer-1] 25 | # move top to right 26 | matrix[i][-layer-1] = top 27 | 28 | return matrix 29 | 30 | 31 | print(rotate_matrix(arr)) 32 | 33 | -------------------------------------------------------------------------------- /Python_/DataStructure/validParentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/valid-parentheses/ 3 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 4 | 5 | An input string is valid if: 6 | 7 | Open brackets must be closed by the same type of brackets. 8 | Open brackets must be closed in the correct order. 9 | 10 | Input: s = "()" 11 | Output: true 12 | 13 | Input: s = "()[]{}" 14 | Output: true 15 | 16 | Input: s = "(]" 17 | Output: false 18 | """ 19 | 20 | s = "(){}[]" 21 | 22 | def isValid(s): 23 | stack = [] 24 | dict = { 25 | "]":"[", 26 | "}":"{", 27 | ")":"(" 28 | } 29 | 30 | for char in s: 31 | if char in dict.values(): 32 | stack.append(char) 33 | elif char in dict.keys(): 34 | if stack == [] or dict[char] != stack.pop(): 35 | return False 36 | else: 37 | return False 38 | return stack == [] 39 | 40 | 41 | print( 42 | isValid(s) 43 | ) -------------------------------------------------------------------------------- /Python_/blind75/11_maximumSubarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | A subarray is a contiguous part of an array. 5 | 6 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 7 | Output: 6 8 | Explanation: [4,-1,2,1] has the largest sum = 6. 9 | 10 | Input: nums = [1] 11 | Output: 1 12 | 13 | Input: nums = [5,4,-1,7,8] 14 | Output: 23 15 | """ 16 | nums = [-2,1,-3,4,-1,2,1,-5,4] 17 | 18 | def maximunSum(nums): 19 | maxTilNow = nums[0] 20 | currentMax = 0 21 | 22 | for i in nums: 23 | # print(f'nums, {i}') 24 | currentMax = max(i,currentMax+i) 25 | # print(f'current ', currentMax) 26 | maxTilNow = max(currentMax, maxTilNow) 27 | # print(f"maxTilNow ", maxTilNow) 28 | 29 | return maxTilNow 30 | 31 | def approch2(nums): 32 | for i in range(1, len(nums)): 33 | if nums[i-1] >0: 34 | nums[i] += nums[i-1] 35 | return nums 36 | 37 | print(approch2(nums)) -------------------------------------------------------------------------------- /JavaScript_/BinaryTree/bfs.js: -------------------------------------------------------------------------------- 1 | class Node{ 2 | constructor(val){ 3 | this.val = val; 4 | this.left = null; 5 | this.right= null; 6 | } 7 | 8 | } 9 | 10 | const breadthFirstValue = (root) =>{ 11 | if (root === null) return []; 12 | 13 | const values = [] 14 | const queue = [root]; 15 | 16 | 17 | while (queue.length > 0){ 18 | const current = queue.shift(); 19 | values.push(current.val); 20 | 21 | if (current.left != null) queue.push(current.left); 22 | if (current.right != null) queue.push(current.right); 23 | 24 | 25 | } 26 | 27 | return values 28 | 29 | } 30 | 31 | 32 | const a = new Node("A") 33 | const b = new Node("B") 34 | const c = new Node("C") 35 | const d = new Node("D") 36 | const e = new Node("E") 37 | const f = new Node("F") 38 | 39 | a.left = b; 40 | a.right = c; 41 | b.left = d ; 42 | b.right = e ; 43 | c.right = f; 44 | 45 | // # a 46 | // # / \ 47 | // # b c 48 | // # / \ \ 49 | // # d e f 50 | 51 | console.log( 52 | breadthFirstValue(a) 53 | ) -------------------------------------------------------------------------------- /Python_/DataStructure/incresingTripletSubsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/increasing-triplet-subsequence/ 3 | 4 | Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. 5 | 6 | Input: nums = [1,2,3,4,5] 7 | Output: true 8 | Explanation: Any triplet where i < j < k is valid. 9 | 10 | Input: nums = [5,4,3,2,1] 11 | Output: false 12 | Explanation: No triplet exists. 13 | 14 | Input: nums = [2,1,5,0,4,6] 15 | Output: true 16 | Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. 17 | """ 18 | nums = [20,100,10,12,5,13] 19 | 20 | def increasingTriplet(nums): 21 | first = second = float('inf') 22 | for n in nums: 23 | if n <= first: 24 | first = n 25 | elif n <= second: 26 | second = n 27 | else: 28 | return True 29 | return False 30 | # return nums 31 | 32 | print( 33 | increasingTriplet(nums) 34 | ) -------------------------------------------------------------------------------- /Python_/Questions/AllPathsFromSourceToTarget.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/all-paths-from-source-to-target/ 3 | 4 | Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. 5 | 6 | The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). 7 | 8 | Input: graph = [[1,2],[3],[3],[]] 9 | Output: [[0,1,3],[0,2,3]] 10 | Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. 11 | 12 | Input: graph = [[4,3,1],[3,2,4],[3],[4],[]] 13 | Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]] 14 | """ 15 | 16 | graph = [[1,2],[3],[3],[]] 17 | 18 | def allPathsSourceTarget(graph): 19 | def dfs(cur, path): 20 | if cur == len(graph) - 1: res.append(path) 21 | else: 22 | for i in graph[cur]: dfs(i, path + [i]) 23 | res = [] 24 | dfs(0, [0]) 25 | return res 26 | 27 | 28 | print( 29 | allPathsSourceTarget(graph) 30 | ) -------------------------------------------------------------------------------- /Python_/qus/binarySearch.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | 6 | Input: nums = [-1,0,3,5,9,12], target = 9 7 | Output: 4 8 | Explanation: 9 exists in nums and its index is 4 9 | 10 | Input: nums = [-1,0,3,5,9,12], target = 2 11 | Output: -1 12 | Explanation: 2 does not exist in nums so return -1 13 | """ 14 | 15 | # nums = [-1,0,3,5,9,12] 16 | # target = 9 17 | 18 | nums = [-1,0,3,5,9,12] 19 | target = 2 20 | 21 | def search(nums, target): 22 | l , r = 0, len(nums)-1 23 | 24 | while l <= r: 25 | mid = (l+r)//2 26 | if nums[mid] == target: 27 | return mid 28 | 29 | if nums[mid] > target: 30 | r = mid-1 31 | elif nums[mid] < target: 32 | l = mid + 1 33 | 34 | return -1 35 | 36 | 37 | print( 38 | search(nums, target) 39 | ) -------------------------------------------------------------------------------- /Python_/Questions/jumpGame2.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/jump-game-ii/ 3 | 4 | Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 5 | 6 | Each element in the array represents your maximum jump length at that position. 7 | 8 | Your goal is to reach the last index in the minimum number of jumps. 9 | 10 | You can assume that you can always reach the last index. 11 | 12 | Input: nums = [2,3,1,1,4] 13 | Output: 2 14 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. 15 | 16 | Input: nums = [2,3,0,1,4] 17 | Output: 2 18 | 19 | """ 20 | 21 | nums = [2,3,1,1,4] 22 | 23 | def jump(nums): 24 | res = 0 25 | l = r = 0 26 | 27 | while r < len(nums)-1: 28 | farthest = 0 29 | for i in range(l, r+1): 30 | farthest = max(farthest,i+nums[i]) 31 | l = r+1 32 | r = farthest 33 | res +=1 34 | 35 | 36 | return res 37 | 38 | print( 39 | jump(nums) 40 | ) -------------------------------------------------------------------------------- /Python_/1_Recursion/interview_question3.py: -------------------------------------------------------------------------------- 1 | # How to find GCD (Greatest Common Divisor) of two numbers using recursion? 2 | 3 | # Step 1 : Recursive Case - the flow 4 | # GCD is the largest positive interger that divides the numbers without a remainder 5 | # gcd(8,12) = 4 6 | # 8 = 2 * 2 * 2 7 | # 12 = 2 * 2 * 3 8 | 9 | # Euclidean algorithms 10 | # gcd(48,18) 11 | # step 1 : 48/18 = 2 remainder 12 12 | # step 2 : 18/12 = 1 remainder 6 13 | # step 3 : 12/6 = 2 remainder 0 === (so for gcd (48,18) is 6) 14 | # gcd (a,0) = a 15 | # gcd (a,b) = gcd(b, a mod b) 16 | 17 | 18 | # Step 2 : Base case - the stopping criterion 19 | # b == 0 20 | 21 | # Step 3 : Unintentional case - the constraint 22 | # - positive integers 23 | # - covert negative to positive 24 | 25 | def GCD(a, b): 26 | assert int(a)== a and int(b) == b , "Number should be Integer!" 27 | if a < 0 or b < 0: 28 | a = -1 * a 29 | b = -1 * b 30 | 31 | if b == 0: 32 | return a 33 | else: 34 | return GCD(b, a % b) 35 | 36 | 37 | print(GCD(-48, -18)) -------------------------------------------------------------------------------- /Python_/Questions/backspaceStringCompare.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/backspace-string-compare/ 3 | 4 | Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. 5 | 6 | Note that after backspacing an empty text, the text will continue empty. 7 | 8 | Input: s = "ab#c", t = "ad#c" 9 | Output: true 10 | Explanation: Both s and t become "ac". 11 | 12 | Input: s = "ab##", t = "c#d#" 13 | Output: true 14 | Explanation: Both s and t become "". 15 | 16 | Input: s = "a#c", t = "b" 17 | Output: false 18 | Explanation: s becomes "c" while t becomes "b". 19 | """ 20 | 21 | s = "y#fo##f" 22 | t = "y#f#o##f" 23 | 24 | 25 | def backspaceCompare(s, t): 26 | 27 | def compare(s): 28 | result =[] 29 | for i in s: 30 | if i == "#" and result: 31 | result.pop() 32 | elif i != "#": 33 | result.append(i) 34 | return result 35 | 36 | return compare(s) == compare(t) 37 | 38 | 39 | print( 40 | backspaceCompare(s,t) 41 | ) -------------------------------------------------------------------------------- /Python_/Questions/binarySearch.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | 6 | Input: nums = [-1,0,3,5,9,12], target = 9 7 | Output: 4 8 | Explanation: 9 exists in nums and its index is 4 9 | 10 | Input: nums = [-1,0,3,5,9,12], target = 2 11 | Output: -1 12 | Explanation: 2 does not exist in nums so return -1 13 | 14 | """ 15 | 16 | def search(nums, target): 17 | lower = 0 18 | upper = len(nums)-1 19 | 20 | while lower <= upper: 21 | mid = (lower+upper)//2 22 | 23 | if nums[mid] == target: 24 | return mid 25 | 26 | if nums[mid] < target: 27 | lower = mid+1 28 | elif nums[mid] > target: 29 | upper = mid -1 30 | 31 | return -1 32 | 33 | 34 | 35 | nums = [1,3,5,6] 36 | target = 9 37 | 38 | print(search(nums, target)) -------------------------------------------------------------------------------- /Python_/DataStructure/wordPattern.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a pattern and a string s, find if s follows the same pattern. 3 | 4 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. 5 | 6 | Input: pattern = "abba", s = "dog cat cat dog" 7 | Output: true 8 | 9 | Input: pattern = "abba", s = "dog cat cat fish" 10 | Output: false 11 | 12 | Input: pattern = "aaaa", s = "dog cat cat dog" 13 | Output: false 14 | """ 15 | pattern = "abba";s = "dog cat cat dog" 16 | 17 | def wordPattern(pattern, s): 18 | words, w_to_p = s.split(" "), dict() 19 | # print(words, w_to_p) 20 | 21 | if len(pattern) != len(words): 22 | return False 23 | 24 | if len(set(pattern)) != len(set(words)): 25 | return False 26 | 27 | for i in range(len(words)): 28 | if words[i] not in w_to_p: 29 | w_to_p[words[i]] = pattern[i] 30 | elif w_to_p[words[i]] != pattern[i]: 31 | return False 32 | 33 | # print(w_to_p) 34 | return True 35 | 36 | 37 | print(wordPattern(pattern, s)) -------------------------------------------------------------------------------- /Python_/Graphs/makeGraph.py: -------------------------------------------------------------------------------- 1 | # undirected path 2 | 3 | # check if there exist a path for Node A to Node B 4 | 5 | 6 | edges = [ 7 | ["i", "j"], 8 | ['k', "i"], 9 | ["m", "k"], 10 | ["k", "l"], 11 | ["o", "n"] 12 | ] 13 | 14 | 15 | def buildGraph(edges): 16 | graph = {} 17 | 18 | for a, b in edges: 19 | if a not in graph: 20 | graph[a] = [] 21 | if b not in graph: 22 | graph[b] = [] 23 | 24 | graph[a].append(b) 25 | graph[b].append(a) 26 | 27 | return graph 28 | 29 | 30 | def hasPath(graph, src, dst, visited): 31 | if src == dst: 32 | return True 33 | 34 | # get rid of infinity loop 35 | 36 | if src in visited: 37 | return False 38 | 39 | visited.add(src) 40 | 41 | for n in graph[src]: 42 | if hasPath(graph, n, dst) == True: 43 | return True 44 | 45 | return False 46 | 47 | 48 | def main(): 49 | graph = buildGraph(edges) 50 | 51 | # visited = set() 52 | print(hasPath(graph, "i", "o", set())) 53 | 54 | 55 | main() 56 | -------------------------------------------------------------------------------- /Python_/blind75/10_mergeIntervals.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. 3 | 4 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 5 | Output: [[1,6],[8,10],[15,18]] 6 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 7 | 8 | Input: intervals = [[1,4],[4,5]] 9 | Output: [[1,5]] 10 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 11 | 12 | """ 13 | intervals = [[1,3],[2,6],[8,10],[15,18]] 14 | 15 | def mergeIntervals(intervals): 16 | # sort items in there starting value 17 | intervals.sort(key=lambda x:x[0]) 18 | # make list for the output 19 | output = [intervals[0]] 20 | 21 | for start, end in intervals[1:]: 22 | lastEnd = output[-1][1] 23 | 24 | if start <= lastEnd: 25 | output[-1][1] = max(lastEnd, end) 26 | else: 27 | output.append([start, end]) 28 | return output 29 | 30 | print(mergeIntervals(intervals)) -------------------------------------------------------------------------------- /Python_/Questions/easy/maximunSubarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/maximum-subarray/ 3 | 4 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 5 | 6 | A subarray is a contiguous part of an array. 7 | 8 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 9 | Output: 6 10 | Explanation: [4,-1,2,1] has the largest sum = 6. 11 | 12 | Input: nums = [1] 13 | Output: 1 14 | 15 | Input: nums = [5,4,-1,7,8] 16 | Output: 23 17 | """ 18 | 19 | nums = [-2,1,-3,4,-1,2,1,-5,4] 20 | 21 | # def maxSubArray(nums): 22 | # maxSub = nums[0] 23 | # curSum = 0 24 | 25 | # for n in nums: 26 | # if curSum < 0: 27 | # curSum = 0 28 | # curSum += n 29 | # maxSub = max(maxSub, curSum) 30 | # return maxSub 31 | 32 | # (Kadane's Algorithm) 33 | def maxSubArray(nums): 34 | curSum, largetSum = 0 , nums[0] 35 | for c in nums: 36 | curSum = max(c , curSum + c) 37 | largetSum = max(largetSum, curSum) 38 | 39 | return largetSum 40 | 41 | print(maxSubArray(nums)) -------------------------------------------------------------------------------- /Python_/qus/searcha2Dmatrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | 7 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 8 | Output: true 9 | 10 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 11 | Output: false 12 | """ 13 | matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]] 14 | target = 3 15 | 16 | def searchMatrix(matrix, target): 17 | row, COLS = len(matrix), len(matrix[0]) 18 | 19 | l , r = 0, row*COLS-1 20 | 21 | while l <= r: 22 | mid = (l+r)//2 23 | if matrix[mid//COLS][mid%COLS] == target: 24 | return True 25 | elif matrix[mid//COLS][mid%COLS] < target: 26 | l = mid +1 27 | elif matrix[mid//COLS][mid%COLS] > target: 28 | r = mid - 1 29 | return False 30 | 31 | print( 32 | searchMatrix(matrix, target) 33 | ) -------------------------------------------------------------------------------- /Python_/qus/constructBinaryTreeFromPreAndInorderTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. 3 | 4 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 5 | Output: [3,9,20,null,null,15,7] 6 | 7 | Input: preorder = [-1], inorder = [-1] 8 | Output: [-1] 9 | 10 | preorder -> root, left, right 11 | inorder -> left, root, right 12 | 13 | [3,9,20] 14 | """ 15 | 16 | # Definition for a binary tree node. 17 | class TreeNode: 18 | def __init__(self, val=0, left=None, right=None): 19 | self.val = val 20 | self.left = left 21 | self.right = right 22 | 23 | def buildTree(preorder, inorder): 24 | if not preorder or not inorder: 25 | return None 26 | 27 | root = TreeNode(preorder[0]) 28 | 29 | mid = inorder.index(preorder[0]) 30 | 31 | root.left = buildTree(preorder[1:mid+1], inorder[:mid]) 32 | root.right = buildTree(preorder[mid+1:], inorder[mid+1:]) 33 | 34 | return root 35 | -------------------------------------------------------------------------------- /Python_/Questions/longestIncreasingSubsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/longest-increasing-subsequence/ 3 | 4 | Given an integer array nums, return the length of the longest strictly increasing subsequence. 5 | 6 | A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. 7 | 8 | Input: nums = [10,9,2,5,3,7,101,18] 9 | Output: 4 10 | Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 11 | 12 | Input: nums = [0,1,0,3,2,3] 13 | Output: 4 14 | 15 | Input: nums = [7,7,7,7,7,7,7] 16 | Output: 1 17 | """ 18 | 19 | nums = [10,9,2,5,3,7,101,18] 20 | 21 | def longSubSequence(nums): 22 | # o(n^2) 23 | 24 | LIS = [1] * len(nums) 25 | 26 | for i in range(len(nums)-1, -1,-1): 27 | for j in range(i+1, len(nums)): 28 | if nums[i] < nums[j]: 29 | LIS[i] = max(LIS[i], 1 + LIS[j]) 30 | 31 | return max(LIS) 32 | 33 | print( 34 | longSubSequence(nums) 35 | ) -------------------------------------------------------------------------------- /Python_/Questions/squareOfSortedArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 3 | 4 | Input: nums = [-4,-1,0,3,10] 5 | Output: [0,1,9,16,100] 6 | Explanation: After squaring, the array becomes [16,1,0,9,100]. 7 | After sorting, it becomes [0,1,9,16,100]. 8 | """ 9 | 10 | nums = [-4,-1,0,3,10] 11 | 12 | # o(nlogn) 13 | print(sorted([i*i for i in nums])) 14 | 15 | 16 | # o(n) 17 | def sortedSquares(nums): 18 | result = [None] * len(nums) 19 | initial_indx = 0 20 | final_indx = len(nums)-1 21 | insertion_indx = len(nums)-1 22 | #compare the initial_indx and final_indx 23 | for _ in range(len(result)): 24 | if abs(nums[initial_indx]) < abs(nums[final_indx]): 25 | result[insertion_indx] = nums[final_indx] ** 2 26 | insertion_indx -= 1 27 | final_indx -= 1 28 | else: 29 | result[insertion_indx] = nums[initial_indx] ** 2 30 | insertion_indx -= 1 31 | initial_indx += 1 32 | return result -------------------------------------------------------------------------------- /Python_/qus/invertBinaryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, invert the tree, and return its root. 3 | 4 | Input: root = [4,2,7,1,3,6,9] 5 | Output: [4,7,2,9,6,3,1] 6 | 7 | Input: root = [2,1,3] 8 | Output: [2,3,1] 9 | 10 | Input: root = [] 11 | Output: [] 12 | """ 13 | 14 | # Definition for a binary tree node. 15 | class TreeNode: 16 | def __init__(self, val=0, left=None, right=None): 17 | self.val = val 18 | self.left = left 19 | self.right = right 20 | 21 | def revert(root): 22 | if not root: return [] 23 | 24 | stack = [root] 25 | while stack: 26 | curNode = stack.pop() 27 | if curNode: 28 | curNode.left, curNode.right = curNode.right, curNode.left 29 | # if curNode.right: 30 | stack.append(curNode.right) 31 | # if curNode.left: 32 | stack.append(curNode.left) 33 | 34 | 35 | root = TreeNode(4) 36 | root.left = TreeNode(2) 37 | root.left.left = TreeNode(1) 38 | root.left.right = TreeNode(3) 39 | root.right = TreeNode(7) 40 | root.right.left = TreeNode(6) 41 | root.right.right = TreeNode(9) -------------------------------------------------------------------------------- /Python_/DataStructure/symmetricTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/symmetric-tree/ 3 | 4 | Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). 5 | 6 | Input: root = [1,2,2,3,4,4,3] 7 | Output: true 8 | 9 | Input: root = [1,2,2,null,3,null,3] 10 | Output: false 11 | """ 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None): 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def isSymmetric(root): 21 | 22 | def isMirror(left, right): 23 | if left in None and right is None: 24 | return True 25 | if left in None or right is None: 26 | return False 27 | 28 | if left.val == right.val: 29 | outPair = isMirror(left.left, right.right) 30 | inPair = isMirror(left.right, right.left) 31 | return outPair and inPair 32 | else: 33 | return False 34 | 35 | if root is None: 36 | return True 37 | else: 38 | return isMirror(root.left, root.right) 39 | -------------------------------------------------------------------------------- /Python_/1_Recursion/l2.py: -------------------------------------------------------------------------------- 1 | # reverse an array 2 | 3 | # using 2 pointer 4 | def rev(l,r, arr): 5 | if l>=r: return 6 | arr[l],arr[r] = arr[r], arr[l] 7 | rev(l+1, r-1, arr) 8 | 9 | # using only 1 pointer 10 | def rev1(i,arr): 11 | """ 12 | n = len(arr) == 5 13 | n-1-1 == (5-1-1) = 4(get forth index) 14 | n-2-1 == (5-2-1) = 3(get third index) 15 | 16 | until i>n//2 (or in middle) 17 | """ 18 | n = len(arr) 19 | if i>n//2: 20 | return 21 | arr[i], arr[n-i-1] = arr[n-i-1], arr[i] 22 | rev1(i+1, arr) 23 | 24 | def reverse_array(arr): 25 | # rev(0,len(arr)-1, arr) 26 | rev1(0, arr) 27 | return arr 28 | 29 | 30 | 31 | # ------------------------- 32 | def check(idx, value): 33 | n = len(value) 34 | 35 | if idx > n//2: 36 | return True 37 | 38 | if value[idx] != value[n- idx -1]: 39 | return False 40 | 41 | return check(idx+1, value) 42 | 43 | def pallindrome(value): 44 | return(check(0, value)) 45 | 46 | # print(reverse_array([3,1,4,2,5])) 47 | print(pallindrome("hima")) 48 | print(pallindrome("raccar")) -------------------------------------------------------------------------------- /Python_/Graphs/01Matix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. 3 | 4 | The distance between two adjacent cells is 1. 5 | 6 | Input: mat = [[0,0,0], 7 | [0,1,0], 8 | [0,0,0]] 9 | Output: [[0,0,0],[0,1,0],[0,0,0]] 10 | 11 | Input: mat = [[0,0,0], 12 | [0,1,0], 13 | [1,1,1]] 14 | Output: [[0,0,0],[0,1,0],[1,2,1]] 15 | """ 16 | mat = [[0,0,0], 17 | [0,1,0], 18 | [1,1,1]] 19 | 20 | def updateMatrix(mat): 21 | r,c = len(mat), len(mat[0]) 22 | q = [] 23 | 24 | for i in range(r): 25 | for j in range(c): 26 | if mat[i][j] == 0: 27 | q.append((i,j)) 28 | else: 29 | mat[i][j] = "#" 30 | 31 | for row, col in q: 32 | for dx, dy in (1,0),(-1,0),(0,1),(0,-1): 33 | nr = row + dx 34 | nc = col + dy 35 | if 0 <= nr < r and 0<=nc n : 28 | return key 29 | 30 | # using sorting 31 | """ 32 | If the elements are sorted in monotonically increasing (or decreasing) order, the majority element can be found at index 33 | n/2 and n/2+1 incidentally, if n is even). 34 | """ 35 | # TC :- o(nlogn) 36 | # SC :- o(1) or o(n) 37 | def majorityElementSorting(nums): 38 | nums.sort() 39 | return nums[len(nums)//2] 40 | 41 | print( 42 | majorityElementSorting(nums) 43 | ) -------------------------------------------------------------------------------- /Python_/Questions/01Matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/01-matrix/ 3 | Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. 4 | 5 | The distance between two adjacent cells is 1. 6 | 7 | Input: mat = [[0,0,0],[0,1,0],[0,0,0]] 8 | Output: [[0,0,0],[0,1,0],[0,0,0]] 9 | 10 | Input: mat = [[0,0,0],[0,1,0],[1,1,1]] 11 | Output: [[0,0,0],[0,1,0],[1,2,1]] 12 | """ 13 | # mat = [[0,0,0],[0,1,0],[0,0,0]] 14 | mat = [[0,0,0],[0,1,0],[1,1,1]] 15 | 16 | def updateMatrix(mat): 17 | ROW, COl = len(mat), len(mat[0]) 18 | q = [] 19 | 20 | for i in range(ROW): 21 | for j in range(COl): 22 | if mat[i][j] == 0: 23 | q.append((i,j)) 24 | else: 25 | mat[i][j] = "#" 26 | 27 | for row, col in q: 28 | for dx, dy in (1,0),(-1,0),(0,1),(0,-1): 29 | nr = row + dx 30 | nc = col + dy 31 | 32 | if 0 <= nr < ROW and 0<= nc < COl and mat[nr][nc]== "#": 33 | mat[nr][nc] = mat[row][col]+1 34 | q.append((nr, nc)) 35 | 36 | return mat 37 | 38 | print( 39 | updateMatrix(mat) 40 | ) -------------------------------------------------------------------------------- /Python_/DataStructure/partitionLabels.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. 3 | 4 | Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. 5 | 6 | Return a list of integers representing the size of these parts. 7 | 8 | Input: s = "ababcbacadefegdehijhklij" 9 | Output: [9,7,8] 10 | Explanation: 11 | The partition is "ababcbaca", "defegde", "hijhklij". 12 | This is a partition so that each letter appears in at most one part. 13 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. 14 | 15 | Input: s = "eccbbbbdec" 16 | Output: [10] 17 | """ 18 | s = "ababcbacadefegdehijhklij" 19 | 20 | def partitionLabels(S): 21 | last = {c: i for i, c in enumerate(S)} 22 | j = anchor = 0 23 | ans = [] 24 | for i, c in enumerate(S): 25 | j = max(j, last[c]) 26 | if i == j: 27 | ans.append(i - anchor + 1) 28 | anchor = i + 1 29 | 30 | return ans 31 | 32 | print( 33 | partitionLabels(s) 34 | ) -------------------------------------------------------------------------------- /Python_/Questions/lognestSubstringWithoutRepeatingCharacters.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3. Longest Substring Without Repeating Characters 3 | Given a string s, find the length of the longest substring without repeating characters. 4 | Input: s = "abcabcbb" 5 | Output: 3 6 | Explanation: The answer is "abc", with the length of 3. 7 | 8 | Input: s = "bbbbb" 9 | Output: 1 10 | Explanation: The answer is "b", with the length of 1. 11 | 12 | Input: s = "pwwkew" 13 | Output: 3 14 | Explanation: The answer is "wke", with the length of 3. 15 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 16 | 17 | https://leetcode.com/problems/longest-substring-without-repeating-characters/ 18 | """ 19 | # n = "bbbbb" 20 | # n = "abcabcbb" 21 | n = "pwwkew" 22 | 23 | def lengthOfLongestSubstring(n): 24 | chatSet = set() 25 | l = 0 26 | result = 0 27 | for r in range(len(n)): 28 | while n[r] in chatSet: 29 | chatSet.remove(n[l]) 30 | l+=1 31 | chatSet.add(n[r]) 32 | 33 | result = max(result, r-l+1) 34 | return result 35 | 36 | 37 | print( 38 | lengthOfLongestSubstring(n) 39 | ) 40 | -------------------------------------------------------------------------------- /Python_/leetCode75/isomorphic_strings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s and t, determine if they are isomorphic. 3 | 4 | Two strings s and t are isomorphic if the characters in s can be replaced to get t. 5 | 6 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. 7 | 8 | Input: s = "egg", t = "add" 9 | Output: true 10 | 11 | Input: s = "foo", t = "bar" 12 | Output: false 13 | 14 | Input: s = "paper", t = "title" 15 | Output: true 16 | """ 17 | 18 | 19 | def isIsomorphic(s, t): 20 | mapping_s_t = {} 21 | mapping_t_s = {} 22 | 23 | for c1, c2 in zip(s, t): 24 | if c1 not in mapping_s_t and c2 not in mapping_t_s: 25 | mapping_s_t[c1] = c2 26 | mapping_t_s[c2] = c1 27 | elif mapping_s_t.get(c1) != c2 or mapping_t_s.get(c2) != c1: 28 | return False 29 | 30 | return True 31 | 32 | 33 | print( 34 | isIsomorphic("egg", "add"), 35 | isIsomorphic("foo", "bar"), 36 | isIsomorphic("paper", "title"), 37 | isIsomorphic("badc", "baba") 38 | ) 39 | -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/gridTraveler.js: -------------------------------------------------------------------------------- 1 | /* 2 | say that you are a traveler on a 2D grid, you begin in the top-left corner and your goal is to travel to the bottom-right corner. you may only move down or right. 3 | 4 | In how many ways you travel to the goal on a grid with m*n grid 5 | 6 | */ 7 | // TC:- O(mn) 8 | // SC:- O(mn) 9 | const grid = (m, n) => { 10 | const table = Array(m + 1) 11 | .fill() 12 | .map(() => Array(n + 1).fill(0)); 13 | table[1][1] = 1; 14 | 15 | for (let i = 0; i <= m; i++) { 16 | for (let j = 0; j <= n; j++) { 17 | const current = table[i][j]; 18 | if (j + 1 <= n) table[i][j + 1] += current; 19 | if (i + 1 <= m) table[i + 1][j] += current; 20 | } 21 | } 22 | return table[m][n]; 23 | }; 24 | 25 | console.log(grid(3, 2)); 26 | console.log(grid(30, 20)); 27 | 28 | // Tabulation Recipe 29 | /* 30 | - visualize the problem as a table 31 | - size the table based on the inputs 32 | - initalize the table with default values 33 | - seed the trivial answer into the table 34 | - iterate through the table 35 | - fill further positions based on the current position 36 | */ 37 | -------------------------------------------------------------------------------- /Python_/Graphs/basic.py: -------------------------------------------------------------------------------- 1 | 2 | graph = { 3 | "a": ["b", "c"], 4 | "b": ["d", "c"], 5 | "c": ["e"], 6 | "d": ["f"], 7 | "e": [], 8 | "f": [] 9 | } 10 | """ 11 | a -> c 12 | | | 13 | b < - e 14 | | 15 | d - > f 16 | """ 17 | 18 | 19 | def depthFirstTraversal(graph, node): 20 | stack = [node] 21 | 22 | while len(stack) > 0: 23 | current = stack.pop() 24 | print(current, end="-") 25 | 26 | for n in graph[current]: 27 | stack.append(n) 28 | print("\n") 29 | 30 | 31 | def depthFirstTraversalRecurssive(graph, node): 32 | print(node, end="-") 33 | 34 | for n in graph[node]: 35 | depthFirstTraversalRecurssive(graph, n) 36 | 37 | 38 | def BreadthFirstTraversal(graph, node): 39 | queue = [node] 40 | 41 | while len(queue) > 0: 42 | current = queue.pop(0) 43 | print(current, end="-") 44 | 45 | for n in graph[current]: 46 | queue.append(n) 47 | 48 | print("\n") 49 | 50 | 51 | # depthFirstTraversal(graph, "a") 52 | # depthFirstTraversalRecurssive(graph, "a") 53 | 54 | 55 | # BreadthFirstTraversal(graph, "a") 56 | -------------------------------------------------------------------------------- /Python_/Questions/rotateArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array, rotate the array to the right by k steps, where k is non-negative. 3 | 4 | Input: nums = [1,2,3,4,5,6,7], k = 3 5 | Output: [5,6,7,1,2,3,4] 6 | Explanation: 7 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 8 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 9 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 10 | """ 11 | 12 | nums = [1,2,3,4,5,6,7] 13 | k = 3 14 | # nums = [-1,-100,3,99] 15 | # k = 2 16 | 17 | def rotation(nums, k): 18 | # first reverse array 19 | l,r = 0, len(nums)-1 20 | 21 | k = k % len(nums) 22 | 23 | # reverse whole array 24 | while l < r: 25 | nums[l] , nums[r] = nums[r], nums[l] 26 | l +=1 27 | r -=1 28 | 29 | # reverse 30 | l,r = 0, k-1 31 | while l < r: 32 | nums[l], nums[r] = nums[r], nums[l] 33 | l+=1 34 | r-=1 35 | 36 | # reverse k 37 | l,r = k, len(nums)-1 38 | while l < r: 39 | nums[l], nums[r] = nums[r], nums[l] 40 | l+=1 41 | r-=1 42 | 43 | return nums 44 | 45 | 46 | 47 | 48 | 49 | print(rotation(nums, k)) 50 | 51 | 52 | -------------------------------------------------------------------------------- /Python_/pattern_/max_depth_bt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return its maximum depth. 3 | 4 | A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | Input: root = [3,9,20,null,null,15,7] 7 | Output: 3 8 | 9 | Input: root = [1,null,2] 10 | Output: 2 11 | """ 12 | 13 | 14 | class Node: 15 | def __init__(self, val): 16 | self.val = val 17 | self.right = None 18 | self.left = None 19 | 20 | 21 | def maxDepth(root): 22 | if not root: 23 | return 0 24 | 25 | result = 0 26 | 27 | stack = [root] 28 | 29 | while stack: 30 | result += 1 31 | for _ in range(len(stack)): 32 | node = stack.pop(0) 33 | 34 | if node: 35 | if node.left: 36 | stack.append(node.left) 37 | 38 | if node.right: 39 | stack.append(node.right) 40 | 41 | return result 42 | 43 | 44 | root = Node(3) 45 | root.left = Node(9) 46 | root.right = Node(20) 47 | root.right.left = Node(15) 48 | root.right.right = Node(7) 49 | 50 | print(maxDepth(root)) 51 | -------------------------------------------------------------------------------- /Python_/DataStructure/consturctBinaryTreeFromPreorderAndInorderTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 3 | 4 | Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. 5 | 6 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 7 | Output: [3,9,20,null,null,15,7] 8 | 9 | Input: preorder = [-1], inorder = [-1] 10 | Output: [-1] 11 | """ 12 | 13 | # Definition for a binary tree node. 14 | class TreeNode: 15 | def __init__(self, val=0, left=None, right=None): 16 | self.val = val 17 | self.left = left 18 | self.right = right 19 | 20 | 21 | def buildTree(preorder, inorder): 22 | if not preorder or not inorder: 23 | return None 24 | 25 | root = TreeNode(preorder[0]) 26 | 27 | # find pos in inorder array 28 | mid = inorder.index(preorder[0]) 29 | 30 | root.left = buildTree(preorder[1:mid+1], inorder[:mid]) 31 | root.right = buildTree(preorder[mid+1:], inorder[mid+1:]) 32 | 33 | return root 34 | 35 | 36 | -------------------------------------------------------------------------------- /Python_/Questions/3Sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/3sum/ 3 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 4 | 5 | Notice that the solution set must not contain duplicate triplets. 6 | 7 | Input: nums = [-1,0,1,2,-1,-4] 8 | Output: [[-1,-1,2],[-1,0,1]] 9 | 10 | Input: nums = [] 11 | Output: [] 12 | 13 | Input: nums = [0] 14 | Output: [] 15 | """ 16 | nums = [-1,0,1,2,-1,-4] 17 | 18 | 19 | def threeSum(nums): 20 | nums.sort() 21 | triplates = [] 22 | 23 | for i in range(len(nums)-2): 24 | left = i +1 25 | right = len(nums)-1 26 | 27 | while left < right: 28 | currentSum = nums[i] + nums[left] + nums[right] 29 | 30 | if currentSum == 0: 31 | triplates.append([nums[i], nums[left], nums[right]]) 32 | left +=1 33 | right -=1 34 | elif currentSum < 0: 35 | left +=1 36 | elif currentSum > 0: 37 | right -=1 38 | return triplates 39 | 40 | 41 | print( 42 | set(threeSum(nums)) 43 | ) 44 | -------------------------------------------------------------------------------- /Python_/blind75/4_containerWithMostWater.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 3 | 4 | Find two lines that together with the x-axis form a container, such that the container contains the most water. 5 | 6 | Return the maximum amount of water a container can store. 7 | 8 | Notice that you may not slant the container. 9 | 10 | Input: height = [1,8,6,2,5,4,8,3,7] 11 | Output: 49 12 | Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 13 | 14 | Input: height = [1,1] 15 | Output: 1 16 | """ 17 | height = [1,8,6,2,5,4,8,3,7] 18 | 19 | def maxArea(height): 20 | area = 0 21 | left = 0 22 | right = len(height)-1 23 | 24 | while left <= right: 25 | res = (right - left) * min(height[left], height[right]) 26 | area = max(res, area) 27 | 28 | if height[left] > height[right]: 29 | right -=1 30 | else: 31 | left +=1 32 | 33 | 34 | return area 35 | 36 | print(maxArea(height)) -------------------------------------------------------------------------------- /Python_/dp/coinChange.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 3 | 4 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 5 | 6 | You may assume that you have an infinite number of each kind of coin. 7 | 8 | Input: coins = [1,2,5], amount = 11 9 | Output: 3 10 | Explanation: 11 = 5 + 5 + 1 11 | 12 | Input: coins = [2], amount = 3 13 | Output: -1 14 | 15 | Input: coins = [1], amount = 0 16 | Output: 0 17 | """ 18 | 19 | coins = [1,2,5] 20 | amount = 11 21 | 22 | def coinChange(coins, amount): 23 | dp = [0] + [float('inf') for i in range(amount)] 24 | print(dp) 25 | for i in range(1, amount+1): 26 | for coin in coins: 27 | print(f"i => {i}, coin => {coin}, i-coin => {i-coin}") 28 | print(dp) 29 | if i - coin >= 0: 30 | dp[i] = min(dp[i], dp[i-coin]+1) 31 | print(" ") 32 | if dp[-1] == float('inf'): 33 | return -1 34 | 35 | return dp[-1] 36 | 37 | print(coinChange(coins, amount)) -------------------------------------------------------------------------------- /Python_/leetCode75/merge_two_llist.py: -------------------------------------------------------------------------------- 1 | from linked_list import LinkedList 2 | 3 | 4 | list1 = LinkedList() 5 | list1.append("1") 6 | list1.append("5") 7 | list1.append("7") 8 | list1.append("9") 9 | list1.append("10") 10 | 11 | list2 = LinkedList() 12 | list2.append("2") 13 | list2.append("3") 14 | list2.append("4") 15 | list2.append("6") 16 | list2.append("8") 17 | 18 | 19 | def merge_to_list(list1, list2): 20 | P = list1.head 21 | Q = list2.head 22 | S = None 23 | 24 | if not P: 25 | return Q 26 | 27 | if not Q: 28 | return P 29 | 30 | if P and Q: 31 | if P.data <= Q.data: 32 | S = P 33 | P = S.next 34 | else: 35 | S = Q 36 | Q = S.next 37 | 38 | new_head = S 39 | 40 | while P and Q: 41 | if P.data <= Q.data: 42 | S.next = P 43 | S = P 44 | P = S.next 45 | else: 46 | S.next = Q 47 | S = Q 48 | Q = S.next 49 | 50 | if not P: 51 | S.next = Q 52 | else: 53 | S.next = P 54 | 55 | return new_head 56 | 57 | 58 | merge_to_list(list1, list2) 59 | list1.print_list() 60 | -------------------------------------------------------------------------------- /Python_/qus/bestTimeTobuyAndSell.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 3 | 4 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 5 | 6 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 7 | 8 | Input: prices = [7,1,5,3,6,4] 9 | Output: 5 10 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 11 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 12 | 13 | Input: prices = [7,6,4,3,1] 14 | Output: 0 15 | Explanation: In this case, no transactions are done and the max profit = 0. 16 | """ 17 | prices = [7,1,5,3,6,4] 18 | 19 | def maxProfit(prices): 20 | buy, sell =0, 1 21 | maxP = 0 22 | while sell < len(prices): 23 | if prices[buy] < prices[sell]: 24 | profit = prices[sell] - prices[buy] 25 | maxP = max(maxP, profit) 26 | else: 27 | buy = sell 28 | sell +=1 29 | return maxP 30 | 31 | 32 | print( 33 | maxProfit(prices) 34 | ) -------------------------------------------------------------------------------- /Python_/blind75/13_maximumDepthofBinaryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return its maximum depth. 3 | 4 | A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | Input: root = [3,9,20,null,null,15,7] 7 | Output: 3 8 | 9 | Input: root = [1,null,2] 10 | Output: 2 11 | """ 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None): 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | def maxHeight(root): 20 | if not root: return 0 21 | 22 | stack = [root] 23 | m = 0 24 | while stack: 25 | currentMax = 0 26 | for _ in range(len(stack)): 27 | currentMax+=1 28 | node = stack.pop(0) 29 | if node.left: 30 | stack.append(node.left) 31 | if node.right: 32 | stack.append(node.right) 33 | 34 | m = max(m, currentMax) 35 | return m +1 36 | 37 | root = TreeNode(3) 38 | root.left = TreeNode(9) 39 | root.right = TreeNode(20) 40 | root.right.left = TreeNode(15) 41 | root.right.right = TreeNode(7) 42 | 43 | print(maxHeight(root)) -------------------------------------------------------------------------------- /Python_/stack/largestRectangleInHistogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/largest-rectangle-in-histogram/ 3 | 4 | Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. 5 | 6 | Input: heights = [2,1,5,6,2,3] 7 | Output: 10 8 | Explanation: The above is a histogram where width of each bar is 1. 9 | The largest rectangle is shown in the red area, which has an area = 10 units. 10 | 11 | Input: heights = [2,4] 12 | Output: 4 13 | """ 14 | 15 | # heights = [2,1,5,6,2,3] 16 | heights = [2] 17 | 18 | def lagestRectangleArea(heights): 19 | maxArea = 0 20 | stack = [] # pair : (index, height) 21 | 22 | for i , h in enumerate(heights): 23 | start = i 24 | while stack and stack[-1][1] > h: 25 | index, height = stack.pop() 26 | maxArea = max(maxArea, height * (i - index)) 27 | start = index 28 | stack.append((start, h)) 29 | 30 | for i , h in stack: 31 | maxArea = max(maxArea, h * (len(heights)- i )) 32 | 33 | return maxArea 34 | 35 | 36 | 37 | print( 38 | lagestRectangleArea(heights) 39 | ) -------------------------------------------------------------------------------- /Python_/Questions/stack/largestRectangleInHistogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/largest-rectangle-in-histogram/ 3 | 4 | Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. 5 | 6 | Input: heights = [2,1,5,6,2,3] 7 | Output: 10 8 | Explanation: The above is a histogram where width of each bar is 1. 9 | The largest rectangle is shown in the red area, which has an area = 10 units. 10 | 11 | Input: heights = [2,4] 12 | Output: 4 13 | """ 14 | 15 | # heights = [2,1,5,6,2,3] 16 | heights = [2] 17 | 18 | def lagestRectangleArea(heights): 19 | maxArea = 0 20 | stack = [] # pair : (index, height) 21 | 22 | for i , h in enumerate(heights): 23 | start = i 24 | while stack and stack[-1][1] > h: 25 | index, height = stack.pop() 26 | maxArea = max(maxArea, height * (i - index)) 27 | start = index 28 | stack.append((start, h)) 29 | 30 | for i , h in stack: 31 | maxArea = max(maxArea, h * (len(heights)- i )) 32 | 33 | return maxArea 34 | 35 | 36 | 37 | print( 38 | lagestRectangleArea(heights) 39 | ) -------------------------------------------------------------------------------- /Python_/LinkedList/single_linked_list/merge_to_list.py: -------------------------------------------------------------------------------- 1 | from linked_list import LinkedList 2 | 3 | 4 | list1 = LinkedList() 5 | list1.append("1") 6 | list1.append("5") 7 | list1.append("7") 8 | list1.append("9") 9 | list1.append("10") 10 | 11 | list2 = LinkedList() 12 | list2.append("2") 13 | list2.append("3") 14 | list2.append("4") 15 | list2.append("6") 16 | list2.append("8") 17 | 18 | 19 | def merge_to_list(list1, list2): 20 | P = list1.head 21 | Q = list2.head 22 | S = None 23 | 24 | if not P: 25 | return Q 26 | 27 | if not Q: 28 | return P 29 | 30 | if P and Q: 31 | if P.data <= Q.data: 32 | S = P 33 | P = S.next 34 | else: 35 | S = Q 36 | Q = S.next 37 | 38 | new_head = S 39 | 40 | while P and Q: 41 | if P.data <= Q.data: 42 | S.next = P 43 | S = P 44 | P = S.next 45 | else: 46 | S.next = Q 47 | S = Q 48 | Q = S.next 49 | 50 | if not P: 51 | S.next = Q 52 | else: 53 | S.next = P 54 | 55 | return new_head 56 | 57 | 58 | merge_to_list(list1, list2) 59 | list1.print_list() 60 | -------------------------------------------------------------------------------- /Python_/pattern_/missing_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. 3 | 4 | Input: nums = [3,0,1] 5 | Output: 2 6 | Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. 7 | 8 | Input: nums = [0,1] 9 | Output: 2 10 | Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. 11 | 12 | Input: nums = [9,6,4,2,3,5,7,0,1] 13 | Output: 8 14 | Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. 15 | """ 16 | 17 | """ 18 | n(n+1)/2 19 | 20 | 5(5+1)/2 21 | 5(6)/2 22 | 30/2 23 | 15 24 | """ 25 | 26 | 27 | def find_missing(nums): 28 | n = len(nums) 29 | n_number_sums = n * (n+1)//2 30 | 31 | return abs(sum(nums) - n_number_sums) 32 | 33 | 34 | print( 35 | find_missing([3, 0, 1]), 36 | find_missing([0, 1]), 37 | find_missing([9, 6, 4, 2, 3, 5, 7, 0, 1]) 38 | 39 | ) 40 | -------------------------------------------------------------------------------- /Python_/blind75/12_binaryTreeLevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 3 | 4 | Input: root = [3,9,20,null,null,15,7] 5 | Output: [[3],[9,20],[15,7]] 6 | 7 | Input: root = [1] 8 | Output: [[1]] 9 | 10 | Input: root = [] 11 | Output: [] 12 | """ 13 | 14 | class TreeNode: 15 | def __init__(self, val=0, left=None, right=None): 16 | self.val = val 17 | self.left = left 18 | self.right = right 19 | 20 | def levelOrder(node): 21 | if not node: return [] 22 | 23 | stack = [node] 24 | result = [] 25 | while stack: 26 | values = [] 27 | for _ in range(len(stack)): 28 | curNode = stack.pop(0) 29 | values.append(curNode.val) 30 | if curNode.left: 31 | stack.append(curNode.left) 32 | if curNode.right: 33 | stack.append(curNode.right) 34 | result.append(values) 35 | return result 36 | 37 | root = TreeNode(3) 38 | root.left = TreeNode(9) 39 | root.right = TreeNode(20) 40 | root.right.left = TreeNode(15) 41 | root.right.right = TreeNode(7) 42 | 43 | print(levelOrder(root)) -------------------------------------------------------------------------------- /Python_/dp/grid_uniquePath.py: -------------------------------------------------------------------------------- 1 | """ 2 | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. 3 | 4 | Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 5 | 6 | The test cases are generated so that the answer will be less than or equal to 2 * 109. 7 | 8 | Input: m = 3, n = 7 9 | Output: 28 10 | 11 | Input: m = 3, n = 2 12 | Output: 3 13 | Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 14 | 1. Right -> Down -> Down 15 | 2. Down -> Down -> Right 16 | 3. Down -> Right -> Down 17 | """ 18 | 19 | 20 | def uniquePath(m: int, n: int) -> int: 21 | 22 | def backtrack(i, j): 23 | if i == m-1 and j == n-1: 24 | return 1 25 | if i > m or j > n: 26 | return 0 27 | 28 | right = backtrack(i, j+1) 29 | down = backtrack(i+1, j) 30 | 31 | return right + down 32 | 33 | return backtrack(0, 0) 34 | 35 | 36 | print( 37 | uniquePath(3, 2) 38 | ) 39 | -------------------------------------------------------------------------------- /Python_/DataStructure/nonOverlappingIntervals.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/non-overlapping-intervals/ 3 | 4 | Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. 5 | 6 | Input: intervals = [[1,2],[2,3],[3,4],[1,3]] 7 | Output: 1 8 | Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. 9 | 10 | Input: intervals = [[1,2],[1,2],[1,2]] 11 | Output: 2 12 | Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. 13 | 14 | Input: intervals = [[1,2],[2,3]] 15 | Output: 0 16 | Explanation: You don't need to remove any of the intervals since they're already non-overlapping. 17 | """ 18 | 19 | intervals = [[1,2],[2,3],[3,4],[1,3]] 20 | 21 | def eraseOverlapIntervals(intervals): 22 | intervals.sort(key=lambda x:x[0]) 23 | 24 | res = 0 25 | prevEnd = intervals[0][1] 26 | for start, end in intervals[1:]: 27 | if start >= prevEnd: 28 | prevEnd = end 29 | else: 30 | res +=1 31 | prevEnd = min(end, prevEnd) 32 | 33 | return res 34 | 35 | 36 | print(eraseOverlapIntervals(intervals)) -------------------------------------------------------------------------------- /Python_/blind75/8_3sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 3 | 4 | Notice that the solution set must not contain duplicate triplets. 5 | 6 | Input: nums = [-1,0,1,2,-1,-4] 7 | Output: [[-1,-1,2],[-1,0,1]] 8 | 9 | Input: nums = [] 10 | Output: [] 11 | 12 | Input: nums = [0] 13 | Output: [] 14 | """ 15 | nums = [-2,0,0,2,2] 16 | 17 | def threeSum(nums): 18 | nums.sort() 19 | result = [] 20 | 21 | for i in range(len(nums)-2): 22 | if i >0 and nums[i]==nums[i-1]: 23 | continue 24 | l,r = i+1, len(nums)-1 25 | 26 | while l < r: 27 | s = nums[i] + nums[l]+ nums[r] 28 | if s < 0: 29 | l+=1 30 | elif s > 0 : 31 | r-=1 32 | else: 33 | result.append([nums[i], nums[l], nums[r]]) 34 | while l height[right]: 28 | right -=1 29 | else: 30 | left +=1 31 | 32 | return maxArea 33 | 34 | print( 35 | containerWithMostWater(height) 36 | ) -------------------------------------------------------------------------------- /Python_/Questions/mergeTwoSortedList.py: -------------------------------------------------------------------------------- 1 | # iteratively 2 | def mergeTwoLists1(self, l1, l2): 3 | dummy = cur = ListNode(0) 4 | while l1 and l2: 5 | if l1.val < l2.val: 6 | cur.next = l1 7 | l1 = l1.next 8 | else: 9 | cur.next = l2 10 | l2 = l2.next 11 | cur = cur.next 12 | cur.next = l1 or l2 13 | return dummy.next 14 | 15 | # recursively 16 | def mergeTwoLists2(self, l1, l2): 17 | if not l1 or not l2: 18 | return l1 or l2 19 | if l1.val < l2.val: 20 | l1.next = self.mergeTwoLists(l1.next, l2) 21 | return l1 22 | else: 23 | l2.next = self.mergeTwoLists(l1, l2.next) 24 | return l2 25 | 26 | # in-place, iteratively 27 | def mergeTwoLists(self, l1, l2): 28 | if None in (l1, l2): 29 | return l1 or l2 30 | dummy = cur = ListNode(0) 31 | dummy.next = l1 32 | while l1 and l2: 33 | if l1.val < l2.val: 34 | l1 = l1.next 35 | else: 36 | nxt = cur.next 37 | cur.next = l2 38 | tmp = l2.next 39 | l2.next = nxt 40 | l2 = tmp 41 | cur = cur.next 42 | cur.next = l1 or l2 43 | return dummy.next -------------------------------------------------------------------------------- /Python_/dp/lognestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, return the longest palindromic substring in s. 3 | 4 | Input: s = "babad" 5 | Output: "bab" 6 | Explanation: "aba" is also a valid answer. 7 | 8 | Input: s = "cbbd" 9 | Output: "bb" 10 | """ 11 | s = "babad" 12 | 13 | def longestPalindrome(s): 14 | n = len(s) 15 | dp = [[False]*n for _ in range(n)] 16 | for i in range(n): 17 | dp[i][i] = True 18 | 19 | longest_palindrome_start, longest_palindrome_len = 0,1 20 | 21 | for end in range(0,n): 22 | for start in range(end-1,-1,-1): 23 | # print(f"start :- {start}, end :{end}") 24 | if s[start] == s[end]: 25 | if end - start == 1 or dp[start+1][end-1]: 26 | print(s[start:end+1]) 27 | dp[start][end] = True 28 | palindrome_len = end - start +1 29 | 30 | if longest_palindrome_len < palindrome_len: 31 | longest_palindrome_start = start 32 | longest_palindrome_len = palindrome_len 33 | 34 | return s[longest_palindrome_start: longest_palindrome_start+longest_palindrome_len] 35 | 36 | print( 37 | longestPalindrome(s) 38 | ) -------------------------------------------------------------------------------- /Python_/Questions/premutationInString.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. 3 | 4 | In other words, return true if one of s1's permutations is the substring of s2. 5 | 6 | 7 | Input: s1 = "ab", s2 = "eidbaooo" 8 | Output: true 9 | Explanation: s2 contains one permutation of s1 ("ba"). 10 | 11 | Input: s1 = "ab", s2 = "eidboaoo" 12 | Output: false 13 | 14 | https://leetcode.com/problems/permutation-in-string/ 15 | """ 16 | s1 = "ab" 17 | s2 = "eidboaoo" 18 | 19 | def checkInclusion(s1, s2): 20 | freq1 = {} 21 | freq2 = {} 22 | 23 | for i in range(len(s1)): 24 | if s1[i] not in freq1: 25 | freq1[s1[i]] = 1 26 | else: 27 | freq1[s1[i]] +=1 28 | 29 | for i in range(len(s2)): 30 | if s2[i] not in freq2: 31 | freq2[s2[i]] = 1 32 | else: 33 | freq2[s2[i]] +=1 34 | 35 | 36 | for i, v in freq1.items(): 37 | # print(i,v) 38 | if i in freq2.keys(): 39 | print(v, freq2[i]) 40 | # if v == freq2[i]: 41 | # return True 42 | else: 43 | return False 44 | 45 | print( 46 | checkInclusion(s1, s2) 47 | ) -------------------------------------------------------------------------------- /Python_/Questions/findPeakElement.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/find-peak-element/ 3 | 4 | A peak element is an element that is strictly greater than its neighbors. 5 | 6 | Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. 7 | 8 | You may imagine that nums[-1] = nums[n] = -∞. 9 | 10 | You must write an algorithm that runs in O(log n) time. 11 | 12 | Input: nums = [1,2,3,1] 13 | Output: 2 14 | Explanation: 3 is a peak element and your function should return the index number 2. 15 | 16 | Input: nums = [1,2,1,3,5,6,4] 17 | Output: 5 18 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. 19 | 20 | """ 21 | nums = [1,2,3,1] 22 | 23 | def findPeak(nums): 24 | l, r = 0, len(nums)-1 25 | 26 | while l < r - 1: 27 | mid = (l+r)//2 28 | 29 | if nums[mid] > nums[mid+1] and nums[mid]> nums[mid-1]: 30 | return mid 31 | 32 | if nums[mid] < nums[mid +1]: 33 | l = mid +1 34 | else: 35 | r = mid -1 36 | 37 | return l if nums[l] >= nums[r] else r 38 | 39 | 40 | 41 | print( 42 | findPeak(nums) 43 | ) -------------------------------------------------------------------------------- /JavaScript_/Graphs/makeGraph.js: -------------------------------------------------------------------------------- 1 | const edges = [ 2 | ["i", "j"], 3 | ['k', "i"], 4 | ["m", "k"], 5 | ["k", "l"], 6 | ["o", "n"] 7 | ]; 8 | 9 | // check cycle in undirected graph 10 | 11 | const undirectedPath = (edges, nodeA, nodeB) => { 12 | const graph = buildGraph(edges) 13 | // console.log(graph) 14 | return hasPath(graph, nodeA, nodeB, new Set()) 15 | } 16 | 17 | 18 | // travel in graph 19 | const hasPath = (graph, src, des, visited) => { 20 | if(des === src) return true; 21 | 22 | // check for cycle 23 | if(visited.has(src)) return false; 24 | visited.add(src); 25 | 26 | 27 | for (let n of graph[src]){ 28 | if((hasPath(graph, n, des, visited)) === true){ 29 | return true; 30 | } 31 | } 32 | 33 | return false 34 | } 35 | 36 | 37 | 38 | // make graph form edges 39 | const buildGraph = (edges)=> { 40 | const graph = {}; 41 | 42 | for (let edge of edges){ 43 | const [a, b] = edge; 44 | 45 | if (!(a in graph))graph[a] = []; 46 | if (!(b in graph))graph[b] = []; 47 | 48 | graph[a].push(b); 49 | graph[b].push(a); 50 | 51 | } 52 | 53 | return graph; 54 | 55 | 56 | } 57 | 58 | console.log(undirectedPath(edges, "j", "n")) -------------------------------------------------------------------------------- /Python_/DataStructure/threeSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/3sum/ 3 | 4 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 5 | 6 | Notice that the solution set must not contain duplicate triplets. 7 | 8 | Input: nums = [-1,0,1,2,-1,-4] 9 | Output: [[-1,-1,2],[-1,0,1]] 10 | 11 | Input: nums = [] 12 | Output: [] 13 | 14 | Input: nums = [0] 15 | Output: [] 16 | """ 17 | 18 | nums = [-1,0,1,2,-1,-4] 19 | 20 | def threeSum(nums): 21 | res = [] 22 | nums.sort() 23 | for i in range(len(nums)-2): 24 | if i > 0 and nums[i] == nums[i-1]: 25 | continue 26 | l, r = i+1, len(nums)-1 27 | while l < r: 28 | s = nums[i] + nums[l] + nums[r] 29 | if s < 0: 30 | l +=1 31 | elif s > 0: 32 | r -= 1 33 | else: 34 | res.append((nums[i], nums[l], nums[r])) 35 | while l < r and nums[l] == nums[l+1]: 36 | l += 1 37 | while l < r and nums[r] == nums[r-1]: 38 | r -= 1 39 | l += 1; r -= 1 40 | return res 41 | 42 | print( 43 | threeSum(nums) 44 | ) -------------------------------------------------------------------------------- /JavaScript_/BinaryTree/dfs.js: -------------------------------------------------------------------------------- 1 | class Node{ 2 | constructor(val){ 3 | this.val = val; 4 | this.left = null; 5 | this.right= null; 6 | } 7 | 8 | } 9 | 10 | const depthFirstValue = (root) =>{ 11 | 12 | if (root === null)return []; 13 | 14 | const result = []; 15 | const stack = [root]; 16 | while(stack.length > 0){ 17 | const current = stack.pop() 18 | 19 | result.push(current.val); 20 | 21 | if (current.left) 22 | stack.push(current.left) 23 | if (current.right) 24 | stack.push(current.right) 25 | 26 | 27 | 28 | } 29 | return result; 30 | 31 | } 32 | 33 | 34 | const depthFirstValueRecurssive = (root) =>{ 35 | 36 | if(root === null) return []; 37 | 38 | const leftValues = depthFirstValueRecurssive(root.left); 39 | const rightValues = depthFirstValueRecurssive(root.right); 40 | 41 | return [root.val, ...leftValues, ...rightValues] 42 | 43 | } 44 | 45 | 46 | const a = new Node("A") 47 | const b = new Node("B") 48 | const c = new Node("C") 49 | const d = new Node("D") 50 | const e = new Node("E") 51 | const f = new Node("F") 52 | 53 | a.left = b; 54 | a.right = c; 55 | b.left = d ; 56 | b.right = e ; 57 | c.right = f; 58 | 59 | 60 | console.log( 61 | depthFirstValue(a) 62 | ) -------------------------------------------------------------------------------- /Python_/qus/3sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 3 | 4 | Notice that the solution set must not contain duplicate triplets. 5 | 6 | Input: nums = [-1,0,1,2,-1,-4] 7 | Output: [[-1,-1,2],[-1,0,1]] 8 | 9 | Input: nums = [] 10 | Output: [] 11 | 12 | Input: nums = [0] 13 | Output: [] 14 | """ 15 | nums = [-1,0,1,2,-1,-4] 16 | 17 | def threeSum(nums): 18 | nums.sort() 19 | result = [] 20 | 21 | for i in range(len(nums)-2): 22 | if i > 0 and nums[i] == nums[i-1]: 23 | continue 24 | left , right = i+1, len(nums)-1 25 | 26 | while left < right: 27 | s = nums[i] + nums[left] + nums[right] 28 | 29 | if s > 0: 30 | right -=1 31 | elif s < 0: 32 | left +=1 33 | else: 34 | result.append([nums[i], nums[left], nums[right]]) 35 | while left < right and nums[left] == nums[left +1]: 36 | left +=1 37 | while left < right and nums[right] == nums[right -1]: 38 | right -=1 39 | left+=1; right -=1 40 | return result 41 | 42 | print(threeSum(nums)) -------------------------------------------------------------------------------- /Python_/qus/binaryTreeLevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 3 | 4 | Input: root = [3,9,20,null,null,15,7] 5 | Output: [[3],[9,20],[15,7]] 6 | 7 | Input: root = [1] 8 | Output: [[1]] 9 | 10 | Input: root = [] 11 | Output: [] 12 | """ 13 | 14 | # Definition for a binary tree node. 15 | class TreeNode: 16 | def __init__(self, val=0, left=None, right=None): 17 | self.val = val 18 | self.left = left 19 | self.right = right 20 | 21 | def levelOrdertraversal(root): 22 | if not root: return [] 23 | 24 | stack = [root] 25 | result = [] 26 | 27 | while stack: 28 | current = [] 29 | for _ in range(len(stack)): 30 | curNode = stack.pop(0) 31 | current.append(curNode.val) 32 | if curNode.left: 33 | stack.append(curNode.left) 34 | if curNode.right: 35 | stack.append(curNode.right) 36 | result.append(current) 37 | return result 38 | 39 | root = TreeNode(3) 40 | root.left = TreeNode(9) 41 | root.right = TreeNode(20) 42 | root.right.left = TreeNode(15) 43 | root.right.right = TreeNode(7) 44 | 45 | print( 46 | levelOrdertraversal(root) 47 | ) -------------------------------------------------------------------------------- /Python_/blind75/14_bestTimeToBuyAndSellStock.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 3 | 4 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 5 | 6 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 7 | 8 | Input: prices = [7,1,5,3,6,4] 9 | Output: 5 10 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 11 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 12 | 13 | Input: prices = [7,6,4,3,1] 14 | Output: 0 15 | Explanation: In this case, no transactions are done and the max profit = 0. 16 | """ 17 | prices = [7,1,5,3,6,4] 18 | 19 | def BestTimeToBuyAndSell(prices): 20 | buyPrice, sellPrice = 0, 1 21 | maxP =0 22 | while sellPrice < len(prices): 23 | if prices[buyPrice] < prices[sellPrice]: 24 | profit = prices[sellPrice] - prices[buyPrice] 25 | maxP = max(maxP, profit) 26 | else: 27 | buyPrice = sellPrice 28 | 29 | sellPrice +=1 30 | 31 | return maxP 32 | 33 | 34 | print( 35 | BestTimeToBuyAndSell(prices) 36 | ) -------------------------------------------------------------------------------- /Python_/Questions/letterCombinationsOfAPhoneNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 3 | 4 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. 5 | 6 | A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 7 | 8 | Input: digits = "23" 9 | Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 10 | 11 | Input: digits = "" 12 | Output: [] 13 | 14 | Input: digits = "2" 15 | Output: ["a","b","c"] 16 | 17 | """ 18 | 19 | digits = "23" 20 | 21 | def letterCombinations(digits): 22 | res = [] 23 | 24 | buttons = { 25 | "2":'abc', 26 | "3":'def', 27 | "4":'ghi', 28 | "5":'jkl', 29 | "6":'mno', 30 | "7":'pqrs', 31 | "8":'tuv', 32 | "9":'wxyz' 33 | } 34 | 35 | def backtrack(i, curStr): 36 | if len(curStr) == len(digits): 37 | res.append(curStr) 38 | return 39 | 40 | for c in buttons[digits[i]]: 41 | backtrack(i+1, curStr+c) 42 | 43 | if digits: 44 | backtrack(0, "") 45 | 46 | return res 47 | 48 | print( 49 | letterCombinations(digits) 50 | ) -------------------------------------------------------------------------------- /Python_/Questions/bestTimeToBuyAndSellStock.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 3 | 4 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 5 | 6 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 7 | 8 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 9 | 10 | Input: prices = [7,1,5,3,6,4] 11 | Output: 5 12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 13 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 14 | 15 | Input: prices = [7,6,4,3,1] 16 | Output: 0 17 | Explanation: In this case, no transactions are done and the max profit = 0. 18 | 19 | """ 20 | prices = [7,1,5,3,6,4] 21 | 22 | def maxProfit(prices): 23 | l ,r = 0, 1 # left= buy , right = sell 24 | maxP = 0 25 | 26 | while r< len(prices): 27 | # profitable? 28 | if prices[l] < prices[r]: 29 | profit = prices[r] - prices[l] 30 | maxP = max(maxP, profit) 31 | else: 32 | l = r 33 | r +=1 34 | 35 | return maxP 36 | 37 | 38 | print( 39 | maxProfit(prices) 40 | ) -------------------------------------------------------------------------------- /Python_/dp/2houseRobber.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. 3 | 4 | Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. 5 | 6 | Input: nums = [2,3,2] 7 | Output: 3 8 | Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. 9 | 10 | Input: nums = [1,2,3,1] 11 | Output: 4 12 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 13 | Total amount you can rob = 1 + 3 = 4. 14 | 15 | Input: nums = [1,2,3] 16 | Output: 3 17 | """ 18 | 19 | nums = [1,2,3,1] 20 | 21 | def memorob(nums): 22 | 23 | def rob(nums): 24 | rob1, rob2 = 0,0 25 | for i in nums: 26 | newRob = max(rob1 + i, rob2) 27 | rob1 = rob2 28 | rob2 = newRob 29 | return rob2 30 | 31 | return max(rob(nums[1:]), rob(nums[:-1])) 32 | 33 | print(memorob(nums)) -------------------------------------------------------------------------------- /.github/workflows/python-app.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python application 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: "3.10" 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | pip install flake8 pytest 27 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 28 | - name: Lint with flake8 29 | run: | 30 | # stop the build if there are Python syntax errors or undefined names 31 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 32 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 33 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 34 | - name: Test with pytest 35 | run: | 36 | pytest 37 | -------------------------------------------------------------------------------- /Go/Basics/functions.go: -------------------------------------------------------------------------------- 1 | /* 2 | A function is a block of code that performs a specific 3 | task. A function takes an input, performs some 4 | calculations on the input, and generates an output. 5 | */ 6 | 7 | package main 8 | 9 | import "fmt" 10 | 11 | /* 12 | func functionname(parametername type) returntype { 13 | //function body 14 | } 15 | */ 16 | 17 | // func calculateBill(price int, no int) int { 18 | // var totalPrice = price * no 19 | // return totalPrice 20 | // } 21 | 22 | func calculateBills(price, no int) int { 23 | var totalPrice = price * no 24 | return totalPrice 25 | } 26 | 27 | // multiple return type 28 | func rectProps(length, width float64) (float64, float64) { 29 | var area = length * width 30 | var parameter = (length + width) * 2 31 | return area, parameter 32 | } 33 | 34 | // named return value 35 | func triProps(base, height, side float64) (area, perimeter float64) { 36 | area = (base * height) / 2 37 | perimeter = base + height + side 38 | return 39 | } 40 | 41 | func main() { 42 | // price, no := 50, 2 43 | // fmt.Println(calculateBills(price, no)) 44 | 45 | // area, perimeter := rectProps(10.8, 12.8) 46 | // fmt.Printf("Area %f Perimeter %f\n", area, perimeter) 47 | 48 | area, perimeter := triProps(5.2, 6.1, 2.3) 49 | fmt.Printf("Area %f Perimeter %f\n", area, perimeter) 50 | } 51 | -------------------------------------------------------------------------------- /Python_/1_Recursion/palindrome_partitioning.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. 3 | 4 | A palindrome string is a string that reads the same backward as forward. 5 | 6 | Input: s = "aab" 7 | Output: [["a","a","b"],["aa","b"]] 8 | 9 | Input: s = "a" 10 | Output: [["a"]] 11 | """ 12 | 13 | def partition(s): 14 | output = [] 15 | 16 | def isPalindrome(st): 17 | return st == st[::-1] 18 | 19 | def find(idx, arr): 20 | if idx == len(s)+1: 21 | output.append(arr[:]) 22 | return 23 | 24 | for i in range(idx, len(s)+1): 25 | if isPalindrome(s[idx-1:i]): 26 | arr.append(s[idx-1:i]) 27 | find(i+1, arr) 28 | arr.pop() 29 | 30 | 31 | find(1,[]) 32 | return output 33 | 34 | def partition_2(s): 35 | res = [] 36 | 37 | def find(arr, str): 38 | if str: 39 | for i in range(1, len(str)+1): 40 | if str[:i] == str[:i][::-1]: 41 | find(arr+[str[:i]], str[i:]) 42 | elif arr: 43 | res.append(arr) 44 | 45 | find([],s) 46 | return res 47 | 48 | print( 49 | partition("aab") 50 | # partition("aabb") 51 | ) -------------------------------------------------------------------------------- /Python_/stack/linkedlistStack.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = next 5 | 6 | 7 | class LinkedList: 8 | def __init__(self): 9 | self.head = None 10 | 11 | def __iter__(self): 12 | curNode = self.head 13 | while curNode: 14 | yield curNode 15 | curNode = curNode.next 16 | 17 | 18 | class Stack: 19 | def __init__(self): 20 | self.LinkedList = LinkedList() 21 | 22 | def __str__(self): 23 | value = [str(x.value) for x in self.LinkedList] 24 | return "\n".join(value) 25 | 26 | def isEmpty(self): 27 | if self.LinkedList.head == None: 28 | return True 29 | else: 30 | return False 31 | 32 | def push(self, value): 33 | node = Node(value) 34 | node.next = self.LinkedList.head 35 | self.LinkedList.head = node 36 | 37 | def pop(self): 38 | if self.isEmpty: 39 | return "Nothing to remove" 40 | else: 41 | nodeValue = self.LinkedList.head.value 42 | self.LinkedList.head = self.LinkedList.head.next 43 | return nodeValue 44 | 45 | 46 | s = Stack() 47 | s.push(1) 48 | s.push(2) 49 | s.push(3) 50 | s.pop() 51 | print(s) 52 | # print(s.isEmpty()) 53 | -------------------------------------------------------------------------------- /Python_/stacks/linkedlistStack.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = next 5 | 6 | 7 | class LinkedList: 8 | def __init__(self): 9 | self.head = None 10 | 11 | def __iter__(self): 12 | curNode = self.head 13 | while curNode: 14 | yield curNode 15 | curNode = curNode.next 16 | 17 | 18 | class Stack: 19 | def __init__(self): 20 | self.LinkedList = LinkedList() 21 | 22 | def __str__(self): 23 | value = [str(x.value) for x in self.LinkedList] 24 | return "\n".join(value) 25 | 26 | def isEmpty(self): 27 | if self.LinkedList.head == None: 28 | return True 29 | else: 30 | return False 31 | 32 | def push(self, value): 33 | node = Node(value) 34 | node.next = self.LinkedList.head 35 | self.LinkedList.head = node 36 | 37 | def pop(self): 38 | if self.isEmpty: 39 | return "Nothing to remove" 40 | else: 41 | nodeValue = self.LinkedList.head.value 42 | self.LinkedList.head = self.LinkedList.head.next 43 | return nodeValue 44 | 45 | 46 | s = Stack() 47 | s.push(1) 48 | s.push(2) 49 | s.push(3) 50 | s.pop() 51 | print(s) 52 | # print(s.isEmpty()) 53 | -------------------------------------------------------------------------------- /Python_/DataStructure/MaximunDepthOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/maximum-depth-of-binary-tree/ 3 | 4 | Given the root of a binary tree, return its maximum depth. 5 | 6 | A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | 8 | Input: root = [3,9,20,null,null,15,7] 9 | Output: 3 10 | 11 | Input: root = [1,null,2] 12 | Output: 2 13 | """ 14 | 15 | class TreeNode: 16 | def __init__(self, val=0, left=None, right=None): 17 | self.val = val 18 | self.left = left 19 | self.right = right 20 | 21 | def depthOfBinaryTree(root): 22 | if not root: return [] 23 | 24 | stack = [root] 25 | res = [] 26 | while stack: 27 | currentNode = [] 28 | for _ in range(len(stack)): 29 | value = stack.pop(0) 30 | currentNode.append(value.val) 31 | if value.left: 32 | stack.append(value.left) 33 | if value.right: 34 | stack.append(value.right) 35 | res.append(currentNode) 36 | 37 | return len(res) 38 | 39 | 40 | 41 | root = TreeNode(3) 42 | root.left = TreeNode(9) 43 | root.right = TreeNode(20) 44 | root.right.left = TreeNode(15) 45 | root.right.right = TreeNode(7) 46 | 47 | print(depthOfBinaryTree(root)) -------------------------------------------------------------------------------- /Python_/dp/sneakThroughGrid.py: -------------------------------------------------------------------------------- 1 | grid = [ 2 | [".", ".", "<", "."], 3 | ["X", "A", ".", "X"], 4 | [".", "<", ".", "."], 5 | ["X", ".", "X", "."], 6 | ] 7 | 8 | 9 | def isPossible(grid): 10 | ROW, COL = len(grid), len(grid[0]) 11 | seen = set() 12 | nonTraverse = set() 13 | start = [0, 0] 14 | 15 | def travel(r, c): 16 | if r < 0 or c < 0 or r >= ROW or c >= COL or (r, c) in seen or (r, c) in nonTraverse: 17 | return False 18 | 19 | if (r, c) == (ROW-1, COL-1): 20 | return True 21 | 22 | seen.add((r, c)) 23 | res = travel(r+1, c) or travel(r-1, c) or travel(r, c-1) or \ 24 | travel(r, c+1) 25 | 26 | seen.remove((r, c)) 27 | return res 28 | 29 | def changeCol(r, c): 30 | while c >= 0 or grid[r][c] == ".": 31 | nonTraverse.add([r][c]) 32 | c -= 1 33 | 34 | for r in range(ROW): 35 | for c in range(COL): 36 | if grid[r][c] == "<": 37 | changeCol(r, c) 38 | elif grid[r][c] == "X": 39 | nonTraverse.add(r, c) 40 | elif grid[r][c] == "A": 41 | start[0], start[1] = r, c 42 | 43 | return travel(start[0], start[1]) 44 | # print(grid) 45 | 46 | 47 | print( 48 | isPossible(grid) 49 | ) 50 | -------------------------------------------------------------------------------- /Python_/pattern_/min_depthBT.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | 6 | Note: A leaf is a node with no children. 7 | 8 | Input: root = [3,9,20,null,null,15,7] 9 | Output: 2 10 | 11 | Input: root = [2,null,3,null,4,null,5,null,6] 12 | Output: 5 13 | """ 14 | 15 | 16 | class Node: 17 | def __init__(self, val): 18 | self.val = val 19 | self.right = None 20 | self.left = None 21 | 22 | 23 | def minDepth(root): 24 | if not root: 25 | return 0 26 | 27 | stack = [(root, 1)] 28 | 29 | while stack: 30 | node, level = stack.pop(0) 31 | if not node.left and not node.right: 32 | return level 33 | 34 | if node.left: 35 | stack.append([node.left, level+1]) 36 | if node.right: 37 | stack.append([node.right, level+1]) 38 | 39 | 40 | root = Node(3) 41 | root.left = Node(9) 42 | root.right = Node(20) 43 | root.right.left = Node(15) 44 | root.right.right = Node(7) 45 | 46 | 47 | # root = Node(2) 48 | # root.right = Node(3) 49 | # root.right.right = Node(4) 50 | # root.right.right.right = Node(5) 51 | # root.right.right.right.right = Node(6) 52 | 53 | print( 54 | minDepth(root) 55 | ) 56 | -------------------------------------------------------------------------------- /Python_/qus/validateBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | A valid BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | 10 | Input: root = [2,1,3] 11 | Output: true 12 | 13 | Input: root = [5,1,4,null,null,3,6] 14 | Output: false 15 | Explanation: The root node's value is 5 but its right child's value is 4. 16 | """ 17 | 18 | # Definition for a binary tree node. 19 | class TreeNode: 20 | def __init__(self, val=0, left=None, right=None): 21 | self.val = val 22 | self.left = left 23 | self.right = right 24 | 25 | def isValidBST(root): 26 | if not root: return True 27 | 28 | stack = [root] 29 | 30 | while stack: 31 | curNode = stack.pop(0) 32 | 33 | if curNode.left and curNode.right: 34 | continue 35 | else: 36 | return False 37 | 38 | 39 | 40 | 41 | root = TreeNode(5) 42 | root.left = TreeNode(1) 43 | root.right = TreeNode(4) 44 | root.right.left = TreeNode(3) 45 | root.right.right = TreeNode(6) 46 | 47 | print(isValidBST(root)) -------------------------------------------------------------------------------- /Python_/DataStructure/RansomNote.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/ransom-note/ 3 | 4 | Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. 5 | 6 | Each letter in magazine can only be used once in ransomNote. 7 | 8 | Input: ransomNote = "a", magazine = "b" 9 | Output: false 10 | 11 | Input: ransomNote = "aa", magazine = "ab" 12 | Output: false 13 | 14 | Input: ransomNote = "aa", magazine = "aab" 15 | Output: true 16 | """ 17 | 18 | from tabnanny import check 19 | 20 | 21 | ransomNote = "aa" 22 | magazine = "aab" 23 | 24 | def canConstruct(ransomNote, magazine): 25 | 26 | checkNote ={} 27 | checkMagine = {} 28 | 29 | for s in ransomNote: 30 | if s not in checkNote: 31 | checkNote[s] =1 32 | else: 33 | checkNote[s] +=1 34 | 35 | for i in magazine: 36 | if i not in checkMagine: 37 | checkMagine[i] =1 38 | else: 39 | checkMagine[i] +=1 40 | 41 | for i in checkNote: 42 | if i not in checkMagine: 43 | return False 44 | else: 45 | if checkNote[i] > checkMagine[i]: 46 | return False 47 | return True 48 | 49 | 50 | 51 | 52 | 53 | print( 54 | canConstruct(ransomNote, magazine) 55 | ) 56 | 57 | -------------------------------------------------------------------------------- /Python_/Graphs/numbersOfProvinces.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/number-of-provinces/ 3 | 4 | There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. 5 | 6 | A province is a group of directly or indirectly connected cities and no other cities outside of the group. 7 | 8 | You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. 9 | 10 | Return the total number of provinces. 11 | 12 | Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] 13 | Output: 2 14 | 15 | Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] 16 | Output: 3 17 | """ 18 | isConnected = [[1,1,0],[1,1,0],[0,0,1]] 19 | 20 | def findCircleNum(isConnected): 21 | N = len(isConnected) 22 | seen = set() 23 | result = 0 24 | 25 | def dfs(node): 26 | for nei, adj in enumerate(isConnected[node]): 27 | if adj and nei not in seen: 28 | seen.add(nei) 29 | dfs(nei) 30 | 31 | for i in range(N): 32 | if i not in seen: 33 | dfs(i) 34 | result +=1 35 | 36 | return result 37 | 38 | print( 39 | findCircleNum(isConnected) 40 | ) -------------------------------------------------------------------------------- /Python_/qus/heightBalanceTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as: 5 | 6 | a binary tree in which the left and right subtrees of every node differ in height by no more than 1. 7 | 8 | Input: root = [3,9,20,null,null,15,7] 9 | Output: true 10 | 11 | Input: root = [1,2,2,3,3,null,null,4,4] 12 | Output: false 13 | """ 14 | 15 | # Definition for a binary tree node. 16 | class TreeNode: 17 | def __init__(self, val=0, left=None, right=None): 18 | self.val = val 19 | self.left = left 20 | self.right = right 21 | 22 | # O(n^2) 23 | def isBalanced(root): 24 | 25 | def height(root): 26 | if not root: 27 | return 0 28 | return max(height(root.left), height(root.right)) + 1 29 | 30 | if not root: 31 | return True 32 | 33 | leftHeight = height(root.left) 34 | rightHeight = height(root.right) 35 | 36 | if abs(leftHeight - rightHeight) <=1 and isBalanced(root.left) is True and isBalanced(root.right) is True: 37 | return True 38 | 39 | return False 40 | 41 | 42 | root = TreeNode(3) 43 | root.left = TreeNode(9) 44 | root.right = TreeNode(20) 45 | root.right.left = TreeNode(15) 46 | root.right.right = TreeNode(7) 47 | 48 | print(isBalanced(root)) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/allConstruct.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that accepts a target string and an array of strings. 3 | 4 | The function should return 1 2D array containing all of the ways that the target can be constructed by concatenating elements of the wordBank array. Each element of the 2D array should represent one combination that constructs the target 5 | 6 | */ 7 | 8 | // m = target.length, n = wordBank.length 9 | 10 | // Brute force 11 | // | = target.slice() 12 | // TC => O(n^m) 13 | // SC => O(m) -> height of recurssion tree 14 | 15 | const allConstruct = (target, wordBank, memo = {}) => { 16 | if (target in memo) return memo[target]; 17 | if (target === "") return [[]]; 18 | 19 | const result = []; 20 | 21 | for (let word of wordBank) { 22 | if (target.indexOf(word) === 0) { 23 | const suffix = target.slice(word.length); 24 | const suffixWays = allConstruct(suffix, wordBank, memo); 25 | const targetWays = suffixWays.map((way) => [word, ...way]); 26 | result.push(...targetWays); 27 | } 28 | } 29 | memo[target] = result; 30 | return result; 31 | }; 32 | 33 | console.log(allConstruct("hello", ["cat", "dog", "mouse"])); 34 | console.log( 35 | allConstruct("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef", "c"]) 36 | ); 37 | 38 | // this is just a simple comment 39 | -------------------------------------------------------------------------------- /Python_/DataStructure/binaryTreeLevelOrderTravesal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/binary-tree-level-order-traversal/ 3 | 4 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 5 | 6 | Input: root = [3,9,20,null,null,15,7] 7 | Output: [[3],[9,20],[15,7]] 8 | 9 | Input: root = [1] 10 | Output: [[1]] 11 | 12 | Input: root = [] 13 | Output: [] 14 | """ 15 | 16 | class TreeNode: 17 | def __init__(self, val=0, left=None, right=None): 18 | self.val = val 19 | self.left = left 20 | self.right = right 21 | 22 | 23 | def levelOrderTraversal(root): 24 | if not root: return [] 25 | stack = [root] 26 | res = [] 27 | while stack: 28 | currentNode = [] 29 | for _ in range(len(stack)): 30 | value = stack.pop(0) 31 | currentNode.append(value.val) 32 | if value.left: 33 | stack.append(value.left) 34 | 35 | if value.right: 36 | stack.append(value.right) 37 | 38 | res.append(currentNode) 39 | 40 | return res 41 | 42 | 43 | 44 | root = TreeNode(3) 45 | root.left = TreeNode(9) 46 | root.right = TreeNode(20) 47 | root.right.left = TreeNode(15) 48 | root.right.right = TreeNode(7) 49 | 50 | print( 51 | levelOrderTraversal(root) 52 | ) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/tableCanConstruct.js: -------------------------------------------------------------------------------- 1 | /* 2 | The function should return a boolean indicating wheather or not the 'target' can be constructed by concatenating elements of the 'wordBank' array. 3 | 4 | You may reuse elements of 'wordBank' as many times as needed. 5 | */ 6 | // m = target, 7 | // n = wordBank.length 8 | // 9 | // TC => O(n*m * m) => O(m^2*n) 10 | // SC => O(m) 11 | 12 | const canConstruct = (target, wordBank) => { 13 | const table = Array(target.length + 1).fill(false); 14 | 15 | table[0] = true; 16 | 17 | for (let i = 0; i <= target.length; i++) { 18 | if (table[i] === true) { 19 | for (let word of wordBank) { 20 | // if word matches the characters starting with position i 21 | if (target.slice(i, i + word.length) === word) { 22 | table[i + word.length] = true; 23 | } 24 | } 25 | } 26 | } 27 | return table[target.length]; 28 | }; 29 | 30 | console.log(canConstruct("abcdef", ["ab", "abc", "cd", "def", "abcd"])); 31 | console.log( 32 | canConstruct("skeatboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]) 33 | ); 34 | console.log(canConstruct("himanshu", ["hi", "ma", "hu", "ns", "abcd"])); 35 | console.log( 36 | canConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeef", [ 37 | "e", 38 | "ee", 39 | "eee", 40 | "eeeee", 41 | "eeeeee", 42 | ]) 43 | ); 44 | -------------------------------------------------------------------------------- /Python_/Questions/happyNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/happy-number/ 3 | 4 | Write an algorithm to determine if a number n is happy. 5 | 6 | A happy number is a number defined by the following process: 7 | 8 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 9 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 10 | Those numbers for which this process ends in 1 are happy. 11 | Return true if n is a happy number, and false if not. 12 | 13 | Input: n = 19 14 | Output: true 15 | Explanation: 16 | 12 + 92 = 82 17 | 82 + 22 = 68 18 | 62 + 82 = 100 19 | 12 + 02 + 02 = 1 20 | 21 | Input: n = 2 22 | Output: false 23 | """ 24 | 25 | n = 19 26 | 27 | def isHappy(n): 28 | visit = set() 29 | 30 | # helper function 31 | def sumOfSqaure(n): 32 | output = 0 33 | 34 | while n: 35 | digit = n % 10 36 | digit = digit ** 2 37 | output += digit 38 | 39 | digit = n //10 40 | return output 41 | 42 | 43 | while n not in visit: 44 | visit.add(n) 45 | 46 | n = sumOfSqaure(n) 47 | 48 | if n ==1 : 49 | return True 50 | return False 51 | 52 | 53 | 54 | 55 | 56 | print( 57 | isHappy(n) 58 | ) 59 | -------------------------------------------------------------------------------- /Python_/pattern_/diameter_of_bt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return the length of the diameter of the tree. 3 | 4 | The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 5 | 6 | The length of a path between two nodes is represented by the number of edges between them. 7 | 8 | Input: root = [1,2,3,4,5] 9 | Output: 3 10 | Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. 11 | 12 | Input: root = [1,2] 13 | Output: 1 14 | 15 | """ 16 | 17 | 18 | class Node: 19 | def __init__(self, val): 20 | self.val = val 21 | self.right = None 22 | self.left = None 23 | 24 | 25 | def diameter(root): 26 | 27 | max_val = 0 28 | 29 | def get_len(root): 30 | nonlocal max_val 31 | if not root: 32 | return 0 33 | 34 | left_len = get_len(root.left) 35 | right_len = get_len(root.right) 36 | 37 | max_val = max(max_val, left_len + right_len) 38 | return 1 + max(left_len, right_len) 39 | 40 | get_len(root) 41 | return max_val 42 | 43 | 44 | root = Node(1) 45 | root.left = Node(2) 46 | root.left.left = Node(4) 47 | root.left.right = Node(5) 48 | root.right = Node(3) 49 | 50 | print( 51 | diameter(root) 52 | ) 53 | -------------------------------------------------------------------------------- /Python_/Questions/moveZeros.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | Note that you must do this in-place without making a copy of the array. 5 | 6 | Input: nums = [0,1,0,3,12] 7 | Output: [1,3,12,0,0] 8 | 9 | Input: nums = [0] 10 | Output: [0] 11 | 12 | https://leetcode.com/problems/move-zeroes/ 13 | """ 14 | nums = [0,1,0,3,12] 15 | 16 | # o(n^2) 17 | # def moveZero(nums): 18 | # for i in range(len(nums)): 19 | # for j in range(0,i+1): 20 | # if nums[i] == 0: 21 | # nums[i], nums[j] = nums[j], nums[i] 22 | # if nums[j] == 0: 23 | # nums[i], nums[j] = nums[j], nums[i] 24 | 25 | # return nums 26 | 27 | def moveZero(nums): 28 | snowBallSize = 0; 29 | for i in range(len(nums)): 30 | if (nums[i]==0): 31 | snowBallSize +=1; 32 | 33 | elif(snowBallSize > 0): 34 | t = nums[i]; 35 | nums[i]=0; 36 | nums[i-snowBallSize]=t; 37 | 38 | 39 | 40 | def moveZeroSimplePowerFull(nums): 41 | l = 0 42 | for r in range(len(nums)): 43 | if nums[r]: 44 | nums[l], nums[r] = nums[r], nums[l] 45 | l+=1 46 | return nums 47 | 48 | 49 | print( 50 | moveZeroSimplePowerFull(nums) 51 | ) -------------------------------------------------------------------------------- /Python_/Questions/Permutations_second.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/permutations-ii/ 3 | 4 | Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. 5 | 6 | Input: nums = [1,1,2] 7 | Output: 8 | [[1,1,2], 9 | [1,2,1], 10 | [2,1,1]] 11 | 12 | Input: nums = [1,2,3] 13 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 14 | 15 | """ 16 | 17 | from typing import Counter 18 | 19 | nums = [1,1,2] 20 | 21 | def permuteUnique(nums): 22 | results = [] 23 | def backtrack(comb, counter): 24 | if len(comb) == len(nums): 25 | # make a deep copy of the resulting permutation, 26 | # since the permutation would be backtracked later. 27 | results.append(list(comb)) 28 | return 29 | 30 | for num in counter: 31 | if counter[num] > 0: 32 | # add this number into the current combination 33 | comb.append(num) 34 | counter[num] -= 1 35 | # continue the exploration 36 | backtrack(comb, counter) 37 | # revert the choice for the next exploration 38 | comb.pop() 39 | counter[num] += 1 40 | 41 | backtrack([], Counter(nums)) 42 | 43 | return results 44 | 45 | 46 | print( 47 | permuteUnique(nums) 48 | ) -------------------------------------------------------------------------------- /Python_/pattern_/avg_of_levels.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. 3 | 4 | Input: root = [3,9,20,null,null,15,7] 5 | Output: [3.00000,14.50000,11.00000] 6 | Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. 7 | Hence return [3, 14.5, 11]. 8 | 9 | Input: root = [3,9,20,15,7] 10 | Output: [3.00000,14.50000,11.00000] 11 | """ 12 | 13 | 14 | class Node: 15 | def __init__(self, val): 16 | self.val = val 17 | self.left = None 18 | self.right = None 19 | 20 | 21 | def averageOfLevels(root): 22 | if not root: 23 | return [] 24 | 25 | result = [] 26 | stack = [root] 27 | 28 | while stack: 29 | s = 0 30 | size = len(stack) 31 | for i in range(size): 32 | node = stack.pop(0) 33 | s += node.val 34 | if node.left: 35 | stack.append(node.left) 36 | if node.right: 37 | stack.append(node.right) 38 | 39 | result.append(s/size) 40 | 41 | return result 42 | 43 | 44 | root = Node(3) 45 | root.left = Node(9) 46 | root.right = Node(20) 47 | root.right.left = Node(15) 48 | root.right.right = Node(7) 49 | 50 | print( 51 | averageOfLevels(root) 52 | ) 53 | -------------------------------------------------------------------------------- /Python_/DataStructure/groupAnagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/group-anagrams/ 3 | 4 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 5 | 6 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 7 | 8 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 9 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 10 | 11 | Input: strs = [""] 12 | Output: [[""]] 13 | 14 | Input: strs = ["a"] 15 | Output: [["a"]] 16 | """ 17 | 18 | from collections import defaultdict 19 | 20 | 21 | strs = ["eat","tea","tan","ate","nat","bat"] 22 | 23 | # def groupAnagrams(strs): 24 | # res = defaultdict(list) # mapping charCount to list of Anagrams 25 | 26 | # for s in strs: 27 | # count = [0]*26 28 | 29 | # for c in s: 30 | # count[ord(c) - ord("a")] +=1 31 | 32 | # res[tuple(count)].append(s) 33 | 34 | # return res.values() 35 | 36 | 37 | def groupAnagrams(strs): 38 | anagram = {} 39 | for word in strs: 40 | currentWord = "".join(sorted(word)) 41 | if currentWord in anagram: 42 | anagram[currentWord].append(word) 43 | else: 44 | anagram[currentWord] = [word] 45 | 46 | return list(anagram.values()) 47 | 48 | print(groupAnagrams(strs)) -------------------------------------------------------------------------------- /Python_/DataStructure/sortColors.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/sort-colors/ 3 | 4 | Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 5 | 6 | We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. 7 | 8 | You must solve this problem without using the library's sort function. 9 | 10 | Input: nums = [2,0,2,1,1,0] 11 | Output: [0,0,1,1,2,2] 12 | 13 | Input: nums = [2,0,1] 14 | Output: [0,1,2] 15 | """ 16 | # nums = [2,0,2,1,1,0] 17 | nums = [2,0,1] 18 | 19 | def sortColors(nums): 20 | for i in range(len(nums)): 21 | for j in range(len(nums)): 22 | if nums[i] < nums[j]: 23 | nums[i], nums[j] = nums[j], nums[i] 24 | 25 | return nums 26 | 27 | # quick sort partition 28 | def sortColor2(nums): 29 | 30 | def swap(i,j): 31 | # tmp = nums[i] 32 | # nums[i] = nums[j] 33 | # nums[j] = tmp 34 | nums[i], nums[j] = nums[j], nums[i] 35 | 36 | l,r = 0, len(nums)-1 37 | i=0 38 | 39 | while i<=r: 40 | if nums[i] == 0: 41 | swap(l,i) 42 | l+=1 43 | elif nums[i] ==2: 44 | swap(i,r) 45 | r-=1 46 | 47 | i-=1 48 | i+=1 49 | 50 | 51 | print( 52 | sortColor2(nums) 53 | ) -------------------------------------------------------------------------------- /Python_/Questions/contiguousArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/contiguous-array 3 | Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. 4 | 5 | Input: nums = [0,1] 6 | Output: 2 7 | Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. 8 | 9 | Input: nums = [0,1,0] 10 | Output: 2 11 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 12 | """ 13 | 14 | nums = [0,1] 15 | 16 | def findMaxLengthBF(nums): 17 | maxLen = 0 18 | for i in range(len(nums)): 19 | zero=ones=0 20 | for j in range(len(nums)): 21 | if nums[j] == 0: 22 | zero+=1 23 | else: 24 | ones+=1 25 | 26 | if zero == ones: 27 | maxLen = max(maxLen, j-i +1) 28 | 29 | 30 | return maxLen 31 | 32 | def findMaxLength(nums): 33 | count = 0 34 | maxLength = 0 35 | table = {0:0} 36 | 37 | for index, num in enumerate(nums,1): 38 | if num == 0: 39 | count -=1 40 | else: 41 | count +=1 42 | 43 | if count in table: 44 | maxLength = max(maxLength, index - table[count]) 45 | else: 46 | table[count] = index 47 | 48 | return maxLength 49 | 50 | 51 | 52 | 53 | print( 54 | findMaxLengthBF(nums) 55 | ) -------------------------------------------------------------------------------- /Python_/DataStructure/ValidateBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | A valid BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | 10 | Input: root = [2,1,3] 11 | Output: true 12 | 13 | Input: root = [5,1,4,null,null,3,6] 14 | Output: false 15 | Explanation: The root node's value is 5 but its right child's value is 4. 16 | """ 17 | class TreeNode: 18 | def __init__(self, val=0, left=None, right=None): 19 | self.val = val 20 | self.left = left 21 | self.right = right 22 | 23 | def isValidBST(root): 24 | 25 | def valid(node, left, right): 26 | if not node: return True 27 | 28 | if not (node.val < right and node.val > left): 29 | return False 30 | 31 | return valid(node.left, left, node.val) and \ 32 | valid(node.right, node.val, right) 33 | 34 | return valid(root, float("-inf"), float("inf")) 35 | 36 | 37 | 38 | root = TreeNode(5) 39 | root.left = TreeNode(4) 40 | root.right = TreeNode(6) 41 | 42 | root.right.left = TreeNode(3) 43 | root.right.right = TreeNode(7) 44 | 45 | print( 46 | isValidBST(root) 47 | ) -------------------------------------------------------------------------------- /Python_/DataStructure/treeTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary tree, return the preorder traversal of its nodes' values. 3 | 4 | Tree traversal 5 | - Binary Tree Preorder Traversal 6 | # https://leetcode.com/problems/binary-tree-preorder-traversal/ 7 | 8 | 9 | """ 10 | 11 | class Node: 12 | def __init__(self, value): 13 | self.value = value 14 | self.left = None 15 | self.right = None 16 | 17 | class BinaryTree: 18 | def __init__(self, root): 19 | self.root = Node(root) 20 | 21 | def preorderTraversal(node): 22 | if not node: 23 | return [] 24 | 25 | s = [root.value] 26 | s += preorderTraversal(root.left) 27 | s += preorderTraversal(root.right) 28 | 29 | return s 30 | 31 | 32 | def inorderTraversal(node): 33 | if not node: 34 | return [] 35 | s = [] 36 | 37 | s += preorderTraversal(root.left) 38 | s = [root.value] 39 | s += preorderTraversal(root.right) 40 | 41 | return s 42 | 43 | 44 | def postorderTraversal(node): 45 | if not node: 46 | return [] 47 | s = [] 48 | 49 | 50 | s += preorderTraversal(root.left) 51 | s += preorderTraversal(root.right) 52 | s += [root.value] 53 | 54 | 55 | return s 56 | 57 | 58 | root = Node(1) 59 | root.right = Node(2) 60 | root.right.left = Node(3) 61 | 62 | 63 | # preorderTraversal(root) 64 | inorderTraversal(root) -------------------------------------------------------------------------------- /Python_/Questions/houseRobber2.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/house-robber-ii/ 3 | 4 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. 5 | 6 | Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. 7 | 8 | Input: nums = [2,3,2] 9 | Output: 3 10 | Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. 11 | 12 | Input: nums = [1,2,3,1] 13 | Output: 4 14 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 15 | Total amount you can rob = 1 + 3 = 4. 16 | 17 | Input: nums = [1,2,3] 18 | Output: 3 19 | 20 | """ 21 | 22 | nums = [2,3,2] 23 | 24 | def rob(nums): 25 | 26 | return max(nums[0], helper(nums[1:]), helper(nums[:-1])) 27 | 28 | 29 | def helper(nums): 30 | rob1, rob2 = 0,0 31 | 32 | for n in nums: 33 | newRob = max(rob1 + n, rob2) 34 | rob1 = rob2 35 | rob2 = newRob 36 | 37 | return rob2 38 | 39 | 40 | 41 | print( 42 | rob(nums) 43 | ) -------------------------------------------------------------------------------- /Python_/Graphs/numberOfIslands.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. 3 | 4 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 5 | 6 | Input: grid = [ 7 | ["1","1","1","1","0"], 8 | ["1","1","0","1","0"], 9 | ["1","1","0","0","0"], 10 | ["0","0","0","0","0"] 11 | ] 12 | Output: 1 13 | 14 | Input: grid = [ 15 | ["1","1","0","0","0"], 16 | ["1","1","0","0","0"], 17 | ["0","0","1","0","0"], 18 | ["0","0","0","1","1"] 19 | ] 20 | Output: 3 21 | """ 22 | 23 | grid = [ 24 | ["1","1","0","0","0"], 25 | ["1","1","0","0","0"], 26 | ["0","0","1","0","0"], 27 | ["0","0","0","1","1"] 28 | ] 29 | 30 | def numIslands(grid): 31 | island = 0 32 | r, c = len(grid), len(grid[0]) 33 | 34 | def dfs(i,j): 35 | if i < 0 or i >= r or j < 0 or j >= c or grid[i][j] != "1": 36 | return 37 | grid[i][j] = "#" 38 | dfs(i+1,j) 39 | dfs(i-1,j) 40 | dfs(i,j-1) 41 | dfs(i,j+1) 42 | 43 | 44 | for i in range(r): 45 | for j in range(c): 46 | if grid[i][j] == "1": 47 | dfs(i,j) 48 | island +=1 49 | 50 | return island 51 | print( 52 | numIslands(grid) 53 | ) -------------------------------------------------------------------------------- /Python_/qus/numberOfIslands.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. 3 | 4 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 5 | 6 | Input: grid = [ 7 | ["1","1","1","1","0"], 8 | ["1","1","0","1","0"], 9 | ["1","1","0","0","0"], 10 | ["0","0","0","0","0"] 11 | ] 12 | Output: 1 13 | 14 | Input: grid = [ 15 | ["1","1","0","0","0"], 16 | ["1","1","0","0","0"], 17 | ["0","0","1","0","0"], 18 | ["0","0","0","1","1"] 19 | ] 20 | Output: 3 21 | """ 22 | 23 | grid = [ 24 | ["1","1","0","0","0"], 25 | ["1","1","0","0","0"], 26 | ["0","0","1","0","0"], 27 | ["0","0","0","1","1"] 28 | ] 29 | 30 | def numIslands(grid): 31 | if not grid: return 0 32 | row, column = len(grid), len(grid[0]) 33 | islands = 0 34 | 35 | def dfs(i,j): 36 | if i <0 or i >=row or j<0 or j>= column or grid[i][j] != "1": 37 | return 38 | grid[i][j] = "#" 39 | dfs(i+1,j), dfs(i-1,j), dfs(i,j+1), dfs(i,j-1) 40 | 41 | for i in range(row): 42 | for j in range(column): 43 | if grid[i][j] == "1": 44 | dfs(i,j) 45 | islands +=1 46 | return islands 47 | 48 | print( 49 | numIslands(grid) 50 | ) -------------------------------------------------------------------------------- /Python_/Graphs/minimunJumpsToReachHome.py: -------------------------------------------------------------------------------- 1 | """ 2 | A certain bug's home is on the x-axis at position x. Help them get there from position 0. 3 | 4 | The bug jumps according to the following rules: 5 | 6 | It can jump exactly a positions forward (to the right). 7 | It can jump exactly b positions backward (to the left). 8 | It cannot jump backward twice in a row. 9 | It cannot jump to any forbidden positions. 10 | The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. 11 | 12 | Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. 13 | 14 | Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9 15 | Output: 3 16 | Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. 17 | 18 | Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11 19 | Output: -1 20 | 21 | Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7 22 | Output: 2 23 | Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. 24 | 25 | """ 26 | 27 | forbidden = [14,4,18,1,15]; a = 3; b = 15; x = 9 28 | def minimumJumps(forbidden, a , b, x): 29 | home = x 30 | 31 | 32 | 33 | print(minimumJumps(forbidden, a, b, x)) -------------------------------------------------------------------------------- /Python_/Questions/NumberOfProvinces.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/number-of-provinces/ 3 | 4 | There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. 5 | 6 | A province is a group of directly or indirectly connected cities and no other cities outside of the group. 7 | 8 | You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. 9 | 10 | Return the total number of provinces. 11 | 12 | Input: isConnected = [[1,1,0], 13 | [1,1,0], 14 | [0,0,1]] 15 | Output: 2 16 | 17 | Input: isConnected = [[1,0,0], 18 | [0,1,0], 19 | [0,0,1]] 20 | Output: 3 21 | """ 22 | isConnected = [[1,1,0],[1,1,0],[0,0,1]] 23 | 24 | def findCircleNum(A): 25 | N = len(A) 26 | seen = set() 27 | def dfs(node): 28 | for nei, adj in enumerate(A[node]): 29 | if adj and nei not in seen: 30 | seen.add(nei) 31 | dfs(nei) 32 | 33 | ans = 0 34 | for i in range(N): 35 | if i not in seen: 36 | dfs(i) 37 | ans += 1 38 | return ans 39 | # return isConnected 40 | 41 | 42 | print( 43 | findCircleNum(isConnected) 44 | ) -------------------------------------------------------------------------------- /Python_/stack/stackPythonList_withlimit.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self, maxSize): 3 | self.maxSize = maxSize 4 | self.list = [] 5 | 6 | def __str__(self): 7 | values = self.list.reverse() 8 | values = [str(x) for x in self.list] 9 | return "\n".join(values) 10 | 11 | # isEmpty 12 | def isEmpty(self): 13 | if self.list == []: 14 | return True 15 | else: 16 | return False 17 | 18 | # isFull 19 | def isFull(self): 20 | if len(self.list) == self.maxSize: 21 | return True 22 | else: 23 | return False 24 | 25 | # push 26 | def push(self, value): 27 | if self.isFull(): 28 | return "Can't add items it's full" 29 | else: 30 | self.list.append(value) 31 | return "Added Succssfully" 32 | 33 | # pop 34 | def pop(self): 35 | if self.isEmpty(): 36 | return "No element to remove" 37 | else: 38 | return self.list.pop() 39 | 40 | # peek 41 | def peek(self): 42 | if self.isEmpty(): 43 | return "No top element" 44 | else: 45 | return self.list[len(self.list) - 1] 46 | 47 | # delete entire stack 48 | def delete(self): 49 | self.list = None 50 | 51 | 52 | s = Stack(2) 53 | print(s.isFull()) 54 | s.push(1) 55 | s.push(2) 56 | print(s.push(3)) 57 | print(s) 58 | -------------------------------------------------------------------------------- /Python_/DataStructure/kClosestPointsToOrigin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). 3 | 4 | The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). 5 | 6 | You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). 7 | 8 | Input: points = [[1,3],[-2,2]], k = 1 9 | Output: [[-2,2]] 10 | Explanation: 11 | The distance between (1, 3) and the origin is sqrt(10). 12 | The distance between (-2, 2) and the origin is sqrt(8). 13 | Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. 14 | We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. 15 | 16 | Input: points = [[3,3],[5,-1],[-2,4]], k = 2 17 | Output: [[3,3],[-2,4]] 18 | Explanation: The answer [[-2,4],[3,3]] would also be accepted. 19 | """ 20 | 21 | import math 22 | 23 | points = [[1,3],[-2,2],[2,-2]] 24 | k = 2 25 | 26 | def kClosest(points, k): 27 | distToOrigin = [] 28 | 29 | for x,y in points: 30 | dis = math.sqrt((x-0)**2+(y-0)**2) 31 | distToOrigin.append([dis,(x,y)]) 32 | 33 | points.sort(key= lambda x:x[0]) 34 | # print(dist) 35 | result = [] 36 | for value in distToOrigin: 37 | result.append(value[1]) 38 | return result[:k] 39 | 40 | print( 41 | kClosest(points, k) 42 | ) -------------------------------------------------------------------------------- /Python_/blind75/15_numberOfIslands.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. 3 | 4 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 5 | 6 | Input: grid = [ 7 | ["1","1","1","1","0"], 8 | ["1","1","0","1","0"], 9 | ["1","1","0","0","0"], 10 | ["0","0","0","0","0"] 11 | ] 12 | Output: 1 13 | 14 | Input: grid = [ 15 | ["1","1","0","0","0"], 16 | ["1","1","0","0","0"], 17 | ["0","0","1","0","0"], 18 | ["0","0","0","1","1"] 19 | ] 20 | Output: 3 21 | """ 22 | grid = [ 23 | ["1","1","1","1","0"], 24 | ["1","1","0","1","0"], 25 | ["1","1","0","0","0"], 26 | ["0","0","0","0","0"] 27 | ] 28 | 29 | def numberofIsland(grid): 30 | r, c = len(grid), len(grid[0]) 31 | island = 0 32 | 33 | def dfs(i,j): 34 | if i < 0 or i >= r or j <0 or j >=c or grid[i][j] != "1": 35 | return 0 36 | grid[i][j] = "#" 37 | return dfs(i+1,j),\ 38 | dfs(i-1,j), \ 39 | dfs(i,j+1),\ 40 | dfs(i,j-1) \ 41 | 42 | for i in range(r): 43 | for j in range(c): 44 | if grid[i][j] == "1": 45 | dfs(i,j) 46 | island +=1 47 | 48 | 49 | return island 50 | 51 | print( 52 | numberofIsland(grid) 53 | ) -------------------------------------------------------------------------------- /Python_/stacks/stackPythonList_withlimit.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self, maxSize): 3 | self.maxSize = maxSize 4 | self.list = [] 5 | 6 | def __str__(self): 7 | values = self.list.reverse() 8 | values = [str(x) for x in self.list] 9 | return "\n".join(values) 10 | 11 | # isEmpty 12 | def isEmpty(self): 13 | if self.list == []: 14 | return True 15 | else: 16 | return False 17 | 18 | # isFull 19 | def isFull(self): 20 | if len(self.list) == self.maxSize: 21 | return True 22 | else: 23 | return False 24 | 25 | # push 26 | def push(self, value): 27 | if self.isFull(): 28 | return "Can't add items it's full" 29 | else: 30 | self.list.append(value) 31 | return "Added Succssfully" 32 | 33 | # pop 34 | def pop(self): 35 | if self.isEmpty(): 36 | return "No element to remove" 37 | else: 38 | return self.list.pop() 39 | 40 | # peek 41 | def peek(self): 42 | if self.isEmpty(): 43 | return "No top element" 44 | else: 45 | return self.list[len(self.list) - 1] 46 | 47 | # delete entire stack 48 | def delete(self): 49 | self.list = None 50 | 51 | 52 | s = Stack(2) 53 | print(s.isFull()) 54 | s.push(1) 55 | s.push(2) 56 | print(s.push(3)) 57 | print(s) 58 | -------------------------------------------------------------------------------- /Python_/leetCode75/findPivotIndex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums, calculate the pivot index of this array. 3 | 4 | The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. 5 | 6 | If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. 7 | 8 | Return the leftmost pivot index. If no such index exists, return -1. 9 | 10 | Input: nums = [1,7,3,6,5,6] 11 | Output: 3 12 | Explanation: 13 | The pivot index is 3. 14 | Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 15 | Right sum = nums[4] + nums[5] = 5 + 6 = 11 16 | 17 | Input: nums = [1,2,3] 18 | Output: -1 19 | Explanation: 20 | There is no index that satisfies the conditions in the problem statement. 21 | 22 | Input: nums = [2,1,-1] 23 | Output: 0 24 | Explanation: 25 | The pivot index is 0. 26 | Left sum = 0 (no elements to the left of index 0) 27 | Right sum = nums[1] + nums[2] = 1 + -1 = 28 | 29 | | 30 | 1,2,3 31 | | 32 | leftsum = 1 33 | rightsum = 3 34 | """ 35 | 36 | 37 | def pivotIndex(nums): 38 | left, right = 0, sum(nums) 39 | for index, num in enumerate(nums): 40 | right -= num 41 | if left == right: 42 | return index 43 | left += num 44 | 45 | return -1 46 | 47 | 48 | print( 49 | pivotIndex([1, 7, 3, 6, 5, 6]) 50 | ) 51 | -------------------------------------------------------------------------------- /JavaScript_/Questions/reverseLinkedList.js: -------------------------------------------------------------------------------- 1 | // Given the head of a singly linked list, reverse the list, and return the reversed list. 2 | // Input: head = [1,2,3,4,5] 3 | // Output: [5,4,3,2,1] 4 | // https://leetcode.com/problems/reverse-linked-list/ 5 | 6 | class Node { 7 | constructor(value) { 8 | this.value = value; 9 | this.next = null; 10 | } 11 | } 12 | 13 | class LinkedList { 14 | constructor() { 15 | this.head = null; 16 | } 17 | 18 | append(value) { 19 | var new_node = new Node(value); 20 | 21 | if (this.head === null) { 22 | this.head = new_node; 23 | return; 24 | } 25 | 26 | var cur_node = this.head; 27 | while (cur_node.next) { 28 | cur_node = cur_node.next; 29 | } 30 | 31 | cur_node.next = new_node; 32 | } 33 | 34 | printList() { 35 | var cur_node = this.head; 36 | while (cur_node) { 37 | console.log(cur_node.value); 38 | cur_node = cur_node.next; 39 | } 40 | } 41 | 42 | reverse() { 43 | var prev = null; 44 | var cur_node = this.head; 45 | var nxt = null; 46 | 47 | while (cur_node) { 48 | nxt = cur_node.next; 49 | cur_node.next = prev; 50 | 51 | prev = cur_node; 52 | cur_node = nxt; 53 | } 54 | this.head = prev; 55 | } 56 | } 57 | 58 | var llist = new LinkedList(); 59 | llist.append(1); 60 | llist.append(2); 61 | llist.append(3); 62 | llist.append(4); 63 | llist.append(5); 64 | llist.reverse(); 65 | llist.printList(); 66 | -------------------------------------------------------------------------------- /Python_/Questions/findMinimunInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 3 | 4 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: 5 | 6 | [4,5,6,7,0,1,2] if it was rotated 4 times. 7 | [0,1,2,4,5,6,7] if it was rotated 7 times. 8 | Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. 9 | 10 | Given the sorted rotated array nums of unique elements, return the minimum element of this array. 11 | 12 | You must write an algorithm that runs in O(log n) time. 13 | 14 | Input: nums = [3,4,5,1,2] 15 | Output: 1 16 | Explanation: The original array was [1,2,3,4,5] rotated 3 times. 17 | 18 | Input: nums = [4,5,6,7,0,1,2] 19 | Output: 0 20 | Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. 21 | 22 | Input: nums = [11,13,15,17] 23 | Output: 11 24 | Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 25 | 26 | """ 27 | nums = [11,13,15,17] 28 | 29 | # def findMin(nums): 30 | # nums.sort() 31 | # return nums[0] 32 | # # return min(nums) 33 | 34 | def findMin(nums): 35 | l ,r = 0 ,len(nums)-1 36 | while l < r: 37 | mid = (l+r)//2 38 | 39 | if nums[mid] > nums[r]: 40 | l = mid +1 41 | else: 42 | r = mid 43 | return nums[l] 44 | 45 | print( 46 | findMin(nums) 47 | ) -------------------------------------------------------------------------------- /Python_/Questions/numberOfIslands.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/number-of-islands/ 3 | 4 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. 5 | 6 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 7 | 8 | Input: grid = [ 9 | ["1","1","1","1","0"], 10 | ["1","1","0","1","0"], 11 | ["1","1","0","0","0"], 12 | ["0","0","0","0","0"] 13 | ] 14 | Output: 1 15 | 16 | Input: grid = [ 17 | ["1","1","0","0","0"], 18 | ["1","1","0","0","0"], 19 | ["0","0","1","0","0"], 20 | ["0","0","0","1","1"] 21 | ] 22 | Output: 3 23 | """ 24 | 25 | grid = [ 26 | ["1","1","0","0","0"], 27 | ["1","1","0","0","0"], 28 | ["0","0","1","0","0"], 29 | ["0","0","0","1","1"] 30 | ] 31 | 32 | def numIslands(grid): 33 | ROW, COLS = len(grid), len(grid[0]) 34 | 35 | 36 | def dfs(i,j): 37 | if i < 0 or i >= ROW or j < 0 or j >= COLS or grid[i][j] != "1": 38 | return 39 | grid[i][j] = "#" 40 | dfs(i-1, j) 41 | dfs(i+1, j) 42 | dfs(i, j-1) 43 | dfs(i, j+1) 44 | 45 | island = 0 46 | 47 | for i in range(ROW): 48 | for j in range(COLS): 49 | if grid[i][j] == "1": 50 | dfs(i,j) 51 | island += 1 52 | 53 | 54 | 55 | return island 56 | 57 | 58 | print( 59 | numIslands(grid) 60 | ) 61 | -------------------------------------------------------------------------------- /Python_/DataStructure/minimumRemoveToMakeValidParentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ 3 | 4 | Given a string s of '(' , ')' and lowercase English characters. 5 | 6 | Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. 7 | 8 | Formally, a parentheses string is valid if and only if: 9 | 10 | It is the empty string, contains only lowercase characters, or 11 | It can be written as AB (A concatenated with B), where A and B are valid strings, or 12 | It can be written as (A), where A is a valid string. 13 | 14 | Input: s = "lee(t(c)o)de)" 15 | Output: "lee(t(c)o)de" 16 | Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. 17 | 18 | Input: s = "a)b(c)d" 19 | Output: "ab(c)d" 20 | 21 | Input: s = "))((" 22 | Output: "" 23 | Explanation: An empty string is also valid. 24 | """ 25 | s = "lee(t(c)o)de)" 26 | 27 | def minRemoveToMakeValid(s): 28 | s = list(s) 29 | stack = [] 30 | 31 | for i , char in enumerate(s): 32 | # print(s) 33 | if char == '(': 34 | stack.append(i) 35 | elif char == ')': 36 | if stack: 37 | stack.pop() 38 | else: 39 | s[i] = '' 40 | # print(stack) 41 | 42 | # print(stack) 43 | while stack: 44 | s[stack.pop()] = "" 45 | return "".join(s) 46 | 47 | print(minRemoveToMakeValid(s)) 48 | 49 | -------------------------------------------------------------------------------- /Python_/DataStructure/sortCharactersByFrequency.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. 3 | 4 | Return the sorted string. If there are multiple answers, return any of them. 5 | 6 | Input: s = "tree" 7 | Output: "eert" 8 | Explanation: 'e' appears twice while 'r' and 't' both appear once. 9 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. 10 | 11 | Input: s = "cccaaa" 12 | Output: "aaaccc" 13 | Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers. 14 | Note that "cacaca" is incorrect, as the same characters must be together. 15 | 16 | Input: s = "Aabb" 17 | Output: "bbAa" 18 | Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. 19 | Note that 'A' and 'a' are treated as two different characters. 20 | """ 21 | from ntpath import join 22 | from tabnanny import check 23 | from typing import Counter 24 | 25 | 26 | s = "Aabb" 27 | 28 | 29 | def frequencySort(s): 30 | check = Counter(s) 31 | print(check) 32 | s = list(s) 33 | s.sort(key=lambda x:(-check[x],x)) 34 | return "".join(s) 35 | 36 | 37 | def frequencySort2(s): 38 | res = "" 39 | check = Counter(s) 40 | arr = [[freq, c] for c, freq in check.items()] 41 | arr.sort(key=lambda x:-x[0]) 42 | for count, word in arr: 43 | res+=word*count 44 | return res 45 | 46 | print(frequencySort2(s)) -------------------------------------------------------------------------------- /JavaScript_/Dynamic Programming/countConstruct.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that accepts a target string and an array of strings. 3 | 4 | The function should return the number of ways that the 'target' can be construted by concatenating elements of the 'wordBank' array 5 | 6 | You can resue elements of 'wordBank' as many time as needed. 7 | 8 | */ 9 | 10 | // Brute force 11 | // | = target.slice() 12 | // TC => O(n^m * m) 13 | // SC => O(m * m) 14 | 15 | // memo 16 | // m = target.length, n = wordBank.length 17 | 18 | // | = target.slice() 19 | // TC => O(n*m * m) 20 | // SC => O(m * m) 21 | 22 | const countConstruct = (target, wordBank, memo = {}) => { 23 | if (target === "") return 1; 24 | if (target in memo) return memo[target]; 25 | let totalCount = 0; 26 | 27 | for (let word of wordBank) { 28 | if (target.indexOf(word) === 0) { 29 | const numWays = countConstruct(target.slice(word.length), wordBank, memo); 30 | 31 | totalCount += numWays; 32 | } 33 | } 34 | memo[target] = totalCount; 35 | return totalCount; 36 | }; 37 | 38 | console.log(countConstruct("abcdef", ["ab", "abc", "cd", "def", "abcd"])); 39 | console.log( 40 | countConstruct("skeatboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]) 41 | ); 42 | console.log(countConstruct("himanshu", ["hi", "ma", "hu", "ns", "abcd"])); 43 | console.log( 44 | countConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeee", [ 45 | "e", 46 | "ee", 47 | "eee", 48 | "eeeee", 49 | "eeeeee", 50 | ]) 51 | ); 52 | -------------------------------------------------------------------------------- /Python_/DataStructure/minStack.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/min-stack/ 3 | 4 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 5 | 6 | Implement the MinStack class: 7 | 8 | MinStack() initializes the stack object. 9 | void push(int val) pushes the element val onto the stack. 10 | void pop() removes the element on the top of the stack. 11 | int top() gets the top element of the stack. 12 | int getMin() retrieves the minimum element in the stack. 13 | 14 | Input 15 | ["MinStack","push","push","push","getMin","pop","top","getMin"] 16 | [[],[-2],[0],[-3],[],[],[],[]] 17 | 18 | Output 19 | [null,null,null,null,-3,null,0,-2] 20 | 21 | Explanation 22 | MinStack minStack = new MinStack(); 23 | minStack.push(-2); 24 | minStack.push(0); 25 | minStack.push(-3); 26 | minStack.getMin(); // return -3 27 | minStack.pop(); 28 | minStack.top(); // return 0 29 | minStack.getMin(); // return -2 30 | """ 31 | 32 | class MinStack: 33 | 34 | def __init__(self): 35 | self.stack = [] 36 | 37 | def push(self, val: int) -> None: 38 | self.stack.append(val) 39 | 40 | def pop(self) -> None: 41 | self.stack.pop() 42 | 43 | def top(self) -> int: 44 | return self.stack[0] 45 | 46 | def getMin(self) -> int: 47 | return min(self.stack) 48 | 49 | 50 | minStack = MinStack(); 51 | minStack.push(-2) 52 | minStack.push(0) 53 | minStack.push(-3) 54 | minStack.getMin() 55 | minStack.pop() 56 | minStack.top() 57 | minStack.getMin() -------------------------------------------------------------------------------- /Python_/qus/kthSmallestElementinABSt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. 3 | 4 | 5 | Input: root = [3,1,4,null,2], k = 1 6 | Output: 1 7 | 8 | Input: root = [5,3,6,2,4,null,null,1], k = 3 9 | Output: 3 10 | """ 11 | 12 | # Definition for a binary tree node. 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None): 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | def kthSmallest(root, k): 20 | if not root: return 0 21 | 22 | result = [] 23 | stack = [root] 24 | 25 | while stack: 26 | curNode = stack.pop() 27 | result.append(curNode.val) 28 | 29 | if curNode.left: 30 | stack.append(curNode.left) 31 | if curNode.right: 32 | stack.append(curNode.right) 33 | 34 | result.sort() 35 | return result[k-1] 36 | 37 | def inOrderKthSmallest(root,k): 38 | 39 | def inOrder(root): 40 | if not root: return [] 41 | 42 | return inOrder(root.left) + [root.val] + inOrder(root.right) 43 | 44 | return inOrder(root)[k-1] 45 | 46 | # root = TreeNode(3) 47 | # root.left = TreeNode(1) 48 | # root.right = TreeNode(4) 49 | # root.left.right = TreeNode(2) 50 | 51 | root = TreeNode(5) 52 | root.left = TreeNode(3) 53 | root.left.left = TreeNode(2) 54 | root.left.left.left = TreeNode(1) 55 | root.right = TreeNode(6) 56 | 57 | print(inOrderKthSmallest(root,3)) -------------------------------------------------------------------------------- /Python_/DataStructure/reverseLinkedList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the head of a singly linked list, reverse the list, and return the reversed list. 3 | 4 | Input: head = [1,2,3,4,5] 5 | Output: [5,4,3,2,1] 6 | 7 | Input: head = [1,2] 8 | Output: [2,1] 9 | 10 | Input: head = [] 11 | Output: [] 12 | """ 13 | 14 | class Node: 15 | def __init__(self, value): 16 | self.value = value 17 | self.next = None 18 | 19 | class LinkedList: 20 | def __init__(self): 21 | self.head = None 22 | 23 | def append(self, value): 24 | new_node = Node(value) 25 | 26 | if self.head == None: 27 | self.head = new_node 28 | return 29 | 30 | cur_node = self.head 31 | while cur_node.next: 32 | cur_node = cur_node.next 33 | 34 | cur_node.next = new_node 35 | 36 | def printList(self): 37 | cur_node = self.head 38 | while cur_node: 39 | print(cur_node.value) 40 | cur_node = cur_node.next 41 | 42 | def reverse(self): 43 | prev, curr, nxt= None, self.head, None 44 | 45 | while curr: 46 | nxt = curr.next 47 | curr.next = prev 48 | 49 | prev = curr 50 | curr = nxt 51 | 52 | self.head = prev 53 | 54 | 55 | llink = LinkedList() 56 | llink.append(1) 57 | llink.append(2) 58 | llink.append(3) 59 | llink.append(4) 60 | llink.append(5) 61 | 62 | # llink.printList() 63 | llink.reverse() 64 | llink.printList() 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /Python_/Questions/searchInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/search-in-rotated-sorted-array/ 3 | 4 | There is an integer array nums sorted in ascending order (with distinct values). 5 | 6 | Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. 7 | 8 | Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 9 | 10 | You must write an algorithm with O(log n) runtime complexity. 11 | 12 | Input: nums = [4,5,6,7,0,1,2], target = 0 13 | Output: 4 14 | 15 | Input: nums = [4,5,6,7,0,1,2], target = 3 16 | Output: -1 17 | 18 | Input: nums = [1], target = 0 19 | Output: -1 20 | """ 21 | nums = [1] 22 | target = 1 23 | 24 | def search(nums, target): 25 | l, r = 0, len(nums) 26 | 27 | while l < r: 28 | mid = (l+r)//2 29 | 30 | if target < nums[0] < nums[mid]: 31 | l = mid +1 32 | elif target >= nums[0] > nums[mid]: 33 | r = mid 34 | elif nums[mid] < target: 35 | l = mid +1 36 | elif nums[mid] > target: 37 | r = mid 38 | else: 39 | return mid 40 | return -1 41 | 42 | 43 | print( 44 | search(nums, target) 45 | ) 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /noOfIsland.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. 3 | 4 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 5 | 6 | Input: grid = [ 7 | ["1","1","1","1","0"], 8 | ["1","1","0","1","0"], 9 | ["1","1","0","0","0"], 10 | ["0","0","0","0","0"] 11 | ] 12 | Output: 1 13 | 14 | Input: grid = [ 15 | ["1","1","0","0","0"], 16 | ["1","1","0","0","0"], 17 | ["0","0","1","0","0"], 18 | ["0","0","0","1","1"] 19 | ] 20 | Output: 3 21 | """ 22 | grid = [ 23 | ["1", "1", "0", "0", "0"], 24 | ["1", "1", "0", "0", "0"], 25 | ["0", "0", "1", "0", "0"], 26 | ["0", "0", "0", "1", "1"] 27 | ] 28 | 29 | 30 | def numIslands(grid): 31 | if not grid: 32 | return 0 33 | ROWS, COLS = len(grid), len(grid[0]) 34 | maxCount = 0 35 | 36 | def dfs(r, c): 37 | if r < 0 or r >= ROWS or c < 0 or c >= COLS or grid[r][c] != "1": 38 | return 39 | grid[r][c] = "#" 40 | dfs(r+1, c) 41 | dfs(r-1, c) 42 | dfs(r, c+1) 43 | dfs(r, c-1) 44 | 45 | for i in range(ROWS): 46 | for j in range(COLS): 47 | if grid[i][j] == "1": 48 | dfs(i, j) 49 | maxCount += 1 50 | 51 | return maxCount 52 | 53 | 54 | print( 55 | numIslands(grid) 56 | ) 57 | -------------------------------------------------------------------------------- /Python_/Graphs/numberOfOperationsToMakeNetworkConnected.py: -------------------------------------------------------------------------------- 1 | """ 2 | There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. 3 | 4 | You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. 5 | 6 | Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1. 7 | 8 | Input: n = 4, connections = [[0,1],[0,2],[1,2]] 9 | Output: 1 10 | Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. 11 | 12 | Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] 13 | Output: 2 14 | 15 | Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] 16 | Output: -1 17 | Explanation: There are not enough cables. 18 | """ 19 | 20 | def makeConnected(n, connections): 21 | if len(connections) < n - 1: 22 | return -1 23 | 24 | G = [set() for i in range(n)] 25 | 26 | for i, j in connections: 27 | G[i].add(j) 28 | G[j].add(i) 29 | seen = [0] * n 30 | 31 | def dfs(i): 32 | if seen[i]: return 0 33 | seen[i] = 1 34 | for j in G[i]: dfs(j) 35 | return 1 36 | 37 | return sum(dfs(i) for i in range(n)) - 1 -------------------------------------------------------------------------------- /Python_/Questions/populatingNextRightPointersInEachNode.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ 3 | 4 | You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: 5 | 6 | struct Node { 7 | int val; 8 | Node *left; 9 | Node *right; 10 | Node *next; 11 | } 12 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 13 | 14 | Initially, all next pointers are set to NULL. 15 | 16 | """ 17 | 18 | 19 | class Node: 20 | def __init__(self, value): 21 | self.value = value 22 | self.left = None 23 | self.right = None 24 | 25 | class Tree: 26 | def __init__(self, root): 27 | self.root = Node(root) 28 | 29 | t1 = Tree(1) 30 | t1.root.left = Node(3) 31 | t1.root.right = Node(2) 32 | t1.root.left.left = Node(5) 33 | 34 | t2 = Tree(2) 35 | t2.root.left = Node(1) 36 | t2.root.right = Node(3) 37 | t2.root.left.right = Node(4) 38 | t2.root.right.right = Node(7) 39 | 40 | def connect(root): 41 | if not root: 42 | return root 43 | 44 | leftNode = Node(root) 45 | while leftNode: 46 | head = Node(leftNode) 47 | while head: 48 | head.left.next = head.right 49 | if head.next != None: 50 | head.right.next = head.next.left 51 | head = head.next 52 | leftNode = leftNode.left 53 | 54 | return leftNode -------------------------------------------------------------------------------- /Python_/qus/subtreeOfAnotherTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. 3 | 4 | A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. 5 | 6 | Input: root = [3,4,5,1,2], subRoot = [4,1,2] 7 | Output: true 8 | 9 | Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] 10 | Output: false 11 | 12 | """ 13 | # Definition for a binary tree node. 14 | class TreeNode: 15 | def __init__(self, val=0, left=None, right=None): 16 | self.val = val 17 | self.left = left 18 | self.right = right 19 | 20 | def isSubtree(root, subRoot): 21 | 22 | def traverse_tree(s): 23 | if s: 24 | return f"#{s.val} {traverse_tree(s.left)} {traverse_tree(s.right)}" 25 | 26 | string_s = traverse_tree(root) 27 | string_t = traverse_tree(subRoot) 28 | 29 | print(string_s) 30 | print(string_t) 31 | 32 | if string_t in string_s: 33 | return True 34 | else: 35 | return False 36 | 37 | root = TreeNode(3) 38 | root.left = TreeNode(4) 39 | root.right = TreeNode(5) 40 | root.left.left = TreeNode(1) 41 | root.left.right = TreeNode(2) 42 | # root.left.right.left = TreeNode(0) 43 | 44 | subRoot = TreeNode(4) 45 | subRoot.left = TreeNode(1) 46 | subRoot.right = TreeNode(2) 47 | 48 | print( 49 | isSubtree(root, subRoot) 50 | ) -------------------------------------------------------------------------------- /Python_/qus/uniquePath.py: -------------------------------------------------------------------------------- 1 | """ 2 | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. 3 | 4 | Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 5 | 6 | The test cases are generated so that the answer will be less than or equal to 2 * 109. 7 | 8 | Input: m = 3, n = 7 9 | Output: 28 10 | 11 | Input: m = 3, n = 2 12 | Output: 3 13 | Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 14 | 1. Right -> Down -> Down 15 | 2. Down -> Down -> Right 16 | 3. Down -> Right -> Down 17 | 18 | """ 19 | class Solution: 20 | def uniqueRec(self, m,n,memo= {}): 21 | key = f"{m},{n}" 22 | if key in memo: return memo[key] 23 | if m==0 or n==0: return 0 24 | if m==1 and n==1: return 1 25 | 26 | memo[key] = self.uniqueRec(m-1,n, memo) + self.uniqueRec(m,n-1, memo) 27 | return memo[key] 28 | 29 | 30 | def uniquePaths(self, m: int, n: int) -> int: 31 | 32 | return self.uniqueRec(m,n) 33 | 34 | # aux = [[1 for x in range(n)] for x in range(m)] 35 | # for i in range(1, m): 36 | # for j in range(1, n): 37 | # aux[i][j] = aux[i][j-1]+aux[i-1][j] 38 | # return aux[-1][-1] 39 | -------------------------------------------------------------------------------- /Python_/DataStructure/convertSortedArrayToBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 3 | 4 | Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. 5 | 6 | A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. 7 | 8 | Input: nums = [-10,-3,0,5,9] 9 | Output: [0,-3,9,-10,null,5] 10 | Explanation: [0,-10,5,null,-3,null,9] is also accepted: 11 | 12 | Input: nums = [1,3] 13 | Output: [3,1] 14 | Explanation: [1,3] and [3,1] are both a height-balanced BSTs. 15 | """ 16 | 17 | # Definition for a binary tree node. 18 | class TreeNode: 19 | def __init__(self, val=0, left=None, right=None): 20 | self.val = val 21 | self.left = left 22 | self.right = right 23 | 24 | def sortedArrayToBST(nums): 25 | 26 | """ 27 | As we have nums is sorted we can use 28 | Divide and conqure method (left, right) 29 | - we find middle element (left + right)//2 30 | - then add it into our root 31 | - then root.left (left, middle-1) 32 | - then root.right (middle+1, right) 33 | """ 34 | def helper(l, r): 35 | if l > r: 36 | return None 37 | 38 | m = (l+r)//2 39 | 40 | root = TreeNode(nums[m]) 41 | root.left = helper(l,m-1) 42 | root.right = helper(m+1,r) 43 | 44 | return root 45 | 46 | return helper(0, len(nums)-1) 47 | 48 | -------------------------------------------------------------------------------- /Python_/Questions/CombinationSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | # https://leetcode.com/problems/combination-sum/ 3 | 4 | Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. 5 | 6 | The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. 7 | 8 | It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. 9 | 10 | Input: candidates = [2,3,6,7], target = 7 11 | Output: [[2,2,3],[7]] 12 | Explanation: 13 | 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 14 | 7 is a candidate, and 7 = 7. 15 | These are the only two combinations. 16 | 17 | Input: candidates = [2,3,5], target = 8 18 | Output: [[2,2,2,2],[2,3,3],[3,5]] 19 | 20 | Input: candidates = [2], target = 1 21 | Output: [] 22 | """ 23 | 24 | candidates = [2,3,6,7] 25 | target = 7 26 | 27 | def combinationSum(candidates, target): 28 | ret = [] 29 | dfs(candidates, target, [], ret) 30 | return ret 31 | 32 | def dfs(nums, target, path, ret): 33 | if target < 0: 34 | return 35 | if target == 0: 36 | ret.append(path) 37 | return 38 | for i in range(len(nums)): 39 | dfs(nums[i:], target-nums[i], path+[nums[i]], ret) 40 | 41 | 42 | print( 43 | combinationSum(candidates, target) 44 | ) -------------------------------------------------------------------------------- /Python_/qus/searchInRoatedSortedArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | There is an integer array nums sorted in ascending order (with distinct values). 3 | 4 | Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. 5 | 6 | Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 7 | 8 | You must write an algorithm with O(log n) runtime complexity. 9 | 10 | Input: nums = [4,5,6,7,0,1,2], target = 0 11 | Output: 4 12 | 13 | Input: nums = [4,5,6,7,0,1,2], target = 3 14 | Output: -1 15 | 16 | Input: nums = [1], target = 0 17 | Output: -1 18 | """ 19 | 20 | 21 | nums = [4,5,6,7,0,1,2] 22 | target = 0 23 | 24 | def search(nums, target): 25 | l, r = 0 , len(nums)-1 26 | 27 | while l <= r: 28 | mid = (l+r)//2 29 | 30 | if nums[mid] == target: 31 | return mid 32 | 33 | elif nums[mid] >= nums[l]: 34 | if target <= nums[mid] and target >= nums[l]: 35 | r = mid -1 36 | else: 37 | l = mid + 1 38 | else: 39 | if target >= nums[mid] and target <= nums[r]: 40 | l = mid +1 41 | else: 42 | r = mid - 1 43 | return -1 44 | 45 | print(search(nums, target)) --------------------------------------------------------------------------------