├── .DS_Store ├── April_Leetcode_Challenge_2023 ├── Day13 │ ├── Day14 │ │ └── leetcode_516.cpp │ └── Validate_Stack_Sequences.py └── Day15 │ └── leetcode_2218.cpp ├── DSU.cpp ├── December ├── Day1 │ ├── 1704_Determine_if_String_Halves_Are_Alike.cpp │ └── detemine_if_string_halves_are_alike.py ├── Day10 │ └── leetcode_1339.cpp ├── Day11 │ ├── 124_Binary_Tree_Maximum_Path_Sum.cpp │ ├── binary-tree-maximum-path-sum.cpp │ └── binary_tree_maximum_path_sum.py ├── Day12 │ └── leetcode_70.cpp ├── Day13 │ └── minimum-falling-path-sum.cpp ├── Day14 │ └── 198_House_Robber.cpp ├── Day15 │ └── longestCommonSubsequence.cpp ├── Day16 │ ├── Implement_Queue_using_Stacks.cpp │ └── implement_queue_using_stacks.py ├── Day17 │ └── 150._Evaluate_Reverse_Polish_Notation.cpp ├── Day18 │ ├── 739._Daily_Temperatures.cpp │ ├── 739_Daily_Temperatures.cpp │ └── daily_temperature.py ├── Day19 │ ├── 1971_Find_if_Path_Exists_in_Graph │ │ └── bfs.cpp │ └── find_if_path_exists_in_graph.py ├── Day2 │ ├── 1657._Determine_if_Two_Strings_Are_Close.cpp │ └── determine_if_two_strings_are_close.py ├── Day20 │ └── keys_and_rooms.py ├── Day21 │ └── possible_bipartition.py ├── Day23 │ └── leetcode_309.cpp ├── Day24 │ ├── leetcode_790_dp.cpp │ ├── leetcode_790_memo.cpp │ └── leetcode_790_recrusive.cpp ├── Day25 │ ├── 2389._Longest_Subsequence_With_Limited_Sum.cpp │ └── answerQueries.cpp ├── Day26 │ ├── 55_Jump_Game.cpp │ └── jump_game.cpp ├── Day27 │ ├── 2279_Maximum_Bags_With_Full_Capacity_of_Rocks.cpp │ ├── jsSolution │ └── leetcode_2279.cpp ├── Day28 │ ├── 1962-leetcode.cpp │ ├── 1962_Remove_Stones_to_Minimize_the_Total.cpp │ ├── leetcode_1962.cpp │ └── remove_stones_to_minimize_sum.py ├── Day29 │ └── leetcode_1834.cpp ├── Day3 │ ├── 451_Sort_Characters_By_Frequency.cpp │ └── 451_sort_character_by_frequency.py ├── Day31 │ └── 980_Unique_Paths_III.cpp ├── Day4 │ ├── minimum-average-difference.cpp │ └── minimun-avaerage-difference.py ├── Day5 │ ├── middle-of-the-linked-list.cpp │ ├── middle-of-the-linked-list.py │ └── middle_of_the_linked_list.py ├── Day6 │ ├── 328_Odd_Even_Linked_List.cpp │ ├── odd-even-linked-list.cpp │ └── odd_even_linked_list.py ├── Day7 │ ├── range-sum-of-bst.cpp │ ├── rangeSumBST.cpp │ └── range_sum_of_bst.py ├── Day8 │ ├── leafSimilar.cpp │ └── leaf_similar_trees.py └── Day9 │ ├── leetcode_1026.cpp │ └── maximum_difference_btw_node_n_ancestors.py ├── February_Leetcode_Challenge ├── Day1 │ ├── leetcode_1071.cpp │ └── leetcode_1071.py ├── Day14 │ └── leetcode_67.cpp ├── Day15 │ └── leetcode_989.cpp ├── Day17 │ └── leetcode_783.cpp ├── Day19 │ └── leetcode_103.cpp ├── Day2 │ ├── Verifying an Alien Dictionary.py │ └── leetcode_953.cpp ├── Day3 │ └── leetcode_6.cpp ├── Day4 │ ├── 567_leetcode.cpp │ └── leetcode_567.cpp ├── Day5 │ └── leetcode_438.cpp └── Day7 │ └── leetcode_904.cpp ├── January ├── Day1.cpp ├── Day1 │ └── word_pattern.cpp ├── Day10 │ └── 100._Same_Tree.java ├── Day12 │ ├── leetcode_1519.cpp │ └── leetcode_1519.java ├── Day13 │ └── leetcode_2246.cpp ├── Day15 │ └── 2421_Number_of_Good_Paths.cpp ├── Day16 │ ├── 57_Insert_Interval.cpp │ ├── 57_Insert_Interval.java │ └── 57_Insert_Interval.py ├── Day17 │ ├── minFlipsMonoIncr.cpp │ └── minFlipsMonoIncr.java ├── Day18 │ └── maximum-sum-circular-subarray.java ├── Day19 │ ├── leetcode_974.cpp │ └── leetcode_974.java ├── Day2 │ ├── detect_capital.py │ ├── leetcode_520.cpp │ └── leetcode_520.java ├── Day20 │ └── leetcode_491.cpp ├── Day21 │ └── 93._Restore_IP_Addresses.cpp ├── Day22 │ └── leetcode_131.cpp ├── Day23 │ └── leetcode_997.cpp ├── Day27 │ └── 472_Concatenated_Words.cpp ├── Day28 │ └── leetcode_352.cpp ├── Day29 │ └── 460._LFU_Cache.cpp ├── Day3 │ ├── delete_columns_to_make_sorted.py │ ├── leetcode_944.cpp │ └── leetcode_944.java ├── Day31 │ └── leetcode_1626.cpp ├── Day4 │ ├── minimumRounds.cpp │ ├── minimumRounds.java │ └── minimum_rounds.py ├── Day5 │ ├── jsSolution │ ├── leetcode_452.cpp │ ├── leetcode_452.java │ └── leetcode_minimum_number_of_arrows_to_burst_balloons.py ├── Day6 │ ├── JavaScript-Solution │ ├── leetcode_1833.cpp │ ├── leetcode_1833.java │ ├── leetcode_1833_without_sorting.cpp │ └── maximum_ice_cream_bars.py ├── Day7 │ ├── gas_station.py │ ├── leetcode_134.cpp │ └── leetcode_134.java ├── Day8 │ ├── leetcode_149.cpp │ └── leetcode_149.java ├── Day9 │ └── 144.Binary_Tree_Preorder_Traversal.java └── leetcode_2359.cpp ├── March_Leetcode_Challenge ├── Day1 │ └── leetcode_912.cpp ├── Day2 │ ├── leetcode_443(0(1)).cpp │ └── leetcode_443.cpp ├── Day3 │ ├── 28_leetcode.cpp │ └── leetcode_28.cpp ├── Day4 │ └── leetcode_2444.cpp ├── Day5 │ └── 1345._Jump_Game_IV.cpp ├── Day7 │ └── Leetcode_2187.cpp └── Day9 │ └── leetcode_142.cpp ├── May_Leetcode_Challenge ├── Day11 │ └── 1035_Uncrossed_Lines.cpp ├── Day12 │ └── leetcode_2140.cpp ├── Day13 │ └── leetcode_2466.cpp ├── Day17 │ └── leetcode_2130.cpp ├── Day18 │ └── leetcode_1557.cpp ├── Day3 │ ├── 2215_Find_the_Difference_of_Two_Arrays.cpp │ └── Day4 │ │ └── 649_Dota2_Senate.cpp ├── Day5 │ └── leetcode_1456.cpp ├── Day6 │ └── leetcode_1498.cpp ├── Day7 │ └── leetcode_1964.cpp └── Day8 │ └── leetcode_1572.cpp ├── November ├── .DS_Store ├── Day 22 │ └── 279._Perfect_Squares.cpp ├── Day1 │ ├── 1706._Where_Will _the_Ball_Fall.cpp │ └── Where Will the Ball Fall.py ├── Day10 │ ├── 1047._Remove_All_Adjacent_Duplicates_In_String.cpp │ ├── 1047._Remove_All_Adjacent_Duplicates_In_String.java │ ├── Remove_All_Adjacent _Duplicates_In_String.py │ ├── removeAdjacentString.java │ └── remove_all_adjacent_duplicates_in_string.py ├── Day11 │ ├── 26_Remove_Duplicates_from_Sorted_Array.cpp │ ├── 26_Remove_Duplicates_from_Sorted_Array.java │ ├── removeDuplicates.java │ └── remove_duplicates.py ├── Day12 │ ├── 295_Find_Median_from_Data_Stream.cpp │ ├── 295_Find_Median_from_Data_Stream.java │ ├── find_median_from_data_stream.py │ └── medianFromDataStream.java ├── Day13 │ ├── 151_Reverse_Words_in_a_String.java │ ├── reverseWords.java │ └── reverse_words_in_string.py ├── Day14 │ └── mostStonesRemoved.java ├── Day15 │ ├── 222_Count_Complete_Tree_Nodes.cpp │ └── 222_Count_Complete_Tree_Nodes.java ├── Day16 │ ├── 374_Guess_Number_Higher_or_Lower.cpp │ ├── 374_Guess_Number_Higher_or_Lower.java │ └── guess_number_higher_or_lower.py ├── Day17 │ ├── 223_Rectangle_Area.cpp │ ├── Rectangle Area.py │ └── rectangleArea.java ├── Day18 │ ├── Ugly Number.py │ ├── uglyNumber.java │ └── ugly_number.cpp ├── Day19 │ ├── 587._Erect_the_Fence.cpp │ └── erectTheFence.java ├── Day2 │ └── 433._Minimum_Genetic_Mutation.cpp ├── Day20 │ └── 224 _basic_calculator.cpp ├── Day21 │ └── 1926_Nearest_Exit_from_Entrance_in_Maze.cpp ├── Day22 │ ├── 279_Perfect_squares.cpp │ └── Perfect_Squares.py ├── Day23 │ ├── 36_Valid_Sudoku.cpp │ ├── 36_Valid_Sudoku.java │ └── Valid Sudoku.py ├── Day24 │ └── 79_word_search.cpp ├── Day25 │ └── 907_Sum_of_Subarray_Minimums.cpp ├── Day26 │ └── 1235_Maximum_Profit_in_Job_Scheduling │ │ ├── heap&sorting.cpp │ │ ├── memoization.cpp │ │ └── recursion.cpp ├── Day28 │ └── 2225_Find_Players_With_Zero_or_One_Losses.cpp ├── Day29 │ ├── 380_Insert_Delete_GetRandom_O(1).cpp │ └── 380_Insert_Delete_GetRandom_O(1).java ├── Day3 │ └── longestPalindrome.java ├── Day30 │ ├── uniqueOccurrences.cpp │ └── unique_occurrences.py ├── Day4 │ ├── Reverse_Vowels_of_a_String.py │ └── reverseVowels.java ├── Day5 │ ├── WordSearchII.java │ └── Word_Search_II.cpp ├── Day6 │ ├── 899._Orderly_Queue.cpp │ ├── 899._Orderly_Queue.java │ ├── orderlyQueue.java │ └── orderly_queue.py ├── Day7 │ ├── 1323. Maximum 69 Number.java │ └── Maximum_69_Number.cpp ├── Day8 │ ├── 1544_ Make_The_String_Great.cpp │ ├── 1544_ Make_The_String_Great.java │ ├── makeStringGreat.java │ ├── make_the_string_great.py │ └── one_pass_solution.cpp └── Day9 │ ├── Online_Stock_Span.cpp │ ├── Online_Stock_Span.java │ └── online_stock_span.py ├── Stack └── implementation.cpp └── Topw_Interview_150 ├── 3sum.cpp ├── Matrix ├── set_matrix_zero.cpp └── spiral_matrix.cpp └── Sliding_window ├── 30.cpp └── leetcode_76.cpp /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/niveditaprity/Leetcode_Daily_Challenge/79c071be3047b9346c48a10c7338c4bfe1809d29/.DS_Store -------------------------------------------------------------------------------- /April_Leetcode_Challenge_2023/Day13/Day14/leetcode_516.cpp: -------------------------------------------------------------------------------- 1 | //Recursive solution 2 | 3 | class Solution { 4 | public: 5 | int findlongestPalindromeSubseq(string s, int start, int end) { 6 | if (start > end) { 7 | return 0; 8 | } 9 | if (start == end) { 10 | return 1; 11 | } 12 | if (s[start] == s[end]) { 13 | return 2 + findlongestPalindromeSubseq(s, start+1, end-1); 14 | } 15 | else { 16 | return max(findlongestPalindromeSubseq(s, start+1, end), findlongestPalindromeSubseq(s, start, end-1)); 17 | } 18 | } 19 | 20 | int longestPalindromeSubseq(string s) { 21 | return findlongestPalindromeSubseq(s, 0, s.size()-1); 22 | } 23 | }; 24 | 25 | // Memoization 26 | 27 | class Solution { 28 | public: 29 | int findlongestPalindromeSubseq(string&s, vector>& dp, int start, int end) { 30 | 31 | if (start > end) { 32 | return 0; 33 | } 34 | else if (start == end) { 35 | return 1; 36 | } 37 | if (dp[start][end] != -1) { 38 | return dp[start][end]; 39 | } 40 | else if (s[start] == s[end]) { 41 | return dp[start][end] = 2 + findlongestPalindromeSubseq(s, dp, start+1, end-1); 42 | } 43 | else { 44 | return dp[start][end] = max(findlongestPalindromeSubseq(s, dp, start+1, end), findlongestPalindromeSubseq(s, dp, start, end-1)); 45 | } 46 | } 47 | 48 | int longestPalindromeSubseq(string s) { 49 | int n = s.size(); 50 | vector> dp(n, vector(n, -1)); 51 | 52 | return findlongestPalindromeSubseq(s, dp, 0, n-1); 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /April_Leetcode_Challenge_2023/Day13/Validate_Stack_Sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: 3 | stack = [] 4 | i = 0 5 | for ele in pushed: 6 | stack.append(ele) 7 | while stack and stack[-1] == popped[i]: 8 | stack.pop() 9 | i+=1 10 | return i == len(popped) 11 | -------------------------------------------------------------------------------- /April_Leetcode_Challenge_2023/Day15/leetcode_2218.cpp: -------------------------------------------------------------------------------- 1 | //Recursive 2 | class Solution { 3 | public: 4 | int findMaxValueOfCoins(vector>& piles,int n, int k) 5 | { 6 | if(n< 0 || k == 0) 7 | { 8 | return 0; 9 | } 10 | int maxPick = findMaxValueOfCoins(piles,n-1,k); 11 | int totalPickedValue = 0; 12 | int currPileSize = piles[n].size(); 13 | int maxPile = min(k,currPileSize); 14 | for(int i = 0; i>& piles, int k) { 22 | int n = piles.size(); 23 | return findMaxValueOfCoins(piles, n-1, k); 24 | 25 | } 26 | }; 27 | 28 | //Memoize 29 | 30 | 31 | class Solution { 32 | public: 33 | int findMaxValueOfCoins(vector>& piles,int n, int k, vector>&dp) 34 | { 35 | if(n< 0 || k == 0) 36 | { 37 | return 0; 38 | } 39 | if(dp[n][k]!=-1) 40 | { 41 | return dp[n][k]; 42 | } 43 | int maxPick = findMaxValueOfCoins(piles,n-1,k,dp); 44 | int totalPickedValue = 0; 45 | int currPileSize = piles[n].size(); 46 | int maxPile = min(k,currPileSize); 47 | for(int i = 0; i>& piles, int k) { 56 | int n = piles.size(); 57 | vector>dp(n,vector(k+1,-1)); 58 | return findMaxValueOfCoins(piles, n-1, k, dp); 59 | 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /DSU.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class DSU { 5 | 6 | vectorparent; 7 | vectorrank; 8 | int n; 9 | public: 10 | DSU(int n) 11 | { 12 | parent.resize(n); 13 | rank.resize(n); 14 | this->n = n; 15 | for(int i = 0 ;i rank[b]) 35 | { 36 | parent[b]= a; 37 | } 38 | else if(rank[a] bool: 3 | # using set here so that 'in' operator takes O(1) to check vowel existancy. 4 | vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} 5 | mid = len(s)//2 6 | count_av, count_bv = 0, 0 7 | 8 | for i in range(mid): 9 | if s[i] in vowels: 10 | count_av += 1 11 | if s[mid+i] in vowels: 12 | count_bv += 1 13 | 14 | return count_av == count_bv -------------------------------------------------------------------------------- /December/Day10/leetcode_1339.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long int MOD = 1e9+7; 4 | long long totalSum =0, ans=0; 5 | int find(TreeNode*root) 6 | { 7 | if(root == NULL) 8 | { 9 | return 0; 10 | } 11 | long long sum =find(root->left) + find(root->right) + root->val; 12 | ans = max(ans,(totalSum-sum)*sum ); 13 | return sum; 14 | } 15 | int maxProduct(TreeNode* root) { 16 | totalSum = find(root); 17 | find(root); 18 | return ans%MOD; 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /December/Day11/124_Binary_Tree_Maximum_Path_Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans = INT_MIN; 4 | int find(TreeNode*root) 5 | { 6 | if(root == NULL) 7 | { 8 | return 0; 9 | } 10 | int left = find(root->left); 11 | int right = find(root->right); 12 | left = left>0 ? left : 0; 13 | right = right>0 ? right : 0; 14 | ans = max(ans ,root->val + left + right); 15 | return root->val + max(left,right); 16 | } 17 | int maxPathSum(TreeNode* root) { 18 | find(root); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /December/Day11/binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int compute(TreeNode* root, int &maxPath) { 4 | // if there is no further subtrees then take that subtree path as 0. 5 | if(root==NULL) { 6 | return 0; 7 | } 8 | 9 | // Traverse in both the subtrees to find the maximum path 10 | int left = compute(root->left, maxPath); 11 | int right = compute(root->right, maxPath); 12 | 13 | // Avoid subtree which is giving -ve value as it will reduce the answer for maximum path. 14 | if(left < 0) left = 0; 15 | if(right < 0) right = 0; 16 | 17 | // Answer is getting stored in maxPath variable. 18 | maxPath = max(maxPath, root->val + left + right); 19 | 20 | // Out of left and right subtrees, take only that subtree which is giving the largest value. 21 | return max(left, right) + root->val; 22 | } 23 | public: 24 | int maxPathSum(TreeNode* root) { 25 | // Initialize ans with -∞ as node values can be -ve also. 26 | int ans = INT_MIN; 27 | // Get the maximum path stored in answer variable. 28 | compute(root, ans); 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /December/Day11/binary_tree_maximum_path_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.maxsum = float("-inf") 4 | 5 | def solve(self, root): 6 | if root == None: 7 | return 0 8 | 9 | left_sum = self.solve(root.left) 10 | right_sum = self.solve(root.right) 11 | 12 | all_good_sum = left_sum + right_sum + root.val 13 | one_good_sum = max(left_sum, right_sum) + root.val 14 | only_root_is_good = root.val 15 | 16 | self.maxsum = max(self.maxsum, all_good_sum, one_good_sum, only_root_is_good) 17 | 18 | return max(one_good_sum, only_root_is_good) 19 | 20 | def maxPathSum(self, root: Optional[TreeNode]) -> int: 21 | self.solve(root) 22 | return self.maxsum -------------------------------------------------------------------------------- /December/Day12/leetcode_70.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int count(int n,int step,vector&dp) 4 | { 5 | if(step>n) 6 | { 7 | return 0; 8 | } 9 | if(step == n) 10 | { 11 | return 1; 12 | } 13 | if(dp[step]!=-1) 14 | { 15 | return dp[step]; 16 | } 17 | 18 | dp[step] = count(n,step+1,dp) + count(n,step+2,dp); 19 | return dp[step]; 20 | } 21 | int climbStairs(int n) { 22 | vectordp(n+1,-1); 23 | return count(n,0,dp); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /December/Day13/minimum-falling-path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFallingPathSum(vector>& matrix) { 4 | int n = matrix.size(); 5 | vector prevDP(matrix[0].begin(), matrix[0].end()), currDP(n, 0); 6 | 7 | // Loop through the matrix to find minimum path sum. 8 | for(int i=1; i 0) ? min(minPath, prevDP[j-1]) : minPath; 13 | minPath = (j < (n-1)) ? min(minPath, prevDP[j+1]) : minPath; 14 | 15 | // Add current cell value and prev. min. path sum to get the current min. sum path. 16 | currDP[j] = matrix[i][j] + minPath; 17 | } 18 | prevDP = currDP; 19 | } 20 | 21 | // Find the minimum sum path from the last reached row and return it. 22 | return *min_element(prevDP.begin(), prevDP.end()); 23 | } 24 | }; -------------------------------------------------------------------------------- /December/Day14/198_House_Robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[101]; 4 | int solve(int i,vector& nums) 5 | { 6 | if(i>=nums.size()) 7 | { 8 | return 0; 9 | } 10 | if(dp[i]!=-1) 11 | { 12 | return dp[i]; 13 | } 14 | int take = solve(i+2,nums) + nums[i]; 15 | int notake = solve(i+1,nums)+0; 16 | dp[i]=max(take,notake); 17 | return dp[i]; 18 | } 19 | int rob(vector& nums) { 20 | memset(dp,-1,sizeof(dp)); 21 | return solve(0,nums); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /December/Day15/longestCommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int find(string&text1, int n1, string&text2, int n2,vector>&dp) 4 | { 5 | if(n1<0 || n2<0) 6 | { 7 | return 0; 8 | } 9 | if(dp[n1][n2]!=-1) 10 | { 11 | return dp[n1][n2]; 12 | } 13 | if(text1[n1] == text2[n2]) 14 | { 15 | return dp[n1][n2] = 1 + find(text1,n1-1,text2,n2-1,dp); 16 | } 17 | return dp[n1][n2] = max(find(text1,n1-1,text2,n2,dp),find(text1,n1,text2,n2-1,dp)); 18 | } 19 | int longestCommonSubsequence(string text1, string text2) { 20 | int n1 = text1.size(); 21 | int n2 = text2.size(); 22 | vector> dp( n1 , vector (n2, -1)); 23 | return find(text1,n1-1,text2,n2-1,dp); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /December/Day16/Implement_Queue_using_Stacks.cpp: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | public: 3 | stacks1,s2; 4 | MyQueue() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | s1.push(x); 10 | } 11 | 12 | int pop() { 13 | while(!s1.empty()) 14 | { 15 | s2.push(s1.top()); 16 | s1.pop(); 17 | } 18 | int x = s2.top(); 19 | s2.pop(); 20 | while(!s2.empty()) 21 | { 22 | s1.push(s2.top()); 23 | s2.pop(); 24 | } 25 | return x; 26 | } 27 | 28 | int peek() { 29 | while(!s1.empty()) 30 | { 31 | s2.push(s1.top()); 32 | s1.pop(); 33 | } 34 | int x = s2.top(); 35 | while(!s2.empty()) 36 | { 37 | s1.push(s2.top()); 38 | s2.pop(); 39 | } 40 | return x; 41 | } 42 | 43 | bool empty() { 44 | return s1.empty(); 45 | } 46 | }; 47 | 48 | /** 49 | * Your MyQueue object will be instantiated and called as such: 50 | * MyQueue* obj = new MyQueue(); 51 | * obj->push(x); 52 | * int param_2 = obj->pop(); 53 | * int param_3 = obj->peek(); 54 | * bool param_4 = obj->empty(); 55 | */ 56 | -------------------------------------------------------------------------------- /December/Day16/implement_queue_using_stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | 3 | def __init__(self): 4 | self.stack1 = [] 5 | self.stack2 = [] 6 | 7 | def push(self, x: int) -> None: 8 | self.stack1.append(x) 9 | self.stack2.append(self.stack1.pop()) 10 | 11 | def pop(self) -> int: 12 | return self.stack2.pop(0) 13 | 14 | def peek(self) -> int: 15 | return self.stack2[0] 16 | 17 | def empty(self) -> bool: 18 | if not self.stack2: 19 | return True 20 | return False 21 | -------------------------------------------------------------------------------- /December/Day17/150._Evaluate_Reverse_Polish_Notation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector& tokens) { 4 | stackst; 5 | for(auto x : tokens) 6 | { 7 | if(x!="+" && x!="-" && x!="*" && x!="/") 8 | { 9 | st.push(stoi(x)); 10 | } 11 | else 12 | { 13 | long long a = st.top(); 14 | st.pop(); 15 | long long b = st.top(); 16 | st.pop(); 17 | if(x=="+") 18 | { 19 | st.push(a+b); 20 | } 21 | else if(x=="-") 22 | { 23 | st.push(b-a); 24 | } 25 | else if(x=="*") 26 | { 27 | st.push(a*b); 28 | } 29 | else 30 | { 31 | st.push(b/a); 32 | } 33 | } 34 | } 35 | return st.top(); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /December/Day18/739._Daily_Temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& temp) { 4 | 5 | int n = temp.size(); 6 | vector ans(n); 7 | 8 | stack< pair > s; 9 | s.push({-1, -1}); 10 | 11 | for(int i = n-1; i >= 0; i--) 12 | { 13 | while(temp[i] >= s.top().first && s.top().first != -1) 14 | { 15 | s.pop(); 16 | } 17 | if(s.top().second == -1) 18 | ans[i] = 0; 19 | else 20 | ans[i] = s.top().second-i; 21 | 22 | s.push({temp[i], i}); 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /December/Day18/739_Daily_Temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& temperatures) { 4 | int n = temperatures.size(); 5 | vectorans(n); 6 | stackst; 7 | for(int i = 0;i0 && temperatures[st.top()] < temperatures[i]) 10 | { 11 | ans[st.top()]=i-st.top(); 12 | st.pop(); 13 | } 14 | st.push(i); 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /December/Day18/daily_temperature.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | ans = [0]*len(temperatures) 4 | stack = [] 5 | n = len(temperatures) 6 | for i in range(len(temperatures)-1, -1, -1): 7 | while(stack and temperatures[stack[-1]] <= temperatures[i]): 8 | stack.pop() 9 | if not stack: 10 | ans[i] = 0 11 | else: 12 | ans[i] = stack[-1]-i 13 | stack.append(i) 14 | return ans -------------------------------------------------------------------------------- /December/Day19/1971_Find_if_Path_Exists_in_Graph/bfs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validPath(int n, vector>& edges, int source, int destination) 4 | { 5 | vectorgraph[n]; 6 | vectorvisited(n,false); 7 | queueq; 8 | for(auto x : edges) 9 | { 10 | graph[x[0]].push_back(x[1]); 11 | graph[x[1]].push_back(x[0]); 12 | } 13 | q.push(source); 14 | while(!q.empty()) 15 | { 16 | int x = q.front(); 17 | q.pop(); 18 | if(x == destination ) 19 | { 20 | return true; 21 | } 22 | for(auto ele : graph[x]) 23 | { 24 | if(!visited[ele]) 25 | { 26 | q.push(ele); 27 | visited[ele] = true; 28 | } 29 | } 30 | 31 | } 32 | return false; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /December/Day19/find_if_path_exists_in_graph.py: -------------------------------------------------------------------------------- 1 | # using bfs 2 | class Solution: 3 | def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: 4 | graph = defaultdict(list) 5 | for edge in edges: 6 | u = edge[0] 7 | v = edge[1] 8 | graph[u].append(v) 9 | graph[v].append(u) 10 | 11 | visited = [False]*n 12 | q = [] 13 | q.append(source) 14 | visited[source] = True 15 | 16 | while(len(q)): 17 | node = q.pop(0) 18 | if node == destination: 19 | return True 20 | for i in graph[node]: 21 | if not visited[i]: 22 | q.append(i) 23 | visited[i] = True 24 | return False -------------------------------------------------------------------------------- /December/Day2/1657._Determine_if_Two_Strings_Are_Close.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool closeStrings(string word1, string word2) { 4 | vectors1(26,0),s2(26,0),s3(26,0),s4(26,0); 5 | for(auto x:word1) 6 | { 7 | s1[x-'a']++; 8 | s3[x-'a'] = 1; 9 | } 10 | for(auto x:word2) 11 | { 12 | s2[x-'a']++; 13 | s4[x-'a'] = 1; 14 | } 15 | sort(s1.begin(),s1.end()); 16 | sort(s2.begin(),s2.end()); 17 | return s1 == s2 && s3 == s4; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /December/Day2/determine_if_two_strings_are_close.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def closeStrings(self, word1: str, word2: str) -> bool: 3 | # if len are not equal then return False 4 | if len(word1) != len(word2): 5 | return False 6 | 7 | sorted_w1 = sorted(word1) 8 | sorted_w2 = sorted(word2) 9 | # compare if all characters are same return True 10 | if sorted_w1 == sorted_w2: 11 | return True 12 | 13 | # using counter to cout frequency (MAP) 14 | s1 = Counter(sorted_w1) 15 | s2 = Counter(sorted_w2) 16 | 17 | # if keys and overall frequecy values are equal (mapping doesn't matter) then return True 18 | if (s1.keys() == s2.keys()) and (sorted(s1.values()) == sorted(s2.values())): 19 | return True 20 | return False -------------------------------------------------------------------------------- /December/Day20/keys_and_rooms.py: -------------------------------------------------------------------------------- 1 | # using DFS 2 | class Solution: 3 | def visit(self, graph, key, visited): 4 | visited[key] = True 5 | 6 | for room in graph[key]: 7 | if visited[room] == False: 8 | self.visit(graph, room, visited) 9 | return False 10 | 11 | 12 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 13 | visited = [False]*len(rooms) 14 | graph = dict() 15 | for i, v in enumerate(rooms): 16 | graph[i] = v 17 | visited[0] = True 18 | key = 0 19 | self.visit(graph, key, visited) 20 | return all(visited) == True -------------------------------------------------------------------------------- /December/Day21/possible_bipartition.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bfs(self, dislike_pairs, node, color): 3 | color[node] = 1 4 | queue = [] 5 | queue.append(node) 6 | 7 | while(len(queue) > 0): 8 | u = queue.pop(0) 9 | for i in dislike_pairs[u]: 10 | if(color[u] == color[i]): 11 | return False 12 | if color[i] == -1: 13 | queue.append(i) 14 | color[i] = 1 - color[u] 15 | return True 16 | 17 | def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: 18 | dislike_pairs = defaultdict(list) 19 | for i in dislikes: 20 | dislike_pairs[i[0]].append(i[1]) 21 | dislike_pairs[i[1]].append(i[0]) 22 | 23 | color = [-1]*(n+1) 24 | for i in range(1, n+1): 25 | if color[i] == -1: 26 | if(self.bfs(dislike_pairs, i, color) == False): 27 | return False 28 | return True -------------------------------------------------------------------------------- /December/Day23/leetcode_309.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans; 4 | int find(int i,int n, bool flag, vector& prices,vector>&dp) 5 | { 6 | if(i>=n) 7 | { 8 | return 0; 9 | } 10 | if(dp[flag][i] != -1) 11 | { 12 | return dp[flag][i]; 13 | } 14 | if(flag == false) 15 | { 16 | int buy = (0-prices[i]) + find(i+1,n,true,prices,dp); 17 | int notbuy = 0 + find(i+1,n,false,prices,dp); 18 | ans = max(buy,notbuy); 19 | } 20 | else 21 | { 22 | int sell = prices[i] + find(i+2,n,false,prices,dp); 23 | int notsell = find(i+1,n,true,prices,dp); 24 | ans = max(sell,notsell); 25 | } 26 | dp[flag][i] = ans; 27 | return ans; 28 | } 29 | int maxProfit(vector& prices) { 30 | int n = prices.size(); 31 | vector>dp(2,vector(n,-1)); 32 | return find(0,n,false,prices,dp); 33 | 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /December/Day24/leetcode_790_dp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long mod = 1e9+7; 4 | // int find(int n,vector&dp) 5 | // { 6 | // if(dp[n]!=-1) 7 | // { 8 | // return dp[n]; 9 | // } 10 | // dp[n]=(2*find(n-1,dp)%mod + find(n-3,dp)%mod)%mod; 11 | // return dp[n]; 12 | // } 13 | int numTilings(int n) { 14 | vectordp(1001,-1); 15 | dp[0] =1,dp[1]=1,dp[2]=2; 16 | for(int i=3;i<=n;i++) 17 | { 18 | dp[i] = (2*dp[i-1]%mod + dp[i-3]%mod)%mod; 19 | } 20 | return dp[n]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /December/Day24/leetcode_790_memo.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long mod = 1e9+7; 4 | int find(int n,vector&dp) 5 | { 6 | if(dp[n]!=-1) 7 | { 8 | return dp[n]; 9 | } 10 | dp[n]=(2*find(n-1,dp)%mod + find(n-3,dp)%mod)%mod; 11 | return dp[n]; 12 | } 13 | int numTilings(int n) { 14 | vectordp(1001,-1); 15 | dp[0] =1,dp[1]=1,dp[2]=2; 16 | return find(n,dp); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /December/Day24/leetcode_790_recrusive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long mod = 1e9+7; 4 | int find(int n) 5 | { 6 | if(n<=1) 7 | { 8 | return 1; 9 | } 10 | if(n==2) 11 | { 12 | return 2; 13 | } 14 | return (2*find(n-1)%mod + find(n-3)%mod)%mod; 15 | } 16 | int numTilings(int n) { 17 | return find(n); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /December/Day25/2389._Longest_Subsequence_With_Limited_Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector answerQueries(vector& nums, vector& queries) { 4 | 5 | int n = nums.size(); 6 | 7 | sort(nums.begin(), nums.end()); 8 | vector ans; 9 | 10 | for(auto tar : queries) 11 | { 12 | int cnt = 0; 13 | for(int i = 0; i < n; i++) 14 | { 15 | if(nums[i] <= tar) 16 | { 17 | tar = tar-nums[i]; 18 | cnt++; 19 | } 20 | else 21 | break; 22 | } 23 | ans.push_back(cnt); 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /December/Day25/answerQueries.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector answerQueries(vector& nums, vector& queries) { 4 | int n = nums.size(); 5 | int m = queries.size(); 6 | sort(nums.begin(),nums.end()); 7 | vectorpsum(n); 8 | vectorans(m); 9 | psum[0]=nums[0]; 10 | for(int i=1;i& nums) { 4 | 5 | int n = nums.size(); 6 | int lastInd = n-1; 7 | 8 | for(int i = n-1; i >= 0; i--) 9 | { 10 | if(nums[i] > 0 && i + nums[i] >= lastInd) 11 | lastInd = i; 12 | } 13 | 14 | return lastInd == 0; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /December/Day26/jump_game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int n = nums.size()-1; 5 | int lastpos = n; 6 | for(int i=n-1;i>=0;i--) 7 | { 8 | if(i+nums[i]>=lastpos) 9 | { 10 | lastpos = i; 11 | } 12 | } 13 | return lastpos == 0; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /December/Day27/2279_Maximum_Bags_With_Full_Capacity_of_Rocks.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumBags(vector& capacity, vector& rocks, int additionalRocks) { 4 | 5 | vector> nums; 6 | 7 | for(int i = 0; i < rocks.size(); i++) 8 | { 9 | nums.push_back({capacity[i]-rocks[i], rocks[i]}); 10 | } 11 | 12 | 13 | sort(nums.begin(), nums.end()); 14 | 15 | int cnt = 0; 16 | for(auto ell : nums) 17 | { 18 | if(ell.first == 0) { 19 | cnt++; 20 | continue; 21 | } 22 | 23 | if(additionalRocks >= ell.first) 24 | { 25 | cnt++; 26 | additionalRocks -= ell.first; 27 | } 28 | 29 | if(additionalRocks == 0) break; 30 | 31 | } 32 | 33 | return cnt; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /December/Day27/jsSolution: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} capacity 3 | * @param {number[]} rocks 4 | * @param {number} additionalRocks 5 | * @return {number} 6 | */ 7 | var maximumBags = function(capacity, rocks, additionalRocks) { 8 | let count =0; 9 | for (let i=0;ia-b) 13 | 14 | 15 | for (let i =0;i=capacity[i] ;i++){ 16 | additionalRocks = additionalRocks - capacity[i]; 17 | count++; 18 | } 19 | 20 | return count 21 | }; 22 | -------------------------------------------------------------------------------- /December/Day27/leetcode_2279.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumBags(vector& capacity, vector& rocks, int additionalRocks) { 4 | int n = capacity.size(); 5 | vectorans(n); 6 | for(int i=0;i0 && additionalRocks>=x) 20 | { 21 | additionalRocks -= x; 22 | count++; 23 | } 24 | } 25 | } 26 | return count; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /December/Day28/1962-leetcode.cpp: -------------------------------------------------------------------------------- 1 | // Time complexity -: O(log(n)) 2 | // space complexity -: O(n) 3 | 4 | class Solution { 5 | public: 6 | int minStoneSum(vector& piles, int k) { 7 | 8 | priority_queuepq; // O(n) 9 | 10 | for(int i = 0; i < piles.size(); i++) 11 | { 12 | pq.push(piles[i]); 13 | } 14 | 15 | while(k != 0) 16 | { 17 | int val = pq.top(); 18 | pq.pop(); 19 | pq.push(val - floor(val/2)); 20 | k--; 21 | } 22 | 23 | int ans = 0; 24 | while(!pq.empty()) 25 | { 26 | ans += pq.top(); 27 | pq.pop(); 28 | } 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /December/Day28/1962_Remove_Stones_to_Minimize_the_Total.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minStoneSum(vector& piles, int k) { 4 | 5 | priority_queue pq; 6 | 7 | for(int i = 0; i < piles.size(); i++) 8 | { 9 | pq.push(piles[i]); 10 | } 11 | 12 | while(!pq.empty() && k > 0) 13 | { 14 | k--; 15 | 16 | float el = pq.top(); 17 | pq.pop(); 18 | 19 | el = ceil(el/2); 20 | 21 | pq.push(el); 22 | } 23 | 24 | int ans = 0; 25 | while(!pq.empty()) 26 | { 27 | ans += pq.top(); 28 | pq.pop(); 29 | } 30 | return ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /December/Day28/leetcode_1962.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minStoneSum(vector& piles, int k) { 4 | priority_queuepq; 5 | for(auto x :piles) 6 | { 7 | pq.push(x); 8 | } 9 | while(k--) 10 | { 11 | int x = pq.top(); 12 | pq.pop(); 13 | pq.push(x-floor(x/2)); 14 | } 15 | int sum =0; 16 | while(!pq.empty()) 17 | { 18 | sum+=pq.top(); 19 | pq.pop(); 20 | } 21 | return sum; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /December/Day28/remove_stones_to_minimize_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minStoneSum(self, piles: List[int], k: int) -> int: 3 | pq = [-x for x in piles] 4 | heapify(pq) 5 | for _ in range(k): heapreplace(pq, pq[0]//2) 6 | return -sum(pq) 7 | -------------------------------------------------------------------------------- /December/Day29/leetcode_1834.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getOrder(vector>& tasks) { 4 | for(int i = 0; i < tasks.size(); i++) 5 | { 6 | tasks[i].push_back(i); 7 | } 8 | sort(tasks.begin(), tasks.end()); 9 | priority_queue, vector>, greater>>pq; 10 | vectorans; 11 | int maxEnqTime = 0; 12 | int i = 0; 13 | while(ans.size()=tasks[i][0]) 20 | { 21 | pq.push({tasks[i][1],tasks[i][2]}); 22 | i++; 23 | } 24 | auto x = pq.top(); 25 | pq.pop(); 26 | maxEnqTime = min(1000000000, x[0]+maxEnqTime); 27 | ans.push_back(x[1]); 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /December/Day3/451_Sort_Characters_By_Frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool static cmp(pair& a,pair& b) 4 | { 5 | return a.second > b.second; 6 | } 7 | string frequencySort(string s) { 8 | unordered_mapmp; 9 | for(int i=0;i>v; 14 | for(auto x:mp) 15 | { 16 | v.push_back({x.first,x.second}); 17 | } 18 | sort(v.begin(),v.end(),cmp); 19 | string ans; 20 | for(auto x:v) 21 | { 22 | for(int i=0;i str: 3 | c = Counter(s) 4 | s2 = "" 5 | for i, v in c.most_common(): 6 | for j in range(v): 7 | s2 += i 8 | return s2 9 | 10 | class Solution: 11 | def frequencySort(self, s: str) -> str: 12 | return "".join([i for i,v in Counter(s).most_common() for j in range(v)]) 13 | 14 | 15 | # without using Counter 16 | class Solution: 17 | def frequencySort(self, s: str) -> str: 18 | char_freq = {} 19 | for i in s: 20 | if i not in char_freq: 21 | char_freq[i] = 1 22 | else: 23 | char_freq[i] += 1 24 | 25 | sorted_by_freq = sorted(char_freq.items(), key=lambda x: x[1], reverse=True) 26 | 27 | sorted_string = "" 28 | for ch, fq in sorted_by_freq: 29 | for j in range(fq): 30 | sorted_string += ch 31 | return sorted_string -------------------------------------------------------------------------------- /December/Day31/980_Unique_Paths_III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int ans; 4 | int cnt; 5 | 6 | void dfs(int i, int j, int tar, vector>& grid, int empty) 7 | { 8 | int n = grid.size(); 9 | int m = grid[0].size(); 10 | 11 | if(i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == -1) 12 | return; 13 | 14 | if(grid[i][j] == tar && empty == cnt) 15 | { 16 | ans++; 17 | return; 18 | } 19 | 20 | int val = grid[i][j]; 21 | grid[i][j] = -1; 22 | 23 | 24 | dfs(i+1, j, tar, grid, empty+1); 25 | 26 | 27 | dfs(i-1, j, tar, grid, empty+1); 28 | 29 | 30 | dfs(i, j+1, tar, grid, empty+1); 31 | 32 | 33 | dfs(i, j-1, tar, grid, empty+1); 34 | 35 | 36 | 37 | grid[i][j] = val; 38 | return; 39 | 40 | } 41 | public: 42 | int uniquePathsIII(vector>& grid) { 43 | 44 | int n = grid.size(); 45 | int m = grid[0].size(); 46 | 47 | cnt = 0; //cnt how many 0s or empty 48 | int start_x = 0; 49 | int start_y = 0; 50 | for(int i = 0; i < n; i++) 51 | { 52 | for(int j = 0; j < m; j++) 53 | { 54 | if(grid[i][j] == 0) 55 | cnt++; 56 | 57 | if(grid[i][j] == 1) 58 | { 59 | start_x = i; 60 | start_y = j; 61 | } 62 | } 63 | } 64 | 65 | cnt++; 66 | 67 | int empty = 0; 68 | 69 | dfs(start_x, start_y, 2, grid, empty); 70 | 71 | return ans; 72 | } 73 | }; 74 | -------------------------------------------------------------------------------- /December/Day4/minimum-average-difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumAverageDifference(vector& nums) { 4 | int n = nums.size(); 5 | 6 | // Calculate sum of all elements on nums. 7 | long long totalSum = 0; 8 | for(int i=0; i 0) { 33 | rightAvg = rightSum/rightNums; 34 | } 35 | 36 | // Calculate the absolute difference between left avg. and right avg. 37 | int avg = abs(leftAvg - rightAvg); 38 | 39 | // If the absolute difference is less than the prev. absolute difference. 40 | if(avg < minAvg) { 41 | ans = i; 42 | minAvg = avg; 43 | } 44 | } 45 | 46 | return ans; 47 | } 48 | }; -------------------------------------------------------------------------------- /December/Day4/minimun-avaerage-difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumAverageDifference(self, nums: List[int]) -> int: 3 | total_sum = sum(nums) 4 | presum = 0 5 | len_n = len(nums) 6 | min_avg = float("inf") 7 | min_key = None 8 | for i, v in enumerate(nums): 9 | presum += v 10 | ab1 = presum//(i+1) 11 | divs = len_n-i-1 12 | if divs <=0: 13 | ab2 = total_sum - presum 14 | else: 15 | ab2 = (total_sum - presum)// divs 16 | abs_diff = abs(ab1-ab2) 17 | if abs_diff< min_avg: 18 | min_avg = abs_diff 19 | min_key = i 20 | return min_key 21 | 22 | # using extra space (map) 23 | class Solution: 24 | def minimumAverageDifference(self, nums: List[int]) -> int: 25 | d = {} 26 | total_sum = sum(nums) 27 | presum = 0 28 | len_n = len(nums) 29 | for i, v in enumerate(nums): 30 | presum += v 31 | ab1 = presum//(i+1) 32 | divs = len_n-i-1 33 | if divs <=0: 34 | ab2 = total_sum - presum 35 | else: 36 | ab2 = (total_sum - presum)// divs 37 | 38 | d.update({i: abs(ab1 - ab2)}) 39 | return min(d.items(), key=lambda x: x[1])[0] -------------------------------------------------------------------------------- /December/Day5/middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* middleNode(ListNode* head) { 4 | ListNode *slow = head, *fast = head; 5 | 6 | while(fast && fast->next) { 7 | slow = slow->next; 8 | fast = fast->next->next; 9 | } 10 | 11 | return slow; 12 | } 13 | }; -------------------------------------------------------------------------------- /December/Day5/middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def middle(self, head): 3 | slow, fast = head, head.next 4 | 5 | while (fast.next and fast.next.next): 6 | slow = slow.next 7 | fast = fast.next.next 8 | 9 | return slow 10 | 11 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 12 | if not head.next: 13 | return head 14 | middle = self.middle(head) 15 | return middle.next -------------------------------------------------------------------------------- /December/Day5/middle_of_the_linked_list.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | slow = fast = head 4 | while fast and fast.next: 5 | slow = slow.next 6 | fast = fast.next.next 7 | return slow -------------------------------------------------------------------------------- /December/Day6/328_Odd_Even_Linked_List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* oddEvenList(ListNode* head) { 4 | if(head == NULL) 5 | { 6 | return NULL; 7 | } 8 | ListNode*odd = head; 9 | ListNode*even = head->next; 10 | ListNode*temp = even; 11 | while(even && even->next) 12 | { 13 | odd->next = even->next; 14 | odd = odd->next; 15 | even->next = odd->next; 16 | even = even->next; 17 | } 18 | odd->next= temp; 19 | return head; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /December/Day6/odd-even-linked-list.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* oddEvenList(ListNode* head) { 4 | // If there is no node inside the list, return NULL. 5 | if(head == NULL) { 6 | return head; 7 | } 8 | 9 | // Keep odd pointer on the 1st node and even pointer on the 2nd node. 10 | ListNode *odd = head, *even = head->next; 11 | // 2nd node will be the 1st even node in the list. Take this node as head of even list. 12 | ListNode* evenHead = head->next; 13 | 14 | // At every iteration, connect odd node to next odd node and even node to next even node. 15 | while(even && even->next) { 16 | odd->next = even->next; 17 | even->next = even->next->next; 18 | 19 | // Update odd and even pointer for next iteration. 20 | odd = odd->next; 21 | even = even->next; 22 | } 23 | 24 | // Connect the odd nodes linked list to even nodes linked list. 25 | odd->next = evenHead; 26 | return head; 27 | } 28 | }; -------------------------------------------------------------------------------- /December/Day6/odd_even_linked_list.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | if head == None or head.next == None: 4 | return head 5 | odd = head 6 | even = head.next 7 | temp = even 8 | while even and even.next: 9 | odd.next = even.next 10 | odd = odd.next 11 | even.next = odd.next 12 | even = even.next 13 | odd.next = temp 14 | return head -------------------------------------------------------------------------------- /December/Day7/range-sum-of-bst.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeSumBST(TreeNode* root, int low, int high) { 4 | if(root == NULL) { 5 | return 0; 6 | } 7 | 8 | // Get the current node value. 9 | int currVal = root->val; 10 | // If the node value is within range, take the value into sum else leave it. 11 | int sum = (currVal >= low && currVal <= high) ? currVal : 0; 12 | 13 | // If the current node >= low, go to left to find the node with lesser value. 14 | if(currVal >= low) { 15 | sum += rangeSumBST(root->left, low, high); 16 | } 17 | 18 | // If the current node <= high, go to right to find the node with greater value. 19 | if(currVal <= high) { 20 | sum += rangeSumBST(root->right, low, high); 21 | } 22 | 23 | // Return the final sum. 24 | return sum; 25 | } 26 | }; -------------------------------------------------------------------------------- /December/Day7/rangeSumBST.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 sum = 0; 15 | int rangeSumBST(TreeNode* root, int low, int high) { 16 | if(root == NULL) 17 | { 18 | return 0; 19 | } 20 | if(root->val >= low && root->val <= high) 21 | { 22 | sum+=root->val; 23 | } 24 | rangeSumBST(root->left,low,high); 25 | rangeSumBST(root->right,low,high); 26 | return sum; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /December/Day7/range_sum_of_bst.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.total = 0 4 | 5 | def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: 6 | if root == None: 7 | return 8 | if root.val >= low and root.val <= high: 9 | self.total += root.val 10 | self.rangeSumBST(root.left, low, high) 11 | self.rangeSumBST(root.right, low, high) 12 | return self.total 13 | 14 | 15 | # Optimized solution based on value comparison 16 | class Solution: 17 | 18 | def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: 19 | if root == None: 20 | return 0 21 | 22 | total = root.val if root.val >= low and root.val <= high else 0 23 | 24 | if root.val >= low: 25 | total += self.rangeSumBST(root.left, low, high) 26 | if root.val <= high: 27 | total += self.rangeSumBST(root.right, low, high) 28 | 29 | return total -------------------------------------------------------------------------------- /December/Day8/leafSimilar.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 | void preorder(TreeNode*root,vector&leafNodes) 15 | { 16 | if(root==NULL) 17 | { 18 | return; 19 | } 20 | if(root && root->left == NULL && root->right== NULL) 21 | { 22 | leafNodes.push_back(root->val); 23 | } 24 | preorder(root->left,leafNodes); 25 | preorder(root->right,leafNodes); 26 | } 27 | bool leafSimilar(TreeNode* root1, TreeNode* root2) { 28 | vectorleafNodes1,leafNodes2; 29 | preorder(root1,leafNodes1); 30 | preorder(root2,leafNodes2); 31 | int n = leafNodes1.size(); 32 | if(leafNodes1 == leafNodes2) 33 | { 34 | return true; 35 | } 36 | return false; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /December/Day8/leaf_similar_trees.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.l1 = [] 4 | self.l2 = [] 5 | 6 | def get_leaves(self, root, l): 7 | if root == None: 8 | return 9 | if root.left == None and root.right == None: 10 | l.append(root.val) 11 | 12 | self.get_leaves(root.left, l) 13 | self.get_leaves(root.right, l) 14 | 15 | def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: 16 | 17 | self.get_leaves(root1, self.l1) 18 | self.get_leaves(root2, self.l2) 19 | return self.l1 == self.l2 -------------------------------------------------------------------------------- /December/Day9/leetcode_1026.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int find(TreeNode*root,int maxNum,int minNum) 4 | { 5 | if(root==NULL) 6 | { 7 | return maxNum-minNum; 8 | } 9 | maxNum = max(maxNum,root->val); 10 | minNum = min(minNum,root->val); 11 | 12 | return max(find(root->left,maxNum,minNum),find(root->right,maxNum,minNum)); 13 | } 14 | 15 | int maxAncestorDiff(TreeNode* root) { 16 | int maxNum = 0,minNum =100000; 17 | return find(root,maxNum,minNum); 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /December/Day9/maximum_difference_btw_node_n_ancestors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.maxV = 0 4 | self.minV = 100_000 5 | 6 | def get_diff(self, root, min_value, max_value): 7 | if root == None: 8 | return abs(max_value - min_value) 9 | 10 | min_value = min(min_value, root.val) 11 | max_value = max(max_value, root.val) 12 | 13 | res1 = self.get_diff(root.left, min_value, max_value) 14 | res2 = self.get_diff(root.right, min_value, max_value) 15 | return max(res2, res1) 16 | 17 | 18 | def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: 19 | return self.get_diff(root, self.minV, self.maxV) -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day1/leetcode_1071.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string gcdOfStrings(string str1, string str2) { 4 | int n1 = str1.size(); 5 | int n2 = str2.size(); 6 | if(str1 + str2 != str2 + str1) 7 | { 8 | return ""; 9 | } 10 | return str1.substr(0,gcd(n1,n2)); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day1/leetcode_1071.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def gcd(a,b): 3 | if a == 0: 4 | return b 5 | return gcd(a,b%a) 6 | def gcdOfStrings(self, str1: str, str2: str) -> str: 7 | n1 = len(str1) 8 | n2 = len(str2) 9 | if str1+str2 != str2 + str1: 10 | return "" 11 | return str1[0:gcd(n1,n2)] 12 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day14/leetcode_67.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | 5 | int i = a.size()-1,j = b.size()-1,carry = 0,sum = 0; 6 | string ans; 7 | while(i>= 0 || j>=0) 8 | { 9 | sum = carry; 10 | if(i >= 0) 11 | { 12 | sum += (a[i]-'0'); 13 | i--; 14 | } 15 | if(j >= 0) 16 | { 17 | sum += (b[j]-'0'); 18 | j--; 19 | } 20 | if(sum>1) 21 | { 22 | ans += to_string(sum%2); 23 | carry = 1; 24 | } 25 | else 26 | { 27 | carry = 0; 28 | ans += to_string(sum); 29 | } 30 | } 31 | if(carry == 1) 32 | { 33 | ans += ("1"); 34 | } 35 | reverse(ans.begin(),ans.end()); 36 | return ans; 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day15/leetcode_989.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector addToArrayForm(vector& num, int k) { 4 | 5 | int n = num.size()-1; 6 | int carry = 0; 7 | for(int i = n; i>=0; i--) 8 | { 9 | int sum = num[i] + carry + k%10; 10 | num[i] = sum%10; 11 | carry = sum/10; 12 | k = k/10; 13 | if(k==0 && carry==0) 14 | { 15 | break; 16 | } 17 | } 18 | while(k){ 19 | int val = k%10 + carry; 20 | k/=10; 21 | num.insert(num.begin(), val%10); 22 | carry = val/10; 23 | } 24 | if(carry){ 25 | num.insert(num.begin(), carry); 26 | } 27 | return num; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day17/leetcode_783.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 prev = -1; 15 | int ans = INT_MAX; 16 | void solve(TreeNode*root) 17 | { 18 | if(root == NULL) 19 | { 20 | return; 21 | } 22 | solve(root->left); 23 | if(prev!=-1) 24 | { 25 | ans = min(ans,root->val-prev); 26 | } 27 | prev = root->val; 28 | solve(root->right); 29 | } 30 | int minDiffInBST(TreeNode* root) { 31 | 32 | solve(root); 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day19/leetcode_103.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 | vector> zigzagLevelOrder(TreeNode* root) { 15 | vector>v; 16 | queueq; 17 | if(!root) 18 | { 19 | return v; 20 | } 21 | q.push(root); 22 | int level=0; 23 | while(!q.empty()) 24 | { 25 | int n=q.size(); 26 | vectorvec; 27 | for(int i=0;ival); 32 | 33 | if(value->left) 34 | { 35 | q.push(value->left); 36 | } 37 | if(value->right) 38 | { 39 | q.push(value->right); 40 | } 41 | 42 | } 43 | if(level%2 != 0) 44 | { 45 | reverse(vec.begin(),vec.end()); 46 | } 47 | v.push_back(vec); 48 | vec.clear(); 49 | level++; 50 | } 51 | return v; 52 | 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day2/Verifying an Alien Dictionary.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def isAlienSorted(self, words: List[str], order: str) -> bool: 4 | 5 | lookup = {c:ind for ind,c in enumerate(order)} 6 | 7 | word2 = [] 8 | for w in words: 9 | temp = [] 10 | for c in w: 11 | temp.append(lookup[c]) 12 | word2.append(temp) 13 | 14 | for i in range(1, len(word2)): 15 | if word2[i-1] > word2[i]: 16 | return False 17 | return True 18 | 19 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day2/leetcode_953.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAlienSorted(vector& words, string order) { 4 | unordered_mapmp; 5 | for(int i = 0; imp[w2[j]]) 22 | { 23 | return false; 24 | } 25 | if(j == n-1 && w1.size()>w2.size()) 26 | { 27 | return false; 28 | } 29 | } 30 | 31 | } 32 | 33 | 34 | return true; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day3/leetcode_6.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int numRows) { 4 | vectorans(numRows); 5 | if(numRows ==1) 6 | { 7 | return s; 8 | } 9 | bool flag = false; 10 | int i = 0; 11 | for(auto ch : s) 12 | { 13 | ans[i]+=ch; 14 | if(i == 0 || i == numRows-1) 15 | { 16 | flag = !flag; 17 | } 18 | if(flag) 19 | { 20 | i+=1; 21 | } 22 | else 23 | { 24 | i-=1; 25 | } 26 | } 27 | string zigzag=""; 28 | for(auto str:ans) 29 | { 30 | zigzag+=str; 31 | } 32 | return zigzag; 33 | 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /February_Leetcode_Challenge/Day4/567_leetcode.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | int n1 = s1.size(); 5 | int n2 = s2.size(); 6 | if(n1 > n2) 7 | { 8 | return false; 9 | } 10 | sort(s1.begin(),s1.end()); 11 | for(int i = 0; is2.size()) 5 | { 6 | return false; 7 | } 8 | vectorv1(26,0); 9 | vectorv2(26,0); 10 | for(auto ch: s1) 11 | { 12 | v1[ch-'a']++; 13 | } 14 | int i = 0 , j = 0; 15 | while(j findAnagrams(string s, string p) { 4 | vectorans; 5 | if(s.size()v1(26,0); 10 | vectorv2(26,0); 11 | for(auto ch: p) 12 | { 13 | v1[ch-'a']++; 14 | } 15 | int i = 0 , j = 0; 16 | while(j& fruits) { 4 | int ans = 0; 5 | mapmp; 6 | int i =0 ,j =0,n = fruits.size(); 7 | while(i2) 11 | { 12 | if(mp[fruits[j]] == 1) 13 | { 14 | mp.erase(fruits[j]); 15 | } 16 | else 17 | { 18 | mp[fruits[j]]--; 19 | } 20 | j++; 21 | } 22 | ans = max(i-j+1,ans); 23 | i++; 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /January/Day1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string s) { 4 | 5 | stringstream ss(s); 6 | string word; 7 | 8 | vectorwords; 9 | 10 | while(ss >> word) 11 | { 12 | words.push_back(word); 13 | } 14 | 15 | if(words.size() != pattern.size()){ 16 | return false; 17 | } 18 | 19 | unordered_mapm; 20 | setused; 21 | 22 | 23 | for(int i = 0; i < words.size(); i++) 24 | { 25 | if(m.count(pattern[i])) 26 | { 27 | if(m[pattern[i]] != words[i]) 28 | { 29 | return false; 30 | } 31 | } 32 | else 33 | { 34 | if(used.find(words[i]) != used.end()) 35 | { 36 | return false; 37 | } 38 | } 39 | 40 | m[pattern[i]] = words[i]; 41 | used.insert(words[i]); 42 | } 43 | 44 | return true; 45 | } 46 | }; -------------------------------------------------------------------------------- /January/Day1/word_pattern.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/word-pattern/description/ 2 | 3 | class Solution { 4 | public: 5 | void split(string &s,vector&ans) 6 | { 7 | istringstream ss(s); 8 | 9 | string word; 10 | while (ss >> word) 11 | { 12 | ans.push_back(word); 13 | } 14 | } 15 | bool wordPattern(string pattern, string s) { 16 | unordered_mapmp; 17 | vectorv; 18 | unordered_settaken; 19 | split(s, v); 20 | if(pattern.size()!=v.size()) 21 | { 22 | return false; 23 | } 24 | for(int i=0;i>&adj, vector&ans,vector&mp,int curr,int prev) 4 | { 5 | int prevCount = mp[labels[curr]-'a']; 6 | mp[labels[curr]-'a']++; 7 | 8 | for(int&ele : adj[curr]) 9 | { 10 | if(ele!= prev) 11 | { 12 | dfs(labels,adj,ans,mp,ele,curr); 13 | } 14 | } 15 | ans[curr] = mp[labels[curr]-'a']-prevCount; 16 | } 17 | vector countSubTrees(int n, vector>& edges, string labels) { 18 | 19 | vector>adj(n); 20 | for(auto ele : edges) 21 | { 22 | adj[ele[0]].push_back(ele[1]); 23 | adj[ele[1]].push_back(ele[0]); 24 | } 25 | vectorans(n); 26 | vectormp(26,0); 27 | dfs(labels,adj,ans,mp,0,-1); 28 | return ans; 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /January/Day12/leetcode_1519.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int[] countSubTrees(int n, int[][] edges, String labels) { 4 | int []ans=new int[n]; 5 | List> ls = new ArrayList<>(); 6 | for(int i=0;i(0)); 8 | } 9 | for(int i=0;i> ls,String labels,boolean [] visited,int [] label,int i,int []ans){ 20 | if(visited[i]==true)return; 21 | visited[i]=true; 22 | int prevCount = label[labels.charAt(i)-'a']; 23 | label[labels.charAt(i)-'a']++; 24 | for(int index:ls.get(i)){ 25 | if(visited[index]!=true){ 26 | dfs(ls,labels,visited,label,index,ans); 27 | 28 | } 29 | 30 | 31 | } 32 | ans[i]=label[labels.charAt(i)-'a']-prevCount; 33 | //label=new int[26]; 34 | return ; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /January/Day13/leetcode_2246.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(vector>&adj,vector&dist,string&s,int curr,int &ans) 4 | { 5 | dist[curr] = 1; 6 | for(int& x : adj[curr]) 7 | { 8 | dfs(adj,dist,s,x,ans); 9 | if(s[x] != s[curr] ) 10 | { 11 | ans = max(ans,dist[curr]+dist[x]); 12 | dist[curr] = max(dist[curr],dist[x]+1); 13 | } 14 | } 15 | } 16 | int longestPath(vector& parent, string s) { 17 | int n = parent.size(); 18 | vector>adj(n); 19 | vectordist(n); 20 | for(int i = 1;iparent; 4 | vectorrank; 5 | int find(int x) { 6 | if (x == parent[x]) { 7 | return x; 8 | } 9 | return parent[x] = find(parent[x]); 10 | } 11 | 12 | void Union(int x, int y) { 13 | int p1 = find(x), p2 = find(y); 14 | if (p1 != p2) { 15 | if (rank[p1] > rank[p2]) { 16 | parent[p2] = p1; 17 | rank[p1] += rank[p2]; 18 | } 19 | else { 20 | parent[p1] = p2; 21 | rank[p2] ++; 22 | } 23 | } 24 | } 25 | int numberOfGoodPaths(vector& vals, vector>& edges) { 26 | int n = vals.size(); 27 | vectoradj[n]; 28 | for (auto edge : edges) { 29 | adj[edge[0]].push_back(edge[1]); 30 | adj[edge[1]].push_back(edge[0]); 31 | } 32 | rank.resize(n); 33 | parent.resize(n); 34 | for (int i = 0; i < n; i++) 35 | { 36 | rank[i] = 0; 37 | parent[i] = i; 38 | } 39 | 40 | map>Node; 41 | for (int i = 0; i < n; i++) { 42 | Node[vals[i]].push_back(i); 43 | } 44 | int ans = 0; 45 | 46 | for (auto[value,nodes] : Node) { 47 | for (auto node: nodes) { 48 | for (auto neighbour : adj[node]) { 49 | if (vals[neighbour] <= vals[node]) { 50 | Union(node, neighbour); 51 | } 52 | } 53 | } 54 | 55 | unordered_mapfreq; 56 | for (auto node : nodes) { 57 | freq[find(node)]++; 58 | } 59 | for (auto it : freq) { 60 | int count = (it.second * (it.second+1)) / 2; 61 | ans += count; 62 | } 63 | } 64 | return ans; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /January/Day16/57_Insert_Interval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> insert(vector>& intervals, vector& newInterval) { 4 | vector>ans; 5 | 6 | for(auto interval : intervals) 7 | { 8 | if(interval[1]< newInterval[0]) 9 | { 10 | ans.push_back(interval); 11 | } 12 | else if(interval[0]>newInterval[1]) 13 | { 14 | ans.push_back(newInterval); 15 | newInterval = interval; 16 | } 17 | else 18 | { 19 | newInterval[0] = min(newInterval[0],interval[0]); 20 | newInterval[1] = max(newInterval[1],interval[1]); 21 | } 22 | } 23 | 24 | ans.push_back(newInterval); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /January/Day16/57_Insert_Interval.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] insert(int[][] intervals, int[] newInterval) { 3 | List ls = new ArrayList<>(); 4 | for(int [] p:intervals){ 5 | if(p[1] List[List[int]]: 3 | ans = [] 4 | for interval in intervals: 5 | if interval[1] < newInterval[0]: 6 | ans.append(interval) 7 | elif newInterval[1] < interval[0]: 8 | ans.append(newInterval) 9 | newInterval = interval 10 | else : 11 | newInterval[0] = min(interval[0], newInterval[0]) 12 | newInterval[1] = max(interval[1], newInterval[1]) 13 | ans.append(newInterval) 14 | return ans 15 | -------------------------------------------------------------------------------- /January/Day17/minFlipsMonoIncr.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFlipsMonoIncr(string s) { 4 | int countFlip = 0; 5 | int countOne = 0; 6 | for(int i = 0 ;i0) 15 | { 16 | countFlip++; 17 | } 18 | } 19 | if(countOne < countFlip) 20 | { 21 | countFlip = countOne; 22 | } 23 | } 24 | return countFlip; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /January/Day17/minFlipsMonoIncr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minFlipsMonoIncr(String s) { 3 | int countone=0; 4 | int flip=0; 5 | for(char c:s.toCharArray()){ 6 | if(c=='1')countone++; 7 | if(c=='0' && countone>0)flip++; 8 | flip= Math.min(countone,flip); 9 | } 10 | return flip; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /January/Day18/maximum-sum-circular-subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubarraySumCircular(int[] nums) { 3 | int totalsum=0; 4 | int maxcurr=0; 5 | int maxsum=nums[0]; 6 | int mincurr=0; 7 | int minsum=nums[0]; 8 | for(int el:nums){ 9 | maxcurr=Math.max(maxcurr+el,el); 10 | maxsum=Math.max(maxcurr,maxsum); 11 | 12 | mincurr=Math.min(mincurr+el,el); 13 | minsum=Math.min(mincurr,minsum); 14 | 15 | totalsum+=el; 16 | } 17 | return maxsum>0?Math.max(maxsum,totalsum-minsum):maxsum; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /January/Day19/leetcode_974.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraysDivByK(vector& nums, int k) { 4 | int count = 0; 5 | unordered_mapmp; 6 | int sum = 0; 7 | mp[0]++; 8 | for(auto x:nums) 9 | { 10 | sum+=x; 11 | if(mp[(sum%k+k)%k]>0) 12 | { 13 | count+=mp[(sum%k+k)%k]; 14 | } 15 | mp[(sum%k+k)%k]++; 16 | } 17 | return count; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /January/Day19/leetcode_974.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraysDivByK(int[] nums, int k) { 3 | int count=0; 4 | int runningsum=0; 5 | HashMap map = new HashMap<>(); 6 | map.put(0,1); 7 | for(int num:nums){ 8 | runningsum+=num; 9 | int rem=runningsum%k; 10 | rem=rem<0?rem+k:rem; 11 | if(map.containsKey(rem)){ 12 | count=count+map.get(rem); 13 | map.put(rem,map.getOrDefault(rem,0)+1); 14 | } 15 | else{ 16 | map.put(rem,1); 17 | } 18 | } 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /January/Day2/detect_capital.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def detectCapitalUse(self, word: str) -> bool: 3 | if word.isupper(): 4 | return True 5 | elif word.islower(): 6 | return True 7 | elif word.capitalize() == word: 8 | return True 9 | else: 10 | return False -------------------------------------------------------------------------------- /January/Day2/leetcode_520.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool detectCapitalUse(string word) { 4 | 5 | bool allUpper = true, allLower = true; 6 | if(word.size() == 0 or word.size() == 1) 7 | { 8 | return true; 9 | } 10 | for(int i = 1 ; i='A'&& word.charAt(0)<='Z'){ 5 | if(word.length()>=2 && word.charAt(1)>='A' && word.charAt(1)<='Z'){ 6 | isAllCapital=true; 7 | } 8 | else 9 | isAllCapital=false; 10 | } 11 | else 12 | isAllCapital=false; 13 | for(int i=1;i='a' && word.charAt(i)<='z') 15 | return false; 16 | if(isAllCapital==false && word.charAt(i)>='A' && word.charAt(i)<='Z') 17 | return false; 18 | 19 | } 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /January/Day20/leetcode_491.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map,int>mp; 4 | void solve(vector>&ans, vector&temp,vector& nums,int i) 5 | { 6 | if(i>nums.size()) 7 | { 8 | return; 9 | } 10 | if(temp.size()>=2) 11 | { 12 | if(mp[temp]>=1) 13 | { 14 | return; 15 | } 16 | mp[temp]++; 17 | ans.push_back(temp); 18 | } 19 | for(int j = i ;j=1 && nums[j]< temp[temp.size()-1]) 22 | { 23 | continue; 24 | } 25 | temp.push_back(nums[j]); 26 | solve(ans,temp,nums,j+1); 27 | temp.pop_back(); 28 | } 29 | } 30 | vector> findSubsequences(vector& nums) { 31 | vector>ans; 32 | vectortemp; 33 | solve(ans,temp,nums,0); 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /January/Day21/93._Restore_IP_Addresses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isvalid(string s) 4 | { 5 | int n=s.size(); 6 | if(n==1){ 7 | return true; 8 | } 9 | if(n>3||s[0]=='0'){ 10 | return false; 11 | } 12 | int num =stoi(s); 13 | if(num>255){ 14 | return false; 15 | } 16 | return true; 17 | } 18 | void solve(vector&ans,string temp, int i,int part, string s) 19 | { 20 | if(s.size() == i && part == 4) 21 | { 22 | ans.push_back(temp.substr(0,temp.size()-1)); 23 | return; 24 | } 25 | else if(s.size()== i || part == 4) 26 | { 27 | return; 28 | } 29 | solve(ans,temp+s[i]+"." ,i+1,part+1,s); 30 | if(s.size()>i+1 && isvalid(s.substr(i,2))) 31 | { 32 | solve(ans,temp+s.substr(i,2)+".",i+2,part+1,s); 33 | } 34 | if(s.size()>i+2 && isvalid(s.substr(i,3))) 35 | { 36 | solve(ans,temp+s.substr(i,3)+".",i+3,part+1,s); 37 | } 38 | 39 | } 40 | vector restoreIpAddresses(string s) { 41 | vectorans; 42 | if(s.size()>12 || s.size()<4) 43 | { 44 | return ans; 45 | } 46 | string temp; 47 | solve(ans,temp,0,0,s); 48 | return ans; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /January/Day22/leetcode_131.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool isPalindrome(string S){ 5 | string P = S; 6 | reverse(P.begin(), P.end()); 7 | 8 | 9 | if (S == P) { 10 | return true; 11 | } 12 | 13 | return false; 14 | } 15 | void solve(vector>&ans, vector&temp,string s) 16 | { 17 | if(s.size() == 0) 18 | { 19 | ans.push_back(temp); 20 | return; 21 | } 22 | for(int j=0;j> partition(string s) { 34 | vector>ans; 35 | vectortemp; 36 | solve(ans,temp,s); 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /January/Day23/leetcode_997.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | vector>v(n+1,{0,0}); 5 | for(int i=0;i findAllConcatenatedWordsInADict(vector& words) { 4 | 5 | vector res; 6 | int size=words.size(); 7 | unordered_map mp; 8 | for(auto word : words) 9 | { 10 | mp[word]++; 11 | } 12 | for(int i=0;i=2) 15 | { 16 | res.push_back(words[i]); 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | 23 | 24 | int solve(string&s, int index, int part, int n,unordered_map&mp){ 25 | 26 | if(index>=n) 27 | return part; 28 | 29 | 30 | string temp=""; 31 | for(int i=index;i=2) 38 | return ans; 39 | } 40 | } 41 | 42 | return -1; 43 | 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /January/Day28/leetcode_352.cpp: -------------------------------------------------------------------------------- 1 | class SummaryRanges { 2 | public: 3 | setnums; 4 | SummaryRanges() { 5 | 6 | } 7 | 8 | void addNum(int value) { 9 | nums.insert(value); 10 | } 11 | 12 | vector> getIntervals() { 13 | vector>res; 14 | int start = -1,end = -1; 15 | for(auto &ele : nums) 16 | { 17 | if(start == -1) 18 | { 19 | start = ele; 20 | end = ele; 21 | } 22 | else if(ele == end+1) 23 | { 24 | end = ele; 25 | } 26 | else 27 | { 28 | res.push_back({start,end}); 29 | start = ele; 30 | end = ele; 31 | } 32 | 33 | } 34 | if(start!=-1) 35 | { 36 | res.push_back({start,end}); 37 | } 38 | return res; 39 | 40 | } 41 | }; 42 | 43 | /** 44 | * Your SummaryRanges object will be instantiated and called as such: 45 | * SummaryRanges* obj = new SummaryRanges(); 46 | * obj->addNum(value); 47 | * vector> param_2 = obj->getIntervals(); 48 | */ 49 | -------------------------------------------------------------------------------- /January/Day29/460._LFU_Cache.cpp: -------------------------------------------------------------------------------- 1 | class Node 2 | { 3 | public: 4 | int val,key,freq; 5 | Node*prev,*next; 6 | Node(int key,int val) 7 | { 8 | this->key = key; 9 | this->val = val; 10 | freq = 1; 11 | } 12 | }; 13 | 14 | class List { 15 | public: 16 | int len; 17 | Node *head, *tail; 18 | 19 | List() { 20 | head = new Node(-1, -1); 21 | tail = new Node(-1, -1); 22 | head->next = tail; 23 | tail->prev = head; 24 | len = 0; 25 | } 26 | void addNode(Node*newNode) 27 | { 28 | Node*temp = head->next; 29 | head->next = newNode; 30 | newNode->prev = head; 31 | newNode->next = temp; 32 | temp->prev = newNode; 33 | len++; 34 | } 35 | 36 | void deleteNode(Node*node) 37 | { 38 | Node*delPrev = node->prev; 39 | Node*delNext = node->next; 40 | delPrev->next = delNext; 41 | delNext->prev = delPrev; 42 | len--; 43 | } 44 | }; 45 | 46 | class LFUCache { 47 | public: 48 | unordered_map addOfKey; 49 | unordered_map freqListMap; 50 | int minFreq, currSize; 51 | int cacheCapacity; 52 | LFUCache(int capacity) { 53 | cacheCapacity = capacity; 54 | minFreq = 0; 55 | currSize = 0; 56 | } 57 | 58 | int get(int key) { 59 | if (addOfKey.find(key) == addOfKey.end()) { 60 | return -1; 61 | } 62 | Node *resNode = addOfKey[key]; 63 | int res = resNode->val; 64 | updateFreq(resNode); 65 | return res; 66 | } 67 | 68 | void put(int key, int value) { 69 | if(cacheCapacity == 0) 70 | { 71 | return; 72 | } 73 | if(addOfKey.find(key) != addOfKey.end()) 74 | { 75 | Node*availNode = addOfKey[key]; 76 | availNode->val = value; 77 | updateFreq(availNode); 78 | } 79 | else 80 | { 81 | if (currSize == cacheCapacity) { 82 | List *list = freqListMap[minFreq]; 83 | Node *prevNode = list->tail->prev; 84 | int keyRemoved = prevNode->key; 85 | addOfKey.erase(keyRemoved); 86 | freqListMap[minFreq]->deleteNode(prevNode); 87 | currSize--; 88 | } 89 | currSize++; 90 | minFreq = 1; 91 | 92 | List *listFreq = new List(); 93 | if (freqListMap.find(minFreq) != freqListMap.end()) { 94 | listFreq = freqListMap[minFreq]; 95 | } 96 | Node *newNode = new Node(key, value); 97 | listFreq->addNode(newNode); 98 | addOfKey[key] = newNode; 99 | freqListMap[minFreq] = listFreq; 100 | 101 | } 102 | } 103 | 104 | void updateFreq(Node*node) 105 | { 106 | addOfKey.erase(node->key); 107 | freqListMap[node->freq]->deleteNode(node); 108 | if (node->freq == minFreq && freqListMap[node->freq]->len == 0) { 109 | minFreq++; 110 | } 111 | List *nextHigherFreqList = new List(); 112 | if (freqListMap.find(node->freq + 1) != freqListMap.end()) { 113 | nextHigherFreqList = freqListMap[node->freq + 1]; 114 | } 115 | node->freq += 1; 116 | nextHigherFreqList->addNode(node); 117 | freqListMap[node->freq] = nextHigherFreqList; 118 | addOfKey[node->key] = node; 119 | } 120 | }; 121 | 122 | /** 123 | * Your LFUCache object will be instantiated and called as such: 124 | * LFUCache* obj = new LFUCache(capacity); 125 | * int param_1 = obj->get(key); 126 | * obj->put(key,value); 127 | */ 128 | -------------------------------------------------------------------------------- /January/Day3/delete_columns_to_make_sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDeletionSize(self, strs: List[str]) -> int: 3 | 4 | count = 0 5 | for row in range(len(strs[0])): 6 | s = [] 7 | for col in range(len(strs)): 8 | s.append(strs[col][row]) 9 | 10 | if sorted(s) != s: 11 | count += 1 12 | return count 13 | 14 | 15 | class Solution: 16 | def minDeletionSize(self, strs: List[str]) -> int: 17 | 18 | count = 0 19 | for row in range(len(strs[0])): 20 | for col in range(1, len(strs)): 21 | if strs[col][row] < strs[col-1][row]: 22 | count += 1 23 | break 24 | return count -------------------------------------------------------------------------------- /January/Day3/leetcode_944.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDeletionSize(vector& strs) { 4 | 5 | int ans = 0; 6 | 7 | for(int j = 0; jstrs[i][j]) 12 | { 13 | ans++; 14 | break; 15 | } 16 | } 17 | } 18 | return ans; 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /January/Day3/leetcode_944.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDeletionSize(String[] strs) { 3 | int count=0; 4 | for(int i=0;i>dp; 4 | int solve(int i,int j,int n,vector>&players) 5 | { 6 | if(i == n) 7 | { 8 | return 0; 9 | } 10 | if(dp[i][j+1]!= -1) 11 | { 12 | return dp[i][j+1]; 13 | } 14 | int notake = solve(i+1,j,n,players); 15 | if(j == -1 or players[j].second<= players[i].second) 16 | { 17 | int take = players[i].second + solve(i+1,i,n,players); 18 | return dp[i][j+1] = max(take,notake); 19 | } 20 | return dp[i][j+1] = notake; 21 | 22 | } 23 | 24 | int bestTeamScore(vector& scores, vector& ages) { 25 | dp.resize(1002,vector(1002,-1)); 26 | vector>players; 27 | int n = scores.size(); 28 | 29 | for(int i = 0;i& tasks) { 4 | 5 | unordered_mapmp; 6 | for(auto task:tasks) 7 | { 8 | mp[task]++; 9 | } 10 | int round = 0; 11 | for(auto x : mp) 12 | { 13 | if(x.second<=1) 14 | { 15 | return -1; 16 | } 17 | else if(x.second == 2) 18 | { 19 | round++; 20 | } 21 | else 22 | { 23 | round+=ceil((double)x.second/3.0); 24 | 25 | } 26 | 27 | } 28 | return round; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /January/Day4/minimumRounds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumRounds(int[] tasks) { 3 | int count=0; 4 | HashMap map = new HashMap<>(); 5 | for(int n:tasks){ 6 | map.put(n,map.getOrDefault(n,0)+1); 7 | } 8 | for (Map.Entry mapElement : map.entrySet()) { 9 | Integer value=mapElement.getValue(); 10 | if(value==1)return -1; 11 | else if(value==2)count++; 12 | else { 13 | count+=Math.ceil(value/3.0); 14 | } 15 | } 16 | return count; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /January/Day4/minimum_rounds.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumRounds(self, tasks: List[int]) -> int: 3 | c = Counter(tasks) 4 | count = 0 5 | for key, value in c.items(): 6 | if value == 1: 7 | return -1 8 | if value%3 == 0: 9 | count += value//3 10 | else: 11 | count += value//3 + 1 12 | return count -------------------------------------------------------------------------------- /January/Day5/jsSolution: -------------------------------------------------------------------------------- 1 | // JavaScript Solution of 452. Minimum Number of Arrows to Burst Balloons 2 | 3 | 4 | /** 5 | * @param {number[][]} points 6 | * @return {number} 7 | */ 8 | var findMinArrowShots = function(points) { 9 | points = points.sort((a,b)=> a[1]-b[1]); 10 | 11 | let arrowCount= 1; 12 | let endPoint = points[0][1]; 13 | 14 | for (let i=0;iendPoint){ 16 | arrowCount++; 17 | endPoint = points[i][1]; 18 | } 19 | } 20 | return arrowCount; 21 | 22 | }; 23 | -------------------------------------------------------------------------------- /January/Day5/leetcode_452.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool static sorted(const vector& v1,const vector& v2) { 4 | return v1[1] < v2[1]; 5 | } 6 | int findMinArrowShots(vector>& points) { 7 | sort(points.begin(),points.end(),sorted); 8 | int x = points[0][1]; 9 | int count = 1; 10 | for(int i = 1 ;i=points[i][0] && x<=points[i][1]) 13 | { 14 | continue; 15 | } 16 | else 17 | { 18 | count++; 19 | x = points[i][1]; 20 | } 21 | } 22 | return count; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /January/Day5/leetcode_452.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMinArrowShots(int[][] points) { 3 | Arrays.sort(points, new Comparator() { 4 | @Override 5 | public int compare(final int[] entry1, 6 | final int[] entry2) { 7 | if (entry1[1] > entry2[1]) 8 | return 1; 9 | else 10 | return -1; 11 | } 12 | }); 13 | int count=1; 14 | int x=points[0][1]; 15 | for(int i=1;i=points[i][0] && x<=points[i][1])continue; 17 | else{ 18 | count++; 19 | x=points[i][1]; 20 | } 21 | } 22 | return count; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /January/Day5/leetcode_minimum_number_of_arrows_to_burst_balloons.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinArrowShots(self, points: List[List[int]]) -> int: 3 | points.sort(key=lambda x: x[0]) 4 | prev = points[0] 5 | 6 | count = 1 7 | for curr in range(1, len(points)): 8 | if points[curr][0]>prev[1]: 9 | count += 1 10 | prev = points[curr] 11 | else: #Overlapping 12 | prev[0] = max(points[curr][0], prev[0]) 13 | prev[1] = min(points[curr][1], prev[1]) 14 | return count -------------------------------------------------------------------------------- /January/Day6/JavaScript-Solution: -------------------------------------------------------------------------------- 1 | //JavaScript Solution of Leetcode Q 1833. Maximum Ice Cream Bars added 2 | 3 | 4 | var maxIceCream = function(costs, coins) { 5 | let count =0; 6 | costs.sort((a,b)=>a-b); 7 | 8 | for (let i=0;i=costs[i] ;i++){ 9 | count++; 10 | coins-=costs[i]; 11 | } 12 | return count; 13 | }; 14 | -------------------------------------------------------------------------------- /January/Day6/leetcode_1833.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIceCream(vector& costs, int coins) { 4 | sort(costs.begin(),costs.end()); 5 | int count = 0; 6 | for(int i=0;icoins) 8 | { 9 | break; 10 | } 11 | coins -= costs[i]; 12 | count++; 13 | } 14 | return count; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /January/Day6/leetcode_1833.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxIceCream(int[] costs, int coins) { 3 | Arrays.sort(costs); 4 | int count=0; 5 | for(int n:costs){ 6 | coins-=n; 7 | if(coins<0)break; 8 | else count++; 9 | } 10 | return count; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /January/Day6/leetcode_1833_without_sorting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIceCream(vector& costs, int coins) { 4 | vectormp(100001,0); 5 | int count = 0; 6 | for(int i=0;i=i) 11 | { 12 | if((long)mp[i]*i > coins && coins>=i) 13 | { 14 | int bars = coins/i; 15 | coins = coins - bars*i; 16 | count+=bars; 17 | break; 18 | } 19 | if(mp[i]!=0 && coins>=0) 20 | { 21 | coins = coins - mp[i]*i; 22 | count+=mp[i]; 23 | } 24 | i++; 25 | } 26 | return count; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /January/Day6/maximum_ice_cream_bars.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxIceCream(self, costs: List[int], coins: int) -> int: 3 | heapq.heapify(costs) 4 | count = 0 5 | while(coins>0 and costs): 6 | min_el = heapq.heappop(costs) 7 | if min_el <= coins: 8 | coins -= min_el 9 | count += 1 10 | else: 11 | break 12 | return count -------------------------------------------------------------------------------- /January/Day7/gas_station.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | n, total_surplus, surplus, start = len(gas), 0, 0, 0 4 | 5 | for i in range(n): 6 | total_surplus += gas[i] - cost[i] 7 | surplus += gas[i] - cost[i] 8 | if surplus < 0: 9 | surplus = 0 10 | start = i + 1 11 | return -1 if (total_surplus < 0) else start -------------------------------------------------------------------------------- /January/Day7/leetcode_134.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int lowest_index = 0; 5 | int totalGas = 0,totalCost = 0; 6 | int n = gas.size(); 7 | int currGas = 0; 8 | for(int i = 0; i= totalCost) 20 | { 21 | return lowest_index; 22 | } 23 | return -1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /January/Day7/leetcode_134.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | int gascost=0; 4 | int actualcost=0; 5 | int index=0; 6 | int total=0; 7 | for(int i=0;i>& points) { 4 | int max_num = 10001; 5 | int count = 0; 6 | for(int i = 0; imp; 9 | for(int j =i+1;j map= new HashMap<>(); 7 | for(int j=i+1;j mapElement : map.entrySet()) { 18 | count=Math.max(count,mapElement.getValue()+1); 19 | } 20 | 21 | } 22 | return count==0?1:count; 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /January/Day9/144.Binary_Tree_Preorder_Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | List ls= new ArrayList(); 18 | public List preorderTraversal(TreeNode root) { 19 | helper(root); 20 | return ls; 21 | } 22 | private void helper(TreeNode root){ 23 | if(root==null)return; 24 | ls.add(root.val); 25 | if(root.left!=null) helper(root.left); 26 | if(root.right!=null)helper(root.right); 27 | return ; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /January/leetcode_2359.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int closestMeetingNode(vector& edges, int node1, int node2) { 4 | int n = edges.size(); 5 | vectordist1(n,-1); 6 | vectordist2(n,-1); 7 | int d = 1; 8 | while(node1 !=-1) 9 | { 10 | if(dist1[node1] != -1) 11 | { 12 | break; 13 | } 14 | dist1[node1]+=d; 15 | node1 = edges[node1]; 16 | d++; 17 | } 18 | d = 1; 19 | while(node2!=-1) 20 | { 21 | if(dist2[node2] != -1) 22 | { 23 | break; 24 | } 25 | dist2[node2]+=d; 26 | node2 = edges[node2]; 27 | d++; 28 | } 29 | int minD = INT_MAX; 30 | int ans = -1; 31 | for(int i =0 ;i max(dist1[i],dist2[i])) 36 | { 37 | minD = max(dist1[i],dist2[i]); 38 | ans = i; 39 | } 40 | } 41 | } 42 | return ans; 43 | 44 | 45 | 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /March_Leetcode_Challenge/Day1/leetcode_912.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void merge(vector&nums, int l , int mid, int r) 5 | { int ln = mid-l+1; 6 | int rn = r-mid; 7 | vectorleft(ln); 8 | vectorright(rn); 9 | int s = 0; 10 | for(int i = l;i<=mid;i++) 11 | { 12 | left[s++] = nums[i]; 13 | } 14 | s = 0; 15 | for(int i = mid+1; i<=r; i++) 16 | { 17 | right[s++] = nums[i]; 18 | } 19 | int ls = 0 , rs = 0, ms = l; 20 | while(ls&nums, int l, int r) 42 | { 43 | if(l sortArray(vector& nums) { 52 | int n = nums.size()-1; 53 | mergeSort(nums,0,n); 54 | return nums; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /March_Leetcode_Challenge/Day2/leetcode_443(0(1)).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int compress(vector& chars) { 4 | int count = 1; 5 | int j = 0; 6 | if(chars.size()==1) 7 | { 8 | return 1; 9 | } 10 | for(int i = 1; i<=chars.size();i++) 11 | { 12 | count = 1; 13 | while(i1) 20 | { 21 | string c = to_string(count); 22 | for(auto ch : c) 23 | { 24 | chars[j++]= (char)ch; 25 | } 26 | } 27 | } 28 | 29 | return j; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /March_Leetcode_Challenge/Day2/leetcode_443.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int compress(vector& chars) { 4 | int count = 1; 5 | string ans; 6 | for(int i = 1; i<=chars.size(); i++) 7 | { 8 | if(in1) 7 | { 8 | return -1; 9 | } 10 | int j = 0; 11 | int i = 0; 12 | int start = 0; 13 | while(i < n1 && j < n2) 14 | { 15 | if(haystack[i] == needle[j]) 16 | { 17 | if(i-start+1 == n2) 18 | { 19 | return start; 20 | } 21 | j++; 22 | i++; 23 | } 24 | else 25 | { 26 | j=0; 27 | start++; 28 | i = start; 29 | } 30 | } 31 | return -1; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /March_Leetcode_Challenge/Day3/leetcode_28.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strStr(string haystack, string needle) { 4 | int n1 = haystack.size(); 5 | int n2 = needle.size(); 6 | if(n2>n1) 7 | { 8 | return -1; 9 | } 10 | for(int i = 0 ;i& nums, int minK, int maxK) { 4 | int minB = -1 , maxB = -1 , badB = -1; 5 | long long count = 0; 6 | for(int i = 0; i maxK) { 9 | badB = i; 10 | } 11 | if(nums[i] == minK) 12 | { 13 | minB = i; 14 | } 15 | if(nums[i] == maxK) { 16 | maxB = i; 17 | } 18 | count += max(0,min(minB,maxB)-badB); 19 | 20 | } 21 | return count; 22 | 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /March_Leetcode_Challenge/Day5/1345._Jump_Game_IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minJumps(vector& arr) { 4 | unordered_map>map_indices; 5 | for(int i = 0 ;ivisited(arr.size(),false); 10 | queueq; 11 | q.push(0); 12 | visited[0] = true; 13 | int jump = 0; 14 | while(!q.empty()) 15 | { 16 | int size = q.size(); 17 | for(int i = 0 ;i&temp_index = map_indices[arr[index]]; 27 | temp_index.push_back(index+1); 28 | temp_index.push_back(index-1); 29 | for(auto ele : temp_index ) 30 | { 31 | if(ele>=0 && ele& time, int totalTrips) { 4 | sort(time.begin(),time.end()); 5 | long long l = 0; 6 | long long h = 1LL*time[time.size()-1]*totalTrips; 7 | long long mintime = 1LL*time[time.size()-1]*totalTrips; 8 | while(l=totalTrips) 17 | { 18 | mintime = min(mintime, mid); 19 | h = mid; 20 | } 21 | else 22 | { 23 | l = mid+1; 24 | } 25 | } 26 | return mintime; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /March_Leetcode_Challenge/Day9/leetcode_142.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *detectCycle(ListNode *head) { 4 | unordered_mapmp; 5 | ListNode*temp = head; 6 | while(temp!=NULL) { 7 | if(mp[temp]) 8 | { 9 | return temp; 10 | } 11 | mp[temp]++; 12 | temp = temp->next; 13 | } 14 | return NULL; 15 | } 16 | }; 17 | 18 | 19 | 20 | // slow and fast pointer 21 | 22 | class Solution { 23 | public: 24 | ListNode *detectCycle(ListNode *head) { 25 | ListNode*fast=head; 26 | ListNode*slow=head; 27 | bool flag=0; 28 | while(fast!=NULL && fast->next!=NULL) 29 | { 30 | fast=fast->next->next; 31 | slow=slow->next; 32 | if(slow==fast) 33 | { 34 | fast=head; 35 | while(fast!=slow) 36 | { 37 | slow=slow->next; 38 | fast=fast->next; 39 | } 40 | return slow; 41 | } 42 | } 43 | return NULL; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day11/1035_Uncrossed_Lines.cpp: -------------------------------------------------------------------------------- 1 | //Recursion 2 | class Solution { 3 | public: 4 | int solve(vector& nums1, vector& nums2, int i, int j , int n1, int n2) 5 | { 6 | if(i>n1 || j>n2) 7 | { 8 | return 0; 9 | } 10 | if(nums1[i] == nums2[j]) 11 | { 12 | return 1 + solve(nums1, nums2, i+1, j+1, n1, n2); 13 | } 14 | else 15 | { 16 | return max(solve(nums1, nums2, i+1, j, n1, n2),solve(nums1, nums2, i, j+1, n1, n2)); 17 | } 18 | } 19 | int maxUncrossedLines(vector& nums1, vector& nums2) { 20 | return solve(nums1,nums2,0,0,nums1.size()-1,nums2.size()-1); 21 | } 22 | }; 23 | 24 | 25 | //Memoization 26 | class Solution { 27 | public: 28 | int solve(vector& nums1, vector& nums2, int i, int j , int n1, int n2,vector>&dp) 29 | { 30 | if(i>n1 || j>n2) 31 | { 32 | return 0; 33 | } 34 | if(dp[i][j] != -1) 35 | { 36 | return dp[i][j]; 37 | } 38 | if(nums1[i] == nums2[j]) 39 | { 40 | dp[i][j] = 1 + solve(nums1, nums2, i+1, j+1, n1, n2, dp); 41 | return dp[i][j]; 42 | } 43 | else 44 | { 45 | dp[i][j] = max(solve(nums1, nums2, i+1, j, n1, n2, dp),solve(nums1, nums2, i, j+1, n1, n2, dp)); 46 | return dp[i][j]; 47 | } 48 | } 49 | int maxUncrossedLines(vector& nums1, vector& nums2) { 50 | int n1 = nums1.size(), n2 = nums2.size(); 51 | vector>dp(n1, vector(n2,-1)); 52 | return solve(nums1, nums2, 0, 0, n1-1, n2-1, dp); 53 | } 54 | }; 55 | // dp 56 | 57 | class Solution { 58 | public: 59 | int maxUncrossedLines(vector& nums1, vector& nums2) { 60 | int n1 = nums1.size(), n2 = nums2.size(); 61 | vector>dp(n1+1, vector(n2+1,0)); 62 | 63 | for(int i = 1; i<=n1; i++) 64 | { 65 | for(int j = 1; j<=n2; j++) 66 | { 67 | if(nums1[i-1] == nums2[j-1] ) 68 | { 69 | dp[i][j] = 1 + dp[i-1][j-1]; 70 | } 71 | else 72 | { 73 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 74 | } 75 | } 76 | } 77 | return dp[n1][n2]; 78 | 79 | 80 | } 81 | }; 82 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day12/leetcode_2140.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long solve(vector>& questions, int i, int n) 4 | { 5 | if(i>n) 6 | { 7 | return 0; 8 | } 9 | 10 | long long solveProblem = questions[i][0] + solve(questions, i+questions[i][1]+1, n); 11 | long long skipProblem = solve(questions, i+1, n); 12 | return max(solveProblem, skipProblem); 13 | 14 | } 15 | long long mostPoints(vector>& questions) { 16 | int n = questions.size(); 17 | return solve(questions, 0, n-1); 18 | } 19 | }; 20 | 21 | 22 | 23 | 24 | 25 | 26 | class Solution { 27 | public: 28 | long long solve(vector>& questions, int i, int n,vector&dp) 29 | { 30 | if(i>=n) 31 | { 32 | return 0; 33 | } 34 | if(dp[i] != -1) 35 | { 36 | return dp[i]; 37 | } 38 | 39 | long long solveProblem = questions[i][0] + solve(questions, i+questions[i][1]+1, n, dp); 40 | long long skipProblem = solve(questions, i+1, n, dp); 41 | dp[i] = max(solveProblem, skipProblem); 42 | return dp[i]; 43 | 44 | } 45 | long long mostPoints(vector>& questions) { 46 | int n = questions.size(); 47 | vectordp(n,-1); 48 | return solve(questions, 0, n, dp); 49 | } 50 | }; 51 | 52 | 53 | class Solution { 54 | public: 55 | long long mostPoints(vector>& questions) { 56 | int n = questions.size(); 57 | vector dp(n+1, 0); 58 | 59 | for(int i=n-1; i>=0; i--) { 60 | int skip = min(n, i+questions[i][1]+1); 61 | long long solveProblem = questions[i][0] + dp[skip]; 62 | long long skipProblem = dp[i+1]; 63 | dp[i] = max(solveProblem, skipProblem); 64 | } 65 | 66 | return dp[0]; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day13/leetcode_2466.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int MOD = 1e9+7; 4 | 5 | int solve(int n, int zero, int one) 6 | { 7 | if(n == 0) 8 | { 9 | return 1; 10 | } 11 | if(n<0) 12 | { 13 | return 0; 14 | } 15 | int total = 0; 16 | if(n >= zero) 17 | { 18 | total+= solve(n-zero,zero,one); 19 | } 20 | if(n >= one) 21 | { 22 | total+=solve(n-one,zero,one); 23 | } 24 | return total%MOD; 25 | } 26 | int countGoodStrings(int low, int high, int zero, int one) { 27 | long long int ans = 0; 28 | for(int len = low; len<=high; len++) 29 | { 30 | ans+=solve(len, zero, one) % MOD; 31 | } 32 | return ans%MOD; 33 | } 34 | }; 35 | 36 | 37 | 38 | 39 | class Solution { 40 | public: 41 | int MOD = 1e9+7; 42 | 43 | int solve(int n, int zero, int one, vector&dp) 44 | { 45 | if(n == 0) 46 | { 47 | return 1; 48 | } 49 | if(n<0) 50 | { 51 | return 0; 52 | } 53 | if(dp[n]!=-1) 54 | { 55 | return dp[n]; 56 | } 57 | int total = 0; 58 | if(n >= zero) 59 | { 60 | total+= solve(n-zero,zero,one,dp); 61 | } 62 | if(n >= one) 63 | { 64 | total+=solve(n-one,zero,one,dp); 65 | } 66 | dp[n] = total%MOD; 67 | return dp[n]; 68 | } 69 | int countGoodStrings(int low, int high, int zero, int one) { 70 | long long int ans = 0; 71 | vectordp(high+1, -1); 72 | for(int len = low; len<=high; len++) 73 | { 74 | ans+=solve(len, zero, one, dp)% MOD; 75 | } 76 | return ans%MOD; 77 | } 78 | }; 79 | 80 | 81 | class Solution { 82 | public: 83 | int MOD = 1e9+7; 84 | 85 | int countGoodStrings(int low, int high, int zero, int one) { 86 | long long int ans = 0; 87 | vectordp(high+1, 0); 88 | dp[0] = 1; 89 | for(int len = 1; len<=high; len++) 90 | { 91 | int total = 0; 92 | if(len>=zero) 93 | { 94 | total+=dp[len-zero]; 95 | } 96 | if(len>=one) 97 | { 98 | total+= dp[len-one]; 99 | } 100 | 101 | dp[len] = total%MOD; 102 | } 103 | 104 | for(int len = low; len<=high; len++) 105 | { 106 | ans+= dp[len]; 107 | } 108 | return ans%MOD; 109 | } 110 | }; 111 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day17/leetcode_2130.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 | int pairSum(ListNode* head) { 14 | ListNode*slow = head; 15 | ListNode*fast = head; 16 | 17 | while(fast && fast->next) 18 | { 19 | slow = slow->next; 20 | fast = fast->next->next; 21 | } 22 | ListNode*nextNode,*prev = NULL; 23 | while(slow) 24 | { 25 | nextNode = slow->next; 26 | slow->next = prev; 27 | prev = slow; 28 | slow = nextNode; 29 | } 30 | int maxsum = 0; 31 | ListNode*left = head; 32 | while(prev) 33 | { 34 | maxsum = max(maxsum, prev->val+left->val); 35 | prev = prev->next; 36 | left = left->next; 37 | } 38 | return maxsum; 39 | } 40 | }; 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | /** 49 | * Definition for singly-linked list. 50 | * struct ListNode { 51 | * int val; 52 | * ListNode *next; 53 | * ListNode() : val(0), next(nullptr) {} 54 | * ListNode(int x) : val(x), next(nullptr) {} 55 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 56 | * }; 57 | */ 58 | class Solution { 59 | public: 60 | int pairSum(ListNode* head) { 61 | vectorans; 62 | while(head) 63 | { 64 | ans.push_back(head->val); 65 | head = head->next; 66 | } 67 | int n = ans.size(); 68 | int maxsum = 0; 69 | for(int i = 0; i<=(n/2)-1; i++) 70 | { 71 | maxsum = max(maxsum, ans[i]+ans[n-i-1]); 72 | } 73 | 74 | return maxsum; 75 | } 76 | }; 77 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day18/leetcode_1557.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSmallestSetOfVertices(int n, vector>& edges) { 4 | 5 | vectorvisited(n); 6 | for(auto edge : edges) 7 | { 8 | visited[edge[1]] = 1; 9 | } 10 | 11 | vectorans; 12 | for(int i = 0; i < n; i++) 13 | { 14 | if(visited[i] == 0) 15 | { 16 | ans.push_back(i); 17 | } 18 | } 19 | return ans; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day3/2215_Find_the_Difference_of_Two_Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findDifference(vector& nums1, vector& nums2) { 4 | vector>ans(2); 5 | unordered_sets1(nums1.begin(),nums1.end()); 6 | unordered_sets2(nums2.begin(),nums2.end()); 7 | 8 | for(auto ele : s1) 9 | { 10 | if(!s2.count(ele)) 11 | { 12 | ans[0].push_back(ele); 13 | } 14 | } 15 | for(auto ele : s2) 16 | { 17 | if(!s1.count(ele)) 18 | { 19 | ans[1].push_back(ele); 20 | } 21 | } 22 | 23 | return ans; 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day3/Day4/649_Dota2_Senate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string predictPartyVictory(string senate) { 4 | queueradiantQ,direQ; 5 | for(int i = 0; i direQ.size())? "Radiant" : "Dire"; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day5/leetcode_1456.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxVowels(string s, int k) { 4 | int maxCount = 0, count = 0; 5 | unordered_setvowels = {'a','e','i','o','u'}; 6 | for(int i = 0; i=k && vowels.count(s[i-k])) 9 | { 10 | count--; 11 | } 12 | if(vowels.count(s[i])) 13 | { 14 | count++; 15 | } 16 | maxCount = max(count, maxCount); 17 | } 18 | return maxCount; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day6/leetcode_1498.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int MOD = 1e9 + 7; 4 | int numSubseq(vector& nums, int target) { 5 | int n = nums.size(); 6 | sort(nums.begin(), nums.end()); 7 | int l = 0, r = n - 1; 8 | long long res = 0; 9 | vectorpower(n); 10 | power[0] = 1; 11 | for (int i = 1; i < n; ++i) { 12 | power[i] = (power[i - 1] * 2) % MOD; 13 | } 14 | while (l <= r) { 15 | if (nums[l] + nums[r] > target) { 16 | r--; 17 | } else { 18 | int len = r - l; 19 | res = (res + power[len] % MOD); 20 | l++; 21 | } 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day7/leetcode_1964.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector longestObstacleCourseAtEachPosition(vector& obstacles) { 4 | int n = obstacles.size(); 5 | vector ans(n, 0); 6 | vector s; 7 | for (int i = 0; i < n; i++) { 8 | if (s.empty() || obstacles[i] >= s.back()) { 9 | s.push_back(obstacles[i]); 10 | ans[i] = s.size(); 11 | } else { 12 | auto it = upper_bound(s.begin(), s.end(), obstacles[i]); 13 | *it = obstacles[i]; 14 | ans[i] = it - s.begin() + 1; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /May_Leetcode_Challenge/Day8/leetcode_1572.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int diagonalSum(vector>& mat) { 4 | 5 | int totalSum = 0; 6 | int m = mat.size(); 7 | for(int i = 0; i &nums, int tar, vector> &dp) 3 | { 4 | if(tar == 0) 5 | return 0; 6 | 7 | if(ind == 0) 8 | return tar; 9 | 10 | 11 | if(dp[ind][tar] != -1) return dp[ind][tar]; 12 | 13 | int excl = solve(ind-1, nums, tar, dp); 14 | int incl = 1e9; 15 | if(nums[ind] <= tar) 16 | incl = 1 + solve(ind, nums, tar-nums[ind], dp); 17 | 18 | return dp[ind][tar] = min(excl, incl); 19 | } 20 | public: 21 | int numSquares(int n) { 22 | 23 | if(n <= 3) return n; 24 | 25 | vector nums; 26 | 27 | for(int i = 1; i*i <= n; i++) 28 | { 29 | nums.push_back(i*i); 30 | 31 | } 32 | int m = nums.size(); 33 | 34 | vector> dp(m+1, vector(n+1, -1)); //n is target 35 | 36 | return solve(m-1, nums, n , dp); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /November/Day1/1706._Where_Will _the_Ball_Fall.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dfs(int i, int j, vector>& grid ) 4 | { 5 | if(i>= grid.size()) 6 | { 7 | return j; 8 | } 9 | //left to right 10 | if(grid[i][j] == 1 && j+1=0 && grid[i][j-1] == -1) 15 | { 16 | return dfs(i+1,j-1,grid); 17 | } 18 | else if(grid[i][j]==1 && j+1>=grid[0].size() ) 19 | { 20 | return -1; 21 | } 22 | else 23 | { 24 | return -1; 25 | } 26 | 27 | } 28 | vector findBall(vector>& grid) { 29 | int row = grid.size(); 30 | int col = grid[0].size(); 31 | vectorans(col); 32 | for(int j=0;j List[int]: 7 | m, n = len(grid), len(grid[0]) 8 | #@cache 9 | def helper(i, j): 10 | if i == m: 11 | return j 12 | if grid[i][j] == 1: 13 | if j==n-1 or grid[i][j+1]==-1: 14 | return -1 15 | return helper(i+1, j+1) 16 | if grid[i][j] == -1: 17 | if j==0 or grid[i][j-1]==1: 18 | return -1 19 | return helper(i+1, j-1) 20 | return [helper(0,j) for j in range(n)] 21 | -------------------------------------------------------------------------------- /November/Day10/1047._Remove_All_Adjacent_Duplicates_In_String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string s) { 4 | string ans; 5 | for(int i=0;i st = new Stack<>(); 4 | for(char c:s.toCharArray()){ 5 | if(!st.isEmpty() && st.peek()==c){ 6 | st.pop(); 7 | } 8 | else{ 9 | st.push(c); 10 | } 11 | } 12 | String ans=""; 13 | while(!st.isEmpty()){ 14 | ans=st.pop()+ans; 15 | } 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /November/Day10/Remove_All_Adjacent _Duplicates_In_String.py: -------------------------------------------------------------------------------- 1 | # For Loop 2 | class Solution: 3 | def removeDuplicates(self, s: str) -> str: 4 | 5 | res=[] 6 | for i in s: 7 | if res and res[-1]==i: 8 | res.pop() 9 | else: 10 | res.append(i) 11 | 12 | return "".join(res) 13 | 14 | # While Loop 15 | class Solution: 16 | def removeDuplicates(self, s: str) -> str: 17 | 18 | res = [] 19 | n = len(s) 20 | i = 0 21 | 22 | while(i < n): 23 | if res and res[-1] == s[i]: 24 | res.pop() 25 | else: 26 | res.append(s[i]) 27 | i += 1 28 | 29 | return ''.join(res) 30 | -------------------------------------------------------------------------------- /November/Day10/removeAdjacentString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String removeDuplicates(String s) { 3 | StringBuilder str_b = new StringBuilder(); 4 | for (char c : s.toCharArray()) { 5 | if (str_b.length() > 0 && str_b.charAt(str_b.length() - 1) == c) { 6 | str_b.deleteCharAt(str_b.length() - 1); 7 | } else { 8 | str_b.append(c); 9 | } 10 | } 11 | return str_b.toString(); 12 | } 13 | } -------------------------------------------------------------------------------- /November/Day10/remove_all_adjacent_duplicates_in_string.py: -------------------------------------------------------------------------------- 1 | # Brute Force (TLE on second last test case) 2 | class Solution: 3 | def removeDuplicates(self, s: str) -> str: 4 | if len(s) == 1: 5 | return s 6 | 7 | def helper(s): 8 | p1 = 0 9 | p2 = 1 10 | s = list(s) 11 | flag = True 12 | while p2 < len(s): 13 | if s[p1] == s[p2]: 14 | flag = False 15 | s[p1] = '' 16 | s[p2] = '' 17 | p1 += 2 18 | p2 += 2 19 | else: 20 | p1 += 1 21 | p2 += 1 22 | 23 | return ("".join(s), flag) 24 | 25 | out, flg = helper(s) 26 | 27 | while not flg: 28 | out, flg = helper(out) 29 | 30 | return out 31 | 32 | # solution using stack 33 | class Solution: 34 | def removeDuplicates(self, s: str) -> str: 35 | if len(s) == 1: 36 | return s 37 | 38 | stack = [s[0]] 39 | 40 | for i in range(1, len(s)): 41 | if stack and stack[-1] == s[i]: 42 | stack.pop() 43 | else: 44 | stack.append(s[i]) 45 | 46 | s = "".join(stack) 47 | 48 | return s 49 | -------------------------------------------------------------------------------- /November/Day11/26_Remove_Duplicates_from_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | 5 | int k, i=1; 6 | for(k=1;k int: 3 | if len(nums) < 2: 4 | return 1 5 | 6 | left = 0 7 | right = 1 8 | 9 | while right < len(nums): 10 | if nums[left] != nums[right]: 11 | left += 1 12 | nums[left] = nums[right] 13 | right += 1 14 | 15 | else: 16 | right += 1 17 | 18 | return left + 1 19 | -------------------------------------------------------------------------------- /November/Day12/295_Find_Median_from_Data_Stream.cpp: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | public: 3 | priority_queuemax_heap; 4 | priority_queue,greater>min_heap; 5 | MedianFinder() { 6 | 7 | } 8 | 9 | void addNum(int num) { 10 | if(max_heap.size()>0&&num>max_heap.top()) 11 | { 12 | min_heap.push(num); 13 | } 14 | else{ 15 | max_heap.push(num); 16 | } 17 | if(max_heap.size()>min_heap.size()+1) 18 | { 19 | min_heap.push(max_heap.top()); 20 | max_heap.pop(); 21 | } 22 | if(min_heap.size()>max_heap.size()+1) 23 | { 24 | max_heap.push(min_heap.top()); 25 | min_heap.pop(); 26 | } 27 | 28 | } 29 | 30 | double findMedian() { 31 | if(max_heap.size()==min_heap.size()) 32 | { 33 | return (max_heap.top()+min_heap.top())/2.0; 34 | } 35 | if(max_heap.size()>min_heap.size()) 36 | { 37 | return max_heap.top(); 38 | } 39 | else 40 | { 41 | return min_heap.top(); 42 | } 43 | } 44 | }; 45 | 46 | /** 47 | * Your MedianFinder object will be instantiated and called as such: 48 | * MedianFinder* obj = new MedianFinder(); 49 | * obj->addNum(num); 50 | * double param_2 = obj->findMedian(); 51 | */ -------------------------------------------------------------------------------- /November/Day12/295_Find_Median_from_Data_Stream.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | PriorityQueue max_heap=new PriorityQueue<>(Collections.reverseOrder()); 3 | PriorityQueue min_heap=new PriorityQueue<>(); 4 | public MedianFinder() { 5 | 6 | } 7 | 8 | public void addNum(int num) { 9 | if(max_heap.size()>0 && max_heap.peek()min_heap.size()+1){ 14 | min_heap.offer(max_heap.poll()); 15 | } 16 | if(min_heap.size()>max_heap.size()+1){ 17 | max_heap.offer(min_heap.poll()); 18 | } 19 | 20 | } 21 | 22 | public double findMedian() { 23 | if(max_heap.size()==min_heap.size()) 24 | return (max_heap.peek()+min_heap.peek())/2.0; 25 | if(max_heap.size()>min_heap.size())return (double)max_heap.peek(); 26 | else return (double)min_heap.peek(); 27 | } 28 | 29 | } 30 | 31 | /** 32 | * Your MedianFinder object will be instantiated and called as such: 33 | * MedianFinder obj = new MedianFinder(); 34 | * obj.addNum(num); 35 | * double param_2 = obj.findMedian(); 36 | */ 37 | -------------------------------------------------------------------------------- /November/Day12/find_median_from_data_stream.py: -------------------------------------------------------------------------------- 1 | # Brute Force 2 | class MedianFinder: 3 | 4 | def __init__(self): 5 | self.input = [] 6 | 7 | def addNum(self, num: int) -> None: 8 | self.input.append(num) 9 | 10 | def findMedian(self) -> float: 11 | self.input.sort() 12 | 13 | mid = 0 + len(self.input) - 1 14 | mid = mid // 2 15 | 16 | if len(self.input) % 2 == 0: 17 | return (self.input[mid] + self.input[mid + 1]) / 2.0 18 | else: 19 | return self.input[mid] 20 | 21 | # Your MedianFinder object will be instantiated and called as such: 22 | # obj = MedianFinder() 23 | # obj.addNum(num) 24 | # param_2 = obj.findMedian() 25 | 26 | 27 | # Cleaner Brute Force 28 | class MedianFinder: 29 | 30 | def __init__(self): 31 | self.input = [] 32 | self.isOdd = True 33 | 34 | def addNum(self, num: int) -> None: 35 | if self.isOdd and self.input: 36 | self.isOdd = False 37 | elif not self.isOdd: 38 | self.isOdd = True 39 | 40 | self.input.append(num) 41 | 42 | def findMedian(self) -> float: 43 | self.input.sort() 44 | 45 | mid = 0 + len(self.input) - 1 46 | mid = mid // 2 47 | 48 | if not self.isOdd: 49 | return (self.input[mid] + self.input[mid + 1]) / 2.0 50 | else: 51 | return self.input[mid] 52 | 53 | # Your MedianFinder object will be instantiated and called as such: 54 | # obj = MedianFinder() 55 | # obj.addNum(num) 56 | # param_2 = obj.findMedian() 57 | 58 | 59 | # Two Heaps 60 | class MedianFinder: 61 | 62 | def __init__(self): 63 | self.maxHeap = [] 64 | self.minHeap = [] 65 | 66 | def addNum(self, num: int) -> None: 67 | heappush(self.maxHeap, -num) 68 | 69 | heappush(self.minHeap, -heappop(self.maxHeap)) 70 | 71 | if len(self.minHeap) > len(self.maxHeap): 72 | heappush(self.maxHeap, -heappop(self.minHeap)) 73 | 74 | def findMedian(self) -> float: 75 | if len(self.minHeap) == len(self.maxHeap): 76 | return (self.minHeap[0] - self.maxHeap[0]) / 2.0 77 | 78 | else: 79 | return -self.maxHeap[0] 80 | 81 | 82 | # Your MedianFinder object will be instantiated and called as such: 83 | # obj = MedianFinder() 84 | # obj.addNum(num) 85 | # param_2 = obj.findMedian() 86 | -------------------------------------------------------------------------------- /November/Day12/medianFromDataStream.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | PriorityQueue MaxHeap; 3 | PriorityQueue MinHeap; 4 | 5 | public MedianFinder() { 6 | MaxHeap = new PriorityQueue<>(Collections.reverseOrder()); 7 | MinHeap = new PriorityQueue<>(); 8 | } 9 | 10 | public void addNum(int num) { 11 | MaxHeap.offer(num); 12 | MinHeap.offer(MaxHeap.poll()); 13 | if (MinHeap.size() > MaxHeap.size()) { 14 | MaxHeap.offer(MinHeap.poll()); 15 | } 16 | } 17 | 18 | public double findMedian() { 19 | if (MinHeap.size() != MaxHeap.size()) { 20 | return MaxHeap.peek(); 21 | } 22 | return (MinHeap.peek() + MaxHeap.peek()) / 2.0; 23 | } 24 | } -------------------------------------------------------------------------------- /November/Day13/151_Reverse_Words_in_a_String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | String [] arr= s.split(" "); 4 | String ans=""; 5 | for(String p:arr){ 6 | if(!(p.equals("") ||p.contains(" "))){ 7 | ans=p+" "+ans; 8 | } 9 | } 10 | return ans.trim(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /November/Day13/reverseWords.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | String ans=""; 4 | int i = 0; 5 | while(i str: 4 | s = s.split() 5 | s = " ".join(s[::-1]) 6 | return s 7 | 8 | 9 | # using stack (39ms - faster than 87%) 10 | class Solution: 11 | def reverseWords(self, s: str) -> str: 12 | stack = [] 13 | 14 | currentWord = '' 15 | 16 | # if character is a space in the beginning of the string 17 | # without any actual word yet (like " hello" then ignore it (pass) 18 | 19 | # if character is a space in the middle, then push the currently 20 | # formed to stack and reset it to '' 21 | 22 | # if the character isnt a space, just add to current word 23 | for i in range(len(s)): 24 | if s[i] == ' ' and currentWord == '': 25 | pass 26 | elif s[i] == ' ': 27 | stack.append(currentWord) 28 | currentWord = '' 29 | else: 30 | currentWord += s[i] 31 | 32 | # push the last word to stack only if its not a trailing space 33 | if currentWord != '': 34 | stack.append(currentWord) 35 | 36 | out = '' 37 | 38 | while stack: 39 | word = stack.pop() 40 | if word != '': 41 | out += word 42 | 43 | # add a space between words except the last word 44 | if len(stack) > 0: 45 | out += ' ' 46 | 47 | return out 48 | -------------------------------------------------------------------------------- /November/Day14/mostStonesRemoved.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | boolean isValid(int[] coord1, int[]coord2){ 4 | if(coord1[0] == coord2[0]) return true; 5 | if(coord1[1] == coord2[1]) return true; 6 | return false; 7 | } 8 | 9 | void dfs(int[][] stones, boolean[] visited, int currIndx){ 10 | visited[currIndx] = true; 11 | for(int i = 0; ileft; 20 | } 21 | return lh; 22 | } 23 | int rightHeight(TreeNode*root) { 24 | int rh =0; 25 | while(root) 26 | { 27 | rh++; 28 | root = root->right; 29 | } 30 | return rh; 31 | } 32 | int countNodes(TreeNode* root) { 33 | if(root == NULL) 34 | { 35 | return 0; 36 | } 37 | int lh = leftHeight(root); 38 | int rh = rightHeight(root); 39 | if(lh == rh) 40 | { 41 | return (1<left) + countNodes(root->right); 44 | } 45 | }; -------------------------------------------------------------------------------- /November/Day15/222_Count_Complete_Tree_Nodes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public int countNodes(TreeNode root) { 18 | if(root==null)return 0; 19 | return 1+countNodes(root.left)+countNodes(root.right); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /November/Day16/374_Guess_Number_Higher_or_Lower.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param num your guess 4 | * @return -1 if num is higher than the picked number 5 | * 1 if num is lower than the picked number 6 | * otherwise return 0 7 | * int guess(int num); 8 | */ 9 | 10 | class Solution { 11 | public: 12 | int guessNumber(int n) { 13 | int s = 1, e = n; 14 | while(s<=e) 15 | { 16 | int mid =s+(e-s)/2; 17 | int p = guess(mid); 18 | if(p == -1) 19 | { 20 | e = mid; 21 | } 22 | else if(p==1) 23 | { 24 | s=mid+1; 25 | } 26 | else if(p==0) 27 | { 28 | return mid; 29 | } 30 | } 31 | return 0; 32 | } 33 | }; -------------------------------------------------------------------------------- /November/Day16/374_Guess_Number_Higher_or_Lower.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param num your guess 4 | * @return -1 if num is higher than the picked number 5 | * 1 if num is lower than the picked number 6 | * otherwise return 0 7 | * int guess(int num); 8 | */ 9 | 10 | public class Solution extends GuessGame { 11 | public int guessNumber(int n) { 12 | int start=0; 13 | int end=n; 14 | while(start<=end){ 15 | int mid= (end - start)/2+ start; 16 | if(guess(mid)==0)return mid; 17 | else if(guess(mid)==-1)end=mid-1; 18 | else start=mid+1; 19 | } 20 | return 0; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /November/Day16/guess_number_higher_or_lower.py: -------------------------------------------------------------------------------- 1 | # The guess API is already defined for you. 2 | # @param num, your guess 3 | # @return -1 if num is higher than the picked number 4 | # 1 if num is lower than the picked number 5 | # otherwise return 0 6 | # def guess(num: int) -> int: 7 | 8 | 9 | # solution based on binary search 10 | # time complexity: O(nlogn) 11 | # space complexity: O(1) 12 | class Solution: 13 | def guessNumber(self, n: int) -> int: 14 | start = 1 15 | end = n 16 | 17 | while True: 18 | mid = start + (end - start) / 2 19 | 20 | guessRes = guess(mid) 21 | 22 | if guessRes == -1: 23 | end = mid - 1 24 | 25 | elif guessRes == 1: 26 | start = mid + 1 27 | 28 | else: 29 | return int(mid) 30 | -------------------------------------------------------------------------------- /November/Day17/223_Rectangle_Area.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { 4 | 5 | int areaR1 = (ax2 - ax1) * (ay2 - ay1); 6 | int areaR2 = (bx2 - bx1) * (by2 - by1); 7 | 8 | int cx1 = max(ax1,bx1),cy1 = max(ay1,by1); 9 | int cx2 = min(ax2,bx2), cy2 = min(ay2,by2); 10 | 11 | int cl = (cx2-cx1); 12 | int ch = (cy2-cy1); 13 | 14 | int cArea = 0; 15 | if(cl>0 && ch>0) 16 | { 17 | cArea = cl*ch; 18 | } 19 | 20 | return areaR1 + areaR2 - cArea; 21 | 22 | 23 | } 24 | }; -------------------------------------------------------------------------------- /November/Day17/Rectangle Area.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: 4 | 5 | A1 = (ax2-ax1) * (ay2-ay1) 6 | A2 = (bx2-bx1) * (by2-by1) 7 | 8 | 9 | cx1 = max(ax1,bx1) 10 | cy1 = max(ay1,by1) 11 | cx2 = min(ax2,bx2) 12 | cy2 = min(ay2,by2) 13 | 14 | cl = cx2 - cx1 15 | ch = cy2 - cy1 16 | 17 | A3 = 0 18 | if(cl > 0 and ch > 0): 19 | A3 = cl*ch 20 | 21 | return A1+A2-A3 22 | 23 | -------------------------------------------------------------------------------- /November/Day17/rectangleArea.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { 3 | int x_overlap, y_overlap; 4 | int overlap = 0; 5 | 6 | int Area1 = (ax2-ax1)*(ay2-ay1); 7 | int Area2 = (bx2-bx1) * (by2-by1); 8 | 9 | x_overlap = Math.min(ax2,bx2)-Math.max(ax1,bx1); 10 | y_overlap = Math.min(ay2,by2) - Math.max(ay1,by1); 11 | 12 | if(x_overlap > 0 && y_overlap > 0) 13 | overlap = x_overlap * y_overlap; 14 | 15 | return Area1+Area2-overlap; 16 | } 17 | } -------------------------------------------------------------------------------- /November/Day18/Ugly Number.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def isUgly(self, n: int) -> bool: 4 | 5 | while(n > 1): 6 | if(n % 2 == 0): 7 | n = n / 2 8 | elif(n % 3 == 0): 9 | n = n / 3 10 | elif(n % 5 == 0): 11 | n = n / 5 12 | else: 13 | break 14 | 15 | return n == 1 16 | 17 | -------------------------------------------------------------------------------- /November/Day18/uglyNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isUgly(int n) { 3 | if(n==0) return false; 4 | while(n%2 ==0) n/=2; 5 | while(n%3==0) n/=3; 6 | while(n%5 == 0) n/=5; 7 | return n==1; 8 | } 9 | } -------------------------------------------------------------------------------- /November/Day18/ugly_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int n) { 4 | while(n>1) 5 | { 6 | if(n%2==0) 7 | { 8 | n = n/2; 9 | } 10 | else if(n%3==0) 11 | { 12 | n = n/3; 13 | } 14 | else if(n%5 == 0) 15 | { 16 | n = n/5; 17 | } 18 | else 19 | { 20 | break; 21 | } 22 | } 23 | return n==1; 24 | 25 | } 26 | }; -------------------------------------------------------------------------------- /November/Day19/587._Erect_the_Fence.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | // To calculate the crossProduct 5 | // Cross product of two vectors AB and AC 6 | // returns positive for counter clockwise 7 | // turn and negative for clockwise turn 8 | int getRotationAngle(vector A, vector B, vector C) 9 | { 10 | // (x2-x1)(y3-y1) - (y2-y1)(x3-x1) -> 3D Cross-product of AB and AC vectors 11 | return ((B[0] - A[0]) *(C[1] - A[1])) - ((B[1] - A[1]) *(C[0] - A[0])); 12 | } 13 | 14 | vector> outerTrees(vector> &trees) 15 | { 16 | // If less then or equal to 3 return Trees. They all need to included . 17 | if (trees.size() <= 3) return trees; 18 | 19 | // sort them according to increasing order of x cordinates. 20 | sort(trees.begin(), trees.end()); 21 | 22 | // Upper HULL construction 23 | vector> UpperHullTrees; 24 | 25 | // Push first 2 points in UpperHullTrees. 26 | UpperHullTrees.push_back(trees[0]); 27 | UpperHullTrees.push_back(trees[1]); 28 | 29 | // Travese throw all the points of sorted Trees. 30 | for (int i = 2; i < trees.size(); i++) 31 | { 32 | int Us = UpperHullTrees.size(); 33 | 34 | // Cross Product > 0 bigger counterclockwise angle . So,we need to remove B and insert C. 35 | while (UpperHullTrees.size() >= 2 && getRotationAngle(UpperHullTrees[Us - 2], UpperHullTrees[Us - 1], trees[i]) > 0) 36 | { 37 | UpperHullTrees.pop_back(); 38 | Us--; 39 | } 40 | UpperHullTrees.push_back(trees[i]); 41 | } 42 | 43 | // Lower HULL construction 44 | vector> LowerHullTrees; 45 | 46 | LowerHullTrees.push_back(trees[trees.size() - 1]); 47 | LowerHullTrees.push_back(trees[trees.size() - 2]); 48 | 49 | for (int i = trees.size() - 3; i >= 0; --i) 50 | { 51 | int Ls = LowerHullTrees.size(); 52 | while (LowerHullTrees.size() >= 2 && getRotationAngle(LowerHullTrees[Ls - 2], LowerHullTrees[Ls - 1], trees[i]) > 0) 53 | { 54 | LowerHullTrees.pop_back(); 55 | Ls--; 56 | } 57 | LowerHullTrees.push_back(trees[i]); 58 | } 59 | 60 | // Add the top hull to down hull 61 | UpperHullTrees.insert(UpperHullTrees.end(), LowerHullTrees.begin(), LowerHullTrees.end()); 62 | 63 | // Remove the duplicates present in the lTrees. 64 | sort(UpperHullTrees.begin(), UpperHullTrees.end()); 65 | UpperHullTrees.erase(unique(UpperHullTrees.begin(), UpperHullTrees.end()), UpperHullTrees.end()); 66 | 67 | return UpperHullTrees; 68 | 69 | 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /November/Day19/erectTheFence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int orientation(int[] cord1,int[] cord2,int[] cord3){ 3 | return (cord3[1]-cord2[1]) * (cord2[0]-cord1[0]) - ((cord2[1]-cord1[1]) * (cord3[0]-cord2[0])); 4 | } 5 | public int[][] outerTrees(int[][] trees) { 6 | 7 | Stack upperHull= new Stack<>(); 8 | Stack lowerHull= new Stack<>(); 9 | Arrays.sort(trees,(p,q) ->q[0]==p[0]?q[1]-p[1]:q[0]-p[0]); 10 | 11 | for(int i=0;i= 2 && orientation(lowerHull.get(lowLen-2),lowerHull.get(lowLen-1),trees[i]) >0){ 16 | lowerHull.pop(); 17 | lowLen--; 18 | } 19 | 20 | while(upLen>= 2 && orientation(upperHull.get(upLen-2),upperHull.get(upLen-1),trees[i])<0){ 21 | upperHull.pop(); 22 | upLen--; 23 | } 24 | 25 | lowerHull.push(trees[i]); 26 | upperHull.push(trees[i]); 27 | } 28 | 29 | Set ans= new HashSet<>(lowerHull); 30 | ans.addAll(upperHull); 31 | return ans.toArray(new int[ans.size()][]); 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /November/Day2/433._Minimum_Genetic_Mutation.cpp: -------------------------------------------------------------------------------- 1 | S 2 | 3 | class Solution { 4 | public: 5 | int minMutation(string start, string end, vector& bank) { 6 | queueq; 7 | unordered_setvisited; 8 | 9 | q.push(start); 10 | visited.insert(start); 11 | 12 | int count = 0; 13 | 14 | while(!q.empty()) 15 | { 16 | int n = q.size(); 17 | for(int i=0;ist; 8 | 9 | 10 | for(int i=0;i='0' && s[i]<='9') 15 | { 16 | 17 | int num=0; 18 | while(s.size()>i&&s[i]>='0' && s[i]<='9') 19 | 20 | { 21 | num=num*10+(s[i]-'0'); 22 | i++; 23 | } 24 | sum+=num*sign; 25 | i--; 26 | } 27 | //'+' 28 | else if(s[i]=='+') 29 | { 30 | sign=1; 31 | } 32 | // '-' 33 | else if(s[i]=='-') 34 | { 35 | sign=-1; 36 | } 37 | // '(' 38 | else if(s[i]=='(') 39 | { 40 | st.push(sum); 41 | st.push(sign); 42 | sum=0; 43 | sign=1; 44 | } 45 | 46 | //')' 47 | else if(s[i]==')') 48 | { 49 | sum=st.top()*sum; 50 | st.pop(); 51 | sum+=st.top(); 52 | st.pop(); 53 | } 54 | } 55 | return sum; 56 | 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /November/Day21/1926_Nearest_Exit_from_Entrance_in_Maze.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nearestExit(vector>& maze, vector& entrance) { 4 | int m = maze[0].size(),n = maze.size(); 5 | queue>q; 6 | 7 | q.push({entrance[0],entrance[1]}); 8 | maze[entrance[0]][entrance[1]] = '+'; 9 | int level = 0; 10 | int dr[4] = {1 , -1 , 0 , 0}; 11 | int dc[4] = {0 , 0 , -1 , 1}; 12 | 13 | while(!q.empty()) 14 | { 15 | int size = q.size(); 16 | level++; 17 | for(int i=0;i= 0 && new_col >=0 && new_row dp(n+1,1000000); 5 | dp[0]=0; 6 | for(int i=1;i<=n;i++){ 7 | for(int j=0;j*j<=i;j++) dp[i]=min(dp[i],1+dp[i-j*j]); 8 | } 9 | return dp[n]; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /November/Day22/Perfect_Squares.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def numSquares(self, n: int) -> int: 4 | squares = set([i ** 2 for i in range(1, int(sqrt(n)) + 1)]) 5 | if n in squares: 6 | return 1 7 | 8 | seen = set(squares) 9 | q = deque([(sq, 1) for sq in squares]) 10 | 11 | while q: 12 | item, depth = q.popleft() 13 | for sq in squares: 14 | newSum = sq + item 15 | if newSum <= n and newSum not in seen: 16 | if newSum == n: 17 | return depth + 1 18 | seen.add(newSum) 19 | q.append((newSum, depth + 1)) 20 | 21 | -------------------------------------------------------------------------------- /November/Day23/36_Valid_Sudoku.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSudoku(vector>& board) { 4 | sets; 5 | 6 | for(int i=0;i<9;i++) 7 | { 8 | for(int j=0;j<9;j++) 9 | { 10 | if(board[i][j]!='.') 11 | { 12 | string row = "row"+to_string(i)+board[i][j]; 13 | string col = "col"+to_string(j)+board[i][j]; 14 | string box = "box"+to_string((i/3)*3+(j/3))+board[i][j]; 15 | 16 | if(s.find(row)==s.end() && s.find(col)==s.end() && s.find(box)==s.end()) 17 | { 18 | s.insert(row); 19 | s.insert(col); 20 | s.insert(box); 21 | } 22 | else 23 | { 24 | return false; 25 | } 26 | } 27 | } 28 | } 29 | return true; 30 | 31 | 32 | } 33 | }; -------------------------------------------------------------------------------- /November/Day23/36_Valid_Sudoku.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | Set set= new HashSet(); 4 | for(int i=0;i<9;i++){ 5 | for(int j=0;j<9;j++){ 6 | if(board[i][j]!='.'){ 7 | String row="row"+i+board[i][j]; 8 | String col="col"+j+board[i][j]; 9 | String box="box"+((i/3)*3+(j/3))+board[i][j]; 10 | if(set.contains(row) || set.contains(col) || set.contains(box)){ 11 | return false; 12 | } 13 | else{ 14 | set.add(row); 15 | set.add(col); 16 | set.add(box); 17 | } 18 | } 19 | 20 | 21 | } 22 | } 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /November/Day23/Valid Sudoku.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def isValidSudoku(self, board: List[List[str]]) -> bool: 4 | 5 | columns = collections.defaultdict(set) 6 | rows = collections.defaultdict(set) 7 | square = collections.defaultdict(set) 8 | 9 | for r in range(9): 10 | 11 | for c in range(9): 12 | 13 | if board[r][c] == ".": 14 | continue 15 | 16 | if(board[r][c] in rows[r] or 17 | board[r][c] in columns[c] or 18 | board[r][c] in square[(r // 3,c // 3)] 19 | ): 20 | return False 21 | 22 | columns[c].add(board[r][c]) 23 | rows[r].add(board[r][c]) 24 | square[(r // 3,c // 3)].add(board[r][c]) 25 | 26 | return True 27 | 28 | 29 | -------------------------------------------------------------------------------- /November/Day24/79_word_search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool search(int index, int i, int j ,vector>& board, string word) 5 | { 6 | if(index == word.size()) 7 | { 8 | return true; 9 | } 10 | if(i<0 or j<0 or i>=board.size() or j>=board[0].size()) 11 | { 12 | return false; 13 | } 14 | bool ans = false; 15 | if(word[index] == board[i][j]) 16 | { 17 | board[i][j] = '*'; 18 | 19 | ans = search(index+1,i+1,j,board,word) or 20 | search(index+1,i,j+1,board,word) or 21 | search(index+1,i-1,j,board,word) or 22 | search(index+1,i,j-1,board,word); 23 | 24 | board[i][j] = word[index]; 25 | } 26 | 27 | return ans; 28 | } 29 | 30 | 31 | 32 | 33 | bool exist(vector>& board, string word) { 34 | int m = board[0].size(); 35 | int n = board.size(); 36 | int index = 0; 37 | bool ans = false; 38 | 39 | for(int i=0; i& arr) { 5 | int n = arr.size(); 6 | vectorleft(n); 7 | vectorright(n); 8 | stack>st; 9 | 10 | for(int i=0;i0 && st.top().first>curr) 14 | { 15 | count+=st.top().second; 16 | st.pop(); 17 | } 18 | st.push({curr,count}); 19 | left[i]=count; 20 | } 21 | 22 | stack>s; 23 | for(int i=n-1;i>=0;i--) 24 | { 25 | 26 | int count = 1 , curr = arr[i]; 27 | while(s.size()>0 && s.top().first>=curr) 28 | { 29 | count+=s.top().second; 30 | s.pop(); 31 | } 32 | s.push({curr,count}); 33 | right[i]=count; 34 | 35 | } 36 | //reverse(right.begin(),right.end()); 37 | long long sum =0; 38 | for(int i=0;i &startTime, vector &endTime, vector< int > &profit) 3 | { 4 | 5 | vector>> events; 6 | for (int i = 0; i < profit.size(); i++) 7 | { 8 | events.push_back({ startTime[i], 9 | { 10 | endTime[i], 11 | profit[i] 12 | } }); 13 | } 14 | 15 | int maxVal = 0; 16 | priority_queue, vector< pair>, greater>> pq; 17 | sort(events.begin(), events.end()); 18 | 19 | for (auto &e: events) 20 | { 21 | while (!pq.empty() && pq.top().first <= e.first) 22 | { 23 | maxVal = max(maxVal, pq.top().second); 24 | pq.pop(); 25 | } 26 | 27 | pq.push({ e.second.first, 28 | maxVal + e.second.second }); 29 | } 30 | 31 | while (!pq.empty()) 32 | { 33 | maxVal = max(maxVal, pq.top().second); 34 | pq.pop(); 35 | } 36 | return maxVal; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /November/Day26/1235_Maximum_Profit_in_Job_Scheduling/memoization.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int find(int i,vector>& job,vector&startTime,int n,vector& dp){ 5 | if(i>=n) return 0; 6 | if(dp[i]!=-1) return dp[i]; 7 | int index = lower_bound(startTime.begin(),startTime.end(),job[i][1])-startTime.begin(); 8 | int pick=job[i][2]+find(index,job,startTime,n,dp); 9 | int notpick=find(i+1,job,startTime,n,dp); 10 | return dp[i]=max(pick,notpick); 11 | } 12 | int jobScheduling(vector &startTime, vector &endTime, vector< int > &profit) { 13 | int n=startTime.size(); 14 | vector> job; 15 | vector dp(n,-1); 16 | for(int i=0;i>& job,vector&startTime,int n){ 5 | if(i>=n) return 0; 6 | int index = lower_bound(startTime.begin(),startTime.end(),job[i][1])-startTime.begin(); 7 | int pick=job[i][2]+find(index,job,startTime,n); 8 | int notpick=find(i+1,job,startTime,n); 9 | return max(pick,notpick); 10 | } 11 | int jobScheduling(vector &startTime, vector &endTime, vector< int > &profit) { 12 | int n=startTime.size(); 13 | vector> job; 14 | for(int i=0;i> findWinners(vector>& matches) { 4 | 5 | mapmp; 6 | for(int i=0;iloser; 11 | vectorwinner; 12 | for(int i=0;imp; 4 | vectorarr; 5 | RandomizedSet() { 6 | 7 | } 8 | 9 | bool insert(int val) { 10 | if(mp.count(val)) 11 | { 12 | return false; 13 | } 14 | arr.push_back(val); 15 | mp[val] = arr.size()-1; 16 | return true; 17 | } 18 | 19 | bool remove(int val) { 20 | if(mp.count(val)) 21 | { 22 | int index = mp[val]; 23 | int v = arr.back(); 24 | arr[index] = v; 25 | mp[v] = index; 26 | arr.pop_back(); 27 | mp.erase(val); 28 | return true; 29 | } 30 | return false; 31 | } 32 | 33 | int getRandom() { 34 | int index = rand()%arr.size(); 35 | return arr[index]; 36 | } 37 | }; 38 | 39 | /** 40 | * Your RandomizedSet object will be instantiated and called as such: 41 | * RandomizedSet* obj = new RandomizedSet(); 42 | * bool param_1 = obj->insert(val); 43 | * bool param_2 = obj->remove(val); 44 | * int param_3 = obj->getRandom(); 45 | */ -------------------------------------------------------------------------------- /November/Day29/380_Insert_Delete_GetRandom_O(1).java: -------------------------------------------------------------------------------- 1 | class RandomizedSet { 2 | List ls = new ArrayList<>(); 3 | HashMap map = new HashMap<>(); 4 | public RandomizedSet() { 5 | 6 | } 7 | 8 | public boolean insert(int val) { 9 | if(map.containsKey(val))return false; 10 | map.put(val,ls.size()); 11 | ls.add(val); 12 | return true; 13 | } 14 | 15 | public boolean remove(int val) { 16 | if(!map.containsKey(val))return false; 17 | 18 | int index= map.get(val); 19 | int lastel= ls.get(ls.size()-1); 20 | ls.set(index,lastel); 21 | map.put(lastel,index); 22 | map.remove(val); 23 | ls.remove(ls.size()-1); 24 | return true; 25 | } 26 | 27 | public int getRandom() { 28 | int randomIdx = (int) (Math.random() * ls.size()); 29 | return ls.get(randomIdx); 30 | 31 | } 32 | } 33 | 34 | /** 35 | * Your RandomizedSet object will be instantiated and called as such: 36 | * RandomizedSet obj = new RandomizedSet(); 37 | * boolean param_1 = obj.insert(val); 38 | * boolean param_2 = obj.remove(val); 39 | * int param_3 = obj.getRandom(); 40 | */ 41 | -------------------------------------------------------------------------------- /November/Day3/longestPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestPalindrome(String[] words) { 3 | int[][] count = new int[26][26]; 4 | int ans = 0; 5 | for (String word : words) { 6 | int a = word.charAt(0) - 'a'; 7 | int b = word.charAt(1) - 'a'; 8 | if (count[b][a] > 0) { 9 | ans += 4; 10 | count[b][a]--; 11 | } else { 12 | count[a][b]++; 13 | } 14 | } 15 | for (int i = 0; i < 26; i++) { 16 | if (count[i][i] > 0) { 17 | ans += 2; 18 | break; 19 | } 20 | } 21 | return ans; 22 | } 23 | } -------------------------------------------------------------------------------- /November/Day30/uniqueOccurrences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool uniqueOccurrences(vector& arr) { 4 | unordered_mapfreq; 5 | for(auto x: arr) 6 | { 7 | freq[x]++; 8 | } 9 | unordered_sets; 10 | for(auto x: freq) 11 | { 12 | s.insert(x.second); 13 | } 14 | return freq.size() == s.size(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /November/Day30/unique_occurrences.py: -------------------------------------------------------------------------------- 1 | # One liner solution using "Counter" 2 | 3 | class Solution: 4 | def uniqueOccurrences(self, arr: List[int]) -> bool: 5 | return len(c := Counter(arr)) == len(set(c.values())) -------------------------------------------------------------------------------- /November/Day4/Reverse_Vowels_of_a_String.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def reverseVowels(self, s: str) -> str: 4 | 5 | s = list(s) 6 | left = 0 7 | right = len(s) - 1 8 | m = 'aeiouAEIOU' 9 | 10 | while left < right: 11 | if s[left] in m and s[right] in m: 12 | 13 | s[left], s[right] = s[right], s[left] 14 | 15 | left += 1; right -= 1 16 | 17 | elif s[left] not in m: 18 | left += 1 19 | 20 | elif s[right] not in m: 21 | right -= 1 22 | 23 | return ''.join(s) 24 | 25 | -------------------------------------------------------------------------------- /November/Day4/reverseVowels.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public String reverseVowels(String s) { 4 | 5 | char[] chars = s.toCharArray(); 6 | 7 | int start = 0; 8 | int end = s.length() - 1; 9 | 10 | while (start < end) { 11 | while (start < end && !isVowel(chars[start])) { 12 | start++; 13 | } 14 | 15 | while (start < end && !isVowel(chars[end])) { 16 | end--; 17 | } 18 | 19 | if (start < end) { 20 | char temp = chars[start]; 21 | chars[start++] = chars[end]; 22 | chars[end--] = temp; 23 | } 24 | } 25 | return new String(chars); 26 | } 27 | 28 | private boolean isVowel(char ch) { 29 | return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' 30 | || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'; 31 | } 32 | } -------------------------------------------------------------------------------- /November/Day5/WordSearchII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findWords(char[][] board, String[] words) { 3 | List ans = new ArrayList<>(); 4 | TrieNode root = buildTrie(words); 5 | for (int i = 0; i < board.length; i++) { 6 | for (int j = 0; j < board[0].length; j++) { 7 | dfs (board, i, j, root, ans); 8 | } 9 | } 10 | return ans; 11 | } 12 | 13 | public void dfs(char[][] board, int i, int j, TrieNode p, List ans) { 14 | char c = board[i][j]; 15 | if (c == '#' || p.child[c - 'a'] == null) return; 16 | p = p.child[c - 'a']; 17 | if (p.word != null) { 18 | ans.add(p.word); 19 | p.word = null; 20 | } 21 | 22 | board[i][j] = '#'; 23 | if (i > 0) dfs(board, i - 1, j ,p, ans); 24 | if (j > 0) dfs(board, i, j - 1, p, ans); 25 | if (i < board.length - 1) dfs(board, i + 1, j, p, ans); 26 | if (j < board[0].length - 1) dfs(board, i, j + 1, p, ans); 27 | board[i][j] = c; 28 | } 29 | 30 | public TrieNode buildTrie(String[] words) { 31 | TrieNode root = new TrieNode(); 32 | for (String str : words) { 33 | TrieNode p = root; 34 | for (char c : str.toCharArray()) { 35 | int i = c - 'a'; 36 | if (p.child[i] == null) p.child[i] = new TrieNode(); 37 | p = p.child[i]; 38 | } 39 | p.word = str; 40 | } 41 | return root; 42 | } 43 | 44 | class TrieNode { 45 | TrieNode[] child = new TrieNode[26]; 46 | String word; 47 | } 48 | } -------------------------------------------------------------------------------- /November/Day5/Word_Search_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | struct TrieNode{ 4 | TrieNode*child[26]; 5 | bool flag=false; 6 | string str; 7 | bool containChar(char ch) 8 | { 9 | return child[ch-'a']!=NULL; 10 | } 11 | void putNode(char ch,TrieNode*node) 12 | { 13 | child[ch-'a'] = node; 14 | } 15 | TrieNode*getNode(char ch) 16 | { 17 | return child[ch-'a']; 18 | } 19 | void setEnd() 20 | { 21 | flag = true; 22 | } 23 | bool isEnd() 24 | { 25 | return flag; 26 | } 27 | }; 28 | TrieNode*root = new TrieNode(); 29 | void insert(string word) { 30 | TrieNode *node = root; 31 | for (int i = 0; i < word.size(); i++) { 32 | if (!node->containChar(word[i])) { 33 | node->putNode(word[i], new TrieNode()); 34 | } 35 | //moves to reference trie 36 | node = node->getNode(word[i]); 37 | } 38 | node->setEnd(); 39 | node->str = word; 40 | } 41 | void dfs(vector>& board,int i,int j,TrieNode*node,set& res,vector>& visit){ 42 | if(i<0 || j<0 || i>=board.size() || j>= board[0].size()) 43 | { 44 | return; 45 | } 46 | 47 | node = node->getNode(board[i][j]); 48 | if(visit[i][j] || !node)return ; 49 | 50 | if(node->isEnd()) res.insert((node->str)); 51 | visit[i][j] = true; 52 | dfs(board,i+1,j,node,res,visit); 53 | dfs(board,i-1,j,node,res,visit); 54 | dfs(board,i,j+1,node,res,visit); 55 | dfs(board,i,j-1,node,res,visit); 56 | visit[i][j]= false; 57 | } 58 | 59 | 60 | vector findWords(vector>& board, vector& words) { 61 | set res; 62 | for(string &s:words){ 63 | insert(s); 64 | } 65 | vector> visit(board.size(),vector(board[0].size(),false)); 66 | for(int i = 0 ;i ans(res.begin(),res.end()); 72 | return ans; 73 | } 74 | }; 75 | -------------------------------------------------------------------------------- /November/Day6/899._Orderly_Queue.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string orderlyQueue(string s, int k) { 4 | 5 | if (k==1) 6 | { 7 | int n=s.size(); 8 | string doublestring=s+s; 9 | string ans=s; 10 | for (int i=1;i1){ 4 | char tempArray[] = s.toCharArray(); 5 | Arrays.sort(tempArray); 6 | return new String(tempArray); 7 | } 8 | 9 | int n=s.length(); 10 | String doublestring=s+s; 11 | String ans=s; 12 | for(int i=1;i0)ans=sub; 15 | 16 | } 17 | return ans; 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /November/Day6/orderlyQueue.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String orderlyQueue(String s, int k) { 3 | if (k > 1) { 4 | char arr[] = s.toCharArray(); 5 | Arrays.sort(arr); 6 | return new String(arr); 7 | } 8 | String ans = s; 9 | for (int i = 1; i < s.length(); i++) { 10 | String tmp = s.substring(i) + s.substring(0, i); 11 | if (tmp.compareTo(ans) < 0) ans = tmp; 12 | } 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /November/Day6/orderly_queue.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/orderly-queue/description/ 2 | 3 | class Solution: 4 | def orderlyQueue(self, s: str, k: int) -> str: 5 | if k > 1: 6 | return "".join(sorted(s)) 7 | 8 | else: 9 | ans = s 10 | for _ in range(len(s)): 11 | s = s[1:] + s[0] 12 | ans = min(ans, s) 13 | 14 | return ans 15 | -------------------------------------------------------------------------------- /November/Day7/1323. Maximum 69 Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximum69Number (int num) { 3 | int temp=num; 4 | int index=0; 5 | int i=1; 6 | while(temp>0){ 7 | int rem=temp%10; 8 | if(rem==6){ 9 | index=i; 10 | } 11 | temp=temp/10; 12 | i++; 13 | } 14 | if(index==0)return num; 15 | num=num+3*(int)Math.pow(10,index-1); 16 | return num; 17 | } 18 | } -------------------------------------------------------------------------------- /November/Day7/Maximum_69_Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximum69Number (int num) { 4 | string str = to_string(num); 5 | for(auto &ch :str) 6 | { 7 | if(ch=='6') 8 | { 9 | ch='9'; 10 | break; 11 | } 12 | } 13 | return stoi(str); 14 | } 15 | }; -------------------------------------------------------------------------------- /November/Day8/1544_ Make_The_String_Great.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeGood(string s) { 4 | stackst; 5 | for(int i=0;i st=new Stack<>(); 4 | for(char c:s.toCharArray()){ 5 | if(!st.isEmpty() && Math.abs(st.peek()-c)==32 ){ 6 | st.pop(); 7 | } 8 | else 9 | st.push(c); 10 | 11 | } 12 | String p=""; 13 | while(!st.isEmpty()){ 14 | p=st.pop().toString()+p; 15 | } 16 | return p; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /November/Day8/makeStringGreat.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String makeGood(String s) { 3 | int end = 0; 4 | char arr[] = s.toCharArray(); 5 | for (int curr = 0; curr < s.length(); curr++) { 6 | if (end > 0 && Math.abs(arr[curr] - arr[end-1]) == 32) 7 | end--; 8 | else { 9 | arr[end] = arr[curr]; 10 | end++; 11 | } 12 | } 13 | 14 | return new String(arr).substring(0, end); 15 | } 16 | } -------------------------------------------------------------------------------- /November/Day8/make_the_string_great.py: -------------------------------------------------------------------------------- 1 | # brute force 2 | class Solution: 3 | def makeGood(self, s: str) -> str: 4 | def checkGood(s): 5 | s = list(s) 6 | flag = True 7 | for i in range(len(s) - 1): 8 | if s[i].lower() == s[i+1].lower(): 9 | if (s[i].islower() and s[i+1].isupper()) or (s[i].isupper() and s[i+1].islower()): 10 | flag = False 11 | s[i] = '' 12 | s[i+1] = '' 13 | 14 | return ("".join(s), flag) 15 | 16 | response, isGood = checkGood(s) 17 | 18 | while not isGood: 19 | response, isGood = checkGood(response) 20 | return response 21 | 22 | 23 | 24 | # cleaner brute force 25 | class Solution: 26 | def makeGood(self, s: str) -> str: 27 | def checkGood(s): 28 | s = list(s) 29 | flag = True 30 | for i in range(len(s) - 1): 31 | if s[i] == s[i+1].swapcase(): 32 | flag = False 33 | s[i] = '' 34 | s[i+1] = '' 35 | 36 | return ("".join(s), flag) 37 | 38 | response, isGood = checkGood(s) 39 | 40 | while not isGood: 41 | response, isGood = checkGood(response) 42 | return response 43 | 44 | 45 | 46 | # using stack 47 | class Solution: 48 | def makeGood(self, s: str) -> str: 49 | stack = [] 50 | for i in range(len(s)): 51 | if stack and stack[-1] == s[i].swapcase(): 52 | stack.pop() 53 | else: 54 | stack.append(s[i]) 55 | 56 | return "".join(stack) 57 | 58 | # Easy String 59 | class Solution: 60 | def makeGood(self, s: str) -> str: 61 | st = [] 62 | for i in s: 63 | if len(st) == 0: 64 | st.append(i) 65 | else: 66 | if st[-1].lower() == i.lower() and st[-1] != i: 67 | st.pop() 68 | else: 69 | st.append(i) 70 | return "".join(st) 71 | -------------------------------------------------------------------------------- /November/Day8/one_pass_solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeGood(string s) { 4 | string ans; 5 | 6 | for(int i = 0 ; i < s.size() ; i++) 7 | { 8 | ans.push_back(s[i]); 9 | while(ans.size() && abs(ans.back()-s[i+1])==32) { 10 | ans.pop_back(); 11 | i++; 12 | } 13 | } 14 | 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /November/Day9/Online_Stock_Span.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | stack>st; 4 | StockSpanner() { 5 | 6 | } 7 | 8 | int next(int price) { 9 | if(st.empty()) 10 | { 11 | st.push({price,1}); 12 | return 1; 13 | } 14 | else 15 | { 16 | int ans = 1; 17 | while(!st.empty() && st.top().first<=price) 18 | { 19 | auto x = st.top(); 20 | st.pop(); 21 | int first = x.first; 22 | int second = x.second; 23 | ans+=second; 24 | } 25 | st.push({price,ans}); 26 | return ans; 27 | } 28 | return 0; 29 | } 30 | }; 31 | 32 | /** 33 | * Your StockSpanner object will be instantiated and called as such: 34 | * StockSpanner* obj = new StockSpanner(); 35 | * int param_1 = obj->next(price); 36 | */ -------------------------------------------------------------------------------- /November/Day9/Online_Stock_Span.java: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | Stack> st = new Stack<>(); 3 | 4 | public StockSpanner() { 5 | 6 | } 7 | 8 | public int next(int price) { 9 | if(st.isEmpty()){ 10 | st.push(new Pair(price,1)); 11 | return 1; 12 | } 13 | int ans=1; 14 | while(!st.isEmpty() && st.peek().getKey()<=price){ 15 | Pair p=st.pop(); 16 | ans+=p.getValue(); 17 | } 18 | st.push(new Pair(price,ans)); 19 | return ans; 20 | } 21 | } 22 | 23 | /** 24 | * Your StockSpanner object will be instantiated and called as such: 25 | * StockSpanner obj = new StockSpanner(); 26 | * int param_1 = obj.next(price); 27 | */ 28 | -------------------------------------------------------------------------------- /November/Day9/online_stock_span.py: -------------------------------------------------------------------------------- 1 | # brute force (TLE on test case 86/99) 2 | class StockSpanner: 3 | def __init__(self): 4 | self.prices = [] 5 | 6 | def next(self, price: int) -> int: 7 | self.prices.append(price) 8 | count = 0 9 | 10 | for i in range(len(self.prices) - 1, -1, -1): 11 | 12 | if self.prices[i] <= price: 13 | count += 1 14 | else: 15 | break 16 | 17 | return count 18 | 19 | 20 | # Your StockSpanner object will be instantiated and called as such: 21 | # obj = StockSpanner() 22 | # param_1 = obj.next(price) 23 | 24 | 25 | # using stack 26 | class StockSpanner: 27 | def __init__(self): 28 | self.stack = [] 29 | 30 | def next(self, price: int) -> int: 31 | if not self.stack: 32 | item = (price, 1) 33 | self.stack.append(item) 34 | return 1 35 | 36 | count = 1 37 | 38 | while self.stack and self.stack[-1][0] <= price: 39 | _, oldCount = self.stack.pop() 40 | count += oldCount 41 | 42 | newItem = (price, count) 43 | self.stack.append(newItem) 44 | 45 | return count 46 | 47 | # Your StockSpanner object will be instantiated and called as such: 48 | # obj = StockSpanner() 49 | # param_1 = obj.next(price) 50 | -------------------------------------------------------------------------------- /Stack/implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | class stack { 7 | vector v; 8 | 9 | public: 10 | void push(T ele) { 11 | v.push_back(ele); 12 | } 13 | 14 | T top() { 15 | return v[v.size() - 1]; 16 | } 17 | 18 | void pop() { 19 | v.pop_back(); 20 | } 21 | 22 | bool isEmpty() { 23 | return v.size() == 0; 24 | } 25 | }; 26 | 27 | int main() { 28 | stackst; 29 | st.push(1); 30 | st.push(2); 31 | st.push(3); 32 | st.push(4); 33 | cout<<"Top element:"<> threeSum(vector& nums) { 4 | vector>res; 5 | sort(nums.begin(),nums.end()); 6 | 7 | for(int i=0; itar) end--; 15 | else if(sumtemp; 18 | temp.push_back(nums[i]); 19 | temp.push_back(nums[start]); 20 | temp.push_back(nums[end]); 21 | res.push_back(temp); 22 | start++; 23 | end--; 24 | 25 | while(start>& matrix) { 5 | int c = matrix[0].size(); 6 | int r = matrix.size(); 7 | vectorcol(c, false); 8 | vectorrow(r,false); 9 | 10 | for(int i = 0; i>& matrix) { 47 | int c = matrix[0].size(); 48 | int r = matrix.size(); 49 | // vectorcol(c, false); 50 | // vectorrow(r,false); 51 | bool col = false; 52 | 53 | for(int i = 0; i spiralOrder(vector>& matrix) { 4 | vectorans; 5 | int left = 0, right = matrix[0].size()-1; 6 | int top = 0, down = matrix.size()-1; 7 | while(left<=right && top<=down) { 8 | if(left<=right && top<=down) { 9 | for(int i = left; i<=right; i++) { 10 | ans.push_back(matrix[top][i]); 11 | } 12 | } 13 | top++; 14 | if(left<=right && top<=down) { 15 | for(int i = top; i<=down; i++) { 16 | ans.push_back(matrix[i][right]); 17 | } 18 | } 19 | right--; 20 | if(left<=right && top<=down) { 21 | for(int i = right; i>=left; i--) { 22 | ans.push_back(matrix[down][i]); 23 | } 24 | } 25 | down--; 26 | if(left<=right && top<=down) { 27 | for(int i = down; i>=top; i--) { 28 | ans.push_back(matrix[i][left]); 29 | } 30 | } 31 | left++; 32 | 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Topw_Interview_150/Sliding_window/30.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSubstring(string s, vector& words) { 4 | 5 | int m = words[0].size(); 6 | int n = words.size(); 7 | int tl = m*n; 8 | unordered_mapmp1; 9 | vectorans; 10 | for(auto word : words) { 11 | mp1[word]++; 12 | } 13 | if(tl >s.size()) { 14 | return ans; 15 | } 16 | 17 | for(int i = 0; imp2; 20 | int left = i; 21 | for(int j = i; j<=s.size()-m; j+=m) { 22 | string temp = s.substr(j,m); 23 | 24 | if(mp1.find(temp) != mp1.end()) { 25 | mp2[temp]++; 26 | 27 | while(mp2[temp]>mp1[temp]) { 28 | mp2[s.substr(left,m)]--; 29 | left+=m; 30 | } 31 | if(j-left+m == tl) { 32 | ans.push_back(left); 33 | mp2[s.substr(left,m)]--; 34 | left+=m; 35 | } 36 | } 37 | else{ 38 | mp2.clear(); 39 | left = j+m; 40 | 41 | } 42 | } 43 | 44 | 45 | } 46 | return ans; 47 | 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Topw_Interview_150/Sliding_window/leetcode_76.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minWindow(string s, string t) { 4 | 5 | int m = s.size(); 6 | int n = t.size(); 7 | vectormp1(256,0); 8 | vectormp2(256,0); 9 | int count = 0; 10 | int startIndex = -1, len = INT_MAX; 11 | for(auto ch : t) { 12 | mp1[ch]++; 13 | } 14 | int i = 0, j = 0; 15 | 16 | while(j mp1[s[i]] || mp1[s[i]] == 0) { 28 | 29 | if(mp2[s[i]]> mp1[s[i]]) { 30 | mp2[s[i]]--; 31 | } 32 | i++; 33 | 34 | } 35 | 36 | if(len > j-i+1) { 37 | len = j-i+1; 38 | startIndex = i; 39 | } 40 | } 41 | j++; 42 | } 43 | if(startIndex == -1) { 44 | return ""; 45 | } 46 | return s.substr(startIndex, len); 47 | 48 | 49 | 50 | 51 | } 52 | }; 53 | --------------------------------------------------------------------------------