├── 2020 ├── strings │ ├── kmp_str_match.py │ ├── kmp_prefix_arr.py │ └── kmp.py ├── graphs │ ├── dijikstra.py │ ├── prim.py │ ├── kruskal.py │ └── mst.py ├── twoPointers │ ├── twoPointers.py │ └── slidingWindow.py └── greedy │ └── mergingIntervals.py ├── 2021 ├── Day25 │ ├── Find Center of Star Graph │ │ ├── Find Center of Star Graph.py │ │ └── Find Center of Star Graph.cpp │ ├── Minimum Number of Vertices to Reach All Nodes │ │ ├── Minimum Number of Vertices to Reach All Nodes.py │ │ └── Minimum Number of Vertices to Reach All Nodes.cpp │ ├── Find the Town Judge │ │ ├── Find the Town Judge.py │ │ └── Find the Town Judge.cpp │ ├── All Paths From Source to Target │ │ ├── All Paths From Source to Target.py │ │ └── All Paths From Source to Target.cpp │ ├── Pacific Atlantic Water Flow │ │ ├── Pacific Atlantic Water Flow.py │ │ └── Pacific Atlantic Water Flow.cpp │ ├── Number of Islands │ │ ├── Number of Islands.py │ │ └── Number of Islands.cpp │ └── Accounts Merge │ │ ├── Accounts Merge.py │ │ └── Accounts Merge.cpp ├── Day11 │ ├── Missing Number │ │ ├── Missing Number.py │ │ └── Missing Number.cpp │ ├── Number of 1 Bits │ │ ├── Number of 1 Bits.cpp │ │ └── Number of 1 Bits.py │ ├── Counting Bits │ │ ├── Counting Bits.py │ │ └── Counting Bits.cpp │ ├── Sum of Two Integers │ │ ├── Sum of Two Integers.cpp │ │ └── Sum of Two Integers.py │ ├── README.md │ └── Bits.txt ├── Day8 │ ├── Valid_Palindrome │ │ ├── valid_palindrome.py │ │ └── valid_palindrome.cpp │ ├── Longest_Substring_Without_Repeating_Characters │ │ ├── Longest_Substring_Without_Repeating_Characters.cpp │ │ └── Longest_Substring_Without_Repeating_Characters.py │ ├── Longest Repeating Character Replacement │ │ ├── Longest_Repeating_Character_Replacement_Longest_Repeating_Character_Replacement.cpp │ │ └── Longest_Repeating_Character_Replacement_Longest_Repeating_Character_Replacement.py │ └── README.md ├── Day12 │ ├── Pow(x, n) │ │ ├── Pow(x, n).py │ │ └── Pow(x, n).cpp │ ├── Sqrt(x) │ │ ├── sqrt(x).py │ │ └── sqrt(x).cpp │ ├── Integer to English Words │ │ ├── Integer to English Words.py │ │ └── Integer to English Words.cpp │ └── Minimum Window Substring │ │ ├── Minimum Window Substring.cpp │ │ └── Minimum Window Substring.py ├── Day9 │ ├── Valid Anagram │ │ ├── valid_anagram.py │ │ └── valid_anagram.cpp │ ├── Group Anagrams │ │ ├── Group_anagrams.py │ │ └── Group_anagrams.cpp │ ├── Valid palindrome 2 │ │ ├── valid_palindrome_2.py │ │ └── valid_palindrome_2.cpp │ └── README.md ├── Day21 │ ├── Top K Frequent Elements │ │ ├── Top K Frequent Elements.py │ │ └── Top K Frequent Elements.cpp │ ├── Pastebin.txt │ ├── Find Median from Data Stream │ │ ├── Find Median from Data Stream.cpp │ │ └── Find Median from Data Stream.py │ └── Merge k Sorted Lists │ │ ├── Merge k Sorted Lists.py │ │ └── Merge k Sorted Lists.cpp ├── Day3 │ ├── Max Subarray │ │ ├── Max_subarray.cpp │ │ └── Max_subaaray.py │ ├── 3sum │ │ ├── 3sum.py │ │ └── 3sum.cpp │ ├── Valid parantheses │ │ ├── Valid_parantheses.py │ │ └── Valid_parantheses.cpp │ ├── Product of array except self │ │ ├── Product_of_array_except.cpp │ │ └── Product_of_array_except.py │ └── README.md ├── day1 │ ├── contains-duplicate │ │ ├── Contains_duplicate.cpp │ │ ├── ContainsDuplicates.py │ │ └── ContainsDuplicate.java │ ├── best-time-to-buy-and-sell-stock │ │ ├── Buy_and_sell_stock.cpp │ │ ├── BuySellStock.py │ │ └── BuySellStock.java │ ├── valid-anagram │ │ ├── Valid_anagram.cpp │ │ ├── ValidAnagram.py │ │ └── ValidAnagram.java │ ├── two-sum │ │ ├── Two_Sum.cpp │ │ └── TwoSumPython.py │ └── README.md ├── Day10 │ ├── Subsets │ │ ├── subsets.py │ │ └── subsets.cpp │ ├── Subsets2 │ │ ├── subsets2.py │ │ └── subsets2.cpp │ └── README.md ├── Day16 │ ├── Same Tree │ │ ├── Same Tree.py │ │ └── Same Tree.cpp │ ├── Maximum Depth of Binary Tree │ │ ├── Maximum Depth of Binary Tree.py │ │ └── Maximum Depth of Binary Tree.cpp │ ├── Invert Binary Tree │ │ ├── Invert Binary Tree.py │ │ └── Invert Binary Tree.cpp │ ├── Merge Two Binary Trees │ │ ├── Merge Two Binary Trees.py │ │ └── Merge Two Binary Trees.cpp │ └── Minimum Depth of Binary Tree │ │ ├── Minimum Depth of Binary Tree.py │ │ └── Minimum Depth of Binary Tree.cpp ├── Day5 │ ├── Rotate Image │ │ ├── Rotate_image.py │ │ └── Rotate_image.cpp │ ├── Spiral Matrix │ │ ├── spiral_matrix.py │ │ └── spiral_matrix.cpp │ ├── Set Matrix zeroes │ │ ├── set_matrix_zeroes.py │ │ └── set_matrix_zeroes.cpp │ ├── README.md │ └── Word Search │ │ └── Word_search.py ├── Day7 │ ├── Median of two sorted arrays │ │ ├── median_of_two_sorted_arrays.py │ │ └── median_of two_sorted arrays.cpp │ ├── Search in Rotated Sorted Array │ │ ├── Search_in_Rotated_Sorted_Array.cpp │ │ └── Search_in_Rotated_Sorted_Array.py │ └── README.md ├── Day14 │ ├── Reverse Linked List │ │ ├── Reverse Linked List.py │ │ └── Reverse Linked List.cpp │ ├── Remove Nth Node From End of List │ │ ├── Remove Nth Node From End of List.py │ │ └── Remove Nth Node From End of List.cpp │ ├── Add Two Numbers II │ │ ├── Add Two Numbers II.py │ │ └── Add Two Numbers II.cpp │ └── Reorder List │ │ ├── Reorder List.cpp │ │ └── Reorder List.py ├── Day22 │ ├── Is Graph Bipartite │ │ ├── Is Graph Bipartite.py │ │ └── Is Graph Bipartite.cpp │ ├── Redundant Connection │ │ ├── Redundant Connection.cpp │ │ └── Redundant Connection.py │ └── cycledetection.txt ├── Day26 │ ├── Number of Provinces │ │ ├── Number of Provinces.py │ │ └── Number of Provinces.cpp │ ├── Surrounded Regions │ │ ├── Surrounded Regions.py │ │ └── Surrounded Regions.cpp │ ├── Course Schedule │ │ ├── Course Schedule.cpp │ │ └── Course Schedule.py │ ├── Redundant Connection │ │ ├── Redundant Connection.cpp │ │ └── Redundant Connection.py │ ├── Course Schedule II │ │ ├── Course Schedule II.py │ │ └── Course Schedule II.cpp │ └── Longest Increasing Path in a Matrix │ │ ├── Longest Increasing Path in a Matrix.cpp │ │ └── Longest Increasing Path in a Matrix.py ├── Day20 │ ├── K Largest Element in a Stream.py │ ├── classroom.txt │ └── Kth Largest Element in a Stream.py.cpp ├── Day4 │ ├── Non overlapping intervals │ │ ├── non_overlapping_intervals.py │ │ └── non_overlapping_intervals.cpp │ ├── Container with most water │ │ ├── container_with_most_water.cpp │ │ └── Container_with_most_water.py │ ├── Insert Intervals │ │ ├── insert_intervals.py │ │ └── insert_intervals.cpp │ ├── Merge Intervals │ │ ├── Merge_intervals.cpp │ │ └── Merge_intervals.py │ └── README.md ├── Day6 │ ├── Next Greater Element 1 │ │ ├── Next_greater_element_1.py │ │ └── Next_greater_element_1.cpp │ ├── Remove all adjacent dupes in string │ │ └── Remove all adjacent dupes in string.cpp │ └── README.md ├── Day17 │ ├── Subtree of Another Tree │ │ ├── Subtree of Another Tree.py │ │ └── Subtree of Another Tree.cpp │ ├── Construct Binary Tree from Preorder and Inorder Traversal │ │ ├── Construct Binary Tree from Preorder and Inorder Traversal.py │ │ └── Construct Binary Tree from Preorder and Inorder Traversal.cpp │ ├── Serialize and Deserialize Binary Tree │ │ ├── Serialize and Deserialize Binary Tree.py │ │ └── Serialize and Deserialize Binary Tree.cpp │ └── Binary Tree Level Order Traversal │ │ ├── Binary Tree Level Order Traversal.py │ │ └── Binary Tree Level Order Traversal.cpp ├── Day19 │ ├── Lowest Common Ancestor of a Binary Search Tree │ │ ├── Lowest Common Ancestor of a Binary Search Tree.py │ │ └── Lowest Common Ancestor of a Binary Search Tree.cpp │ ├── Binary Search Tree to Greater Sum Tree │ │ ├── Binary Search Tree to Greater Sum Tree.py │ │ └── Binary Search Tree to Greater Sum Tree.cpp │ └── Kth Smallest Element in a BST │ │ ├── Kth Smallest Element in a BST.py │ │ └── Kth Smallest Element in a BST.cpp ├── Day15 │ ├── Binary Tree Inorder Traversal │ │ ├── Binary Tree Inorder Traversal.py │ │ └── Binary Tree Inorder Traversal.cpp │ ├── Diameter of Binary Tree │ │ ├── Diameter of Binary Tree.py │ │ └── Diameter of Binary Tree.cpp │ ├── Lowest Common Ancestor of a Binary Tree │ │ ├── Lowest Common Ancestor of a Binary Tree.cpp │ │ └── Lowest Common Ancestor of a Binary Tree.py │ └── Maximum Width of Binary Tree │ │ ├── Maximum Width of Binary Tree.py │ │ └── Maximum Width of Binary Tree.cpp ├── Day18 │ ├── Range Sum of BST │ │ └── Range Sum of BST.py │ ├── Two Sum IV - Input is a BST │ │ ├── Two Sum IV - Input is a BST.py │ │ └── Two Sum IV - Input is a BST.cpp │ ├── Search in a Binary Search Tree │ │ ├── Search in a Binary Search Tree.py │ │ └── Search in a Binary Search Tree.cpp │ ├── Validate Binary Search Tree │ │ ├── Validate Binary Search Tree.cpp │ │ └── Validate Binary Search Tree.py │ ├── Delete Node in a BST │ │ ├── Delete Node in a BST.py │ │ └── Delete Node in a BST.cpp │ └── Convert Sorted Array to Binary Search Tree │ │ ├── Convert Sorted Array to Binary Search Tree.cpp │ │ └── Convert Sorted Array to Binary Search Tree.py ├── Day13 │ ├── Merge Two Sorted Lists │ │ ├── Merge Two Sorted Lists.py │ │ └── Merge Two Sorted Lists.cpp │ └── Odd Even Linked List │ │ ├── Odd Even Linked List.cpp │ │ └── Odd Even Linked List.py ├── Day23 │ ├── Network Delay Time │ │ ├── Network Delay Time.py │ │ └── Network Delay Time.cpp │ └── Path With Minimum Effort │ │ ├── Path With Minimum Effort.cpp │ │ └── Path With Minimum Effort.py └── Day24 │ └── Bellman Ford Algo.txt └── .gitignore /.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | .idea -------------------------------------------------------------------------------- /2021/Day25/Find Center of Star Graph/Find Center of Star Graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCenter(self, e: List[List[int]]) -> int: 3 | return e[0][e[0][1] in e[1]] 4 | -------------------------------------------------------------------------------- /2021/Day11/Missing Number/Missing Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | return sum(list(range(len(nums)+1))) - sum(nums) 4 | -------------------------------------------------------------------------------- /2021/Day11/Number of 1 Bits/Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int hammingWeight(uint32_t n) 5 | { 6 | return bitset<32>(n).count(); 7 | } 8 | }; -------------------------------------------------------------------------------- /2021/Day11/Number of 1 Bits/Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n): 3 | ans = 0 4 | while n: 5 | n &= (n-1) 6 | ans += 1 7 | return ans 8 | -------------------------------------------------------------------------------- /2021/Day8/Valid_Palindrome/valid_palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | s1 = ''.join(i for i in s.lower() if i.isalnum()) 4 | return True if s1 == s1[::-1] else False 5 | -------------------------------------------------------------------------------- /2021/Day11/Counting Bits/Counting Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, num: int) -> List[int]: 3 | counter = [0] 4 | for i in range(1, num+1): 5 | counter.append(counter[i >> 1] + i % 2) 6 | return counter 7 | -------------------------------------------------------------------------------- /2021/Day25/Find Center of Star Graph/Find Center of Star Graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findCenter(vector> &edges) 5 | { 6 | return (edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1]) ? edges[0][0] : edges[0][1]; 7 | } 8 | }; -------------------------------------------------------------------------------- /2021/Day11/Counting Bits/Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector countBits(int num) 5 | { 6 | vector ret(num + 1, 0); 7 | for (int i = 1; i <= num; ++i) 8 | ret[i] = ret[i & (i - 1)] + 1; 9 | return ret; 10 | } 11 | }; -------------------------------------------------------------------------------- /2021/Day12/Pow(x, n)/Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x, n): 3 | if not n: 4 | return 1 5 | if n < 0: 6 | return 1 / self.myPow(x, -n) 7 | if n % 2: 8 | return x * self.myPow(x, n-1) 9 | return self.myPow(x*x, n/2) 10 | -------------------------------------------------------------------------------- /2021/Day25/Minimum Number of Vertices to Reach All Nodes/Minimum Number of Vertices to Reach All Nodes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSmallestSetOfVertices(self, n, A): 3 | B = set(range(n)) 4 | for x, y in A: 5 | if y in B: 6 | B.remove(y) 7 | return list(B) 8 | -------------------------------------------------------------------------------- /2021/Day9/Valid Anagram/valid_anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | ns, nt = len(s), len(t) 4 | if ns != nt: return False 5 | if ns == 0 and nt == 0: return True 6 | elif ns == 0 or nt == 0: return False 7 | return self.isAnagram(s.replace(s[0], ''), t.replace(s[0], '')) -------------------------------------------------------------------------------- /2021/Day11/Missing Number/Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int missingNumber(vector &nums) 5 | { 6 | int sum = 0; 7 | int n = nums.size(); 8 | for (int i = 0; i < n; i++) 9 | sum += nums[i]; 10 | 11 | return n * (n + 1) / 2 - sum; 12 | } 13 | }; -------------------------------------------------------------------------------- /2021/Day12/Sqrt(x)/sqrt(x).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mySqrt(self, x: int) -> int: 3 | l = 1 4 | r = x 5 | while l <= r: 6 | mid = (l + r) // 2 7 | if mid * mid <= x: 8 | l = mid + 1 9 | else: 10 | r = mid - 1 11 | 12 | return l - 1 13 | -------------------------------------------------------------------------------- /2021/Day25/Find the Town Judge/Find the Town Judge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, N, trust): 3 | count = [0] * (N + 1) 4 | for i, j in trust: 5 | count[i] -= 1 6 | count[j] += 1 7 | for i in range(1, N + 1): 8 | if count[i] == N - 1: 9 | return i 10 | return -1 11 | -------------------------------------------------------------------------------- /2021/Day21/Top K Frequent Elements/Top K Frequent Elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums, k): 3 | bucket = [[] for _ in range(len(nums) + 1)] 4 | Count = Counter(nums).items() 5 | for num, freq in Count: 6 | bucket[freq].append(num) 7 | flat_list = list(chain(*bucket)) 8 | return flat_list[::-1][:k] 9 | -------------------------------------------------------------------------------- /2021/Day11/Sum of Two Integers/Sum of Two Integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int getSum(int a, int b) 5 | { 6 | if (b == 0) 7 | return a; 8 | int sum = a ^ b; // finding the sum 9 | int carry = (unsigned int)(a & b) << 1; // finding the carry 10 | return getSum(sum, carry); 11 | } 12 | }; -------------------------------------------------------------------------------- /2021/Day9/Group Anagrams/Group_anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | frequencies = dict() 4 | for s in strs: 5 | key = ''.join(sorted(s)) 6 | try: 7 | frequencies[key].append(s) 8 | except: 9 | frequencies[key] = [s] 10 | return list(frequencies.values()) 11 | -------------------------------------------------------------------------------- /2021/Day3/Max Subarray/Max_subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | int maxSubArray(vector &nums) 5 | { 6 | int cur = nums[0]; 7 | int maxv = cur; 8 | for (int i = 1; i < nums.size(); i++) 9 | { 10 | cur = cur + nums[i] > nums[i] ? cur + nums[i] : nums[i]; 11 | maxv = max(maxv, cur); 12 | } 13 | return maxv; 14 | } 15 | }; -------------------------------------------------------------------------------- /2021/Day25/All Paths From Source to Target/All Paths From Source to Target.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def allPathsSourceTarget(self, graph): 3 | def dfs(formed): 4 | if formed[-1] == n - 1: 5 | sol.append(formed) 6 | return 7 | for child in graph[formed[-1]]: 8 | dfs(formed + [child]) 9 | 10 | sol, n = [], len(graph) 11 | dfs([0]) 12 | return sol 13 | -------------------------------------------------------------------------------- /2021/Day25/Find the Town Judge/Find the Town Judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findJudge(int N, vector> &trust) 5 | { 6 | vector count(N + 1, 0); 7 | for (auto &t : trust) 8 | count[t[0]]--, count[t[1]]++; 9 | for (int i = 1; i <= N; ++i) 10 | { 11 | if (count[i] == N - 1) 12 | return i; 13 | } 14 | return -1; 15 | } 16 | }; -------------------------------------------------------------------------------- /2021/day1/contains-duplicate/Contains_duplicate.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | bool containsDuplicate(vector &nums) 5 | { 6 | unordered_set seen; 7 | 8 | for (auto x : nums) 9 | { 10 | if (seen.find(x) != seen.end()) 11 | { 12 | return true; 13 | } 14 | seen.insert(x); 15 | } 16 | return false; 17 | } 18 | }; -------------------------------------------------------------------------------- /2021/Day10/Subsets/subsets.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def subsets(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[List[int]] 6 | """ 7 | res, path = [], [] 8 | 9 | def inner(nums, path, res): 10 | for i, el in enumerate(nums): 11 | inner(nums[i+1:], path + [el], res) 12 | res.append(path) 13 | inner(nums, path, res) 14 | return res 15 | -------------------------------------------------------------------------------- /2021/Day16/Same Tree/Same Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSameTree(self, p, q): 9 | if p and q: 10 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 11 | return p is q 12 | -------------------------------------------------------------------------------- /2021/Day5/Rotate Image/Rotate_image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. //CyFun 5 | """ 6 | 7 | #Transpose 8 | for i in range(len(matrix)): 9 | for j in range(i): 10 | matrix[i][j],matrix[j][i]= matrix[j][i],matrix[i][j] 11 | 12 | #reverse rows 13 | for row in matrix: 14 | row.reverse() -------------------------------------------------------------------------------- /2021/Day16/Maximum Depth of Binary Tree/Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def maxDepth(self, root): 10 | if not root: 11 | return 0 12 | 13 | return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 14 | -------------------------------------------------------------------------------- /2021/Day25/Minimum Number of Vertices to Reach All Nodes/Minimum Number of Vertices to Reach All Nodes.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector findSmallestSetOfVertices(int n, vector> &edges) 5 | { 6 | vector res, in(n); 7 | for (auto edge : edges) 8 | in[edge[1]]++; 9 | for (int i = 0; i != n; ++i) 10 | if (in[i] == 0) 11 | res.push_back(i); 12 | return res; 13 | } 14 | }; -------------------------------------------------------------------------------- /2020/strings/kmp_str_match.py: -------------------------------------------------------------------------------- 1 | str = "abxabcabcaby" #n 2 | p = "abcaby" # m 3 | p_arr = [0, 0, 0, 1, 2, 0] 4 | 5 | i = 0 6 | j = 0 7 | f = True 8 | 9 | while(i float: 3 | nums3 = sorted(nums1 + nums2) 4 | x = len(nums3) 5 | if(x % 2 == 0): 6 | x = x//2 7 | a = nums3[x] 8 | x = x-1 9 | a = float(a + nums3[x])/2.0 10 | return a 11 | else: 12 | x = x//2 13 | return (float(nums3[x])) 14 | -------------------------------------------------------------------------------- /2021/Day16/Invert Binary Tree/Invert Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def invertTree(self, root): 9 | if not root: 10 | return None 11 | root.left, root.right = self.invertTree( 12 | root.right), self.invertTree(root.left) 13 | 14 | return root 15 | -------------------------------------------------------------------------------- /2021/Day9/Valid Anagram/valid_anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | bool isAnagram(string s, string t) { 5 | vector temp(26,0); 6 | if(s.length() != t.length()) return false; 7 | for(int i = 0; i < s.length(); i++){ 8 | temp[(int)s[i]-(int)'a']++; 9 | temp[(int)t[i]-(int)'a']--; 10 | } 11 | for(int i=0; i<26; i++){ 12 | if(temp[i] != 0) return false; 13 | } 14 | return true; 15 | } 16 | }; -------------------------------------------------------------------------------- /2021/Day14/Reverse Linked List/Reverse Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def reverseList(self, head): 8 | prev = None 9 | curr = head 10 | 11 | while curr: 12 | next = curr.next 13 | curr.next = prev 14 | prev = curr 15 | curr = next 16 | 17 | return prev 18 | -------------------------------------------------------------------------------- /2021/Day8/Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int lengthOfLongestSubstring(string s) 5 | { 6 | int n = s.size(), rez = 0; 7 | int frec[128] = {0}; 8 | for (int pos = 0, i = 0; pos < n; pos++) 9 | { 10 | i = max(frec[s[pos]], i); 11 | rez = max(rez, pos - i + 1); 12 | frec[s[pos]] = pos + 1; 13 | } 14 | return rez; 15 | } 16 | }; -------------------------------------------------------------------------------- /2021/Day22/Is Graph Bipartite/Is Graph Bipartite.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isBipartite(self, graph): 3 | color = defaultdict(lambda: -1) 4 | return all(self.dfs(graph, v, edges, 0, color) for v, edges in enumerate(graph) if color[v] == -1) 5 | 6 | def dfs(self, graph, v, edges, cur_color, color): 7 | if color[v] != -1: 8 | return color[v] == cur_color 9 | color[v] = cur_color 10 | return all(self.dfs(graph, e, graph[e], int(not cur_color), color) for e in edges) 11 | -------------------------------------------------------------------------------- /2021/Day26/Number of Provinces/Number of Provinces.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCircleNum(self, A): 3 | N = len(A) 4 | seen = set() 5 | 6 | def dfs(node): 7 | for nei, adj in enumerate(A[node]): 8 | if adj and nei not in seen: 9 | seen.add(nei) 10 | dfs(nei) 11 | 12 | ans = 0 13 | for i in range(N): 14 | if i not in seen: 15 | dfs(i) 16 | ans += 1 17 | return ans 18 | -------------------------------------------------------------------------------- /2021/Day7/Median of two sorted arrays/median_of two_sorted arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | double findMedianSortedArrays(vector &nums1, vector &nums2) 5 | { 6 | double med = 0.0; 7 | for (int val : nums2) 8 | { 9 | nums1.push_back(val); 10 | } 11 | sort(nums1.begin(), nums1.end()); 12 | int n = nums1.size(); 13 | med = (n % 2 == 0) ? (double)(nums1[n / 2] + nums1[(n / 2) - 1]) / 2 : nums1[n / 2]; 14 | 15 | return med; 16 | } 17 | }; -------------------------------------------------------------------------------- /2021/Day20/K Largest Element in a Stream.py: -------------------------------------------------------------------------------- 1 | class KthLargest(object): 2 | 3 | 4 | def __init__(self, k, nums): 5 | self.pool = nums 6 | self.k = k 7 | heapq.heapify(self.pool) 8 | while len(self.pool) > k: 9 | heapq.heappop(self.pool) 10 | 11 | 12 | def add(self, val): 13 | if len(self.pool) < self.k: 14 | heapq.heappush(self.pool, val) 15 | elif val > self.pool[0]: 16 | heapq.heapreplace(self.pool, val) 17 | return self.pool[0] -------------------------------------------------------------------------------- /2021/day1/best-time-to-buy-and-sell-stock/Buy_and_sell_stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | int maxProfit(vector &prices) 5 | { 6 | int max_profit = 0, min_price = INT_MAX; 7 | 8 | for (int &price : prices) 9 | { 10 | // Min priced stock so far 11 | min_price = min(min_price, price); 12 | // profit if stock is sold at current price 13 | max_profit = max(max_profit, price - min_price); 14 | } 15 | return max_profit; 16 | } 17 | }; -------------------------------------------------------------------------------- /2021/Day9/Valid palindrome 2/valid_palindrome_2.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | # Time: O(n) 8 | # Space: O(n) 9 | left, right = 0, len(s) - 1 10 | while left < right: 11 | if s[left] != s[right]: 12 | one, two = s[left:right], s[left + 1:right + 1] 13 | return one == one[::-1] or two == two[::-1] 14 | left, right = left + 1, right - 1 15 | return True 16 | -------------------------------------------------------------------------------- /2021/Day8/Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @return an integer 3 | def lengthOfLongestSubstring(self, s): 4 | start = maxLength = 0 5 | usedChar = {} 6 | 7 | for i in range(len(s)): 8 | if s[i] in usedChar and start <= usedChar[s[i]]: 9 | start = usedChar[s[i]] + 1 10 | else: 11 | maxLength = max(maxLength, i - start + 1) 12 | 13 | usedChar[s[i]] = i 14 | 15 | return maxLength 16 | -------------------------------------------------------------------------------- /2021/Day12/Pow(x, n)/Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | double myPow(double x, int n) 5 | { 6 | if (n == std::numeric_limits::lowest()) 7 | { 8 | return myPow(1 / x, -(n + 1)) / x; 9 | } 10 | if (n < 0) 11 | { 12 | return myPow(1 / x, -n); 13 | } 14 | double ans = 1; 15 | while (n) 16 | { 17 | if (n & 1 == 1) 18 | ans *= x; 19 | x *= x; 20 | n >>= 1; 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /2021/Day7/Search in Rotated Sorted Array/Search_in_Rotated_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int search(vector &nums, int target) 5 | { 6 | int n = nums.size(); 7 | int ans; 8 | bool found = false; 9 | for (int i = 0; i < n; i++) 10 | { 11 | if (nums[i] == target) 12 | { 13 | ans = i; 14 | found = true; 15 | } 16 | } 17 | if (found == false) 18 | { 19 | return -1; 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /2021/Day4/Non overlapping intervals/non_overlapping_intervals.py: -------------------------------------------------------------------------------- 1 | class Solution:# By CyFun 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | if len(intervals) <= 1: 4 | return 0 5 | intervals.sort() 6 | overleap = 0 7 | 8 | end = intervals[0][1] 9 | 10 | for i in range(1, len(intervals)): 11 | if intervals[i][0] < end: 12 | overleap += 1 13 | end = min(intervals[i][1], end) 14 | else: 15 | end = intervals[i][1] 16 | 17 | return overleap 18 | -------------------------------------------------------------------------------- /2021/day1/valid-anagram/Valid_anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | bool isAnagram(string s, string t) 5 | { 6 | vector temp(26, 0); 7 | if (s.length() != t.length()) 8 | return false; 9 | for (int i = 0; i < s.length(); i++) 10 | { 11 | temp[(int)s[i] - (int)'a']++; 12 | temp[(int)t[i] - (int)'a']--; 13 | } 14 | for (int i = 0; i < 26; i++) 15 | { 16 | if (temp[i] != 0) 17 | return false; 18 | } 19 | return true; 20 | } 21 | }; -------------------------------------------------------------------------------- /2021/Day6/Next Greater Element 1/Next_greater_element_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | mem = defaultdict(lambda: '') 4 | stack = [] 5 | 6 | for num in nums2: 7 | if stack: 8 | while stack and stack[-1] < num: 9 | mem[stack.pop()] = num 10 | stack.append(num) 11 | 12 | while stack: 13 | mem[stack.pop()] = -1 14 | 15 | for i in range(len(nums1)): 16 | nums1[i] = mem[nums1[i]] 17 | 18 | return nums1 19 | -------------------------------------------------------------------------------- /2021/Day16/Merge Two Binary Trees/Merge Two Binary Trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def mergeTrees(self, t1, t2): 9 | if t1 and t2: 10 | root = TreeNode(t1.val + t2.val) 11 | root.left = self.mergeTrees(t1.left, t2.left) 12 | root.right = self.mergeTrees(t1.right, t2.right) 13 | return root 14 | else: 15 | return t1 or t2 16 | -------------------------------------------------------------------------------- /2021/Day26/Surrounded Regions/Surrounded Regions.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solve(self, board): 3 | if not any(board): 4 | return 5 | 6 | m, n = len(board), len(board[0]) 7 | save = [ij for k in range(m+n) 8 | for ij in ((0, k), (m-1, k), (k, 0), (k, n-1))] 9 | while save: 10 | i, j = save.pop() 11 | if 0 <= i < m and 0 <= j < n and board[i][j] == 'O': 12 | board[i][j] = 'S' 13 | save += (i, j-1), (i, j+1), (i-1, j), (i+1, j) 14 | 15 | board[:] = [['XO'[c == 'S'] for c in row] for row in board] 16 | -------------------------------------------------------------------------------- /2021/Day14/Remove Nth Node From End of List/Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeNthFromEnd(self, head, n): 8 | fast = slow = head 9 | for _ in range(n): 10 | fast = fast.next 11 | if not fast: 12 | return head.next 13 | while fast.next: 14 | fast = fast.next 15 | slow = slow.next 16 | slow.next = slow.next.next 17 | return head 18 | -------------------------------------------------------------------------------- /2021/Day17/Subtree of Another Tree/Subtree of Another Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def isSubtree(self, s, t): 9 | """ 10 | :type s: TreeNode 11 | :type t: TreeNode 12 | :rtype: bool 13 | """ 14 | def convert(p): 15 | return "^" + str(p.val) + "#" + convert(p.left) + convert(p.right) if p else "$" 16 | 17 | return convert(t) in convert(s) 18 | -------------------------------------------------------------------------------- /2021/Day3/3sum/3sum.py: -------------------------------------------------------------------------------- 1 | class Solution:#By CyFun 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | counter = Counter(nums) 4 | nums, tripluts = list(counter.keys()), set() 5 | if counter[0] >= 3: 6 | tripluts.add((0, 0, 0)) 7 | plus, minus = [n for n in nums if n > 0], [ 8 | n for n in nums if n < 0] 9 | for a in minus: 10 | for b in plus: 11 | c = -(a + b) 12 | if c in counter and ((c != a and c != b) or counter[c] > 1): 13 | tripluts.add(tuple(sorted([a, b, c]))) 14 | return tripluts 15 | -------------------------------------------------------------------------------- /2021/Day3/Valid parantheses/Valid_parantheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | if len(s) < 2: 4 | return False 5 | 6 | parentHash = {"(": ")", "{": "}", "[": "]"} 7 | stack = [] 8 | 9 | for i in range(len(s)): 10 | if s[i] == "(" or s[i] == "{" or s[i] == "[": 11 | stack.append(s[i]) 12 | else: 13 | if len(stack) < 1: 14 | return False 15 | 16 | if not s[i] == parentHash[stack.pop(-1)]: 17 | return False 18 | 19 | return len(stack) == 0 20 | -------------------------------------------------------------------------------- /2021/Day19/Lowest Common Ancestor of a Binary Search Tree/Lowest Common Ancestor of a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | 10 | def lowestCommonAncestor(self, root, p, q): 11 | while root: 12 | if root.val > p.val and root.val > q.val: 13 | root = root.left 14 | elif root.val < p.val and root.val < q.val: 15 | root = root.right 16 | else: 17 | return root 18 | -------------------------------------------------------------------------------- /2021/Day8/Valid_Palindrome/valid_palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPalindrome(string s) 5 | { 6 | for (int i = 0, j = s.length() - 1; i < j;) 7 | { 8 | if (!isalnum(s[i])) 9 | { 10 | i++; 11 | continue; 12 | } 13 | if (!isalnum(s[j])) 14 | { 15 | j--; 16 | continue; 17 | } 18 | if (tolower(s[i]) != tolower(s[j])) 19 | return false; 20 | i++; 21 | j--; 22 | } 23 | return true; 24 | } 25 | }; -------------------------------------------------------------------------------- /2021/Day4/Container with most water/container_with_most_water.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | int maxArea(vector &height) 5 | { 6 | int lidx = 0, ridx = height.size() - 1, answer = 0; 7 | 8 | while (lidx < ridx) 9 | { 10 | int h = min(height[ridx], height[lidx]); 11 | int square = (ridx - lidx) * h; 12 | if (answer < square) 13 | answer = square; 14 | 15 | if (height[ridx] > height[lidx]) 16 | lidx++; 17 | else 18 | ridx--; 19 | } 20 | 21 | return answer; 22 | } 23 | }; -------------------------------------------------------------------------------- /2021/Day19/Binary Search Tree to Greater Sum Tree/Binary Search Tree to Greater Sum Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def bstToGst(self, root: TreeNode) -> TreeNode: 9 | 10 | def recur(node, sumTillNow): 11 | if not node: 12 | return sumTillNow 13 | node.val += recur(node.right, sumTillNow) 14 | return recur(node.left, node.val) 15 | 16 | recur(root, 0) 17 | return root 18 | -------------------------------------------------------------------------------- /2021/Day3/Valid parantheses/Valid_parantheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValid(string s) 5 | { 6 | std::unordered_map match{{')', '('}, {']', '['}, {'}', '{'}}; 7 | std::deque stack; 8 | for (const auto &c : s) 9 | { 10 | if (c == '(' || c == '[' || c == '{') 11 | stack.push_back(c); 12 | else 13 | { 14 | if (stack.empty() || stack.back() != match[c]) 15 | return false; 16 | stack.pop_back(); 17 | } 18 | } 19 | return (stack.empty()); 20 | } 21 | }; -------------------------------------------------------------------------------- /2021/Day16/Minimum Depth of Binary Tree/Minimum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | # @param root, a tree node 9 | # @return an integer 10 | def minDepth(self, root): 11 | if root == None: 12 | return 0 13 | if root.left == None or root.right == None: 14 | return self.minDepth(root.left)+self.minDepth(root.right)+1 15 | return min(self.minDepth(root.right), self.minDepth(root.left))+1 16 | -------------------------------------------------------------------------------- /2021/Day26/Course Schedule/Course Schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool canFinish(int n, vector> &prerequisites) 5 | { 6 | vector> G(n); 7 | vector degree(n, 0), bfs; 8 | for (auto &e : prerequisites) 9 | G[e[1]].push_back(e[0]), degree[e[0]]++; 10 | for (int i = 0; i < n; ++i) 11 | if (!degree[i]) 12 | bfs.push_back(i); 13 | for (int i = 0; i < bfs.size(); ++i) 14 | for (int j : G[bfs[i]]) 15 | if (--degree[j] == 0) 16 | bfs.push_back(j); 17 | return bfs.size() == n; 18 | } 19 | }; -------------------------------------------------------------------------------- /2021/Day3/Product of array except self/Product_of_array_except.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector productExceptSelf(vector &nums) 5 | { 6 | vector left(nums.size(), 1); 7 | vector right(nums.size(), 1); 8 | int n = nums.size(); 9 | 10 | for (int i = 1; i < nums.size(); i++) 11 | { 12 | left[i] = left[i - 1] * nums[i - 1]; 13 | right[n - 1 - i] = right[n - 1 - i + 1] * nums[n - 1 - i + 1]; 14 | } 15 | for (int i = 0; i < nums.size(); i++) 16 | { 17 | right[i] *= left[i]; 18 | } 19 | return right; 20 | } 21 | }; -------------------------------------------------------------------------------- /2021/Day6/Next Greater Element 1/Next_greater_element_1.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector nextGreaterElement(vector &nums1, vector &nums2) 5 | { 6 | stack stk; 7 | unordered_map mp; 8 | 9 | for (auto &x : nums2) 10 | { 11 | while (!stk.empty() && stk.top() < x) 12 | { 13 | mp[stk.top()] = x; 14 | stk.pop(); 15 | } 16 | stk.push(x); 17 | } 18 | 19 | vector ans; 20 | for (auto &x : nums1) 21 | ans.push_back(mp.count(x) ? mp[x] : -1); 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /2021/Day8/Longest Repeating Character Replacement/Longest_Repeating_Character_Replacement_Longest_Repeating_Character_Replacement.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int characterReplacement(string s, int k) 5 | { 6 | int size = s.size(), i = 0, j = 0, same = 0; 7 | vector m(128, 0); 8 | while (j < size) 9 | { 10 | same = max(same, ++m[s[j++]]); // Update table, count for maximum character in window, and increment right bound 11 | if (j - i - same > k) 12 | --m[s[i++]]; // If criteria is not satisfied, increment left bound, update table 13 | } 14 | return j - i; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /2021/Day10/Subsets2/subsets2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 3 | out = [] 4 | dic = {} 5 | if len(nums) == 0: 6 | return [[]] 7 | 8 | def permute(combo, index): 9 | dic[tuple(sorted(combo))] = dic.get(tuple(sorted(combo)), 0)+1 10 | if dic[tuple(sorted(combo))] > 1: 11 | return 12 | out.append(combo) 13 | if len(combo) == len(nums): 14 | return 15 | for i in range(index, len(nums)): 16 | permute(combo+[nums[i]], i+1) 17 | return out 18 | return permute([], 0) 19 | -------------------------------------------------------------------------------- /2021/Day15/Binary Tree Inorder Traversal/Binary Tree Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | #recursive 8 | class Solution: 9 | def __init__(self): 10 | self.return_list = [] 11 | 12 | def inorderTraversal(self, root: TreeNode) -> List[int]: 13 | 14 | if root: 15 | self.inorderTraversal(root.left) 16 | 17 | self.return_list.append(root.val) 18 | 19 | self.inorderTraversal(root.right) 20 | 21 | return self.return_list 22 | -------------------------------------------------------------------------------- /2021/Day14/Reverse Linked List/Reverse Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode *cur=head,*prev=NULL,*temp; 15 | while(cur){ 16 | temp=cur->next; 17 | cur->next=prev; 18 | prev=cur; 19 | cur=temp; 20 | } 21 | return prev; 22 | } 23 | }; -------------------------------------------------------------------------------- /2021/Day17/Construct Binary Tree from Preorder and Inorder Traversal/Construct Binary Tree from Preorder and Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def buildTree(self, preorder, inorder): 9 | if inorder: 10 | ind = inorder.index(preorder.pop(0)) 11 | root = TreeNode(inorder[ind]) 12 | root.left = self.buildTree(preorder, inorder[0:ind]) 13 | root.right = self.buildTree(preorder, inorder[ind+1:]) 14 | return root 15 | -------------------------------------------------------------------------------- /2021/Day15/Diameter of Binary Tree/Diameter of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def diameterOfBinaryTree(self, root): 9 | self.best = 1 10 | 11 | def depth(root): 12 | if not root: 13 | return 0 14 | ansL = depth(root.left) 15 | ansR = depth(root.right) 16 | self.best = max(self.best, ansL + ansR + 1) 17 | return 1 + max(ansL, ansR) 18 | 19 | depth(root) 20 | return self.best - 1 21 | -------------------------------------------------------------------------------- /2021/Day4/Insert Intervals/insert_intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: # ByCyFun 2 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 3 | index = 0 4 | ret = [] 5 | while index < len(intervals) and intervals[index][1] < newInterval[0]: 6 | ret += [intervals[index]] 7 | index += 1 8 | 9 | while index < len(intervals) and newInterval[1] >= intervals[index][0]: 10 | newInterval[0] = min(newInterval[0], intervals[index][0]) 11 | newInterval[1] = max(newInterval[1], intervals[index][1]) 12 | index += 1 13 | 14 | ret += [newInterval] 15 | return ret + intervals[index:] 16 | -------------------------------------------------------------------------------- /2021/Day16/Maximum Depth of Binary Tree/Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | int maxDepth(TreeNode *root) 16 | { 17 | if (root == NULL) 18 | return 0; 19 | return 1 + std::max(maxDepth(root->left), maxDepth(root->right)); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /2021/Day18/Range Sum of BST/Range Sum of BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 9 | if not root: 10 | return 0 11 | elif root.val >= L and root.val <= R: 12 | return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R) 13 | elif root.val < L: 14 | return self.rangeSumBST(root.right, L, R) 15 | else: 16 | return self.rangeSumBST(root.left, L, R) 17 | -------------------------------------------------------------------------------- /2021/Day18/Two Sum IV - Input is a BST/Two Sum IV - Input is a BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def findTarget(self, root, k): 9 | if not root: 10 | return False 11 | bfs, s = [root], set() 12 | for i in bfs: 13 | if k - i.val in s: 14 | return True 15 | s.add(i.val) 16 | if i.left: 17 | bfs.append(i.left) 18 | if i.right: 19 | bfs.append(i.right) 20 | return False 21 | -------------------------------------------------------------------------------- /2021/Day12/Sqrt(x)/sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | long long binarySearch(int x) 5 | { 6 | long long s = 2, e = x / 2 + 1, mid; 7 | while (s <= e) 8 | { 9 | mid = s + (e - s) / 2; 10 | if (mid * mid == x || mid * mid < x && (mid + 1) * (mid + 1) > x) 11 | break; 12 | else if (mid * mid > x) 13 | e = mid - 1; 14 | else 15 | s = mid + 1; 16 | } 17 | return mid; 18 | } 19 | 20 | int mySqrt(int x) 21 | { 22 | if (x == 0) 23 | return 0; 24 | if (x < 4) 25 | return 1; 26 | return binarySearch(x); 27 | } 28 | }; -------------------------------------------------------------------------------- /2021/Day13/Merge Two Sorted Lists/Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTwoLists(self, l1: ListNode, l2: ListNode): 3 | head = cur = ListNode(0) 4 | 5 | while l1 or l2: 6 | if not l1: 7 | cur.next = l2 8 | return head.next 9 | if not l2: 10 | cur.next = l1 11 | return head.next 12 | 13 | if l2.val < l1.val: 14 | cur.next = ListNode(l2.val) 15 | l2 = l2.next if l2 else None 16 | else: 17 | cur.next = ListNode(l1.val) 18 | l1 = l1.next if l1 else None 19 | 20 | cur = cur.next 21 | return head.next 22 | -------------------------------------------------------------------------------- /2021/Day18/Search in a Binary Search Tree/Search in a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def searchBST(self, root, val): 9 | """ 10 | :type root: TreeNode 11 | :type val: int 12 | :rtype: TreeNode 13 | """ 14 | trav = root 15 | while trav: 16 | if trav.val == val: 17 | return trav 18 | elif trav.val < val: 19 | trav = trav.right 20 | else: 21 | trav = trav.left 22 | -------------------------------------------------------------------------------- /2021/day1/two-sum/Two_Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | vector twoSum(vector &nums, int target) 5 | { 6 | map hash; 7 | vector res(2); 8 | for (int it = 0; it < nums.size(); it++) 9 | { 10 | hash[nums[it]] = it; 11 | } 12 | for (int i = 0; i < nums.size(); i++) 13 | { 14 | int temp = target - nums[i]; 15 | auto a = hash.find(temp); 16 | if (a != hash.end() && a->second != i) 17 | { 18 | res[0] = i; 19 | res[1] = a->second; 20 | return res; 21 | } 22 | } 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /2021/Day15/Lowest Common Ancestor of a Binary Tree/Lowest Common Ancestor of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) 5 | { 6 | if (root == NULL) 7 | return NULL; 8 | 9 | if (root == p || root == q) 10 | return root; 11 | 12 | TreeNode *left = lowestCommonAncestor(root->left, p, q); 13 | TreeNode *right = lowestCommonAncestor(root->right, p, q); 14 | 15 | if (left != NULL and right != NULL) 16 | return root; 17 | 18 | if (left == NULL and right == NULL) 19 | return NULL; 20 | 21 | return left != NULL ? left : right; 22 | } 23 | }; -------------------------------------------------------------------------------- /2021/Day9/Valid palindrome 2/valid_palindrome_2.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool validPalindrome(string s) 5 | { 6 | for (int i = 0, j = s.size() - 1; i < j; i++, j--) 7 | if (s[i] != s[j]) 8 | { 9 | int i1 = i, j1 = j - 1, i2 = i + 1, j2 = j; 10 | while (i1 < j1 && s[i1] == s[j1]) 11 | { 12 | i1++; 13 | j1--; 14 | }; 15 | while (i2 < j2 && s[i2] == s[j2]) 16 | { 17 | i2++; 18 | j2--; 19 | }; 20 | return i1 >= j1 || i2 >= j2; 21 | } 22 | return true; 23 | } 24 | }; -------------------------------------------------------------------------------- /2021/Day14/Add Two Numbers II/Add Two Numbers II.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 8 | 9 | s1, s2 = 0, 0 10 | 11 | while l1 != None: 12 | s1 = s1*10+l1.val 13 | l1 = l1.next 14 | 15 | while l2 != None: 16 | s2 = s2*10+l2.val 17 | l2 = l2.next 18 | 19 | dummylist = dummy = ListNode(0) 20 | 21 | for i in str(s1+s2): 22 | dummy.next = ListNode(i) 23 | dummy = dummy.next 24 | 25 | return dummylist.next 26 | -------------------------------------------------------------------------------- /2021/Day16/Same Tree/Same Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | bool isSameTree(TreeNode *p, TreeNode *q) 16 | { 17 | if (!p && !q) 18 | return true; 19 | if (!p || !q) 20 | return false; 21 | return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 22 | } 23 | }; -------------------------------------------------------------------------------- /2021/Day9/Group Anagrams/Group_anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> groupAnagrams(vector &strs) 5 | { 6 | 7 | vector> ans; 8 | int ptr = 1; 9 | unordered_map mp; 10 | 11 | for (string s : strs) 12 | { 13 | string d = s; 14 | sort(d.begin(), d.end()); 15 | 16 | if (mp[d] == 0) 17 | { 18 | mp[d] = ptr++; 19 | } 20 | 21 | if (ans.size() == mp[d] - 1) 22 | { 23 | ans.push_back(vector()); 24 | } 25 | 26 | ans[mp[d] - 1].push_back(s); 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /2021/Day11/Sum of Two Integers/Sum of Two Integers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: int 6 | :rtype: int 7 | """ 8 | # 32 bits integer max 9 | MAX = 0x7FFFFFFF 10 | # 32 bits interger min 11 | MIN = 0x80000000 12 | # mask to get last 32 bits 13 | mask = 0xFFFFFFFF 14 | while b != 0: 15 | # ^ get different bits and & gets double 1s, << moves carry 16 | a, b = (a ^ b) & mask, ((a & b) << 1) & mask 17 | # if a is negative, get a's 32 bits complement positive first 18 | # then get 32-bit positive's Python complement negative 19 | return a if a <= MAX else ~(a ^ mask) 20 | -------------------------------------------------------------------------------- /2021/Day18/Search in a Binary Search Tree/Search in a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | TreeNode *searchBST(TreeNode *root, int val) 16 | { 17 | while (root != nullptr && root->val != val) 18 | { 19 | root = (root->val > val) ? root->left : root->right; 20 | } 21 | return root; 22 | } 23 | }; -------------------------------------------------------------------------------- /2021/Day16/Invert Binary Tree/Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | TreeNode *invertTree(TreeNode *root) 16 | { 17 | if (root) 18 | { 19 | invertTree(root->left); 20 | invertTree(root->right); 21 | std::swap(root->left, root->right); 22 | } 23 | return root; 24 | } 25 | }; -------------------------------------------------------------------------------- /2021/Day21/Top K Frequent Elements/Top K Frequent Elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector topKFrequent(vector &nums, int k) 5 | { 6 | unordered_map m; 7 | for (int num : nums) 8 | ++m[num]; 9 | 10 | vector> buckets(nums.size() + 1); 11 | for (auto p : m) 12 | buckets[p.second].push_back(p.first); 13 | 14 | vector ans; 15 | for (int i = buckets.size() - 1; i >= 0 && ans.size() < k; --i) 16 | { 17 | for (int num : buckets[i]) 18 | { 19 | ans.push_back(num); 20 | if (ans.size() == k) 21 | break; 22 | } 23 | } 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /2020/graphs/dijikstra.py: -------------------------------------------------------------------------------- 1 | 2 | import heapq 3 | 4 | d = { 5 | 0: [[1, 3], [3, 10]], 6 | 1: [[2, 5], [4, 11]], 7 | 2: [[3, 1], [4, 7]], 8 | 3: [], 9 | 4: [] 10 | } 11 | 12 | n = 5 13 | distance = [10**9]*n 14 | distance[0] = 0 15 | 16 | visited = [False]*n 17 | 18 | node = 0 19 | heap = [] 20 | 21 | heapq.heapify(heap) 22 | heapq.heappush(heap, [distance[node], node]) 23 | 24 | while(len(heap) > 0): 25 | node = heapq.heappop(heap)[1] 26 | 27 | if visited[node] == True: 28 | continue 29 | 30 | visited[node] = True 31 | 32 | for nn, w in d[node]: 33 | if distance[nn] > distance[node] + w: 34 | distance[nn] = distance[node] + w 35 | heapq.heappush(heap, [distance[nn], nn]) 36 | 37 | 38 | print distance 39 | -------------------------------------------------------------------------------- /2021/Day7/Search in Rotated Sorted Array/Search_in_Rotated_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | low = 0 4 | high = len(nums)-1 5 | 6 | while low <= high: 7 | mid = (low+high)//2 8 | 9 | if nums[mid] == target: 10 | return mid 11 | 12 | if nums[mid] >= nums[low]: 13 | if target >= nums[low] and target < nums[mid]: 14 | high = mid-1 15 | else: 16 | low = mid+1 17 | 18 | else: 19 | if target > nums[mid] and target <= nums[high]: 20 | low = mid+1 21 | else: 22 | high = mid-1 23 | 24 | return -1 25 | -------------------------------------------------------------------------------- /2021/Day15/Maximum Width of Binary Tree/Maximum Width of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def widthOfBinaryTree(self, root): 9 | queue = [(root, 0, 0)] 10 | cur_depth = left = ans = 0 11 | for node, depth, pos in queue: 12 | if node: 13 | queue.append((node.left, depth+1, pos*2)) 14 | queue.append((node.right, depth+1, pos*2 + 1)) 15 | if cur_depth != depth: 16 | cur_depth = depth 17 | left = pos 18 | ans = max(pos - left + 1, ans) 19 | 20 | return ans 21 | -------------------------------------------------------------------------------- /2021/Day5/Rotate Image/Rotate_image.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void rotate(vector> &matrix) 5 | { 6 | int r = matrix.size(), c = matrix[0].size(); 7 | // Transpose Of Matrix By CyFun 8 | for (int i = 0; i < r; i++) 9 | { 10 | for (int j = 0; j < c; j++) 11 | { 12 | if (i <= j) 13 | { 14 | swap(matrix[i][j], matrix[j][i]); 15 | } 16 | } 17 | } 18 | // Swapping Columns from left to right till half 19 | for (int i = 0; i < c / 2; i++) 20 | { 21 | for (int j = 0; j < r; j++) 22 | { 23 | swap(matrix[j][i], matrix[j][r - i - 1]); 24 | } 25 | } 26 | } 27 | }; -------------------------------------------------------------------------------- /2021/Day19/Kth Smallest Element in a BST/Kth Smallest Element in a BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | # @param {TreeNode} root 9 | # @param {integer} k 10 | # @return {integer} 11 | def kthSmallest(self, root, k): 12 | i = 0 13 | stack = [] 14 | node = root 15 | while node or stack: 16 | while node: 17 | stack.append(node) 18 | node = node.left 19 | node = stack.pop() 20 | i += 1 21 | if i == k: 22 | return node.val 23 | node = node.right 24 | -------------------------------------------------------------------------------- /2021/Day18/Two Sum IV - Input is a BST/Two Sum IV - Input is a BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | unordered_set s; 16 | bool findTarget(TreeNode *root, int k) 17 | { 18 | if (!root) 19 | return false; 20 | if (s.count(k - root->val)) 21 | return true; 22 | s.insert(root->val); 23 | return findTarget(root->left, k) || findTarget(root->right, k); 24 | } 25 | }; -------------------------------------------------------------------------------- /2021/Day22/Redundant Connection/Redundant Connection.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector parent; 5 | vector findRedundantConnection(vector> &edges) 6 | { 7 | if (edges.size() == 0) 8 | return {}; 9 | parent.resize(edges.size() + 1); 10 | for (int i = 1; i < edges.size() + 1; i++) 11 | { 12 | parent[i] = i; 13 | } 14 | for (vector edge : edges) 15 | { 16 | int f1 = find(edge[0]); 17 | int f2 = find(edge[1]); 18 | if (f1 != f2) 19 | parent[f1] = f2; 20 | else 21 | return edge; 22 | } 23 | return {}; 24 | } 25 | int find(int x) 26 | { 27 | return parent[x] == x ? x : find(parent[x]); 28 | } 29 | }; -------------------------------------------------------------------------------- /2021/Day26/Redundant Connection/Redundant Connection.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector parent; 5 | vector findRedundantConnection(vector> &edges) 6 | { 7 | if (edges.size() == 0) 8 | return {}; 9 | parent.resize(edges.size() + 1); 10 | for (int i = 1; i < edges.size() + 1; i++) 11 | { 12 | parent[i] = i; 13 | } 14 | for (vector edge : edges) 15 | { 16 | int f1 = find(edge[0]); 17 | int f2 = find(edge[1]); 18 | if (f1 != f2) 19 | parent[f1] = f2; 20 | else 21 | return edge; 22 | } 23 | return {}; 24 | } 25 | int find(int x) 26 | { 27 | return parent[x] == x ? x : find(parent[x]); 28 | } 29 | }; -------------------------------------------------------------------------------- /2020/graphs/prim.py: -------------------------------------------------------------------------------- 1 | 2 | import heapq 3 | d = { 4 | 1: [[2,12], [3,19]], 5 | 2: [[1,12],[3,16], [4,11]], 6 | 3: [[1,19],[2,16], [5, 14]], 7 | 4: [[2,11],[5,25]], 8 | 5: [[4,25],[3,14]] 9 | } 10 | 11 | 12 | h = [] 13 | heapq.heapify(h) 14 | 15 | h = [] 16 | 17 | V= [1,2,3,4,5] 18 | X = set() 19 | result = [] 20 | n = V[0] # first node 21 | X.add(n) 22 | 23 | for edge in d[n]: 24 | node, weight = edge 25 | heapq.heappush(h, [weight, node, n]) 26 | 27 | while(len(X) != len(V)): 28 | weight, n, st = heapq.heappop(h) 29 | if n in X: 30 | continue 31 | X.add(n) 32 | result.append([st, n, weight]) 33 | for edge in d[n]: 34 | node, weight = edge 35 | if node not in X: 36 | heapq.heappush(h, [weight, node, n]) 37 | 38 | print (result) 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /2021/Day15/Diameter of Binary Tree/Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int diameterOfBinaryTree(TreeNode* root) { 15 | int d=0; 16 | rec(root, d); 17 | return d; 18 | } 19 | 20 | int rec(TreeNode* root, int &d) { 21 | if(root == NULL) return 0; 22 | int ld = rec(root->left, d); 23 | int rd = rec(root->right, d); 24 | d=max(d,ld+rd); 25 | return max(ld,rd)+1; 26 | } 27 | }; -------------------------------------------------------------------------------- /2021/Day13/Odd Even Linked List/Odd Even Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | ListNode *oddEvenList(ListNode *head) 15 | { 16 | if (!head) 17 | return head; 18 | ListNode *odd = head, *evenhead = head->next, *even = evenhead; 19 | while (even && even->next) 20 | { 21 | odd->next = odd->next->next; 22 | even->next = even->next->next; 23 | odd = odd->next; 24 | even = even->next; 25 | } 26 | odd->next = evenhead; 27 | return head; 28 | } 29 | }; -------------------------------------------------------------------------------- /2020/strings/kmp_prefix_arr.py: -------------------------------------------------------------------------------- 1 | # Hello World program in Python 2 | 3 | print "Hello World!\n" 4 | 5 | 6 | s = "acacabacacabacacac" 7 | i = 1 8 | j = 0 9 | p_arr = [0]*len(s) 10 | 11 | while(ival += t2->val; 24 | t1->left = mergeTrees(t1->left, t2->left); 25 | t1->right = mergeTrees(t1->right, t2->right); 26 | return t1; 27 | } 28 | }; -------------------------------------------------------------------------------- /2021/Day25/Pacific Atlantic Water Flow/Pacific Atlantic Water Flow.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: 3 | if not matrix: 4 | return [] 5 | p_land = set() 6 | a_land = set() 7 | R, C = len(matrix), len(matrix[0]) 8 | 9 | def spread(i, j, land): 10 | land.add((i, j)) 11 | for x, y in ((i+1, j), (i, j+1), (i-1, j), (i, j-1)): 12 | if (0 <= x < R and 0 <= y < C and matrix[x][y] >= matrix[i][j] 13 | and (x, y) not in land): 14 | spread(x, y, land) 15 | 16 | for i in range(R): 17 | spread(i, 0, p_land) 18 | spread(i, C-1, a_land) 19 | for j in range(C): 20 | spread(0, j, p_land) 21 | spread(R-1, j, a_land) 22 | return list(p_land & a_land) 23 | -------------------------------------------------------------------------------- /2021/Day19/Lowest Common Ancestor of a Binary Search Tree/Lowest Common Ancestor of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | /** 12 | * Definition for a binary tree node. 13 | * struct TreeNode { 14 | * int val; 15 | * TreeNode *left; 16 | * TreeNode *right; 17 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 18 | * }; 19 | */ 20 | class Solution 21 | { 22 | public: 23 | TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) 24 | { 25 | while ((root->val - p->val) * (root->val - q->val) > 0) 26 | { 27 | root = root->val > p->val ? root->left : root->right; 28 | } 29 | return root; 30 | } 31 | }; -------------------------------------------------------------------------------- /2021/Day17/Subtree of Another Tree/Subtree of Another Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | bool isSubtree(TreeNode *s, TreeNode *t) 14 | { 15 | 16 | if (!s) 17 | return false; 18 | if (isSame(s, t)) 19 | return true; 20 | 21 | return isSubtree(s->left, t) || isSubtree(s->right, t); 22 | } 23 | bool isSame(TreeNode *s, TreeNode *t) 24 | { 25 | if (!s && !t) 26 | return true; 27 | if (!s || !t) 28 | return false; 29 | if (s->val != t->val) 30 | return false; 31 | 32 | return isSame(s->left, t->left) && isSame(s->right, t->right); 33 | } 34 | }; -------------------------------------------------------------------------------- /2021/Day26/Course Schedule/Course Schedule.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canFinish(self, numCourses, prerequisites): 3 | indegree = [set() for _ in range(numCourses)] 4 | outdegree = [[] for _ in range(numCourses)] 5 | for pre in prerequisites: 6 | indegree[pre[0]].add(pre[1]) 7 | outdegree[pre[1]].append(pre[0]) 8 | start, count = [i for i in range(numCourses) if not indegree[i]], 0 9 | while start: # start contains courses without prerequisites 10 | newStart = [] 11 | for i in start: 12 | count += 1 # add one course which can finish 13 | for j in outdegree[i]: 14 | indegree[j].remove(i) 15 | if not indegree[j]: 16 | newStart.append(j) 17 | start = newStart 18 | return count == numCourses # all courses will be visited 19 | -------------------------------------------------------------------------------- /2021/Day10/README.md: -------------------------------------------------------------------------------- 1 | # Day 10 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Subsets](https://leetcode.com/problems/subsets/) has been explained in his DSA course on arrays in [Day 10 video](https://www.youtube.com/watch?v=v4R0F-IQzT0). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Subsets](https://leetcode.com/problems/subsets/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day10/Subsets/subsets.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day10/Subsets/subsets.py) 10 | 11 | ## Assignment Questions Editorial 12 | 13 | 1. [Subsets-2](https://leetcode.com/problems/subsets-ii/) 14 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day10/Subsets2/subsets2.cpp) 15 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day10/Subsets2/subsets2.py) 16 | -------------------------------------------------------------------------------- /2020/twoPointers/twoPointers.py: -------------------------------------------------------------------------------- 1 | #Given a sorted array, we need to find a pair of numbers a[i] and a[j] whose sum is K 2 | # a = [1,2,3,4,5,10] 3 | # i -> [1,2,3,4,5,10]: 4 | # j->i+1....[1,3,4,5,6,10]: 5 | # if a[i] + a[j] == k: 6 | # print a[i] 7 | # print a[j] 8 | #Time complexity - O(n*n) 9 | 10 | 11 | # i = 0 12 | # j = n-1 13 | 14 | # while i k: 18 | # j-- 19 | # else: 20 | # i++ 21 | 22 | #Time complexity- O(n) 23 | 24 | if __name__ == '__main__': 25 | k =9 26 | l = raw_input().split(' '); 27 | my_list = list(int(num) for num in l) 28 | print my_list 29 | i = 0 30 | j = len(my_list) -1 31 | while i k: 36 | j = j - 1 37 | else: 38 | i = i + 1 39 | 40 | -------------------------------------------------------------------------------- /2021/Day4/Non overlapping intervals/non_overlapping_intervals.cpp: -------------------------------------------------------------------------------- 1 | bool cmpr(vector &a, vector &b) 2 | { 3 | return a[1] < b[1]; 4 | } 5 | class Solution 6 | { 7 | public: 8 | int eraseOverlapIntervals(vector> &intervals) 9 | { 10 | //sort on the basis of end time 11 | //set of jobs which can give us max non overlapping 12 | //iterate through each job and then see if prev[1]> current[0] - true - add++ 13 | //otherwise - prev = curr; 14 | //By CyFun 15 | int n = intervals.size(); 16 | int ans = -1; 17 | if (n == 0) 18 | return 0; 19 | sort(intervals.begin(), intervals.end(), cmpr); 20 | vector prev = intervals[0]; 21 | for (auto i : intervals) 22 | { 23 | if (prev[1] > i[0]) 24 | ans++; 25 | else 26 | prev = i; 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /2021/Day19/Kth Smallest Element in a BST/Kth Smallest Element in a BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | void inorder(TreeNode *root, vector &res) 16 | { 17 | if (!root) 18 | return; 19 | inorder(root->left, res); 20 | res.push_back(root->val); 21 | inorder(root->right, res); 22 | } 23 | int kthSmallest(TreeNode *root, int k) 24 | { 25 | if (!root) 26 | return -1; 27 | vector arr; 28 | inorder(root, arr); 29 | return arr[k - 1]; 30 | } 31 | }; -------------------------------------------------------------------------------- /2021/Day4/Merge Intervals/Merge_intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution//By CyFun 2 | { 3 | public: 4 | vector> merge(vector> &a) 5 | { 6 | if (a.size() == 1) 7 | return a; 8 | sort(a.begin(), a.end(), [](const vector &v1, const vector &v2) { return v1[0] < v2[0]; }); 9 | 10 | vector> res; 11 | 12 | for (int i = 1; i < a.size(); i++) 13 | { 14 | if (a[i][0] <= a[i - 1][1]) 15 | { 16 | a[i][0] = a[i - 1][0]; 17 | a[i][1] = max(a[i][1], a[i - 1][1]); 18 | 19 | if (i == a.size() - 1) 20 | res.push_back(a[i]); 21 | } 22 | else 23 | { 24 | res.push_back(a[i - 1]); 25 | 26 | if (i == a.size() - 1) 27 | res.push_back(a[i]); 28 | } 29 | } 30 | 31 | return res; 32 | } 33 | }; -------------------------------------------------------------------------------- /2021/Day19/Binary Search Tree to Greater Sum Tree/Binary Search Tree to Greater Sum Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | TreeNode *bstToGst(TreeNode *root) 16 | { 17 | int acc_sum = 0; 18 | sum_node(root, acc_sum); 19 | return root; 20 | } 21 | 22 | void sum_node(TreeNode *node, int &acc_sum) 23 | { 24 | if (node == NULL) 25 | return; 26 | sum_node(node->right, acc_sum); 27 | node->val += acc_sum; 28 | acc_sum = node->val; 29 | sum_node(node->left, acc_sum); 30 | } 31 | }; -------------------------------------------------------------------------------- /2021/Day26/Course Schedule II/Course Schedule II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findOrder(self, numCourses, prerequisites): 3 | indegree = [set() for _ in range(numCourses)] 4 | outdegree = [[] for _ in range(numCourses)] 5 | for p in prerequisites: 6 | indegree[p[0]].add(p[1]) 7 | outdegree[p[1]].append(p[0]) 8 | ret, start = [], [i for i in range(numCourses) if not indegree[i]] 9 | while start: # start contains courses without prerequisites 10 | newStart = [] 11 | for i in start: 12 | ret.append(i) 13 | for j in outdegree[i]: 14 | indegree[j].remove(i) 15 | if not indegree[j]: 16 | newStart.append(j) 17 | start = newStart # newStart contains new courses with no prerequisites 18 | # can finish if ret contains all courses 19 | return ret if len(ret) == numCourses else [] 20 | -------------------------------------------------------------------------------- /2021/Day26/Longest Increasing Path in a Matrix/Longest Increasing Path in a Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int dp[201][201]; 5 | int dfs(vector> &mat, int i, int j, int pre) 6 | { 7 | if (i < 0 || j < 0 || i == mat.size() || j == mat[0].size() || pre >= mat[i][j]) 8 | return 0; 9 | if (dp[i][j]) 10 | return dp[i][j]; 11 | int l = dfs(mat, i, j - 1, mat[i][j]); 12 | int r = dfs(mat, i, j + 1, mat[i][j]); 13 | int u = dfs(mat, i - 1, j, mat[i][j]); 14 | int d = dfs(mat, i + 1, j, mat[i][j]); 15 | return dp[i][j] = max({l, r, u, d}) + 1; 16 | } 17 | int longestIncreasingPath(vector> &matrix) 18 | { 19 | int maxVal = 0; 20 | for (int i = 0; i < matrix.size(); i++) 21 | for (int j = 0; j < matrix[i].size(); j++) 22 | maxVal = max(maxVal, dfs(matrix, i, j, -1)); 23 | return maxVal; 24 | } 25 | }; -------------------------------------------------------------------------------- /2021/Day4/Container with most water/Container_with_most_water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def maxArea(self, height: List[int]) -> int: 4 | """ 5 | Two-pointer approach 6 | 1. one pointer start from the start 7 | 2. one pointer start from the end 8 | 3. calculate the areas 9 | 4. update max area. 10 | 5. return max area once 1st pointer = 2nd pointer 11 | """ 12 | firstp = 0 13 | secondp = len(height)-1 14 | maxarea = 0 15 | 16 | while firstp != secondp: 17 | currfirst = height[firstp] 18 | secondfirst = height[secondp] 19 | hlength = secondp - firstp 20 | area = hlength*min(currfirst, secondfirst) 21 | if maxarea < area: 22 | maxarea = area 23 | 24 | if currfirst >= secondfirst: 25 | secondp -= 1 26 | else: 27 | firstp += 1 28 | 29 | return maxarea 30 | -------------------------------------------------------------------------------- /2021/day1/contains-duplicate/ContainsDuplicates.py: -------------------------------------------------------------------------------- 1 | # @Author: Araika Singh 2 | # @Date: 2021-03-20T00:17:56+05:30 3 | # @Email: roseymods@gmail.com 4 | # @Last modified by: NonZeroExitCode 5 | # @Last modified time: 2021-03-20T01:26:20+05:30 6 | # Link to question: https://leetcode.com/problems/contains-duplicate/ 7 | 8 | class ContainsDuplicate(object): 9 | def containsDuplicate(self, nums): 10 | 11 | # Keep a set that keeps track of distict elements in nums array 12 | hashSet = set() 13 | 14 | # Traversing the nums array 15 | for num in nums: 16 | 17 | # If the set doesn't contain the nums[i] then add it to set 18 | if num not in hashSet: 19 | hashSet.add(num) 20 | else: 21 | # In case the set already contains the number then return true 22 | return True 23 | 24 | # In case no element was found again the set, hence no duplicate present 25 | return False 26 | -------------------------------------------------------------------------------- /2021/Day18/Validate Binary Search Tree/Validate Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | bool isValidBST(TreeNode *root) 16 | { 17 | return isValidBST(root, NULL, NULL); 18 | } 19 | 20 | bool isValidBST(TreeNode *root, TreeNode *minNode, TreeNode *maxNode) 21 | { 22 | if (!root) 23 | return true; 24 | if (minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val) 25 | return false; 26 | return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode); 27 | } 28 | }; -------------------------------------------------------------------------------- /2021/Day14/Remove Nth Node From End of List/Remove Nth Node From End of List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* removeNthFromEnd(ListNode* head, int n) { 14 | ListNode *ans,*slow=head,*fast=head; 15 | for(int i=0;inext; 17 | } 18 | if(!fast) { //delete first element 19 | ans=head->next; 20 | delete head; 21 | return ans; 22 | } 23 | while(fast->next) { 24 | slow=slow->next; 25 | fast=fast->next; 26 | } 27 | ans=slow->next->next; 28 | delete slow->next; 29 | slow->next=ans; 30 | return head; 31 | } 32 | }; -------------------------------------------------------------------------------- /2021/Day12/Integer to English Words/Integer to English Words.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberToWords(self, num: int) -> str: 3 | to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \ 4 | 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split() 5 | tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split() 6 | thousand = 'Thousand Million Billion'.split() 7 | 8 | def word(num, idx=0): 9 | if num == 0: 10 | return [] 11 | if num < 20: 12 | return [to19[num-1]] 13 | if num < 100: 14 | return [tens[num//10-2]] + word(num % 10) 15 | if num < 1000: 16 | return [to19[num//100-1]] + ['Hundred'] + word(num % 100) 17 | 18 | p, r = num//1000, num % 1000 19 | space = [thousand[idx]] if p % 1000 != 0 else [] 20 | return word(p, idx+1) + space + word(r) 21 | return ' '.join(word(num)) or 'Zero' 22 | -------------------------------------------------------------------------------- /2021/Day5/Spiral Matrix/spiral_matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: #CyFun 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | result = [] 4 | 5 | while matrix: 6 | # Add top row 7 | result.extend(matrix.pop(0)) 8 | 9 | # Iterate through new top till 2nd last row while 10 | # adding last element of row if row is non empty 11 | for row in matrix[0:-1]: 12 | if row: 13 | result.append(row.pop()) 14 | 15 | # Add reversed bottom row if exists 16 | if not matrix: 17 | break 18 | result.extend(matrix.pop()[::-1]) 19 | 20 | # Iterate from new bottom row back up till 2nd row 21 | # while adding first element from row if row is non empty 22 | for row in matrix[:0:-1]: 23 | if row: 24 | result.append(row.pop(0)) 25 | 26 | return result -------------------------------------------------------------------------------- /2021/day1/two-sum/TwoSumPython.py: -------------------------------------------------------------------------------- 1 | # @Author: Kshitiz Miglani 2 | # SDE @AMAZON | Founder @Devsnest.in 3 | # @Link to question: https://leetcode.com/problems/two-sum/ 4 | class TwoSumPython(object): 5 | def twoSum(self, nums, target): 6 | # Creating a HashMap to keep track of numbers and their indices 7 | nummap = {} 8 | 9 | # Traversing through the array 10 | # Say for testcase array = {0, 1, -1, 2} if required sum is 0. 11 | # Then the present element should have a number (target - present element) 12 | # Like for n = 2, the list should have (0 - 2) = -2 to have a sum = 0 13 | for i in range(len(nums)): 14 | num = nums[i] 15 | 16 | # if the map contains (target - present element) then we got our pair and 17 | # hence the required indices is to be returned 18 | if target - num in nummap: 19 | return [nummap[target-num], i] 20 | 21 | nummap[num]=i 22 | # If no pair is found, there is no pair then nothing is returned 23 | -------------------------------------------------------------------------------- /2020/twoPointers/slidingWindow.py: -------------------------------------------------------------------------------- 1 | # Given an array of size N, we need to find the maximum sum of consecutive K elements 2 | # [1,2,3,100,200,300,400,200,500] 3 | # k = 3 4 | # for i in [1,2,3,100,200,300,400,200,500]: 5 | # tempSum = 0 6 | # for j in (i,i+k): 7 | # tempSum = tempSum+a[i] 8 | # ans = max(ans, tempSum) 9 | 10 | 11 | #Time complexity - O(n*n) 12 | # [1,2,3,100,200,300,400,200,500] 13 | # 6, x = [1,2,3] 14 | # 6 + 100 -1 [2,3,100], x+100-1 15 | # (6 + 100 -1) + 200 -2 16 | 17 | if __name__ == '__main__': 18 | k = 3 19 | l = raw_input().split(' '); 20 | my_list = list(int(num) for num in l) 21 | maxSum = 0 22 | i = 0 23 | j = 0 24 | n = len(my_list) 25 | maxSum = 0 26 | while j < k: 27 | maxSum = maxSum + my_list[j] 28 | j = j +1 29 | print maxSum 30 | tempSum = maxSum 31 | while j < n: 32 | j = j + 1 33 | tempSum = tempSum + my_list[j] - my_list[i] 34 | i = i +1 35 | maxSum = max(maxSum, tempSum) 36 | print maxSum 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /2021/Day4/Merge Intervals/Merge_intervals.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | #By CyFun 3 | 4 | class Solution(object): 5 | def __init__(self): 6 | self.startToEnds = defaultdict(list) 7 | 8 | def merge(self, intervals): 9 | """ 10 | :type intervals: List[List[int]] 11 | :rtype: List[List[int]] 12 | """ 13 | for (start, end) in intervals: 14 | self.startToEnds[start].append(end) 15 | 16 | intervals = [[start, max(endList)] 17 | for start, endList in self.startToEnds.items()] 18 | intervals.sort(key=lambda x: x[0]) 19 | 20 | mergedIntervals = [] 21 | for interval in intervals: 22 | if not mergedIntervals or interval[0] > mergedIntervals[-1][1]: 23 | mergedIntervals.append(interval) 24 | else: 25 | mergedIntervals[-1][1] = max(mergedIntervals[-1] 26 | [1], interval[1]) 27 | 28 | return mergedIntervals 29 | -------------------------------------------------------------------------------- /2021/Day15/Binary Tree Inorder Traversal/Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | vector inorderTraversal(TreeNode *root) 16 | { 17 | vector nodes; 18 | stack todo; 19 | while (root || !todo.empty()) 20 | { 21 | while (root) 22 | { 23 | todo.push(root); 24 | root = root->left; 25 | } 26 | root = todo.top(); 27 | todo.pop(); 28 | nodes.push_back(root->val); 29 | root = root->right; 30 | } 31 | return nodes; 32 | } 33 | }; -------------------------------------------------------------------------------- /2021/Day25/All Paths From Source to Target/All Paths From Source to Target.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | // setting a few class variables, so that we do not have to pass them down all the time in the recursive dfs calls 5 | int target; 6 | vector> res; 7 | vector tmp; 8 | void dfs(vector> &graph, int currNode = 0) 9 | { 10 | // updating tmp 11 | tmp.push_back(currNode); 12 | // and either updating res with it if target is met 13 | if (currNode == target) 14 | res.push_back(tmp); 15 | // or callling dfs again recursively 16 | else 17 | for (int node : graph[currNode]) 18 | { 19 | dfs(graph, node); 20 | } 21 | // backtracking with tmp 22 | tmp.pop_back(); 23 | } 24 | vector> allPathsSourceTarget(vector> &graph) 25 | { 26 | target = graph.size() - 1; 27 | dfs(graph); 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /2021/day1/contains-duplicate/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author: Araika Singh 3 | * @Date: 2021-03-19T22:02:05+05:30 4 | * @Email: roseymods@gmail.com 5 | * @Last modified by: NonZeroExitCode 6 | * @Last modified time: 2021-03-20T01:26:04+05:30 7 | * @Link to question: https://leetcode.com/problems/contains-duplicate/ 8 | */ 9 | 10 | class ContainsDuplicate{ 11 | 12 | public boolean containsDuplicate(int[] nums) { 13 | 14 | // Keep a set that keeps track of distict elements in nums array 15 | HashSet set = new HashSet<>(); 16 | 17 | // Traversing the nums array 18 | for(int i = 0; i < nums.length; i++){ 19 | 20 | // In case the set already contains the number then return true 21 | if(set.contains(nums[i])) { 22 | return true; 23 | }else{ 24 | // If the set doesn't contain the nums[i] then add it to set 25 | set.add(nums[i]); 26 | } 27 | } 28 | 29 | // In case no element was found again the set, hence no duplicate present 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /2021/Day18/Delete Node in a BST/Delete Node in a BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def deleteNode(self, root, key): 9 | if not root: 10 | return None 11 | 12 | if root.val == key: 13 | if not root.right: 14 | return root.left 15 | 16 | if not root.left: 17 | return root.right 18 | 19 | if root.left and root.right: 20 | temp = root.right 21 | while temp.left: 22 | temp = temp.left 23 | root.val = temp.val 24 | root.right = self.deleteNode(root.right, root.val) 25 | 26 | elif root.val > key: 27 | root.left = self.deleteNode(root.left, key) 28 | else: 29 | root.right = self.deleteNode(root.right, key) 30 | 31 | return root 32 | -------------------------------------------------------------------------------- /2021/Day20/classroom.txt: -------------------------------------------------------------------------------- 1 | mc = n/4 + 2n/8 + 3n/16 + 4n/32 + 5n/64 + .... 2 | 3 | mc = 2n(1/4 + 2/8 + 3/16 + 4/32 + 5/64 + ...) 4 | 5 | => mc/2n = 1/4 + 2/8 + 3/16 + 4/32 + 5/64 + ... : equation A 6 | 7 | mc = 2n(1/4 + 1/8 + 1/16 + 1/32 + 1/64 + ... # this equals 1/2 8 | + 1/8 + 2/16 + 3/32 + 4/64 + ...) 9 | 10 | mc = 2n(1/2 + 1/8 + 2/16 + 3/32 + 4/64 + ...) 11 | mc = n + 2n(1/8 + 2/16 + 3/32 + 4/64 + ...) 12 | mc = n + 2n/2(1/4 + 2/8 + 3/16 + 4/32 + 5/64 + ...) 13 | substitutinng from eq A 14 | 15 | mc = n + n(mc/2n) 16 | 17 | => mc = 2n 18 | 19 | time complexity = O(n) 20 | 21 | 22 | --------------------------- 23 | for not perfect heap: 24 | 25 | if there are n elements in a heap of k levels (starting from 0) and last level has x elements 26 | 27 | we can say that 2^0 + 2^1 + 2^2 + ... + 2^(k-1) + x = n 28 | 29 | => n = 2^(k) -1 + x 30 | => n + 1 -x = 2^(k) 31 | 32 | leaf nodes (l) = x + 2^(k-1) - (x+1)/2 33 | l = x + 2^k/2 -x/2 -1/2 34 | 35 | = x/2 -1/2 + n/2 + 1/2 - x/2 36 | 37 | = n/2 38 | 39 | l = n/2 40 | 41 | ------------------------ -------------------------------------------------------------------------------- /2021/Day21/Pastebin.txt: -------------------------------------------------------------------------------- 1 | mc = n/4 + 2n/8 + 3n/16 + 4n/32 + 5n/64 + .... 2 | 3 | mc = 2n(1/4 + 2/8 + 3/16 + 4/32 + 5/64 + ...) 4 | 5 | => mc/2n = 1/4 + 2/8 + 3/16 + 4/32 + 5/64 + ... : equation A 6 | 7 | mc = 2n(1/4 + 1/8 + 1/16 + 1/32 + 1/64 + ... # this equals 1/2 8 | + 1/8 + 2/16 + 3/32 + 4/64 + ...) 9 | 10 | mc = 2n(1/2 + 1/8 + 2/16 + 3/32 + 4/64 + ...) 11 | mc = n + 2n(1/8 + 2/16 + 3/32 + 4/64 + ...) 12 | mc = n + 2n/2(1/4 + 2/8 + 3/16 + 4/32 + 5/64 + ...) 13 | substitutinng from eq A 14 | 15 | mc = n + n(mc/2n) 16 | 17 | => mc = 2n 18 | 19 | time complexity = O(n) 20 | 21 | 22 | --------------------------- 23 | for not perfect heap: 24 | 25 | if there are n elements in a heap of k levels (starting from 0) and last level has x elements 26 | 27 | we can say that 2^0 + 2^1 + 2^2 + ... + 2^(k-1) + x = n 28 | 29 | => n = 2^(k) -1 + x 30 | => n + 1 -x = 2^(k) 31 | 32 | leaf nodes (l) = x + 2^(k-1) - (x+1)/2 33 | l = x + 2^k/2 -x/2 -1/2 34 | 35 | = x/2 -1/2 + n/2 + 1/2 - x/2 36 | 37 | = n/2 38 | 39 | l = n/2 40 | 41 | ------------------------ -------------------------------------------------------------------------------- /2021/day1/best-time-to-buy-and-sell-stock/BuySellStock.py: -------------------------------------------------------------------------------- 1 | # @Author: Kshitiz Miglani 2 | # SDE @AMAZON | Founder @Devsnest.in 3 | # @Link to question: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 4 | 5 | class BuySellStock(object): 6 | def maxProfit(self, prices): 7 | # Keeping the pointer of minimum cost at 0th index of prices array 8 | # and for the time being the maximum profit is zero 9 | min_till_now = 100000 10 | best_profit = 0 11 | 12 | # Traversing through each element in prices array 13 | for price in prices: 14 | 15 | # if min_till_now is more than present price then update min_till_now to present price 16 | if min_till_now > price: 17 | min_till_now = price 18 | 19 | # If difference between the present prices and the minimum min_till_now 20 | # is more than previous best_profit then update it 21 | elif best_profit < price - min_till_now: 22 | best_profit = price - min_till_now 23 | 24 | # Answer returned here 25 | return best_profit 26 | -------------------------------------------------------------------------------- /2021/Day20/Kth Largest Element in a Stream.py.cpp: -------------------------------------------------------------------------------- 1 | class KthLargest 2 | { 3 | public: 4 | priority_queue, greater> pq; 5 | int size, gk; 6 | KthLargest(int k, vector &nums) 7 | { 8 | int n = nums.size(); 9 | gk = k; 10 | if (n < k) 11 | size = n; 12 | else 13 | size = k; 14 | for (int i = 0; i < size; i++) 15 | pq.push(nums[i]); 16 | for (int i = k; i < n; i++) 17 | { 18 | if (nums[i] > pq.top()) 19 | { 20 | pq.pop(); 21 | pq.push(nums[i]); 22 | } 23 | } 24 | } 25 | 26 | int add(int val) 27 | { 28 | if (pq.empty() || pq.size() < gk) 29 | pq.push(val); 30 | else if (val > pq.top()) 31 | { 32 | pq.pop(); 33 | pq.push(val); 34 | } 35 | return pq.top(); 36 | } 37 | }; 38 | /** 39 | * Your KthLargest object will be instantiated and called as such: 40 | * KthLargest* obj = new KthLargest(k, nums); 41 | * int param_1 = obj->add(val); 42 | */ -------------------------------------------------------------------------------- /2021/Day23/Network Delay Time/Network Delay Time.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: 3 | 4 | graph = collections.defaultdict(dict) 5 | 6 | for frm, to, cost in times: 7 | graph[frm][to] = cost 8 | 9 | distances = { i: float("inf") for i in range(1, N+1)} 10 | distances[K] = 0 11 | min_dist = [(0,K)] 12 | visited = set() 13 | 14 | while min_dist: 15 | 16 | cur_dist, cur = heapq.heappop(min_dist) 17 | if cur in visited: continue 18 | visited.add(cur) 19 | 20 | for neighbor in graph[cur]: 21 | if neighbor in visited: continue 22 | this_dist = cur_dist + graph[cur][neighbor] 23 | if this_dist < distances[neighbor]: 24 | distances[neighbor] = this_dist 25 | heapq.heappush(min_dist, (this_dist, neighbor)) 26 | 27 | if len(visited) != len(distances): return -1 28 | return distances[max(distances,key=distances.get)] -------------------------------------------------------------------------------- /2021/Day21/Find Median from Data Stream/Find Median from Data Stream.cpp: -------------------------------------------------------------------------------- 1 | class MedianFinder 2 | { 3 | private: 4 | int size; 5 | multiset numsSet; 6 | multiset::iterator midIter; 7 | 8 | public: 9 | // Adds a number into the data structure. 10 | void addNum(int num) 11 | { 12 | if (numsSet.empty()) 13 | { 14 | midIter = numsSet.insert(num); 15 | size++; 16 | return; 17 | } 18 | numsSet.insert(num); 19 | if ((size & 1) && num < *midIter) 20 | --midIter; 21 | else if (!(size & 1) && num >= *midIter) 22 | ++midIter; 23 | size++; 24 | } 25 | 26 | // Returns the median of current data stream 27 | double findMedian() 28 | { 29 | if (size & 1) 30 | return *midIter; 31 | else 32 | return (double)(*midIter + *next(midIter)) / 2; 33 | } 34 | }; 35 | 36 | /** 37 | * Your MedianFinder object will be instantiated and called as such: 38 | * MedianFinder* obj = new MedianFinder(); 39 | * obj->addNum(num); 40 | * double param_2 = obj->findMedian(); 41 | */ -------------------------------------------------------------------------------- /2021/day1/best-time-to-buy-and-sell-stock/BuySellStock.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author: Araika Singh 3 | * @Date: 2021-03-19T20:58:27+05:30 4 | * @Email: roseymods@gmail.com 5 | * @Last modified by: NonZeroExitCode 6 | * @Last modified time: 2021-03-20T01:27:49+05:30 7 | * @Link to question: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 8 | */ 9 | 10 | class BuySellStock{ 11 | 12 | public int maxProfit(int[] prices) { 13 | // Keeping the pointer of minimum cost at 0th index of prices array 14 | // and for the time being the maximum profit is zero 15 | int minCost = prices[0], maxProfit = 0; 16 | 17 | // Traversing through each element in prices array 18 | for(int i = 1; i < prices.length; i++){ 19 | 20 | // if minCost is more than present price then update minCost to prices[i] 21 | minCost = Math.min(minCost, prices[i]); 22 | 23 | // If difference between the present prices and the minimum minCost 24 | // is more than previous maxProfit then update it 25 | maxProfit = Math.max(maxProfit, prices[i]-minCost); 26 | } 27 | 28 | // Answer returned here 29 | return maxProfit; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /2021/Day18/Convert Sorted Array to Binary Search Tree/Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | TreeNode *sortedArrayToBST(vector &num) 16 | { 17 | if (num.size() == 0) 18 | return NULL; 19 | if (num.size() == 1) 20 | { 21 | return new TreeNode(num[0]); 22 | } 23 | 24 | int middle = num.size() / 2; 25 | TreeNode *root = new TreeNode(num[middle]); 26 | 27 | vector leftInts(num.begin(), num.begin() + middle); 28 | vector rightInts(num.begin() + middle + 1, num.end()); 29 | 30 | root->left = sortedArrayToBST(leftInts); 31 | root->right = sortedArrayToBST(rightInts); 32 | 33 | return root; 34 | } 35 | }; -------------------------------------------------------------------------------- /2021/Day13/Merge Two Sorted Lists/Merge Two Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 15 | { 16 | if (!l1) 17 | return l2; 18 | if (!l2) 19 | return l1; 20 | ListNode *temp = new ListNode(0); 21 | ListNode *newh = temp; 22 | while (l1 && l2) 23 | { 24 | if (l1->val <= l2->val) 25 | { 26 | temp->next = l1; 27 | l1 = l1->next; 28 | } 29 | else 30 | { 31 | temp->next = l2; 32 | l2 = l2->next; 33 | } 34 | temp = temp->next; 35 | } 36 | if (l1) 37 | temp->next = l1; 38 | if (l2) 39 | temp->next = l2; 40 | 41 | return newh->next; 42 | } 43 | }; -------------------------------------------------------------------------------- /2021/Day21/Merge k Sorted Lists/Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def mergeKLists(self, lists): 8 | if not lists: 9 | return None 10 | if len(lists) == 1: 11 | return lists[0] 12 | mid = len(lists) // 2 13 | l, r = self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:]) 14 | return self.merge(l, r) 15 | 16 | def merge(self, l, r): 17 | dummy = p = ListNode() 18 | while l and r: 19 | if l.val < r.val: 20 | p.next = l 21 | l = l.next 22 | else: 23 | p.next = r 24 | r = r.next 25 | p = p.next 26 | p.next = l or r 27 | return dummy.next 28 | 29 | def merge1(self, l, r): 30 | if not l or not r: 31 | return l or r 32 | if l.val < r.val: 33 | l.next = self.merge(l.next, r) 34 | return l 35 | r.next = self.merge(l, r.next) 36 | return r 37 | -------------------------------------------------------------------------------- /2021/Day17/Serialize and Deserialize Binary Tree/Serialize and Deserialize Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Codec: 9 | 10 | def serialize(self, root): 11 | def doit(node): 12 | if node: 13 | vals.append(str(node.val)) 14 | doit(node.left) 15 | doit(node.right) 16 | else: 17 | vals.append('#') 18 | vals = [] 19 | doit(root) 20 | return ' '.join(vals) 21 | 22 | def deserialize(self, data): 23 | def doit(): 24 | val = next(vals) 25 | if val == '#': 26 | return None 27 | node = TreeNode(int(val)) 28 | node.left = doit() 29 | node.right = doit() 30 | return node 31 | vals = iter(data.split()) 32 | return doit() 33 | 34 | 35 | # Your Codec object will be instantiated and called as such: 36 | # ser = Codec() 37 | # deser = Codec() 38 | # ans = deser.deserialize(ser.serialize(root)) 39 | -------------------------------------------------------------------------------- /2021/Day3/Max Subarray/Max_subaaray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | 8 | # Track a running sum of consecutive numbers and the global max sum. 9 | running_sum = nums[0] 10 | max_sum = running_sum 11 | 12 | for num in nums[1:]: 13 | 14 | # As long as the running sum is positive, adding it to the next 15 | # number will continue to grow the sum. Once the running sum 16 | # becomes negative, adding it to the next number will only 17 | # shrink that number, so we reset the running sum to the next 18 | # number. 19 | 20 | # The following line could've been rewritten more intuitively as: 21 | # if running_sum >= 0: 22 | # running_sum += num 23 | 24 | # elif running_sum < 0: 25 | # running_sum = num 26 | 27 | running_sum = max(running_sum + num, num) 28 | 29 | # Update max_sum if current_sum > max_sum. 30 | max_sum = max(max_sum, running_sum) 31 | 32 | return max_sum 33 | -------------------------------------------------------------------------------- /2021/Day4/Insert Intervals/insert_intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution//By CyFun 2 | { 3 | public: 4 | vector> insert(vector> &v1, vector &v2) 5 | { 6 | if (!v1.size()) 7 | { 8 | v1.push_back(v2); 9 | return v1; 10 | } 11 | v1.push_back(v2); 12 | sort(v1.begin(), v1.end()); 13 | stack> s; 14 | s.push({v1[0][0], v1[0][1]}); 15 | for (int i = 1; i < v1.size(); i++) 16 | { 17 | int a = s.top().second; 18 | int b = v1[i][0]; 19 | if (a >= b && a <= v1[i][1]) 20 | { 21 | s.top().second = v1[i][1]; 22 | } 23 | else if (a < b) 24 | { 25 | s.push({v1[i][0], v1[i][1]}); 26 | } 27 | } 28 | vector> v; 29 | while (s.size() > 0) 30 | { 31 | vector v3; 32 | v3.push_back(s.top().first); 33 | v3.push_back(s.top().second); 34 | v.push_back(v3); 35 | s.pop(); 36 | } 37 | reverse(v.begin(), v.end()); 38 | return v; 39 | } 40 | }; -------------------------------------------------------------------------------- /2021/Day22/Is Graph Bipartite/Is Graph Bipartite.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isBipartite(vector> &graph) 5 | { 6 | int n = graph.size(); 7 | vector colors(n, 0); 8 | queue q; 9 | 10 | for (int i = 0; i < n; i++) 11 | { 12 | if (colors[i]) 13 | continue; 14 | 15 | colors[i] = 1; 16 | q.push(i); 17 | 18 | while (!q.empty()) 19 | { 20 | int temp = q.front(); 21 | 22 | for (auto neighbor : graph[temp]) 23 | { 24 | 25 | // Color neighbor with opposite color 26 | if (!colors[neighbor]) 27 | { 28 | colors[neighbor] = -colors[temp]; 29 | q.push(neighbor); 30 | } 31 | 32 | // If the neighbor has the same color - can't bipartite. 33 | else if (colors[neighbor] == colors[temp]) 34 | return false; 35 | } 36 | q.pop(); 37 | } 38 | } 39 | return true; 40 | } 41 | }; -------------------------------------------------------------------------------- /2021/Day14/Reorder List/Reorder List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | void reorderList(ListNode *head) 15 | { 16 | if (!head) 17 | return; 18 | ListNode *slow = head, *fast = head; 19 | while (fast->next && fast->next->next) 20 | { 21 | slow = slow->next; 22 | fast = fast->next->next; 23 | } 24 | 25 | ListNode *prev = NULL, *cur = slow->next, *save; 26 | while (cur) 27 | { 28 | save = cur->next; 29 | cur->next = prev; 30 | prev = cur; 31 | cur = save; 32 | } 33 | 34 | slow->next = NULL; 35 | 36 | ListNode *head2 = prev; 37 | while (head2) 38 | { 39 | save = head->next; 40 | head->next = head2; 41 | head = head2; 42 | head2 = save; 43 | } 44 | } 45 | }; -------------------------------------------------------------------------------- /2020/graphs/kruskal.py: -------------------------------------------------------------------------------- 1 | #union find 2 | 3 | # edges = [[1,2,4], [2,3,5], [3,4,6],[4,2,8] ] 4 | 5 | 6 | nodes = 4 7 | 8 | size = [1]*len(nodes) 9 | link = [] 10 | for i in range(len(nodes)): 11 | link.append(i) 12 | # 0 1 2 3 4 5 6 13 | link = [0, 0, 0, 0, 3, 5, 6] 14 | size = [5, 1, 1, 2, 1, 1, 1] 15 | 16 | 17 | def find(i): 18 | if i == link[i]: 19 | return i 20 | return find(link[i]) 21 | 22 | def merge(i,j): # 2, 3 23 | i = find(i) # 0 24 | j = find(j) # 3 25 | x = size[i] # 3 26 | y = size[j] # 2 27 | 28 | if x aa may become consecutive duplicate characters so move i back to 1 previous char index but since for loop ++i increments by 1 lets decrement by -2 here 17 | // if i is 0 we can't go less than -1.. if we set to -1 then outer for loop resets back to 0 which will be the last character to compare with next character 18 | i = (i) ? i - 2 : i - 1; 19 | } 20 | } 21 | return S; 22 | } -------------------------------------------------------------------------------- /2021/Day18/Delete Node in a BST/Delete Node in a BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | TreeNode *deleteNode(TreeNode *root, int key) 16 | { 17 | if (!root) 18 | return nullptr; 19 | if (root->val == key) 20 | { 21 | if (!root->right) 22 | { 23 | TreeNode *left = root->left; 24 | delete root; 25 | return left; 26 | } 27 | else 28 | { 29 | TreeNode *right = root->right; 30 | while (right->left) 31 | right = right->left; 32 | swap(root->val, right->val); 33 | } 34 | } 35 | root->left = deleteNode(root->left, key); 36 | root->right = deleteNode(root->right, key); 37 | return root; 38 | } 39 | }; -------------------------------------------------------------------------------- /2021/Day3/Product of array except self/Product_of_array_except.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | result = [0]*len(nums) 4 | 5 | prod = 1 6 | num0 = 0 7 | idx_0 = -1 8 | 9 | for cnt, nm in enumerate(nums): 10 | if(nm is 0): 11 | num0 += 1 12 | idx_0 = cnt 13 | elif(num0 > 1): 14 | break 15 | else: 16 | #Store partial products into result array 17 | result[cnt] = prod 18 | prod *= nm 19 | 20 | if(num0 > 1): 21 | #This allocate a new array instead one might want 22 | #to loop over result instead 23 | return [0]*len(nums) 24 | elif(num0 == 1): 25 | #This allocate a new array to save space one might want 26 | #to loop over result instead 27 | result = [0]*len(nums) 28 | result[idx_0] = prod 29 | else: 30 | prod = 1 31 | #Loop into reverse order and multiply partial product 32 | #by products computed from end 33 | for cnt in range(len(nums)-1, -1, -1): 34 | result[cnt] *= prod 35 | prod *= nums[cnt] 36 | 37 | return result 38 | -------------------------------------------------------------------------------- /2021/Day7/README.md: -------------------------------------------------------------------------------- 1 | # Day 7 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Median Of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) has been explained in his DSA course on arrays in [Day 7 video](https://www.youtube.com/watch?v=9GXT1gc953c). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Median Of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day7/Median%20of%20two%20sorted%20arrays/median_of%20two_sorted%20arrays.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day7/Median%20of%20two%20sorted%20arrays/median_of%20two_sorted%20arrays.py) 10 | 11 | 12 | ## Assignment Questions Editorial 13 | 14 | 1. [Search In Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) 15 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day7/Search%20in%20Rotated%20Sorted%20Array/Search_in_Rotated_Sorted_Array.cpp) 16 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day7/Search%20in%20Rotated%20Sorted%20Array/Search_in_Rotated_Sorted_Array.py) 17 | -------------------------------------------------------------------------------- /2021/Day26/Number of Provinces/Number of Provinces.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findCircleNum(vector> &M) 5 | { 6 | if (M.empty()) 7 | return 0; 8 | int n = M.size(); 9 | 10 | vector leads(n, 0); 11 | for (int i = 0; i < n; i++) 12 | { 13 | leads[i] = i; 14 | } // initialize leads for every kid as themselves 15 | 16 | int groups = n; 17 | for (int i = 0; i < n; i++) 18 | { 19 | for (int j = i + 1; j < n; j++) 20 | { // avoid recalculate M[i][j], M[j][i] 21 | if (M[i][j]) 22 | { 23 | int lead1 = find(i, leads); 24 | int lead2 = find(j, leads); 25 | if (lead1 != lead2) 26 | { // if 2 group belongs 2 different leads, merge 2 group to 1 27 | leads[lead1] = lead2; 28 | groups--; 29 | } 30 | } 31 | } 32 | } 33 | return groups; 34 | } 35 | 36 | private: 37 | int find(int x, vector &parents) 38 | { 39 | return parents[x] == x ? x : find(parents[x], parents); 40 | } 41 | }; -------------------------------------------------------------------------------- /2021/Day25/Number of Islands/Number of Islands.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numIslands(self, grid): 3 | """ 4 | :type grid: List[List[str]] 5 | :rtype: int 6 | """ 7 | if len(grid) == 0: 8 | return 0 9 | row = len(grid) 10 | col = len(grid[0]) 11 | self.count = sum(grid[i][j] == '1' for i in range(row) 12 | for j in range(col)) 13 | parent = [i for i in range(row*col)] 14 | 15 | def find(x): 16 | if parent[x] != x: 17 | return find(parent[x]) 18 | return parent[x] 19 | 20 | def union(x, y): 21 | xroot, yroot = find(x), find(y) 22 | if xroot == yroot: 23 | return 24 | parent[xroot] = yroot 25 | self.count -= 1 26 | 27 | for i in range(row): 28 | for j in range(col): 29 | if grid[i][j] == '0': 30 | continue 31 | index = i*col + j 32 | if j < col-1 and grid[i][j+1] == '1': 33 | union(index, index+1) 34 | if i < row-1 and grid[i+1][j] == '1': 35 | union(index, index+col) 36 | return self.count 37 | -------------------------------------------------------------------------------- /2021/Day25/Accounts Merge/Accounts Merge.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def accountsMerge(self, accounts): 3 | from collections import defaultdict 4 | visited_accounts = [False] * len(accounts) 5 | emails_accounts_map = defaultdict(list) 6 | res = [] 7 | # Build up the graph. 8 | for i, account in enumerate(accounts): 9 | for j in range(1, len(account)): 10 | email = account[j] 11 | emails_accounts_map[email].append(i) 12 | # DFS code for traversing accounts. 13 | 14 | def dfs(i, emails): 15 | if visited_accounts[i]: 16 | return 17 | visited_accounts[i] = True 18 | for j in range(1, len(accounts[i])): 19 | email = accounts[i][j] 20 | emails.add(email) 21 | for neighbor in emails_accounts_map[email]: 22 | dfs(neighbor, emails) 23 | # Perform DFS for accounts and add to results. 24 | for i, account in enumerate(accounts): 25 | if visited_accounts[i]: 26 | continue 27 | name, emails = account[0], set() 28 | dfs(i, emails) 29 | res.append([name] + sorted(emails)) 30 | return res 31 | -------------------------------------------------------------------------------- /2021/Day12/Integer to English Words/Integer to English Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string hundredStr(int num) 5 | { 6 | vector arr1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 7 | "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; 8 | vector arr2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; 9 | string ret; 10 | ret = num % 100 < 20 ? arr1[num % 100] : arr2[(num % 100) / 10] + (num % 10 ? " " + arr1[num % 10] : ""); 11 | if (num > 99) 12 | ret = arr1[num / 100] + " Hundred" + (num % 100 ? " " + ret : ""); 13 | return ret; 14 | } 15 | string numberToWords(int num) 16 | { 17 | string ret; 18 | vector strarr = {"Thousand", "Million", "Billion"}; 19 | ret = hundredStr(num % 1000); 20 | for (int i = 0; i < 3; i++) 21 | { 22 | num /= 1000; 23 | ret = num % 1000 ? hundredStr(num % 1000) + " " + strarr[i] + " " + ret : ret; 24 | } 25 | while (ret.back() == ' ') 26 | ret.pop_back(); 27 | return ret.empty() ? "Zero" : ret; 28 | } 29 | }; -------------------------------------------------------------------------------- /2021/Day16/Minimum Depth of Binary Tree/Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | int minDepth(TreeNode *root) 16 | { 17 | if (root == NULL) 18 | return 0; 19 | queue Q; 20 | Q.push(root); 21 | int i = 0; 22 | while (!Q.empty()) 23 | { 24 | i++; 25 | int k = Q.size(); 26 | for (int j = 0; j < k; j++) 27 | { 28 | TreeNode *rt = Q.front(); 29 | if (rt->left) 30 | Q.push(rt->left); 31 | if (rt->right) 32 | Q.push(rt->right); 33 | Q.pop(); 34 | if (rt->left == NULL && rt->right == NULL) 35 | return i; 36 | } 37 | } 38 | return -1; //For the compiler thing. The code never runs here. 39 | } 40 | }; -------------------------------------------------------------------------------- /2021/Day17/Binary Tree Level Order Traversal/Binary Tree Level Order Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | #generate queue and append root to queue 8 | #while there are nodes in the queue, 9 | #iterate through the number of nodes in the queue 10 | #(this is the number of nodes in the next level) 11 | #pop queue(0), add queue(0).val to current ans list and append queue(0)'s children to queue 12 | #append ans to final_list and reset ans = [] 13 | class Solution: 14 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 15 | if root is None: 16 | return root 17 | queue = [] 18 | return_list = [] 19 | queue.append(root) 20 | while len(queue) > 0: 21 | ans = [] 22 | l = len(queue) 23 | for l in range(l): 24 | node = queue.pop(0) 25 | ans.append(node.val) 26 | if node.left != None: 27 | queue.append(node.left) 28 | if node.right != None: 29 | queue.append(node.right) 30 | return_list.append(ans) 31 | return return_list 32 | -------------------------------------------------------------------------------- /2021/Day3/3sum/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution //By CyFun 2 | { 3 | public: 4 | vector> threeSum(vector &nums) 5 | { 6 | int n = nums.size(); 7 | vector> ans; 8 | sort(nums.begin(), nums.end()); 9 | if (n < 3) 10 | return {}; 11 | 12 | for (int i = 0; i < n - 2; i++) 13 | { 14 | 15 | if (i == 0 || nums[i] != nums[i - 1]) 16 | { 17 | int j = i + 1, k = n - 1; 18 | while (j < k) 19 | { 20 | int sum = nums[i] + nums[j] + nums[k]; 21 | if (sum == 0) 22 | { 23 | ans.push_back({nums[i], nums[j], nums[k]}); 24 | while (j < k && nums[j] == nums[j + 1]) 25 | j++; 26 | while (j < k && nums[k] == nums[k - 1]) 27 | k--; 28 | j++; 29 | k--; 30 | } 31 | else if (sum > 0) 32 | { 33 | k--; 34 | } 35 | else 36 | j++; 37 | } 38 | } 39 | } 40 | return ans; 41 | } 42 | }; -------------------------------------------------------------------------------- /2021/Day23/Path With Minimum Effort/Path With Minimum Effort.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minimumEffortPath(vector> &heights) 5 | { 6 | int m = heights.size(), n = heights[0].size(); 7 | int dirs[5] = {-1, 0, 1, 0, -1}; 8 | 9 | std::vector> efforts(m, vector(n, INT_MAX)); 10 | priority_queue, vector>, greater>> pq; 11 | 12 | pq.emplace(0, 0); // First item is effort, second is row * 100 + col 13 | while (!pq.empty()) 14 | { 15 | int effort = pq.top().first; 16 | int x = pq.top().second / 100, y = pq.top().second % 100; 17 | pq.pop(); 18 | 19 | if (x == m - 1 && y == n - 1) 20 | return effort; 21 | if (effort >= efforts[x][y]) 22 | continue; 23 | efforts[x][y] = effort; 24 | 25 | for (int i = 0; i < 4; i++) 26 | { 27 | int nx = x + dirs[i], ny = y + dirs[i + 1]; 28 | if (nx < 0 || nx >= m || ny < 0 || ny >= n) 29 | continue; 30 | int n_effort = max(effort, abs(heights[x][y] - heights[nx][ny])); 31 | pq.emplace(n_effort, nx * 100 + ny); 32 | } 33 | } 34 | return -1; 35 | } 36 | }; -------------------------------------------------------------------------------- /2021/Day17/Construct Binary Tree from Preorder and Inorder Traversal/Construct Binary Tree from Preorder and Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | TreeNode *buildTree(vector &preorder, vector &inorder) 16 | { 17 | int rootIdx = 0; 18 | return build(preorder, inorder, rootIdx, 0, inorder.size() - 1); 19 | } 20 | 21 | TreeNode *build(vector &preorder, vector &inorder, int &rootIdx, int left, int right) 22 | { 23 | if (left > right) 24 | return NULL; 25 | int pivot = left; // find the root from inorder 26 | while (inorder[pivot] != preorder[rootIdx]) 27 | pivot++; 28 | 29 | rootIdx++; 30 | TreeNode *newNode = new TreeNode(inorder[pivot]); 31 | newNode->left = build(preorder, inorder, rootIdx, left, pivot - 1); 32 | newNode->right = build(preorder, inorder, rootIdx, pivot + 1, right); 33 | return newNode; 34 | } 35 | }; -------------------------------------------------------------------------------- /2021/Day25/Number of Islands/Number of Islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numIslands(vector> &grid) 5 | { 6 | int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0, offsets[] = {0, 1, 0, -1, 0}; 7 | for (int i = 0; i < m; i++) 8 | { 9 | for (int j = 0; j < n; j++) 10 | { 11 | if (grid[i][j] == '1') 12 | { 13 | islands++; 14 | grid[i][j] = '0'; 15 | queue> todo; 16 | todo.push({i, j}); 17 | while (!todo.empty()) 18 | { 19 | pair p = todo.front(); 20 | todo.pop(); 21 | for (int k = 0; k < 4; k++) 22 | { 23 | int r = p.first + offsets[k], c = p.second + offsets[k + 1]; 24 | if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') 25 | { 26 | grid[r][c] = '0'; 27 | todo.push({r, c}); 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | return islands; 35 | } 36 | }; -------------------------------------------------------------------------------- /2021/Day21/Merge k Sorted Lists/Merge k Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | ListNode *mergeKLists(vector &lists) 15 | { 16 | if (lists.empty()) 17 | { 18 | return nullptr; 19 | } 20 | while (lists.size() > 1) 21 | { 22 | lists.push_back(mergeTwoLists(lists[0], lists[1])); 23 | lists.erase(lists.begin()); 24 | lists.erase(lists.begin()); 25 | } 26 | return lists.front(); 27 | } 28 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 29 | { 30 | if (l1 == nullptr) 31 | { 32 | return l2; 33 | } 34 | if (l2 == nullptr) 35 | { 36 | return l1; 37 | } 38 | if (l1->val <= l2->val) 39 | { 40 | l1->next = mergeTwoLists(l1->next, l2); 41 | return l1; 42 | } 43 | else 44 | { 45 | l2->next = mergeTwoLists(l1, l2->next); 46 | return l2; 47 | } 48 | } 49 | }; -------------------------------------------------------------------------------- /2021/Day9/README.md: -------------------------------------------------------------------------------- 1 | # Day 9 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Valid Anagram](https://leetcode.com/problems/valid-anagram/) and [Valid Palindrome-2](https://leetcode.com/problems/valid-palindrome-ii/) has been explained in his DSA course on arrays in [Day 9 video](https://www.youtube.com/watch?v=GNSJ_nPRqWY). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Valid Anagram](https://leetcode.com/problems/valid-anagram/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day9/Valid%20Anagram/valid_anagram.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day9/Valid%20Anagram/valid_anagram.py) 10 | 2. [Valid Palindrome-2](https://leetcode.com/problems/valid-palindrome-ii/) 11 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day9/Valid%20palindrome%202/valid_palindrome_2.cpp) 12 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day9/Valid%20palindrome%202/valid_palindrome_2.py) 13 | 14 | ## Assignment Questions Editorial 15 | 16 | 1. [Group Anagrams](https://leetcode.com/problems/group-anagrams/) 17 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day9/Group%20Anagrams/Group_anagrams.cpp) 18 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day9/Group%20Anagrams/Group_anagrams.py) 19 | -------------------------------------------------------------------------------- /2021/Day5/Spiral Matrix/spiral_matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution //CyFun 2 | { 3 | public: 4 | vector spiralOrder(vector> &v) 5 | { 6 | int n = v.size(); 7 | int m = v[0].size(); 8 | vector a; 9 | int minr = 0; 10 | int minc = 0; 11 | int maxr = n - 1; 12 | int maxc = m - 1; 13 | int c = 0; 14 | int tne = n * m; 15 | while (c < tne) 16 | { 17 | //up left 18 | for (int i = minr, j = minc; j <= maxc && c < tne; j++) 19 | { 20 | a.push_back(v[i][j]); 21 | c++; 22 | } 23 | minr++; 24 | 25 | //rightB 26 | for (int i = minr, j = maxc; i <= maxr && c < tne; i++) 27 | { 28 | a.push_back(v[i][j]); 29 | c++; 30 | } 31 | maxc--; 32 | //downleft 33 | for (int i = maxr, j = maxc; j >= minc && c < tne; j--) 34 | { 35 | a.push_back(v[i][j]); 36 | c++; 37 | } 38 | maxr--; 39 | //leftUp 40 | 41 | for (int i = maxr, j = minc; i >= minr && c < tne; i--) 42 | { 43 | a.push_back(v[i][j]); 44 | c++; 45 | } 46 | minc++; 47 | } 48 | return a; 49 | } 50 | }; -------------------------------------------------------------------------------- /2021/Day22/Redundant Connection/Redundant Connection.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: 3 | 4 | parent = {v: -1 for v in range(1, len(edges)+1)} 5 | 6 | # --------------------------------- 7 | 8 | def find(u): 9 | 10 | if parent[u] != -1: 11 | # find root with path compression 12 | parent[u] = find(parent[u]) 13 | return parent[u] 14 | 15 | else: 16 | # root node must be with -1 17 | return u 18 | 19 | # --------------------------------- 20 | 21 | def union(u, v): 22 | 23 | parent_of_u = find(u) 24 | parent_of_v = find(v) 25 | 26 | if parent_of_u == parent_of_v: 27 | 28 | # u and v has the same parent node 29 | # this edges froms a cycle in graph 30 | return True 31 | 32 | else: 33 | 34 | # after adding edge(u, v) 35 | # graph is still a tree without cycle 36 | parent[parent_of_u] = parent_of_v 37 | return False 38 | 39 | # --------------------------------- 40 | 41 | redundant = None 42 | for u, v in edges: 43 | 44 | if union(u, v): 45 | # check if edge (u, v) forms a cycle 46 | redundant = [u, v] 47 | return redundant 48 | -------------------------------------------------------------------------------- /2021/Day23/Path With Minimum Effort/Path With Minimum Effort.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumEffortPath(self, heights: List[List[int]]) -> int: 3 | m, n = len(heights), len(heights[0]) 4 | 5 | s = (0, 0) 6 | d = {} 7 | d[s] = 0 8 | h = [] 9 | heapq.heappush(h, [d[s], s]) 10 | for i in range(len(heights)): 11 | for j in range(len(heights[i])): 12 | if i == 0 and j == 0: 13 | continue 14 | u = (i, j) 15 | d[u] = float('inf') 16 | heapq.heappush(h, [d[u], s]) 17 | 18 | while len(h) > 0: 19 | # route_effort is the maximum abs difference in heights between some pair of 20 | # directly-connected nodes along the path/route s -> ..-> ... -> u 21 | route_effort, u = heapq.heappop(h) 22 | if u == (m - 1, n - 1): 23 | return route_effort 24 | 25 | for delta in [(0, 1), (0, -1), (1, 0), (-1, 0)]: 26 | v = (u[0] + delta[0], u[1] + delta[1]) 27 | if v[0] < 0 or v[0] == m or v[1] < 0 or v[1] == n: 28 | continue 29 | new_route_effort = max( 30 | d[u], abs(heights[u[0]][u[1]] - heights[v[0]][v[1]])) 31 | if d[v] > new_route_effort: 32 | d[v] = new_route_effort 33 | heapq.heappush(h, [d[v], v]) 34 | 35 | return 0 36 | -------------------------------------------------------------------------------- /2021/Day26/Redundant Connection/Redundant Connection.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: 3 | 4 | parent = {v: -1 for v in range(1, len(edges)+1)} 5 | 6 | # --------------------------------- 7 | 8 | def find(u): 9 | 10 | if parent[u] != -1: 11 | # find root with path compression 12 | parent[u] = find(parent[u]) 13 | return parent[u] 14 | 15 | else: 16 | # root node must be with -1 17 | return u 18 | 19 | # --------------------------------- 20 | 21 | def union(u, v): 22 | 23 | parent_of_u = find(u) 24 | parent_of_v = find(v) 25 | 26 | if parent_of_u == parent_of_v: 27 | 28 | # u and v has the same parent node 29 | # this edges froms a cycle in graph 30 | return True 31 | 32 | else: 33 | 34 | # after adding edge(u, v) 35 | # graph is still a tree without cycle 36 | parent[parent_of_u] = parent_of_v 37 | return False 38 | 39 | # --------------------------------- 40 | 41 | redundant = None 42 | for u, v in edges: 43 | 44 | if union(u, v): 45 | # check if edge (u, v) forms a cycle 46 | redundant = [u, v] 47 | return redundant 48 | -------------------------------------------------------------------------------- /2020/graphs/mst.py: -------------------------------------------------------------------------------- 1 | 1. Minimum Spanning Tree. 2 | 2. DSU 3 | 3. How to construct a MST using Kruskal Algorithm 4 | 5 | 6 | 1. MST 7 | 8 | graph -> G 9 | MST OF g WILL BE the tree[ aka a graph without cycle] whose sum of weight of edge is minimum. 10 | DSU-> 11 | Graph G -> there will be certain vertices which will be completly connected to each other and there will be certain 12 | vertices A and B which are not connected, in this scenario we end up with two connected sets in which intersection 13 | of set A and set B is Null 14 | 15 | These sets are disjoint sets! 16 | 17 | Kruskal Algorithm 18 | Agenda: Kruskal Algorithm is used to construct and MST greedily. 19 | 1. Sort all edges in increasing order ( or non -decreasing order). 20 | 2. Pick edges, and see if we can connected the edge without reaching a cycle. 21 | 3. We connect it if we are not reaching a cycle and that's it. 22 | 23 | When we stop? When connected edges are V-1, where V is the total number of vertices. 24 | 25 | 1. Sorting 26 | 2. Where we need to figure out if there is a cycle or not ? 27 | this leads to another problem where we need to find if there exists a cycle or not in a graph? 28 | 29 | 1. How we detect a cycle? 30 | - we do a traversal, and we see if we are encountering any previously visited edge or not? 31 | 32 | T, C -> O(N log M) + N*M 33 | How to figure out how many disjoint sets exists in a graph? 34 | a <-> b <-> c <-> d <-> e f<->g 35 | if root is c: 36 | 37 | - while all nodes are not visited: 38 | dfs() 39 | count++ -------------------------------------------------------------------------------- /2020/greedy/mergingIntervals.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Merging intervals 4 | # 5 | # 6 | # #Given a list of intervals [x,y] remove all the intervals [a,b] for which there exists an interval 7 | # #[c,d] where c<=a,b<=d == 8 | # 9 | # 10 | # 6 11 | # 12 | # 1 2 13 | # 3 6 14 | # 4 5 15 | # 7 10 16 | # 8 9 17 | # 8 10 18 | # 19 | # 1<=N<10^5 20 | # 21 | # n square will not work 22 | # n logN OR N 23 | # 24 | # # # # # # # # # # # 25 | # 1 2 3 4 5 6 7 8 9 10 26 | # 27 | # 28 | # 1 2 29 | # 3 6 30 | # 7 10 31 | # 32 | # O(N*N) 33 | # for set in allSets: N 34 | # for superSet in allSet: N-1 35 | # if set lies in superSet: 36 | # remove it 37 | # 38 | # 39 | # let's sort the array of intervals first in increasing order of second element and then sort it 40 | # on the basis of first 41 | # 42 | # O(NlogN) 43 | # 1 2 44 | # 3 6 45 | # 4 5 46 | # 7 10 47 | # 8 9 48 | # 8 10 49 | # 50 | # Sort it, 51 | # 1. on the basis of second element, 52 | # 1 2 53 | # 4 5 54 | # 3 6 55 | # 8 9 56 | # 7 10 57 | # 8 10, 58 | # 59 | # 2. On the basis of first element 60 | # 1 2 , i = 0 61 | # 3 6 j=1 62 | # 4 5 63 | # 7 10 j =2 64 | # 8 9 65 | # 8 10 66 | # 67 | # j = 1 68 | # 69 | # for set in allSets: 70 | # j++ 71 | # while j < n && set[j] lies in set[i]: 72 | # delete set[j] 73 | # j++ 74 | # 75 | # 76 | # 1,2 77 | # -> 78 | # [3,6] 79 | # -> 80 | # [4,5] 81 | # [7,10] 82 | # -> 83 | # [8,9] , [8,10] 84 | # 85 | # 86 | # 87 | # 88 | -------------------------------------------------------------------------------- /2021/Day15/Lowest Common Ancestor of a Binary Tree/Lowest Common Ancestor of a Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def lowestCommonAncestor(self, root, p, q): 10 | """ 11 | :type root: TreeNode 12 | :type p: TreeNode 13 | :type q: TreeNode 14 | :rtype: TreeNode 15 | """ 16 | # If looking for me, return myself 17 | if root == p or root == q: 18 | return root 19 | 20 | left = right = None 21 | # else look in left and right child 22 | if root.left: 23 | left = self.lowestCommonAncestor(root.left, p, q) 24 | if root.right: 25 | right = self.lowestCommonAncestor(root.right, p, q) 26 | 27 | # if both children returned a node, means 28 | # both p and q found so parent is LCA 29 | if left and right: 30 | return root 31 | else: 32 | # either one of the chidren returned a node, meaning either p or q found on left or right branch. 33 | # Example: assuming 'p' found in left child, right child returned 'None'. This means 'q' is 34 | # somewhere below node where 'p' was found we dont need to search all the way, 35 | # because in such scenarios, node where 'p' found is LCA 36 | return left or right 37 | -------------------------------------------------------------------------------- /2021/Day14/Reorder List/Reorder List.py: -------------------------------------------------------------------------------- 1 | # Splits in place a list in two halves, the first half is >= in size than the second. 2 | # @return A tuple containing the heads of the two halves 3 | def _splitList(head): 4 | fast = head 5 | slow = head 6 | while fast and fast.next: 7 | slow = slow.next 8 | fast = fast.next 9 | fast = fast.next 10 | 11 | middle = slow.next 12 | slow.next = None 13 | 14 | return head, middle 15 | 16 | # Reverses in place a list. 17 | # @return Returns the head of the new reversed list 18 | 19 | 20 | def _reverseList(head): 21 | 22 | last = None 23 | currentNode = head 24 | 25 | while currentNode: 26 | nextNode = currentNode.next 27 | currentNode.next = last 28 | last = currentNode 29 | currentNode = nextNode 30 | 31 | return last 32 | 33 | # Merges in place two lists 34 | # @return The newly merged list. 35 | 36 | 37 | def _mergeLists(a, b): 38 | 39 | tail = a 40 | head = a 41 | 42 | a = a.next 43 | while b: 44 | tail.next = b 45 | tail = tail.next 46 | b = b.next 47 | if a: 48 | a, b = b, a 49 | 50 | return head 51 | 52 | 53 | class Solution: 54 | 55 | # @param head, a ListNode 56 | # @return nothing 57 | def reorderList(self, head): 58 | 59 | if not head or not head.next: 60 | return 61 | 62 | a, b = _splitList(head) 63 | b = _reverseList(b) 64 | head = _mergeLists(a, b) 65 | -------------------------------------------------------------------------------- /2021/Day23/Network Delay Time/Network Delay Time.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | // Using Priority queue (Min-heap) 5 | int networkDelayTime(vector> ×, int N, int K) 6 | { 7 | vector> g[N + 1]; 8 | for (int i = 0; i < times.size(); i++) 9 | g[times[i][0]].push_back(make_pair(times[i][1], times[i][2])); 10 | vector dist(N + 1, 1e9); 11 | dist[K] = 0; 12 | priority_queue, vector>, greater>> q; 13 | q.push(make_pair(0, K)); 14 | pair temp; 15 | bool visit[N + 1]; 16 | memset(visit, false, sizeof(visit)); 17 | while (!q.empty()) 18 | { 19 | temp = q.top(); 20 | q.pop(); 21 | int u = temp.second; 22 | visit[u] = true; 23 | for (int i = 0; i < g[u].size(); i++) 24 | { 25 | int v = g[u][i].first; 26 | int weight = g[u][i].second; 27 | if (visit[v] == false && dist[v] > dist[u] + weight) 28 | { 29 | dist[v] = dist[u] + weight; 30 | q.push(make_pair(dist[v], v)); 31 | } 32 | } 33 | } 34 | int ans = 0; 35 | for (int i = 1; i < dist.size(); i++) 36 | { 37 | ans = max(ans, dist[i]); 38 | } 39 | if (ans == 1e9) 40 | return -1; 41 | return ans; 42 | } 43 | }; -------------------------------------------------------------------------------- /2021/Day17/Serialize and Deserialize Binary Tree/Serialize and Deserialize Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Codec 11 | { 12 | public: 13 | string serialize(TreeNode *root) 14 | { 15 | ostringstream out; 16 | serialize(root, out); 17 | return out.str(); 18 | } 19 | 20 | TreeNode *deserialize(string data) 21 | { 22 | istringstream in(data); 23 | return deserialize(in); 24 | } 25 | 26 | private: 27 | void serialize(TreeNode *root, ostringstream &out) 28 | { 29 | if (root) 30 | { 31 | out << root->val << ' '; 32 | serialize(root->left, out); 33 | serialize(root->right, out); 34 | } 35 | else 36 | { 37 | out << "# "; 38 | } 39 | } 40 | 41 | TreeNode *deserialize(istringstream &in) 42 | { 43 | string val; 44 | in >> val; 45 | if (val == "#") 46 | return nullptr; 47 | TreeNode *root = new TreeNode(stoi(val)); 48 | root->left = deserialize(in); 49 | root->right = deserialize(in); 50 | return root; 51 | } 52 | }; 53 | 54 | // Your Codec object will be instantiated and called as such: 55 | // Codec ser, deser; 56 | // TreeNode* ans = deser.deserialize(ser.serialize(root)); -------------------------------------------------------------------------------- /2021/Day12/Minimum Window Substring/Minimum Window Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string minWindow(string S, string T) 5 | { 6 | if (S.empty() || T.empty()) 7 | { 8 | return ""; 9 | } 10 | int count = T.size(); 11 | int require[128] = {0}; 12 | bool chSet[128] = {false}; 13 | for (int i = 0; i < count; ++i) 14 | { 15 | require[T[i]]++; 16 | chSet[T[i]] = true; 17 | } 18 | int i = -1; 19 | int j = 0; 20 | int minLen = INT_MAX; 21 | int minIdx = 0; 22 | while (i < (int)S.size() && j < (int)S.size()) 23 | { 24 | if (count) 25 | { 26 | i++; 27 | require[S[i]]--; 28 | if (chSet[S[i]] && require[S[i]] >= 0) 29 | { 30 | count--; 31 | } 32 | } 33 | else 34 | { 35 | if (minLen > i - j + 1) 36 | { 37 | minLen = i - j + 1; 38 | minIdx = j; 39 | } 40 | require[S[j]]++; 41 | if (chSet[S[j]] && require[S[j]] > 0) 42 | { 43 | count++; 44 | } 45 | j++; 46 | } 47 | } 48 | if (minLen == INT_MAX) 49 | { 50 | return ""; 51 | } 52 | return S.substr(minIdx, minLen); 53 | } 54 | }; -------------------------------------------------------------------------------- /2021/Day22/cycledetection.txt: -------------------------------------------------------------------------------- 1 | adj = [[0, 1, 0, 0, 0, 1, 0], 2 | [0, 0, 1, 0, 0, 0, 0], 3 | [0, 0, 0, 1, 0, 0, 0], 4 | [0, 0, 0, 0, 0, 1, 0], 5 | [0, 0, 0, 0, 0, 0, 0], 6 | [0, 0, 0, 0, 0, 0, 1], 7 | [0, 0, 0, 1, 0, 0, 0]] 8 | 9 | 10 | def print_dfs(adj, curr, visited): 11 | if curr in visited: 12 | return 13 | print(curr) 14 | visited.add(curr) 15 | for j in range(len(adj[0])): 16 | if adj[curr][j]==1: 17 | print_dfs(adj, j, visited) 18 | 19 | def print_bfs(adj, curr): 20 | q = [curr] 21 | visited = set([curr]) 22 | while len(q)>0: 23 | c = q.pop(0) 24 | print(c) 25 | for j in range(len(adj[0])): 26 | if adj[c][j] == 1 and j not in visited: 27 | visited.add(j) 28 | q.append(j) 29 | 30 | def detect_cycle_in_undirected_graph(adj): 31 | q = [0] 32 | visited = set([0]) 33 | while len(q) > 0: 34 | c = q.pop(0) 35 | # print(c) 36 | for j in range(len(adj[0])): 37 | if adj[c][j] == 1: 38 | if j not in visited: 39 | print(c,j) 40 | visited.add(j) 41 | q.append(j) 42 | else: 43 | print("found cycle at node ",c, j) 44 | return True 45 | print("no cycle") 46 | return False 47 | 48 | 49 | detect_cycle_in_undirected_graph(adj) 50 | 51 | 52 | 53 | # print_dfs(adj, 0, set()) 54 | # print("----") 55 | # print_bfs(adj, 0) -------------------------------------------------------------------------------- /2021/Day26/Surrounded Regions/Surrounded Regions.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void solve(vector> &board) 5 | { 6 | int i, j; 7 | int row = board.size(); 8 | if (!row) 9 | return; 10 | int col = board[0].size(); 11 | 12 | for (i = 0; i < row; i++) 13 | { 14 | check(board, i, 0, row, col); 15 | if (col > 1) 16 | check(board, i, col - 1, row, col); 17 | } 18 | for (j = 1; j + 1 < col; j++) 19 | { 20 | check(board, 0, j, row, col); 21 | if (row > 1) 22 | check(board, row - 1, j, row, col); 23 | } 24 | for (i = 0; i < row; i++) 25 | for (j = 0; j < col; j++) 26 | if (board[i][j] == 'O') 27 | board[i][j] = 'X'; 28 | for (i = 0; i < row; i++) 29 | for (j = 0; j < col; j++) 30 | if (board[i][j] == '1') 31 | board[i][j] = 'O'; 32 | } 33 | void check(vector> &vec, int i, int j, int row, int col) 34 | { 35 | if (vec[i][j] == 'O') 36 | { 37 | vec[i][j] = '1'; 38 | if (i > 1) 39 | check(vec, i - 1, j, row, col); 40 | if (j > 1) 41 | check(vec, i, j - 1, row, col); 42 | if (i + 1 < row) 43 | check(vec, i + 1, j, row, col); 44 | if (j + 1 < col) 45 | check(vec, i, j + 1, row, col); 46 | } 47 | } 48 | }; -------------------------------------------------------------------------------- /2021/Day15/Maximum Width of Binary Tree/Maximum Width of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | int widthOfBinaryTree(TreeNode *root) 16 | { 17 | if (!root) 18 | return 0; 19 | queue> que; 20 | que.push({root, 0}); 21 | int width = 0; 22 | while (que.size() != 0) 23 | { 24 | unsigned long long int left = que.front().second, right = 0; 25 | int size = que.size(); 26 | while (size-- > 0) 27 | { 28 | pair rNode = que.front(); 29 | que.pop(); 30 | right = rNode.second; 31 | if (rNode.first->left) 32 | { 33 | que.push({rNode.first->left, 2 * rNode.second + 1}); 34 | } 35 | if (rNode.first->right) 36 | { 37 | que.push({rNode.first->right, 2 * rNode.second + 2}); 38 | } 39 | } 40 | width = max(width, int(right - left + 1)); 41 | } 42 | return width; 43 | } 44 | }; -------------------------------------------------------------------------------- /2021/Day25/Accounts Merge/Accounts Merge.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int find(vector &union_find, int ind) 4 | { 5 | while (union_find[ind] != ind) 6 | ind = union_find[ind]; 7 | return ind; 8 | } 9 | 10 | public: 11 | vector> accountsMerge(vector> &accounts) 12 | { 13 | unordered_map m; 14 | vector union_find(accounts.size(), 0); 15 | unordered_map> res_map; 16 | for (int i = 0; i < accounts.size(); i++) 17 | { 18 | union_find[i] = i; 19 | for (int j = 1; j < accounts[i].size(); j++) 20 | { 21 | if (m.find(accounts[i][j]) != m.end()) 22 | { 23 | int root1 = find(union_find, i); 24 | int root2 = find(union_find, m[accounts[i][j]]); 25 | union_find[root1] = root2; 26 | } 27 | else 28 | m[accounts[i][j]] = union_find[i]; 29 | } 30 | } 31 | for (auto it : m) 32 | { 33 | int ind = find(union_find, it.second); 34 | res_map[ind].push_back(it.first); 35 | } 36 | vector> res; 37 | for (auto it : res_map) 38 | { 39 | vector email = it.second; 40 | sort(email.begin(), email.end()); 41 | email.insert(email.begin(), accounts[it.first][0]); 42 | res.push_back(email); 43 | } 44 | return res; 45 | } 46 | }; -------------------------------------------------------------------------------- /2021/Day5/Set Matrix zeroes/set_matrix_zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: #By CyFun 2 | def setZeroes(self, matrix: List[List[int]]) -> None: 3 | n = len(matrix) 4 | m = len(matrix[0]) 5 | clear_row = False 6 | clear_col = False 7 | i = 0 8 | j = 0 9 | while j < m: 10 | if matrix[0][j] == 0: 11 | clear_row = True 12 | break 13 | j += 1 14 | while i < n: 15 | if matrix[i][0] == 0: 16 | clear_col = True 17 | break 18 | i += 1 19 | i = 1 20 | while i < n: 21 | j = 1 22 | while j < m: 23 | if matrix[i][j] == 0: 24 | matrix[i][0] = 0 25 | matrix[0][j] = 0 26 | j += 1 27 | i += 1 28 | i = 1 29 | while i < n: 30 | if matrix[i][0] == 0: 31 | j = 1 32 | while j < m: 33 | matrix[i][j] = 0 34 | j += 1 35 | if clear_col: 36 | matrix[i][0] = 0 37 | i += 1 38 | j = 1 39 | while j < m: 40 | if matrix[0][j] == 0: 41 | i = 1 42 | while i < n: 43 | matrix[i][j] = 0 44 | i += 1 45 | if clear_row: 46 | matrix[0][j] = 0 47 | j += 1 48 | if clear_row: 49 | matrix[0][0] = 0 50 | if clear_col: 51 | matrix[0][0] = 0 52 | -------------------------------------------------------------------------------- /2021/Day6/README.md: -------------------------------------------------------------------------------- 1 | # Day 6 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/) has been explained in his DSA course on arrays in [Day 6 video](https://www.youtube.com/watch?v=_MJSOidSSXU). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day6/Remove%20all%20adjacent%20dupes%20in%20string/Remove%20all%20adjacent%20dupes%20in%20string.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day6/Remove%20all%20adjacent%20dupes%20in%20string/Remove%20all%20adjacent%20dupes%20in%20string.py) 10 | 11 | 12 | ## Assignment Questions Editorial 13 | 14 | 1. [Next Greater Element-1](https://leetcode.com/problems/next-greater-element-i/) 15 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day6/Next%20Greater%20Element%201/Next_greater_element_1.cpp) 16 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day6/Next%20Greater%20Element%201/Next_greater_element_1.py) 17 | -------------------------------------------------------------------------------- /2021/Day5/README.md: -------------------------------------------------------------------------------- 1 | # Day 5 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) and [Rotate Image](https://leetcode.com/problems/rotate-image/) has been explained in his DSA course on arrays in [Day 5 video](https://www.youtube.com/watch?v=7rQQzfavigE). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Set%20Matrix%20zeroes/set_matrix_zeroes.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Set%20Matrix%20zeroes/set_matrix_zeroes.py) 10 | 2. [Rotate Image](https://leetcode.com/problems/rotate-image/) 11 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Rotate%20Image/Rotate_image.cpp) 12 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Rotate%20Image/Rotate_image.py) 13 | 14 | ## Assignment Questions Editorial 15 | 16 | 1. [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) 17 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Spiral%20Matrix/spiral_matrix.cpp) 18 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Spiral%20Matrix/spiral_matrix.py) 19 | 2. [Word Search](https://leetcode.com/problems/word-search/) 20 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Word%20Search/Word_search.cpp) 21 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day5/Word%20Search/Word_search.py) -------------------------------------------------------------------------------- /2021/Day3/README.md: -------------------------------------------------------------------------------- 1 | # Day 3 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Valid Parenthesis](https://leetcode.com/problems/valid-parentheses/) and [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) has been explained in his DSA course on arrays in [Day 3 video](https://www.youtube.com/watch?v=D6tOCMtUGRY). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Valid Parenthesis](https://leetcode.com/problems/valid-parentheses/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/Valid%20parantheses/Valid_parantheses.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/Valid%20parantheses/Valid_parantheses.py) 10 | 2. [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) 11 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/Max%20Subarray/Max_subarray.cpp) 12 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/Max%20Subarray/Max_subarray.py) 13 | 14 | ## Assignment Questions Editorial 15 | 16 | 1. [Product Of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) 17 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/Product%20of%20array%20except%20self/Product_of_array_except.cpp) 18 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/Product%20of%20array%20except%20self/Product_of_array_except.py) 19 | 2. [3 SUM](https://leetcode.com/problems/3sum/) 20 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/3sum/3sum.cpp) 21 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day3/3sum/3sum.py) -------------------------------------------------------------------------------- /2021/Day11/README.md: -------------------------------------------------------------------------------- 1 | # Day 11 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Sum Of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) and [Missing Number](https://leetcode.com/problems/missing-number/) has been explained in his DSA course on arrays in [Day 11 video](https://www.youtube.com/watch?v=Lkv_cqxyjcc). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Sum Of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Sum%20of%20Two%20Integers/Sum%20of%20Two%20Integers.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Sum%20of%20Two%20Integers/Sum%20of%20Two%20Integers.py) 10 | 2. [Missing Number](https://leetcode.com/problems/missing-number/) 11 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Missing%20Number/Missing%20Number.cpp) 12 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Missing%20Number/Missing%20Number.py) 13 | 14 | ## Assignment Questions Editorial 15 | 16 | 1. [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) 17 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Number%20of%201%20Bits/Number%20of%201%20Bits.cpp) 18 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Number%20of%201%20Bits/Number%20of%201%20Bits.py) 19 | 2. [Counting Bits](https://leetcode.com/problems/counting-bits/) 20 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Counting%20Bits/Counting%20Bits.cpp) 21 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day11/Counting%20Bits/Counting%20Bits.py) -------------------------------------------------------------------------------- /2021/day1/README.md: -------------------------------------------------------------------------------- 1 | # Day 1 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Two sum](https://leetcode.com/problems/two-sum/) and [best time to buy and sell a stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) has been explained in his DSA course on arrays in [Day 1 video](https://www.youtube.com/watch?v=OSQk34Rtgx0&t=448s). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. The editorial to two sum in java is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/two-sum/TwoSumJava.java) and to python is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/two-sum/TwoSumPython.py) 8 | 2. The editorial to buy and sell a stock in java is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/best-time-to-buy-and-sell-stock/BuySellStock.java) and python is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/best-time-to-buy-and-sell-stock/BuySellStock.py) 9 | 10 | ## Assignment Questions Editorial 11 | 12 | 1. The editorial to [contains duplicates](https://leetcode.com/problems/contains-duplicate/) in java is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/contains-duplicate/ContainsDuplicate.java) and in python is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/contains-duplicate/ContainsDuplicates.py) 13 | 2. The editorial to [valid anagram](https://leetcode.com/problems/valid-anagram/) in java is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/valid-anagram/ValidAnagram.java) and in python is provided [here](https://github.com/devs-nest/Algo-101/blob/master/2021/day1/valid-anagram/ValidAnagram.py) 14 | -------------------------------------------------------------------------------- /2021/Day8/README.md: -------------------------------------------------------------------------------- 1 | # Day 8 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) has been explained in his DSA course on arrays in [Day 8 video](https://www.youtube.com/watch?v=J2vZe59Wl3M). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day8/Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day8/Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.py) 10 | 11 | 12 | ## Assignment Questions Editorial 13 | 14 | 1. [Longest Repeating Character](https://leetcode.com/problems/longest-repeating-character-replacement/) 15 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day8/Longest%20Repeating%20Character%20Replacement/Longest_Repeating_Character_Replacement_Longest_Repeating_Character_Replacement.cpp) 16 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day8/Longest%20Repeating%20Character%20Replacement/Longest_Repeating_Character_Replacement_Longest_Repeating_Character_Replacement.py) 17 | 2. [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) 18 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day8/Valid_Palindrome/valid_palindrome.cpp) 19 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day8/Valid_Palindrome/valid_palindrome.py) -------------------------------------------------------------------------------- /2021/Day26/Longest Increasing Path in a Matrix/Longest Increasing Path in a Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestIncreasingPath(self, matrix): 3 | # idea, use topological sort, search around to find the # of incoming nodes, start with zero indegree with queue, pop from queue, search around and reduce the indegree by 1; push to queue if indegree is 0. output the steps. Time O(mn) and Space O(mn). 4 | if not matrix: 5 | return 0 6 | m, n = len(matrix), len(matrix[0]) 7 | directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] 8 | hmap = {} 9 | queue = collections.deque() 10 | for i in range(m): 11 | for j in range(n): 12 | cnt = 0 13 | for dx, dy in directions: 14 | x = i + dx 15 | y = j + dy 16 | if 0 <= x <= m-1 and 0 <= y <= n-1 and matrix[x][y] < matrix[i][j]: 17 | cnt += 1 18 | hmap[(i, j)] = cnt # map point to the # of incoming degree 19 | if cnt == 0: 20 | queue.append((i, j)) # append point (i,j) to queue 21 | # bfs with queue, and update the step until queue is empty 22 | step = 0 23 | while queue: 24 | size = len(queue) 25 | for k in range(size): 26 | i, j = queue.popleft() 27 | for dx, dy in directions: 28 | x = i + dx 29 | y = j + dy 30 | if 0 <= x <= m-1 and 0 <= y <= n-1 and matrix[x][y] > matrix[i][j] and (x, y) in hmap: 31 | hmap[(x, y)] -= 1 32 | if hmap[(x, y)] == 0: 33 | queue.append((x, y)) 34 | step += 1 35 | return step 36 | -------------------------------------------------------------------------------- /2021/Day11/Bits.txt: -------------------------------------------------------------------------------- 1 | 2 00000010 2 | 3 00000011 3 | -------------- 4 | 5 00000101 5 | 6 | 1 + 1 = 10 7 | 1+0 = 0+1 = 1 8 | 0+0 = 0 9 | 10 | sum = a^b 11 | carry = (a&b)<<1 12 | 13 | def getSum(a, b): 14 | if b == 0: return a 15 | return getSum(a ^ b, (a & b) << 1) 16 | 17 | lets say integers are 32 bit long: 18 | 19 | this means biggest integer can be 0b11111111111111111111111111111111 20 | and smallest can be 0 21 | 22 | but in this range we have not stored negative numbers 23 | 24 | to account for -ve numbers we use right most bit to store that info: 25 | 0 : +ve 26 | 1 : -ve number 27 | 28 | ans the rest of the 31 bits make the number 29 | 30 | this means accounting for -ve numbers, biggest number is 0b01111111111111111111111111111111 31 | 32 | -ve numbers are stored in memory with 2s compliment: 33 | 34 | 4: 00000100 35 | -4: 11111011 36 | 37 | 38 | in bitwise operations we need define how many bits we re going to operate upon and beyond that if the number overflows we will dicard it. 39 | 40 | now python can store much bigger numbers but if we need to dicard any bit > 32nd bit will will use our mask to discard those 41 | 42 | mask = 0b11111111111111111111111111111111 43 | x & mask = x with only last 32 bits. rest discarded 44 | 45 | if x <= max : positive 46 | else : negative 47 | 48 | but python doesnt know 32 bits is the limit for binary integers to be stored. it still sees the ones we defined as negative as positive 49 | 50 | so if we know x is negative : we need to return ~(x^mask) which is 2s compliment of x considering only last 32 bits. 51 | 52 | 53 | mask = 0b11111111111111111111111111111111 54 | MAX = 0b01111111111111111111111111111111 55 | 56 | if b == 0: 57 | return a if a <= MAX else ~(mask^a) 58 | 59 | return self.getSum( 60 | mask & (a^b), 61 | mask & ((a & b) << 1) 62 | ) -------------------------------------------------------------------------------- /2021/Day4/README.md: -------------------------------------------------------------------------------- 1 | # Day 4 Solutions 2 | 3 | These folders contain solutions to leetcode questions explained by Kshitiz Miglani on [Devsnest Channel](https://www.youtube.com/channel/UCkxqJvZRzhM0oaBjbu3ZjFg). [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) and [Merge Intervals](https://leetcode.com/problems/merge-intervals/) has been explained in his DSA course on arrays in [Day 4 video](https://www.youtube.com/watch?v=cEziCzm7mo4). 4 | 5 | ## Class Questions Editorial 6 | 7 | 1. [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) 8 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Container%20with%20most%20water/container_with_most_water.cpp) 9 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Container%20with%20most%20water/container_with_most_water.py) 10 | 2. [Merge Intervals](https://leetcode.com/problems/merge-intervals/) 11 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Merge%20Intervals/Merge_intervals.cpp) 12 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Merge%20Intervals/Merge_intervals.py) 13 | 14 | ## Assignment Questions Editorial 15 | 16 | 1. [Non Overlaping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) 17 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Non%20overlapping%20intervals/non_overlapping_intervals.cpp) 18 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Non%20overlapping%20intervals/non_overlapping_intervals.py) 19 | 2. [Insert Interval](https://leetcode.com/problems/insert-interval/) 20 | 1. [CPP](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Merge%20Intervals/Merge_intervals.cpp) 21 | 2. [Python](https://github.com/devs-nest/Algo-101/blob/master/2021/Day4/Merge%20Intervals/Merge_intervals.py) -------------------------------------------------------------------------------- /2021/Day5/Word Search/Word_search.py: -------------------------------------------------------------------------------- 1 | from collections import Counter, defaultdict 2 | 3 | 4 | class Solution(object): 5 | def exist(self, board, word): 6 | """ 7 | :type board: List[List[str]] 8 | :type word: str 9 | :rtype: bool 10 | """ 11 | char_dict, rows, cols = defaultdict(list), len(board), len(board[0]) 12 | 13 | # keep a dict for all position of a letter 14 | for i in range(rows): 15 | for j in range(cols): 16 | char_dict[board[i][j]].append([i, j]) 17 | 18 | # check if dfs should be performed 19 | cnt_chars = Counter(word) 20 | for x, cnt in cnt_chars.items(): 21 | if cnt > len(char_dict[x]): 22 | return False 23 | 24 | def dfs(board, word, prev_x, prev_y, idx, visited): 25 | letter = word[idx] 26 | if letter in char_dict: 27 | # fetch list of all position 28 | list_pos = char_dict[letter] 29 | for pos in list_pos: 30 | xi, yi = pos[0], pos[1] 31 | if (xi, yi) not in visited and (abs(xi - prev_x) + abs(yi - prev_y)) <= 1: 32 | if idx + 1 == len(word): 33 | return 1 34 | else: 35 | ans = dfs(board, word, xi, yi, idx + 36 | 1, visited + [(xi, yi)]) 37 | if ans: 38 | return 1 39 | 40 | return 0 41 | 42 | if len(word) == 1 and word[0] in char_dict: 43 | return True 44 | if word[0] in char_dict: 45 | for pos in char_dict[word[0]]: 46 | dfs_ans = dfs(board, word, pos[0], pos[1], 1, [ 47 | (pos[0], pos[1])]) 48 | if dfs_ans == 1: 49 | return True 50 | return False 51 | -------------------------------------------------------------------------------- /2021/Day14/Add Two Numbers II/Add Two Numbers II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | int add(ListNode *one, ListNode *two, int sone, int stwo, ListNode *&t) 15 | { 16 | if (sone == 0 && stwo == 0) 17 | return 0; 18 | int carry; 19 | int t1 = 0, t2 = 0; 20 | if (sone > stwo) 21 | { 22 | carry = add(one->next, two, sone - 1, stwo, t); 23 | t1 = one->val; 24 | } 25 | else if (sone < stwo) 26 | { 27 | carry = add(one, two->next, sone, stwo - 1, t); 28 | t2 = two->val; 29 | } 30 | else 31 | { 32 | carry = add(one->next, two->next, sone - 1, stwo - 1, t); 33 | t1 = one->val; 34 | t2 = two->val; 35 | } 36 | int data = t1 + t2 + carry; 37 | ListNode *nn = new ListNode(data % 10); 38 | nn->next = t; 39 | t = nn; 40 | return data / 10; 41 | } 42 | 43 | ListNode *addTwoNumbers(ListNode *one, ListNode *two) 44 | { 45 | ListNode *t = one; 46 | int sone = 0; 47 | while (t != NULL) 48 | { 49 | sone++; 50 | t = t->next; 51 | } 52 | t = two; 53 | int stwo = 0; 54 | while (t != NULL) 55 | { 56 | stwo++; 57 | t = t->next; 58 | } 59 | t = NULL; 60 | int carry = add(one, two, sone, stwo, t); 61 | if (carry) 62 | { 63 | ListNode *nn = new ListNode(carry); 64 | nn->next = t; 65 | t = nn; 66 | } 67 | return t; 68 | } 69 | }; -------------------------------------------------------------------------------- /2021/Day26/Course Schedule II/Course Schedule II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool dfs(int node, vector> &graph, vector &visited, vector &result) 5 | { 6 | visited[node] = 1; 7 | for (int i = 0; i < graph[node].size(); i++) 8 | { 9 | if (visited[graph[node][i]] == 1) 10 | return false; // if this node is unexplored that means there is a cycle 11 | if (visited[graph[node][i]] == 0) 12 | { 13 | if (!dfs(graph[node][i], graph, visited, result)) //return false 14 | return false; 15 | } 16 | } 17 | visited[node] = 2; //if function comes till here then we can mark the current node as 2 i.e, visited 18 | result.push_back(node); //we will push the visited nodes to the resulting array 19 | return true; 20 | } 21 | vector findOrder(int numCourses, vector> &prerequisites) 22 | { 23 | vector> graph(numCourses); 24 | for (int i = 0; i < prerequisites.size(); i++) 25 | { 26 | graph[prerequisites[i][0]].push_back(prerequisites[i][1]); //making an adjacency list 27 | } 28 | vector visited(numCourses, 0); //for keeping track of the nodes position. 29 | //We first initialize every node as 0 i,e. unvisited 30 | vector result; //result vector 31 | bool flag = true; 32 | for (int i = 0; i < numCourses; i++) 33 | { 34 | if (visited[i] == 0) 35 | { 36 | if (!dfs(i, graph, visited, result)) 37 | { 38 | flag = false; // it will return false if there is a cycle detected so we can break it 39 | break; 40 | } 41 | } 42 | } 43 | if (!flag) 44 | return vector(); 45 | return result; 46 | } 47 | }; -------------------------------------------------------------------------------- /2021/Day18/Validate Binary Search Tree/Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def isValidBST(self, root): 9 | return self.valid(root, -sys.maxsize, sys.maxsize) 10 | 11 | def valid(self, root, l, r): 12 | if not root: 13 | return True 14 | if not (l < root.val < r): 15 | return False 16 | return self.valid(root.left, l, root.val) and self.valid(root.right, root.val, r) 17 | 18 | def isValidBST3(self, root): 19 | pre, stack = None, [] 20 | while True: 21 | while root: 22 | stack.append(root) 23 | root = root.left 24 | if not stack: 25 | return True 26 | node = stack.pop() 27 | if pre and pre.val >= node.val: 28 | return False 29 | pre = node 30 | root = node.right 31 | 32 | def isValidBST2(self, root): 33 | ret, stack = [], [] 34 | while True: 35 | while root: 36 | stack.append(root) 37 | root = root.left 38 | if not stack: 39 | break 40 | node = stack.pop() 41 | ret.append(node.val) 42 | root = node.right 43 | for i in range(len(ret)-1): 44 | if ret[i] >= ret[i+1]: 45 | return False 46 | return True 47 | 48 | def isValidBST1(self, root): 49 | ret = [] 50 | self.dfs(root, ret) 51 | for i in range(len(ret)-1): 52 | if ret[i] >= ret[i+1]: 53 | return False 54 | return True 55 | 56 | def dfs(self, root, ret): 57 | if root: 58 | self.dfs(root.left, ret) 59 | ret.append(root.val) 60 | self.dfs(root.right, ret) 61 | -------------------------------------------------------------------------------- /2020/strings/kmp.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Given a string t with length N and string s with length M find number of occurences 4 | # of string t in string S 5 | # 6 | # 7 | # ex: 8 | # 9 | # 10 | # 3 11 | # for i in string t: 12 | # substring temp = t[i]....t[i+M] 13 | # for j in string s 14 | # if s === 15 | # 16 | # O(N*m) 17 | # 18 | # KMP 19 | # #. Prefix of a string 20 | # 21 | # abcbdabdab 22 | # 0 1 2 3 4 5 6 7 23 | # a b c d a b c d 24 | # [0, 0, 0, 0, 1, 2, 3 , 4] 25 | # 26 | # 0 1 2 3 4 5 6 27 | # a a b a a a b 28 | # [0, 1, 0, 1, 2, 2, 3] 29 | # 30 | # 0 1 2 3 4 5 6 7 8 31 | # a b c a b c a b c 32 | # 33 | # [0, 0, 0, 1, 2, 3, 4 ,5 , 6] 34 | # 35 | # prefix_function[5] = 2 36 | # 37 | # a b c a b c a 38 | # 03 39 | # abca 40 | # 36 41 | # abca 42 | # 0 1 2 3 4 43 | # a a a a a 44 | # [0,1,2,3,4] 45 | # 46 | # 47 | # pattern - s 48 | # text - t 49 | # temp s + '#' + t 50 | # calculate prefix 51 | # s - ab 52 | # t - abcbdabdab 53 | # 54 | # ab+ '#' + abcbdabdab 55 | # prefix function 2 56 | # 57 | # string temp = s + # + t 58 | # 59 | # 1. create a temporary pattern 60 | # 3. Calculate prefix function 61 | # 4. calculate occurence of string in result prefix function. 62 | # 63 | # 64 | # Prefix function - O(N+M) = O(n) 65 | # O(n) 66 | # 67 | # O(N) 68 | # 69 | # pattern = divya 70 | # text = divyanshu 71 | # divya#divyanshud 72 | # count = 0 73 | # prefix = [0, 0 , 0 , 0 ,0, 0, 1, 2, 3, 4, 5, 0,0,0, 0, 1 ] 74 | # for i in range(0, prefix): 75 | # if prefix[i] == len(pattern): 76 | # count = count + 1 77 | # print count 78 | # 79 | # 0 1 2 3 4 5 80 | # s = [a, b, c, a,b, c] 81 | # [0, 0, 0, 1, 2, 3] 82 | # 83 | # i = 4 84 | # j = 1 85 | # 86 | # def calculatePrefixFunction(s): 87 | # pi = [] 88 | # n = len(s) 89 | # for i in range(1, n): 90 | # j = pi[i-1] 91 | # while j > 0 and s[i] != s[j]: 92 | # j = p[j-1] 93 | # if s[i]==s[j]: 94 | # j = j +1 95 | # pi[i] = j 96 | # return pi 97 | # 98 | # [0, ] 99 | # 100 | # 101 | # 102 | # 103 | -------------------------------------------------------------------------------- /2021/Day17/Binary Tree Level Order Traversal/Binary Tree Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution 13 | { 14 | public: 15 | vector> levelOrder(TreeNode *root) 16 | { 17 | 18 | // Early return condition. 19 | if (!root) 20 | return {}; 21 | 22 | vector> ourRes; // Carries our result 23 | vector singleIter; // Carries a single iteration 24 | // Store the node pointers for the most flexibility. 25 | queue ourNodes; 26 | 27 | // Seed with initial root value. 28 | ourNodes.push(root); 29 | 30 | while (!ourNodes.empty()) 31 | { 32 | // Get the size of the current level 33 | int size = ourNodes.size(); 34 | 35 | // Work on the current level. 36 | while (size--) 37 | { 38 | // Push all nodes for a given level into the singleIter vector 39 | TreeNode *topElement = ourNodes.front(); 40 | singleIter.push_back(topElement->val); 41 | ourNodes.pop(); 42 | // Prime their children for the next iteration (put all their children in the queue, if they exist). 43 | if (topElement->left) 44 | ourNodes.push(topElement->left); 45 | if (topElement->right) 46 | ourNodes.push(topElement->right); 47 | } 48 | // Store all the nodes of one level in a single grouping and push them into our result 49 | ourRes.push_back(singleIter); 50 | // Clear the group for the next iteration. 51 | singleIter.clear(); 52 | } 53 | 54 | return ourRes; 55 | } 56 | }; -------------------------------------------------------------------------------- /2021/Day21/Find Median from Data Stream/Find Median from Data Stream.py: -------------------------------------------------------------------------------- 1 | """ 2 | ## RC ## 3 | ## APPROACH : 2 HEAPS ## 4 | ## LOGIC ## 5 | ## One minheap to store low values and second maxheap to store max values, we keep track and update median every time after insertion ## 6 | 7 | ## TIME COMPLEXITY : O(logN) ## 8 | ## SPACE COMPLEXITY : O(N) ## 9 | 10 | ## EXAMPLE ## 11 | Adding number 41 12 | MaxHeap lo: [41] // MaxHeap stores the largest value at the top (index 0) 13 | MinHeap hi: [] // MinHeap stores the smallest value at the top (index 0) 14 | Median is 41 15 | ======================= 16 | Adding number 35 17 | MaxHeap lo: [35] // max heap stores smaller half of nums 18 | MinHeap hi: [41] // min heap stores bigger half of nums 19 | Median is 38 20 | ======================= 21 | Adding number 62 22 | MaxHeap lo: [41, 35] 23 | MinHeap hi: [62] 24 | Median is 41 25 | ======================= 26 | Adding number 4 27 | MaxHeap lo: [35, 4] 28 | MinHeap hi: [41, 62] 29 | Median is 38 30 | ======================= 31 | Adding number 97 32 | MaxHeap lo: [41, 35, 4] 33 | MinHeap hi: [62, 97] 34 | Median is 41 35 | ======================= 36 | Adding number 108 37 | MaxHeap lo: [41, 35, 4] 38 | MinHeap hi: [62, 97, 108] 39 | Median is 51.5 40 | """ 41 | 42 | 43 | class MedianFinder: 44 | def __init__(self): 45 | self.lo = [] 46 | self.hi = [] 47 | 48 | def addNum(self, num): 49 | heappush(self.lo, -num) # lo is maxheap, so -1 * num 50 | heappush(self.hi, -self.lo[0]) # hi is minheap 51 | heappop(self.lo) 52 | 53 | if len(self.lo) < len(self.hi): 54 | heappush(self.lo, -self.hi[0]) 55 | heappop(self.hi) 56 | 57 | def findMedian(self): 58 | if len(self.lo) > len(self.hi): 59 | return -self.lo[0] 60 | else: 61 | return (self.hi[0] - self.lo[0]) / 2 # - as low has -ve values 62 | -------------------------------------------------------------------------------- /2021/Day12/Minimum Window Substring/Minimum Window Substring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minWindow(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: str 7 | """ 8 | # Defaultdict is very useful in this problem, though i don't like to import modules 9 | target_count_dict = collections.defaultdict(int) 10 | for ch in t: 11 | target_count_dict[ch] += 1 12 | remain_missing = len(t) 13 | start_pos, end_pos = 0, float('inf') 14 | current_start = 0 15 | 16 | # Enumerate function makes current_end indexes from 1 17 | for current_end, ch in enumerate(s, 1): 18 | # Whenever we encounter a character, no matter ch in target or not, we minus 1 in count dictionary 19 | # But, only when ch is in target, we minus the length of remain_missing 20 | # When the remain_missing is 0, we find a potential solution. 21 | if target_count_dict[ch] > 0: 22 | remain_missing -= 1 23 | target_count_dict[ch] -= 1 24 | 25 | if remain_missing == 0: 26 | # Remove redundant character 27 | # Try to find the fist position in s that makes target_count_dict value equals 0 28 | # Which means we can't skip this character in s when returning answer 29 | while target_count_dict[s[current_start]] < 0: 30 | target_count_dict[s[current_start]] += 1 31 | current_start += 1 32 | if current_end - current_start < end_pos - start_pos: 33 | start_pos, end_pos = current_start, current_end 34 | 35 | # We need to add 1 to current_start, and the correspondence value in dictionary, is because 36 | # this is the first character of the potential answer. So, in future iteration, when we encounter this character, 37 | # We can remove this currently first character to try to find a shorter answer. 38 | target_count_dict[s[current_start]] += 1 39 | remain_missing += 1 40 | current_start += 1 41 | 42 | return s[start_pos:end_pos] if end_pos != float('inf') else "" 43 | -------------------------------------------------------------------------------- /2021/Day8/Longest Repeating Character Replacement/Longest_Repeating_Character_Replacement_Longest_Repeating_Character_Replacement.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def characterReplacement(self, s, k): 3 | """ 4 | :type s: str 5 | :type k: int 6 | :rtype: int 7 | 8 | Given a string s that consists of only uppercase English letters, 9 | you can perform at most k operations on that string. 10 | 11 | In one operation, you can choose any character of the string and 12 | change it to any other uppercase English character. 13 | 14 | Find the length of the longest sub-string containing all repeating 15 | letters you can get after performing the above operations. 16 | """ 17 | # Maximum number of repeated characters. 18 | max_repeats = 0 19 | 20 | # Use two pointers `start` and `end` to track a sliding/caterpillar window. 21 | start = 0 22 | 23 | # Track how many times you see a character in the current window. 24 | char_freq = {} 25 | 26 | # Length of longest valid substring in the current window. 27 | max_length = 0 28 | 29 | # Expand the window to the right until the end of the string. 30 | for end in range(len(s)): 31 | current_char = s[end] 32 | 33 | # Update `char_freq` by incrementing `current_char` count. 34 | char_freq[current_char] = char_freq.get(current_char, 0) + 1 35 | 36 | # If `current_char` now has the most repeating characters, 37 | # update `max_repeats`. 38 | max_repeats = max(max_repeats, char_freq[current_char]) 39 | 40 | current_length = end - start + 1 41 | 42 | # If the number of replacements in order to maximize repeats 43 | # is less than or equal to `k` operations, update `max_length`. 44 | if current_length - max_repeats <= k: 45 | max_length = max(max_length, current_length) 46 | 47 | # Otherwise, slide the window by moving the `start` pointer 48 | # to the right and update `char_freq` to reflect the new window. 49 | else: 50 | char_freq[s[start]] -= 1 51 | start += 1 52 | 53 | return max_length 54 | -------------------------------------------------------------------------------- /2021/Day5/Set Matrix zeroes/set_matrix_zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void setZeroes(vector> &matrix) 5 | { 6 | //By CyFun 7 | // Have to check the marks of first row and column before we modify them. 8 | bool zero_first_row = false; 9 | bool zero_first_col = false; 10 | for (int i = 0; i < matrix.size(); i++) 11 | { 12 | if (matrix[i][0] == 0) 13 | { 14 | zero_first_col = true; 15 | break; 16 | } 17 | } 18 | 19 | for (int j = 0; j < matrix[0].size(); j++) 20 | { 21 | if (matrix[0][j] == 0) 22 | { 23 | zero_first_row = true; 24 | break; 25 | } 26 | } 27 | 28 | // Scan row and column and set marks 29 | for (int i = 1; i < matrix.size(); i++) 30 | { 31 | for (int j = 1; j < matrix[i].size(); j++) 32 | { 33 | if (matrix[i][j] == 0) 34 | { 35 | matrix[i][0] = 0; 36 | matrix[0][j] = 0; 37 | } 38 | } 39 | } 40 | 41 | // Set 0 for rows 42 | for (int i = 1; i < matrix.size(); i++) 43 | { 44 | if (matrix[i][0] == 0) 45 | { 46 | for (int j = 1; j < matrix[i].size(); j++) 47 | { 48 | matrix[i][j] = 0; 49 | } 50 | } 51 | } 52 | 53 | // Set 0 for columns 54 | for (int j = 1; j < matrix[0].size(); j++) 55 | { 56 | if (matrix[0][j] == 0) 57 | { 58 | for (int i = 1; i < matrix.size(); i++) 59 | { 60 | matrix[i][j] = 0; 61 | } 62 | } 63 | } 64 | 65 | // Set 0 for first row. 66 | if (zero_first_row) 67 | { 68 | for (int j = 0; j < matrix[0].size(); j++) 69 | { 70 | matrix[0][j] = 0; 71 | } 72 | } 73 | 74 | // Set 0 for first column 75 | if (zero_first_col) 76 | { 77 | for (int i = 0; i < matrix.size(); i++) 78 | { 79 | matrix[i][0] = 0; 80 | } 81 | } 82 | } 83 | }; -------------------------------------------------------------------------------- /2021/Day13/Odd Even Linked List/Odd Even Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def oddEvenList(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | if not head: 14 | return head 15 | 16 | odd = head # Both of them point at the first node of the target linked list 17 | even = head.next # doesn't matter even there's only one node in the linked list (even will become None) 18 | eHead = even # We have to keep where the even-node list starts 19 | 20 | while even and even.next: # won't get in the loop at first if there's only one node in the linked list 21 | # both even and even.next are necessary condition because even might point to None, which has no attribute 'next' 22 | # AND, why these two, small discussion by myself as below 23 | odd.next = odd.next.next 24 | even.next = even.next.next 25 | # After these two ops, odd/even still points at its original place 26 | # Therefore, we move them to the next node repectively 27 | odd = odd.next 28 | even = even.next 29 | 30 | odd.next = eHead # the odd pointer currently points at the last node of the odd-node list 31 | 32 | return head # We keep the start of the odd-node list in the first of our code 33 | 34 | 35 | #Four conditions I doubt for the while-loop: 36 | 37 | #[A] odd and odd.next -> wrong when 1->2->3->4->None ( even nodes ) because even.next is None, which has no attribute 'next' 38 | #[B] odd and even.next -> wrong when 1->2->3->4->5->None ( odd nodes ) because even is None, which has no attribute 'next' 39 | #[C] even and odd.next -> wrong when 1->2->3->4->None ( even nodes ) because even.next is None, which has no attribute 'next' 40 | #[D] even and even.next -> correct 41 | # (1). when 1->2->3->4->5->None ( odd nodes ) even will become None first and at the same time, odd points at the last node of the linked list; therefore, breaks from the while loop. 42 | # (2). when 1->2->3->4->None ( even nodes ) even.next will become None first and at the same time, odd points at the last-2 node of the linked list and even points at the last node of the linked list; therefore, breaks from the while loop. 43 | -------------------------------------------------------------------------------- /2021/Day25/Pacific Atlantic Water Flow/Pacific Atlantic Water Flow.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | private: 4 | void dfs(const vector> &matrix, const vector> &coords, vector> &visited, int i, int j) 5 | { 6 | visited[i][j] = true; 7 | 8 | for (auto &coord : coords) 9 | { 10 | int next_i = coord.first + i; 11 | int next_j = coord.second + j; 12 | 13 | // since we're going backwards (from "ocean" instead of to) we want the next node's value to be equal to or more than the current node's value 14 | if (is_in_bounds(matrix, next_i, next_j) && !visited[next_i][next_j] && matrix[next_i][next_j] >= matrix[i][j]) 15 | { 16 | dfs(matrix, coords, visited, next_i, next_j); 17 | } 18 | } 19 | } 20 | 21 | bool is_in_bounds(const vector> &matrix, int i, int j) 22 | { 23 | return i >= 0 && j >= 0 && i < matrix.size() && j < matrix[0].size(); 24 | } 25 | 26 | public: 27 | vector> pacificAtlantic(const vector> &matrix) 28 | { 29 | if (matrix.empty()) 30 | return vector>(); 31 | 32 | const vector> coords = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; 33 | 34 | int n = matrix.size(), m = matrix[0].size(); 35 | vector> visited_atlantic(n, vector(m, false)); 36 | vector> visited_pacific(n, vector(m, false)); 37 | 38 | for (int i = 0; i < n; i++) 39 | { 40 | // left edge for pacific ocean 41 | dfs(matrix, coords, visited_pacific, i, 0); 42 | // right edge for atlantic ocean 43 | dfs(matrix, coords, visited_atlantic, i, m - 1); 44 | } 45 | for (int j = 0; j < m; j++) 46 | { 47 | // top edge for pacific ocean 48 | dfs(matrix, coords, visited_pacific, 0, j); 49 | // bottom edge for atlantic ocean 50 | dfs(matrix, coords, visited_atlantic, n - 1, j); 51 | } 52 | 53 | vector> result; 54 | // find the nodes that can reach both oceans 55 | for (int i = 0; i < n; i++) 56 | for (int j = 0; j < m; j++) 57 | if (visited_pacific[i][j] && visited_atlantic[i][j]) 58 | result.push_back({i, j}); 59 | 60 | return result; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /2021/day1/valid-anagram/ValidAnagram.py: -------------------------------------------------------------------------------- 1 | # @Author: Araika Singh 2 | # @Date: 2021-03-20T01:09:24+05:30 3 | # @Email: roseymods@gmail.com 4 | # @Last modified by: NonZeroExitCode 5 | # @Last modified time: 2021-03-20T01:28:58+05:30 6 | # @Link to question: https://leetcode.com/problems/valid-anagram/ 7 | 8 | class ValidAnagram(object): 9 | def isAnagram(self, s, t): 10 | sLen = len(s) 11 | tLen = len(t) 12 | 13 | # If two strings have same letters in same number exactly in same 14 | # or different order then the two strings are anagrams 15 | if sLen != tLen: 16 | return False 17 | 18 | # Keeping a hashmap to keep track of letters 19 | # The intuition used here would be say there are two words 20 | # aka "araika" and "raakia", now when we count the letters in 21 | # string and subtract them, we should get an overrall answer as 22 | # zero, i.e, string "araika"--> 3 a's, 1 r, 1 i and 1 k 23 | # minus string "raakia"--> 3 a's, 1 r, 1 i and 1 k is equal to 24 | # 0 a, 0 r, 0 i and 0 k 25 | nmap = {} 26 | 27 | # Since the length of both strings, it doesn't matter what string size 28 | # is to be taken 29 | for i in range(sLen): 30 | 31 | # If the map doesn't contain the letter in string s then add 32 | # it to list and update the corresponding value as 1 33 | if s[i] not in nmap: 34 | nmap[s[i]] = 1 35 | else: 36 | # If the letter in string s is already present then the value is 37 | # incremented by 1 38 | nmap[s[i]] += 1 39 | 40 | # If the map doesn't contain the letter in string t then add 41 | # it to list and update the corresponding value as -1 42 | if t[i] not in nmap: 43 | nmap[t[i]] = -1 44 | else: 45 | # If the letter in string s is already present then the value is 46 | # decremented by 1 47 | nmap[t[i]] -= 1 48 | 49 | # Checking if the values of any letter is not zero, that means there is an 50 | # extra letter/character in either of the given strings 51 | for key in nmap: 52 | # If the value is not zero then return false 53 | if nmap[key] != 0: 54 | return False 55 | 56 | # No value was found in map that wasn't zero that means the strings s and t 57 | # are anagrams 58 | return True 59 | -------------------------------------------------------------------------------- /2021/Day10/Subsets/subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void subsetsWithDup(const vector &sp, // sub problem 4 | int spi, // sub problem index 5 | vector &ps, // partial solution 6 | int psi, // partial solution index 7 | vector> &res) // result vector 8 | { 9 | // base case if sub problem index == sp.size that means 10 | // there are no more numbers to be considered for subset 11 | // This branch has hit the end and partial solution we have 12 | // is the complete solution 13 | if (spi == sp.size()) { 14 | res.push_back({ps.begin(), ps.begin()+psi}); 15 | return; 16 | } 17 | 18 | // We need to take care of duplicate numbers 19 | // since we have already sorted the nums 20 | // all the duplicates are placed next to each other. 21 | // This loop takes care of counting occurences of any number 22 | // in case of duplicate it counts all occurences of duplicates 23 | int count {1}; 24 | for (int i = spi+1; i < sp.size() && sp[i] == sp[spi]; i++) 25 | ++count; 26 | 27 | // if we count the number of occurence of the number 28 | // then we can avoid duplicates and easily guess the 29 | // end of each unique branch 30 | // This way we can even optimize the solution. 31 | // eg: 2, 2, 2 (3 consecutive 2's) 32 | // Then resultant subsets we can have is numbers in subset till this point 33 | // + {} exclude case, {2} include one instance, {2, 2} include two instances 34 | // {2, 2, 2} include all three instances 35 | 36 | // exclude case: 37 | // Skip count number of elements as exclude case will not have any 38 | // occurence of this element 39 | subsetsWithDup(sp, spi+count, ps, psi, res); 40 | 41 | // include case: 42 | // include incrementally one instance in one branch, 43 | // two instances.. upto count instances 44 | for (int i = 0; i < count; i++) { 45 | ps[psi+i] = sp[spi]; 46 | subsetsWithDup(sp, spi+count, ps, psi+i+1, res); 47 | } 48 | } 49 | 50 | vector> subsetsWithDup(vector& nums) { 51 | vector>res; 52 | vectorslate(nums.size(), 0); 53 | std::sort(nums.begin(), nums.end()); 54 | subsetsWithDup(nums, 0, slate, 0, res); 55 | return res; 56 | } 57 | }; -------------------------------------------------------------------------------- /2021/Day10/Subsets2/subsets2.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void subsetsWithDup(const vector &sp, // sub problem 5 | int spi, // sub problem index 6 | vector &ps, // partial solution 7 | int psi, // partial solution index 8 | vector> &res) // result vector 9 | { 10 | // base case if sub problem index == sp.size that means 11 | // there are no more numbers to be considered for subset 12 | // This branch has hit the end and partial solution we have 13 | // is the complete solution 14 | if (spi == sp.size()) 15 | { 16 | res.push_back({ps.begin(), ps.begin() + psi}); 17 | return; 18 | } 19 | 20 | // We need to take care of duplicate numbers 21 | // since we have already sorted the nums 22 | // all the duplicates are placed next to each other. 23 | // This loop takes care of counting occurences of any number 24 | // in case of duplicate it counts all occurences of duplicates 25 | int count{1}; 26 | for (int i = spi + 1; i < sp.size() && sp[i] == sp[spi]; i++) 27 | ++count; 28 | 29 | // if we count the number of occurence of the number 30 | // then we can avoid duplicates and easily guess the 31 | // end of each unique branch 32 | // This way we can even optimize the solution. 33 | // eg: 2, 2, 2 (3 consecutive 2's) 34 | // Then resultant subsets we can have is numbers in subset till this point 35 | // + {} exclude case, {2} include one instance, {2, 2} include two instances 36 | // {2, 2, 2} include all three instances 37 | 38 | // exclude case: 39 | // Skip count number of elements as exclude case will not have any 40 | // occurence of this element 41 | subsetsWithDup(sp, spi + count, ps, psi, res); 42 | 43 | // include case: 44 | // include incrementally one instance in one branch, 45 | // two instances.. upto count instances 46 | for (int i = 0; i < count; i++) 47 | { 48 | ps[psi + i] = sp[spi]; 49 | subsetsWithDup(sp, spi + count, ps, psi + i + 1, res); 50 | } 51 | } 52 | 53 | vector> subsetsWithDup(vector &nums) 54 | { 55 | vector> res; 56 | vector slate(nums.size(), 0); 57 | std::sort(nums.begin(), nums.end()); 58 | subsetsWithDup(nums, 0, slate, 0, res); 59 | return res; 60 | } 61 | }; -------------------------------------------------------------------------------- /2021/day1/valid-anagram/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author: Araika Singh 3 | * @Date: 2021-03-20T00:25:44+05:30 4 | * @Email: roseymods@gmail.com 5 | * @Last modified by: NonZeroExitCode 6 | * @Last modified time: 2021-03-20T01:28:43+05:30 7 | * @Link to question: https://leetcode.com/problems/valid-anagram/ 8 | */ 9 | 10 | class ValidAnagram { 11 | 12 | // If two strings have same letters in same number exactly in same 13 | // or different order then the two strings are anagrams 14 | public boolean isAnagram(String s, String t) { 15 | int sLen = s.length(), tLen = t.length(); 16 | 17 | // If the length of both strings are different then they 18 | // can't be anagrams 19 | if(sLen != tLen) { 20 | return false; 21 | } 22 | 23 | // Keeping a hashmap to keep track of letters 24 | // The intuition used here would be say there are two words 25 | // aka "araika" and "raakia", now when we count the letters in 26 | // string and subtract them, we should get an overrall answer as 27 | // zero, i.e, string "araika"--> 3 a's, 1 r, 1 i and 1 k 28 | // minus string "raakia"--> 3 a's, 1 r, 1 i and 1 k is equal to 29 | // 0 a, 0 r, 0 i and 0 k 30 | 31 | HashMap map = new HashMap<>(); 32 | 33 | // Since the length of both strings, it doesn't matter what string size 34 | // is to be taken 35 | for(int i = 0; i < sLen; i++){ 36 | char ch = s.charAt(i), ch2 = t.charAt(i); 37 | 38 | // If the map doesn't contain the letter in string s then add 39 | // it to list and update the corresponding value as 1 40 | if(!map.containsKey(ch)){ 41 | map.put(ch, 1); 42 | }else{ 43 | // If the letter in string s is already present then the value is 44 | // incremented by 1 45 | map.put(ch, map.get(ch)+1); 46 | } 47 | 48 | // If the map doesn't contain the letter in string t then add 49 | // it to list and update the corresponding value as -1 50 | if(!map.containsKey(ch2)){ 51 | map.put(ch2, -1); 52 | }else{ 53 | // If the letter in string s is already present then the value is 54 | // decremented by 1 55 | map.put(ch2, map.get(ch2)-1); 56 | } 57 | } 58 | 59 | // Checking if the values of any letter is not zero, that means there is an 60 | // extra letter/character in either of the given strings 61 | for(int val : map.values()){ 62 | 63 | // If the value is not zero then return false 64 | if(val != 0){ 65 | return false; 66 | } 67 | } 68 | 69 | // No value was found in map that wasn't zero that means the strings s and t 70 | // are anagrams 71 | return true; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /2021/Day18/Convert Sorted Array to Binary Search Tree/Convert Sorted Array to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 9 | # ensure we have at least the root 10 | if not nums: 11 | return None 12 | 13 | # we will be creating a stack where each element is the following tuple: 14 | # (left index of nums, right index of nums, parent node, child side), 15 | # where the left and right indices set the bounds of the values in 16 | # nums the current node considers, and child side refers to which side 17 | # of the parent node that the current node will be set to (more clear below) 18 | 19 | # create the root, which is the "first parent" 20 | l, r = 0, len(nums) - 1 # initial left and right bounds of nums 21 | i = (l + r) // 2 # center of the bounds of nums we view 22 | root = TreeNode(nums[i]) 23 | 24 | # create a stack of the first two children values; split bounds of 25 | # parent's left and right bounds in half using the center position, 26 | # then remember the side of the parent (root) to set that child to 27 | stack = [(l, i-1, root, 'l'), 28 | (i+1, r, root, 'r')] 29 | 30 | # while there are more children to create 31 | while stack: 32 | # extract the information for a child 33 | l, r, parent, side = stack.pop() 34 | 35 | # only create the child if it looks at a valid left and right bound 36 | # in nums, so the left index <= right index; this ensures we stop 37 | # adding children after we've exhausted the valid positions in nums 38 | if l <= r: 39 | i = (l + r) // 2 # center position of bounds 40 | 41 | # create the child node from the center position, 42 | # and set the corresponding child side in the parent 43 | child = TreeNode(nums[i]) 44 | if side == 'l': 45 | parent.left = child 46 | else: 47 | parent.right = child 48 | 49 | # add the information for the two children of the current child, 50 | # splitting the left and right bounds of the current child in half 51 | # using the center position, then remember the side of the child 52 | # (which becomes the parent for its children) to set next children 53 | stack.append((l, i - 1, child, 'l')) 54 | stack.append((i + 1, r, child, 'r')) 55 | 56 | return root 57 | -------------------------------------------------------------------------------- /2021/Day24/Bellman Ford Algo.txt: -------------------------------------------------------------------------------- 1 | Bellman Ford Algorithm: 2 | 3 | Single src shortest path: 4 | 5 | Difference between this and dijkstra's algo is thhat this can support -ve weights assigned to edges. 6 | 7 | 8 | 9 | Pre-requisites: 10 | cycles with total path sum as -ve is not allowed 11 | 12 | 13 | Reasoning: 14 | 15 | 1. if src and destination are same then dist is 0. dist[x][x] is always 0 . that means even though we dont know anything about the distance from Src we we know that 16 | 17 | Dist[Src] = 0 which is its absolute shortest distance. 18 | 19 | for all other nodes X we have dist[X] = infinity 20 | 21 | 2. Relaxation Process: 22 | 23 | if dist[x] = dx & dis[y] = dy and we discover edge[x][y] = p such that 24 | 25 | dy > dx + p 26 | 27 | then we can say dist[y] = dx + p . or we can say 28 | 29 | dist[y] = min(dist[y], dist[x] + edge[x][y]) for all nodes x which have an edge to y 30 | 31 | 32 | 3. if we relax all edges and there is a change in some vertice's distance then that change can trigger other changes and we have to redo relaxation for all the nodes again. 33 | if distance does not change we can be certain that this is the shortest path for all nodes. 34 | 35 | 4. Max number of times all edges need to be relaxed is n-1 where n is the number of nodes. 36 | 37 | proof: 38 | relaxation starts from src 39 | 40 | the longest path that can be from src to any node (no cycles included) can be of n-1 edges. 41 | 42 | and every time atleast on of the edge in this path would get updated (if needed) 43 | 44 | so max n - 1 iterations of the relaxation process are required 45 | 46 | 47 | algo: 48 | 49 | for n-1 times: 50 | any_edge_updated = False 51 | for all edges: 52 | if dist[edge.dest] > edge.wt + dist[edge.src]: 53 | dist[edge.dest] = edge.wt + dist[edge.src] 54 | any_edge_updated = True 55 | if not any_edge_updated: 56 | break 57 | 58 | // note that the above code will not update anything if dist[edge.src] is infinity 59 | 60 | code : 61 | 62 | adj = [[None, 5, 2, None, None], 63 | [None, None, 1, None, None], 64 | [None, None, None, -1, -1], 65 | [None, None, None, None, None], 66 | [3, None, None, 2, None]] 67 | 68 | inf = 999999999999999 69 | n = len(adj) 70 | src = 0 71 | dist = [inf] * n 72 | dist[src] = 0 73 | 74 | for _ in range(n - 1): 75 | any_edge_updated = False 76 | for nodefrom in range(n): 77 | for nodeto in range(n): 78 | if adj[nodefrom][nodeto] and dist[nodefrom] != inf and dist[nodeto] > adj[nodefrom][nodeto] + dist[nodefrom]: 79 | dist[nodeto] = adj[nodefrom][nodeto] + dist[nodefrom] 80 | any_edge_updated = True 81 | if not any_edge_updated: 82 | break 83 | 84 | print(dist) 85 | 86 | output: 87 | [0, 5, 2, 1, 1] 88 | 89 | 90 | time complexity: 91 | e*v 92 | 93 | if v is n and we know e is at max v*v-1 94 | 95 | => O(n^3) 96 | --------------------------------------------------------------------------------