├── C++ ├── init.txt ├── Sum_Of_Square_Numbers.cpp ├── Coin Change 2 ├── HouseRobber.cpp ├── Reducing_Dishes.cpp ├── 338_counting_bits.cpp ├── Permutations_II.cpp ├── first_missing_positive.cpp ├── first_missing_positive_2.cpp ├── JumpGame.cpp ├── Container_With_Most_Water.cpp ├── longest_substring_without_repeating_characters.cpp ├── Minimum_Deletion_Cost_to_Avoid_Repeating_Letters.cpp ├── Count_Square_Sub-matrices_with_All_Ones.cpp ├── MedianofTwoSortedArrays.cpp ├── Permutations.cpp ├── TopKFrequent.cpp ├── Sort_Colors.cpp ├── Next_Permutation.cpp ├── SortList.cpp ├── LongestIncreasingSubsequence.cpp ├── String_to_integer_atoi.cpp ├── ShuffleAnArray.cpp ├── Longest_Palindrome_Subsequence.cpp ├── Rotate_List.cpp ├── Pow_x,n.cpp ├── Permutation_Sequence.cpp ├── longest_valid_parentheses.cpp ├── RemoveNthNodeFromEndOfList.cpp ├── Kth_Smallest_Element_BST.cpp ├── largest_rectangle_in_histogram.cpp ├── Decode_Ways.cpp ├── Longest_Palindromic_Substring.cpp ├── 3Sum.cpp ├── Deepest_Leaves_Sum.cpp ├── Wildcard_Matching.cpp ├── Word_Ladder.cpp ├── Lexicographically_Smallest_String_After_Applying_Operations.cpp ├── binarytree_from_traversal.cpp ├── BinaryTreeInorderTraversal.cpp ├── Furthest_building_you_can_reach.cpp ├── Remove_Duplicate_letters.cpp ├── Remove_Nth_Node_From_End_of_List.cpp ├── Contains_duplicate_III.cpp ├── merge-intervals.cpp ├── 4Sum.cpp ├── queue_reconstruction_by_height.cpp ├── Maximal_Square_Of_Ones.cpp ├── MergeKSortedList.cpp ├── Shortest_Common_Supersequence.cpp ├── Maximum_Nesting_Depth_of_Two_Valid_Parentheses_Strings.cpp ├── Valid_Number.cpp ├── RottingOranges.cpp ├── Course_schedule.cpp ├── Text_Justification.cpp └── CompareVersionNumbers.cpp ├── C ├── init.txt ├── pow.c ├── Rotate_List.c └── LongestPalindromicSubstring.c ├── GO ├── init.txt ├── zigzag_conversion.go ├── generate_parenthesis.go └── add_two_numbers.go ├── Java ├── init.txt ├── Pascal_Triangle_2.java ├── 287_Find_the_Duplicate_Number.java ├── SortColors.java ├── PalindromicSubstrings647.java ├── 48_RotateImage.java ├── ReplaceWords648.java ├── Linked List Cycle II.java ├── 3_Sum.java ├── 316_Remove_Duplicate_Letters.java ├── LongestPalindromeSubstring5.java ├── 61_Rotate_List.java ├── 449_Serialize_deserialize_BST.java ├── Minimum_Window_Substring.java └── The_Skyline_Problem.java ├── Python ├── init.txt ├── Shortest_Palindrome.py ├── Intersection_of_Two_Arrays.py ├── Jump_Game.py ├── Count_Number_of_Teams.py ├── Generate Paranthesis.py ├── Bitwise_AND_of_Numbers.py ├── 1492_The_kth_Factor_of_n.py ├── 4Sum_II.py ├── Longest_Common_Prefix.py ├── Rotate_Array.py ├── Linked_List_Cycle_II.py ├── Contiguous_Array.py ├── Group_People_Given_Group_Size_They_Belong_To.py ├── subrectangle_queries.py ├── Word_Break.py ├── Keys_and_Rooms.py ├── Longest_Substring_Without_Repeating_Characters.py ├── 322_coin_change.py ├── ShuffleAnArray.py ├── Add_Two_Numbers.py ├── Remove_Outermost_Parentheses.py ├── Group_Anagrams.py ├── Product_Of_Array_Except_Self.py ├── Letter_Tile_Possibilities.py ├── Increasing_Triplet_Subsequence.py ├── Maximal_Square.py ├── Counting_Bits.py ├── String_Compression.py ├── encode_decode_tinyurl.py ├── Reordered_Power_of_2.py ├── 743_Network_Delay_Time.py ├── 654_Maximum_Binary_Tree.py ├── Product_of_the _last_k_numbers.py ├── Find_And_Replace_Pattern.py ├── 312_Burst_Balloons.py ├── String_to_Integer_atoi.py ├── Binary_Tree_Inorder_Traversal.py ├── Next_Permutation.py ├── Spiral_Matrix.py ├── 25. ReverseNodesInK-Group.py ├── 647_Palindromic_Substrings.py ├── ValidSudoku.py ├── BinaryTreeLevelOrderTraversal.py ├── LRUCache.py ├── Reorder_List.py ├── ZigZag_Conversion.py ├── n_queens_ii.py ├── Exclusive_Time_Of_Functions.py ├── Longest_Palindromic_Substring.py ├── 140_Word break_II.py ├── Recover_BST.py ├── 713_Subarray_Product_Less_Than_K.py ├── MERGE_2_SORTED_LIST.py ├── three_sum.py ├── Subarray_Sum_Equals_K.py ├── Swap_Nodes_in_Pairs.py ├── Merge_k_Sorted_Lists.py ├── 238_Product_of_Array_Except_Self.py ├── Longest_Increasing_Path_in_a_Matrix.py ├── 4Sum.py ├── Largest_Number.py ├── Permutations.py ├── Reverse_Nodes_in_k-Group.py ├── 0420_Strong_Password_Checker.py ├── 1007_Minimum_Domino_Rotations_For_Equal_Row.py ├── Minimum Operations to Make Array Equal.py ├── Integer_To_Roman.py ├── Rotting_Oranges.py ├── 123. Best Time to Buy and Sell Stock III.py ├── 36_Valid_Sudoku.py ├── firstAndLastIndexOfAnElementInSortedArray.py ├── Binary_Tree_Zigzag_Level_Order_Traversal.py ├── median_of_two_sorted_arrays.py ├── 1579_Remove_Max_Number_of_Edges_to_Keep_Graph_Fully_Traversable.py ├── Integer_to_English_Words.py ├── Letter_Combinations_Of_A_Phone_Number.py ├── Basic_Calculator_II.py ├── singleElementInSortedArray.py ├── 449_Serialize_and_Deserialize_BST.py ├── Number_of_Islands.py └── Basic_Calculator.py ├── .github ├── ISSUE_TEMPLATE │ └── custom.md └── workflows │ ├── greetings.yml │ ├── main.yml │ ├── python-app.yml │ └── IssueComment.yml ├── reverse_words_in_a_string.py ├── Sort_Characters_By_Frequency.cpp ├── Javascript ├── Add_Two_Numbers.js ├── Divide_Two_Integers.js ├── Combination_Sum.js ├── Multiply_Strings.js └── 312_House_Robbers_2.js ├── README.md ├── 1329_Sort_the_Matrix_Diagonally_(Medium).py └── CONTRIBUTING.md /C++/init.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /C/init.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /GO/init.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Java/init.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python/init.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python/Shortest_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestPalindrome(self, s: str) -> str: 3 | rev=s[::-1] 4 | for i in range(len(s)): 5 | if s[:len(s)-i]==rev[i:]: 6 | return rev[:i]+s 7 | return "" 8 | -------------------------------------------------------------------------------- /Python/Intersection_of_Two_Arrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 5 | result = set.intersection(set(nums1), set(nums2)) 6 | return list(result) 7 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: New Algorithm Issue 3 | about: Issue template for new algorithms 4 | title: Problem No. | Problem name | Language 5 | labels: hacktoberfest 6 | assignees: '' 7 | 8 | --- 9 | 10 | Problem name: 11 | Difficulty: 12 | Language: 13 | -------------------------------------------------------------------------------- /Python/Jump_Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | lastpos=len(nums)-1 4 | for i in range(len(nums)-1,-1,-1): 5 | if i+nums[i]>=lastpos: 6 | lastpos=i 7 | if lastpos==0: 8 | return True 9 | else: 10 | return False 11 | -------------------------------------------------------------------------------- /C++/Sum_Of_Square_Numbers.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/sum-of-square-numbers/ 2 | class Solution { 3 | public: 4 | bool judgeSquareSum(int c) { 5 | for(int i=0;i<=sqrt(c);i++) { 6 | int t=sqrt(c-i*i); 7 | if(t*t==c-i*i) 8 | return true; 9 | } 10 | return false; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Python/Count_Number_of_Teams.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/count-number-of-teams/ 2 | 3 | import itertools 4 | class Solution: 5 | def numTeams(self, rating: List[int]) -> int: 6 | count = 0 7 | for i,j,k in itertools.combinations(rating,3): 8 | if i>j>k or i getRow(int n) { 3 | List tri = new ArrayList(); 4 | int i=0; 5 | while(i0; j--) 8 | tri.set(j, tri.get(j)+tri.get(j-1)); // tri[j]<- tri[j]+tri[j-1] 9 | i++; 10 | } 11 | return tri; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Python/Bitwise_AND_of_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeBitwiseAnd(self, m: int, n: int) -> int: 3 | p=31 4 | if m==0: 5 | return 0 6 | while p>=0: 7 | if pow(2,p) in range(m,n+1): 8 | return pow(2,p)&m 9 | p-=1 10 | res=m 11 | for i in range(m+1,n+1): 12 | res=res&i 13 | return res 14 | -------------------------------------------------------------------------------- /C++/Coin Change 2: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int change(int k, vector& a) { 4 | int n=a.size(); 5 | int dp[k+1]; 6 | for(int i=0;i<=k;i++) dp[i]=0; 7 | dp[0]=1; 8 | for(int i=0;i& nums) { 4 | vector dp(nums.size()); 5 | if(nums.size()==1) 6 | return nums[0]; 7 | dp[0]=nums[0]; 8 | dp[1]=max(nums[0],nums[1]); 9 | for(int i=2;i int: 3 | factors = [] 4 | for i in range(1, n): 5 | if n % i == 0: 6 | factors.append(i) 7 | factors.append(n) 8 | len_array = len(factors) 9 | print(factors) 10 | if len_array < k: 11 | return -1 12 | else: 13 | return factors[k-1] -------------------------------------------------------------------------------- /Python/4Sum_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: 3 | ab_sum_counts = {} 4 | for a in A: 5 | for b in B: 6 | count = ab_sum_counts.get(a + b, 0) 7 | ab_sum_counts[a + b] = count + 1 8 | ans = 0 9 | for c in C: 10 | for d in D: 11 | ans += ab_sum_counts.get(-(c + d), 0) 12 | return ans 13 | -------------------------------------------------------------------------------- /Python/Longest_Common_Prefix.py: -------------------------------------------------------------------------------- 1 | # LeetCode Problem link - https://leetcode.com/problems/longest-common-prefix/ 2 | 3 | 4 | class Solution(object): 5 | def longestCommonPrefix(self, strs): 6 | if len(strs) == 0: 7 | return "" 8 | else: 9 | s1, s2 = max(strs), min(strs) 10 | i, match = 0, 0 11 | while i < len(s1) and i < len(s2) and s1[i] == s2[i]: 12 | i, match = i+1, match + 1 13 | return s1[0:match] -------------------------------------------------------------------------------- /Python/Rotate_Array.py: -------------------------------------------------------------------------------- 1 | # leetcode problem link: https://leetcode.com/problems/rotate-array/ 2 | 3 | class Solution: 4 | def rotate(self, nums: List[int], k: int) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | num_of_ele = len(nums)-1 9 | for i in range(k): 10 | temp = nums[num_of_ele] 11 | nums.pop(num_of_ele) 12 | nums.insert(0,temp) 13 | return nums 14 | 15 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/first-interaction@v1 10 | with: 11 | repo-token: ${{ secrets.GITHUB_TOKEN }} 12 | issue-message: 'Thankyou for your first issue'' first issue' 13 | pr-message: 'Congrats on your first PR in this repo. Please reference it to the issue so that we can fastrack the review process'' first pr' 14 | -------------------------------------------------------------------------------- /C++/Reducing_Dishes.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reducing-dishes/ 2 | 3 | class Solution { 4 | public: 5 | int maxSatisfaction(vector& satisfaction) { 6 | sort(satisfaction.begin(), satisfaction.end(), greater()); 7 | int ans = 0, cur=0; 8 | for(int n:satisfaction) 9 | { 10 | cur +=n; 11 | if(cur >= 0) 12 | { 13 | ans += cur; 14 | } 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Python/Linked_List_Cycle_II.py: -------------------------------------------------------------------------------- 1 | #LeetCode problem link: https://leetcode.com/problems/linked-list-cycle-ii/ 2 | 3 | class Solution: 4 | def detectCycle(self, head: ListNode) -> ListNode: 5 | node = head 6 | val_holder = [] 7 | while(node.next is not None): 8 | temp = node.val 9 | val_holder.append(temp) 10 | if node.next.val not in val_holder: 11 | node = node.next 12 | else: 13 | return node.next 14 | -------------------------------------------------------------------------------- /C/pow.c: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/powx-n/ 2 | 3 | double myPow2(double x,int n){ 4 | double value; 5 | if(n==0) 6 | return 1; 7 | else{ 8 | value=myPow2(x,n/2); 9 | if(n%2==0) 10 | return value*value; 11 | else 12 | return value*value*x; 13 | } 14 | } 15 | 16 | double myPow(double x, int n){ 17 | double exp; 18 | exp=myPow2(x,n); 19 | if(n>=0) 20 | return exp; 21 | else 22 | return 1/exp; 23 | } 24 | -------------------------------------------------------------------------------- /Python/Contiguous_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxLength(self, nums: List[int]) -> int: 3 | mx=0 4 | d={0:-1} 5 | cnt=0 6 | l=0 7 | for i in range(len(nums)): 8 | if nums[i]==0: 9 | cnt-=1 10 | else: 11 | cnt+=1 12 | if cnt not in d: 13 | d[cnt]=i 14 | else: 15 | l=i-d[cnt] 16 | if l>mx: 17 | mx=l 18 | return mx 19 | -------------------------------------------------------------------------------- /Python/Group_People_Given_Group_Size_They_Belong_To.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: 3 | maxGroupSize= max(groupSizes) 4 | groups = [[] for i in range(maxGroupSize)] 5 | 6 | for i, p in enumerate(groupSizes): 7 | groups[p-1].append(i) 8 | if len(groups[p-1]) == p: 9 | groups.append(groups[p-1]) 10 | groups[p-1] = [] 11 | 12 | return groups[maxGroupSize:] 13 | -------------------------------------------------------------------------------- /GO/zigzag_conversion.go: -------------------------------------------------------------------------------- 1 | // Link: https://leetcode.com/problems/zigzag-conversion/ 2 | func convert(s string, numRows int) string { 3 | s_size := len(s) 4 | ans := "" 5 | if numRows == 1 { 6 | return s 7 | } 8 | cycleLen := (numRows - 1) * 2; 9 | for i := 0; i < numRows; i++ { 10 | for j := 0; j < s_size-i; j = j + cycleLen { 11 | ans += string(s[j+i]) 12 | if i != 0 && i != numRows-1 && j < s_size+i-cycleLen { 13 | ans += string(s[j-i+cycleLen]) 14 | } 15 | } 16 | } 17 | return ans 18 | } 19 | 20 | -------------------------------------------------------------------------------- /Python/subrectangle_queries.py: -------------------------------------------------------------------------------- 1 | 2 | # link: https://leetcode.com/problems/subrectangle-queries/ 3 | 4 | class SubrectangleQueries: 5 | 6 | def __init__(self, lists): 7 | self.rectangle = lists 8 | 9 | def updateSubrectangle(self, row1, col1, row2, col2, newValue): 10 | for i in range(col1, col2 + 1): 11 | for j in range(row1, row2 + 1): 12 | self.rectangle[j][i] = newValue 13 | 14 | def getValue(self, row, col): 15 | return self.rectangle[row][col] 16 | 17 | -------------------------------------------------------------------------------- /C++/338_counting_bits.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/counting-bits/ 2 | /* 3 | Runtime: 4 ms 4 | Memory Usage: 8 MB 5 | */ 6 | class Solution { 7 | public: 8 | vector countBits(int num) { 9 | int hold; 10 | vector ans(num+1); 11 | for(int i=0;i<=num;i++) 12 | { 13 | hold=i/2; 14 | if(i==0) 15 | ans[0]=0; 16 | if(i%2==0) 17 | ans[i]=ans[hold]; 18 | else 19 | ans[i]=ans[hold]+1; 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/Permutations_II.cpp: -------------------------------------------------------------------------------- 1 | // Problem link: https://leetcode.com/problems/permutations-ii/ 2 | class Solution { 3 | public: 4 | vector> permuteUnique(vector& nums) { 5 | vector> ans; 6 | sort(nums.begin(), nums.end()); 7 | do { 8 | ans.push_back(nums); 9 | } while (next_permutation(nums.begin(), nums.end())); 10 | sort(ans.begin(), ans.end()); 11 | ans.erase(unique(ans.begin(), ans.end()), ans.end()); 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /C++/first_missing_positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) { 4 | int n = nums.size(); 5 | vector nums_map(n+1); 6 | for (int i = 0; i < n; i++) { 7 | if(nums[i]<=n && nums[i]>0) { 8 | nums_map[nums[i]] = true; 9 | } 10 | } 11 | for (int i=0; i& nums) { 4 | vector positives; 5 | for(int i: nums) 6 | { 7 | if(i > 0) 8 | positives.push_back(i); 9 | } 10 | for(int i = 1; i < INT_MAX; i++) 11 | { 12 | if(!count(positives.begin(), positives.end(), i)) 13 | { 14 | return i; 15 | } 16 | 17 | } 18 | return -1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Python/Word_Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s, wordDict): 3 | dic = {} 4 | for word in wordDict: 5 | if len(word) in dic: 6 | dic[len(word)].append(word) 7 | else: 8 | dic[len(word)] = [word] 9 | dp = [True] + [False] * len(s) 10 | for i in range(len(s)): 11 | for j in dic: 12 | if i - j + 1 >= 0 and dp[i - j + 1] and s[i - j + 1 : i + 1] in dic[j]: 13 | dp[i + 1] = True 14 | return dp[-1] 15 | -------------------------------------------------------------------------------- /C++/JumpGame.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | vector dp(nums.size(),100001); 5 | int maxJumps; 6 | dp[0]=0; 7 | for(int i=0;i bool: 5 | stack = [rooms[0]] 6 | seen = {0: True} 7 | while stack: 8 | room = stack.pop(-1) 9 | for key in room: 10 | if key not in seen: 11 | stack.append(rooms[key]) 12 | seen[key] = True 13 | if len(seen) == len(rooms): 14 | return True 15 | else: 16 | return False 17 | -------------------------------------------------------------------------------- /Python/Longest_Substring_Without_Repeating_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | lt={} 4 | cnt=0 5 | mx=0 6 | i=0 7 | while imx: 14 | mx=cnt 15 | i=lt[s[i]]+1 16 | lt={} 17 | cnt=0 18 | if cnt>mx: 19 | mx=cnt 20 | return mx 21 | -------------------------------------------------------------------------------- /Python/322_coin_change.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/coin-change/ 2 | 3 | class Solution: 4 | def coinChange(self, coins: List[int], amount: int) -> int: 5 | dp=[float('inf')]*(amount+1) 6 | dp[0]=0 7 | n=len(coins) 8 | for i in range(1, amount+1): 9 | for j in range(0, n): 10 | if(coins[j]<=i): 11 | dp[i]=min(dp[i],dp[i-coins[j]]+1) 12 | if dp[amount]>amount: 13 | return -1 14 | else: 15 | return dp[amount] 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Python/ShuffleAnArray.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/shuffle-an-array/ 2 | class Solution: 3 | def __init__(self, nums): 4 | self.arr = nums 5 | self.original = list(nums) 6 | 7 | def reset(self): 8 | self.arr = self.original 9 | self.original = list(self.original) 10 | return self.arr 11 | 12 | def shuffle(self): 13 | aux = list(self.arr) 14 | 15 | for idx in range(len(self.arr)): 16 | remove_idx = random.randrange(len(aux)) 17 | self.arr[idx] = aux.pop(remove_idx) 18 | 19 | return self.arr 20 | -------------------------------------------------------------------------------- /Python/Add_Two_Numbers.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://leetcode.com/problems/add-two-numbers/ 2 | 3 | class Solution: 4 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 5 | suml = self.reverse(l1) + self.reverse(l2) 6 | head = prev = None 7 | for x in str(suml)[::-1]: 8 | node = ListNode(x) 9 | if prev is not None: 10 | prev.next = node 11 | prev = node 12 | if head is None: 13 | head = prev 14 | return head 15 | 16 | def reverse(self, l: ListNode): 17 | n = '' 18 | while l is not None: 19 | n = n + str(l.val) 20 | l = l.next 21 | return(int(n[::-1])) 22 | -------------------------------------------------------------------------------- /Python/Remove_Outermost_Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeOuterParentheses(self, S: str) -> str: 3 | primitives = [] 4 | parentheses = 0 5 | 6 | temp = [] 7 | for parenthesis in S: 8 | temp.append(parenthesis) 9 | if parenthesis == '(': 10 | parentheses += 1 11 | elif parenthesis == ')': 12 | parentheses -= 1 13 | 14 | if parentheses == 0: 15 | primitives.append(''.join(temp)) 16 | temp = [] 17 | 18 | return ''.join([x[1:-1] for x in primitives]) 19 | -------------------------------------------------------------------------------- /Python/Group_Anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | grp=[] 4 | lsts=[] 5 | d={} 6 | for i in range(len(strs)): 7 | lsts.append([]) 8 | for j in strs[i]: 9 | lsts[i].append(j) 10 | stl=sorted(lsts[i]) 11 | if tuple(stl) in d: 12 | d[tuple(stl)].append(strs[i]) 13 | else: 14 | d[tuple(stl)]=[strs[i]] 15 | lsts=[] 16 | for k in d.keys(): 17 | lsts.append(d[k]) 18 | return lsts 19 | 20 | -------------------------------------------------------------------------------- /Python/Product_Of_Array_Except_Self.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | def productExceptSelf(self, nums: List[int]) -> List[int]: 4 | l=len(nums) 5 | rght=[] 6 | lft=[] 7 | prod=[] 8 | 9 | a=1 10 | for i in range(l): 11 | rght.append(a) 12 | a*=nums[i] 13 | 14 | a=1 15 | for i in range(l-1,-1,-1): 16 | lft.append(a) 17 | a*=nums[i] 18 | 19 | lft=lft[::-1] 20 | 21 | for i in range(l): 22 | prod.append(lft[i]*rght[i]) 23 | 24 | return prod 25 | -------------------------------------------------------------------------------- /C++/Container_With_Most_Water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link: https://leetcode.com/problems/container-with-most-water/ 3 | Author: Shrey Rai 4 | */ 5 | class Solution { 6 | public: 7 | int maxArea(vector& height) { 8 | int n=height.size(); 9 | int i=0,j=n-1; 10 | int f=0; 11 | while(ii) 18 | j--; 19 | } 20 | 21 | return f; 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Python/Letter_Tile_Possibilities.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTilePossibilities(self, tiles: str) -> int: 3 | freq = collections.Counter(tiles) 4 | product = 1 5 | for f in freq.values(): 6 | product *= f + 1 7 | counter = 0 8 | for i in range(1, product): 9 | digits = [] 10 | for f in freq.values(): 11 | digits.append(i % (f + 1)) 12 | i = i // (f + 1) 13 | tmp = math.factorial(sum(digits)) 14 | for d in digits: 15 | tmp //= math.factorial(d) 16 | counter += tmp 17 | return counter 18 | -------------------------------------------------------------------------------- /reverse_words_in_a_string.py: -------------------------------------------------------------------------------- 1 | #problem-link: https://leetcode.com/problems/reverse-words-in-a-string/ 2 | 3 | ''' 4 | Problem Description: 5 | 6 | Given an input string s, reverse the order of the words. 7 | A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. 8 | Return a string of the words in reverse order concatenated by a single space. 9 | 10 | ''' 11 | 12 | class Solution: 13 | def reverseWords(self, s: str) -> str: 14 | 15 | sList = list(map(str, s.split())) 16 | revList = sList[::-1] 17 | rev = " ".join(s for s in revList) 18 | return rev 19 | -------------------------------------------------------------------------------- /C++/longest_substring_without_repeating_characters.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLongestSubstring(string s) { 6 | ios::sync_with_stdio; 7 | int i = 0, j = 0; 8 | int mx = 0; 9 | int cl = 0; 10 | vector mp(128, 0); 11 | while (j < s.length()) { 12 | char ch = s[j]; 13 | i = mp[ch] > i ? mp[ch] : i; 14 | cl = j - i + 1; 15 | mx = mx>cl?mx:cl; 16 | mp[s[j]] = j + 1; 17 | j++; 18 | } 19 | return mx; 20 | } 21 | }; -------------------------------------------------------------------------------- /Java/287_Find_the_Duplicate_Number.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Solution to Find the Duplicate Number at LeetCode in Java 3 | * 4 | * author: hellache 5 | * ref: https://leetcode.com/problems/find-the-duplicate-number/ 6 | */ 7 | class Solution { 8 | public int findDuplicate(int[] nums) { 9 | int p1=nums[0]; 10 | int p2=nums[0]; 11 | p1=nums[p1]; 12 | p2=nums[nums[p2]]; 13 | while(p1!=p2){ 14 | p1=nums[p1]; 15 | p2=nums[nums[p2]]; 16 | } 17 | p1=nums[0]; 18 | while(p1!=p2){ 19 | p1=nums[p1]; 20 | p2=nums[p2]; 21 | } 22 | return p1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /GO/generate_parenthesis.go: -------------------------------------------------------------------------------- 1 | // Link: https://leetcode.com/problems/generate-parentheses/ 2 | func generateParenthesis(n int) []string { 3 | combinations := []string{} 4 | backtrack(&combinations, n, "", 0, 0 ) 5 | return combinations 6 | } 7 | 8 | func backtrack(combinations *[]string, n int, currString string, open int, close int) { 9 | if len(currString) == 2*n { 10 | *combinations = append(*combinations, currString) 11 | return 12 | } 13 | 14 | if (open < n) { 15 | backtrack(combinations, n, currString + "(", open + 1, close) 16 | } 17 | if (close < open) { 18 | backtrack(combinations, n, currString + ")", open, close + 1) 19 | } 20 | return 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Python/Increasing_Triplet_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def increasingTriplet(self, nums: List[int]) -> bool: 3 | if len(nums) < 3: return False 4 | 5 | counter = 1 6 | stack = [] 7 | for i in nums: 8 | if len(stack) == 0: 9 | stack.append(i) 10 | elif i < stack[0]: 11 | stack[0] = i 12 | elif len(stack) == 1 and i > stack[0]: 13 | stack.append(i) 14 | elif len(stack) == 2 and stack[0] < i < stack[1]: 15 | stack[1] = i 16 | elif len(stack) == 2 and i > stack[1]: 17 | return True 18 | return False -------------------------------------------------------------------------------- /Python/Maximal_Square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximalSquare(self, matrix: List[List[str]]) -> int: 3 | dp=[] 4 | if len(matrix)==0: 5 | return 0 6 | col=len(matrix[0]) 7 | for i in range(len(matrix)+1): 8 | dp.append([]) 9 | for j in range(col+1): 10 | dp[i].append(0) 11 | mx=0 12 | for i in range(1,len(matrix)+1): 13 | for j in range(1,col+1): 14 | if matrix[i-1][j-1]=='1': 15 | dp[i][j]=min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1 16 | if dp[i][j]>mx: 17 | mx=dp[i][j] 18 | return mx*mx 19 | -------------------------------------------------------------------------------- /Python/Counting_Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, num: int) -> List[int]: 3 | bits = [0] 4 | 5 | for i in range(1, num+1): 6 | """ 7 | Every i*2 is just one bit off than i 8 | If i is odd, then add +1 to i*2 (just to make it odd) 9 | """ 10 | 11 | """Now divide i by 2 and 12 | access i//2 element and use above Logic 13 | """ 14 | j = i >> 1 # divide by 2 15 | 16 | if i & 1: #odd 17 | bits.append(bits[j]+1) 18 | else: 19 | bits.append(bits[j]) 20 | return bits 21 | 22 | -------------------------------------------------------------------------------- /Python/String_Compression.py: -------------------------------------------------------------------------------- 1 | # Link: https://leetcode.com/problems/string-compression/ 2 | 3 | class Solution: 4 | def compress(self, chars: List[str]) -> int: 5 | index = i = 0 6 | while i < len(chars): 7 | j = i 8 | while j < len(chars) and chars[j] == chars[i]: 9 | j += 1 10 | 11 | chars[index] = chars[i] 12 | index += 1 13 | 14 | if j - i > 1: 15 | count = str(j - i) 16 | for c in list(count): 17 | chars[index] = c 18 | index += 1 19 | 20 | i = j 21 | 22 | return index -------------------------------------------------------------------------------- /C++/Minimum_Deletion_Cost_to_Avoid_Repeating_Letters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem link: https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters/ 3 | 4 | Author: __PRAKHAR__ (leetcode id) 5 | */ 6 | 7 | class Solution { 8 | public: 9 | int minCost(string s, vector& cost) { 10 | int sum = 0; 11 | for(int i = 0; i < s.size()-1; i++) 12 | if(s[i] == s[i+1]){ 13 | sum += min(cost[i],cost[i+1]); 14 | if(cost[i+1] < cost[i]){ 15 | cost[i+1] = cost[i]; 16 | } 17 | } 18 | } 19 | return sum; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Python/encode_decode_tinyurl.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | # link: https://leetcode.com/problems/encode-and-decode-tinyurl/ 4 | 5 | class Codec: 6 | 7 | def __init__(self): 8 | self.urls = {} 9 | self.URL_BASE = "http://tinyurl.com/" 10 | 11 | 12 | def encode(self, longUrl): 13 | urlEnc = longUrl.encode('ascii') 14 | url64Enc = base64.b64encode(urlEnc) 15 | url64Dec = url64Enc.decode('ascii') 16 | self.urls[url64Dec] = longUrl 17 | return self.URL_BASE + url64Dec 18 | 19 | 20 | def decode(self, shortUrl: str) -> str: 21 | urlSplited = shortUrl.split('/', 3) 22 | urlDecoded = self.urls[urlSplited[-1]] 23 | return urlDecoded 24 | -------------------------------------------------------------------------------- /C++/Count_Square_Sub-matrices_with_All_Ones.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/count-square-submatrices-with-all-ones/solution/ 2 | class Solution { 3 | public: 4 | int countSquares(vector>& matrix) { 5 | int result=0; 6 | int row = matrix.size(); 7 | int col = matrix[0].size(); 8 | for(int i=0;i0 && i>0 && j>0) 13 | { 14 | matrix[i][j]=min(matrix[i-1][j],min(matrix[i-1][j-1],matrix[i][j-1]))+1; 15 | } 16 | result+=matrix[i][j]; 17 | } 18 | } 19 | 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/MedianofTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | // Leetcode problem Link: https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | 3 | class Solution { 4 | public: 5 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 6 | vector vec(nums1); 7 | for(auto i:nums2) 8 | { 9 | vec.push_back(i); 10 | } 11 | sort(vec.begin(),vec.end()); 12 | int num=vec.size(); 13 | double median=0; 14 | if(num%2==0) 15 | { 16 | median=(double)(vec[(num-1)/2] + vec[((num-1)/2)+1]) / 2; 17 | } 18 | if(num%2!=0) 19 | { 20 | median=(double)vec[(num-1)/2]; 21 | } 22 | return median; 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/Permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permute(vector& nums) { 4 | vector> res; 5 | vector temp; 6 | backtrack(res,temp,nums,nums.size()); 7 | return res; 8 | } 9 | void backtrack(vector>& res,vector temp,vector nums, int n){ 10 | if(n==0){ 11 | res.push_back(temp); 12 | return; 13 | } 14 | for(int i=0;i temporaryNums = nums; 17 | temporaryNums.erase(temporaryNums.begin()+i); 18 | backtrack(res,temp,temporaryNums,n-1); 19 | temp.pop_back(); 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/TopKFrequent.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | sort(nums.begin(),nums.end()); 5 | priority_queue > p; 6 | int cur=nums[0]; 7 | int freq=1; 8 | for(int i=1;i res; 19 | for(int i=0;i counter; 18 | for(auto x : s){ 19 | counter[x]++; 20 | } 21 | sort(s.begin(),s.end(), 22 | [&](char a, char b){return counter[a] > counter[b] || (counter[a] == counter[b] && a < b);} 23 | ); 24 | return s; 25 | } 26 | 27 | 28 | }; -------------------------------------------------------------------------------- /C++/Sort_Colors.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/sort-colors/ 2 | 3 | class Solution { 4 | public: 5 | void sortColors(vector& nums) { 6 | int low=0, mid=0, high=nums.size()-1; 7 | while(mid <= high){ 8 | switch(nums[mid]){ 9 | case 0: 10 | swap(nums[mid++], nums[low++]); 11 | break; 12 | case 1: 13 | mid++; 14 | break; 15 | default: 16 | swap(nums[mid],nums[high--]); 17 | 18 | } 19 | } 20 | } 21 | }; 22 | 23 | /* 24 | * Hint : If asked to sort array of 3 numbers(elements) only 25 | * Variation of dutch national flag problem 26 | */ 27 | -------------------------------------------------------------------------------- /Javascript/Add_Two_Numbers.js: -------------------------------------------------------------------------------- 1 | // problem link: https://www.leetcode.com/problems/add-two-numbers/ 2 | 3 | // recursive call approach currently clocking @124ms runtime, 4 | // faster than 90.92% amongst all other javascript submissions 5 | // of the same problem. 6 | const addTwoNumbers = (list1, list2, carry = 0) => { 7 | const sum = (list1?.val ?? 0) + (list2?.val ?? 0) + carry; 8 | carry = sum > 9 ? 1 : 0; 9 | if ( 10 | (list1 === undefined || list1 === null || list1.next === null) && 11 | (list2 === undefined || list2 === null || list2.next === null) && 12 | carry == 0 13 | ) { 14 | return new ListNode(sum % 10, null); 15 | } 16 | return new ListNode(sum % 10, addTwoNumbers(list1?.next, list2?.next, carry)); 17 | }; -------------------------------------------------------------------------------- /Python/Reordered_Power_of_2.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/reordered-power-of-2/ 2 | import math 3 | 4 | 5 | class Solution: 6 | def reorderedPowerOf2(self, N: int) -> bool: 7 | """ 8 | Returns true if any reordering (including the original) of an integer N results in a power of 2 9 | The reordering must not contain zeroes as leading digits 10 | """ 11 | N_string = str(N) 12 | log2 = math.log10(2) 13 | 14 | min_power = math.ceil((len(N_string) - 1) / log2) 15 | max_power = math.floor(len(N_string) / log2) 16 | for p in range(min_power, max_power + 1): 17 | if set(str(2 ** p)) == set(N_string): 18 | return True 19 | return False 20 | 21 | -------------------------------------------------------------------------------- /C++/Next_Permutation.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/next-permutation/ 2 | class Solution { 3 | public: 4 | void nextPermutation(vector& nums) { 5 | int g=-1,s=-1,n=nums.size(),i=n-1; 6 | for(i=n-1;i>0;i--){ 7 | if(nums[i]>nums[i-1]){ 8 | g=s; 9 | s=i-1; 10 | break; 11 | } 12 | } 13 | if(s!=-1){ 14 | for(i=n-1;i>g;i--){ 15 | if(nums[i]>nums[s]){ 16 | g=i; 17 | break; 18 | } 19 | } 20 | swap(nums[g],nums[s]); 21 | reverse(nums.begin()+s+1,nums.end()); 22 | } 23 | else 24 | reverse(nums.begin(),nums.end()); 25 | } 26 | }; -------------------------------------------------------------------------------- /Java/SortColors.java: -------------------------------------------------------------------------------- 1 | /* https://leetcode.com/problems/sort-colors/ */ 2 | /* Solving without using the inbuilt "sorting" function which is given in many programming languages because here we have to sort 'in-place' and in linear time */ 3 | /* The time complexity-O(n) Space complexity-O(1) */ 4 | 5 | class Solution{ 6 | public void sortColors(int[] nums) { 7 | int p1=0,index=0,p2=nums.length-1; 8 | int temp; 9 | 10 | while(index <= p2){ 11 | if (nums[index]==0){ 12 | temp=nums[index]; 13 | nums[index]=nums[p1]; 14 | nums[p1]=temp; 15 | p1++; 16 | } 17 | if (nums[index]==2){ 18 | temp=nums[index]; 19 | nums[index]=nums[p2]; 20 | nums[p2]=temp; 21 | p2--; 22 | index--; 23 | } 24 | index++; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Python/743_Network_Delay_Time.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/network-delay-time/ 2 | 3 | from collections import deque 4 | 5 | class Solution: 6 | def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: 7 | self.graph = [deque() for i in range(N+1)] 8 | for u, v, w in times: 9 | self.graph[u].append((v, w)) 10 | 11 | self.dist = [float('inf')] * (N+1) 12 | self.dfs(K) 13 | tot = max(self.dist[1:]) 14 | return tot if tot != float('inf') else -1 15 | 16 | def dfs(self, v, elapsed=0): 17 | if elapsed >= self.dist[v]: return 18 | 19 | self.dist[v] = elapsed 20 | for neighbor, weight in self.graph[v]: 21 | self.dfs(neighbor, elapsed + weight) 22 | -------------------------------------------------------------------------------- /Python/654_Maximum_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/maximum-binary-tree/ 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, val=0, left=None, right=None): 5 | # self.val = val 6 | # self.left = left 7 | # self.right = right 8 | class Solution: 9 | def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: 10 | if len(nums) > 0: 11 | max_elem = max(nums) 12 | max_pos = nums.index(max_elem) 13 | nums.remove(max_elem) 14 | return TreeNode(max_elem, 15 | self.constructMaximumBinaryTree(nums[:max_pos]), 16 | self.constructMaximumBinaryTree(nums[max_pos:])) 17 | return None -------------------------------------------------------------------------------- /Python/Product_of_the _last_k_numbers.py: -------------------------------------------------------------------------------- 1 | class ProductOfNumbers: 2 | 3 | def __init__(self): 4 | self.arr=[1] 5 | self.mul=1 6 | 7 | def add(self, num: int) -> None: 8 | if num == 0: 9 | self.mul=1 10 | self.arr=[1] 11 | else: 12 | self.mul*=num 13 | self.arr.append(self.mul) 14 | 15 | def getProduct(self, k: int) -> int: 16 | l=len(self.arr)-1 # -1 is because I add more 1 to the list at the beggining 17 | if k>l: 18 | return 0 19 | else: 20 | return (self.mul//self.arr[l-k]) 21 | 22 | 23 | # Your ProductOfNumbers object will be instantiated and called as such: 24 | # obj = ProductOfNumbers() 25 | # obj.add(num) 26 | # param_2 = obj.getProduct(k) 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode_Algorithms (Medium/Hard) 2 | 3 | A Collection of solutions for **Medium/Hard** leetcode problems in different languages : Python, C, C++, Java, Ruby, Go. (Feel free to add more). To ensure quality of pull requests instead of quantity , we've decided to consider only Medium and Hard problems from the Leetcode question factory. Also, we'll be checking all the PR's to ensure that there's no plagiarisn. 4 | 5 | ### Why? 6 | This repository is just for educational purpose and for any future reference by anyone 7 | 8 | ### Contribution 9 | Please read the [Contribution Guidelines](./CONTRIBUTING.md) before you contribute. 10 | Please bear with the delays in reviewing or assigning an issue as I'm a working professional. Also, priority would be given to first time contributors. 11 | -------------------------------------------------------------------------------- /Python/Find_And_Replace_Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def get_num_word(self, word: str): 3 | num = '' 4 | alphabets = [None] * 26 5 | for i, letter in enumerate(word): 6 | position = ord(letter) - 97 7 | if alphabets[position] == None: 8 | alphabets[position] = i 9 | num += str(i) 10 | else: 11 | num += str(alphabets[position]) 12 | return num 13 | 14 | def findAndReplacePattern(self, words, pattern: str): 15 | numPattern = self.get_num_word(pattern) 16 | matched = [] 17 | for word in words: 18 | numWord = self.get_num_word(word) 19 | if numPattern == numWord: 20 | matched.append(word) 21 | return matched -------------------------------------------------------------------------------- /C++/SortList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* sortList(ListNode* head) { 14 | vector v; 15 | ListNode *tmp = head; 16 | while(tmp!=NULL){ 17 | v.push_back(tmp->val); 18 | tmp = tmp->next; 19 | } 20 | sort(v.begin(),v.end()); 21 | int i=0; 22 | tmp=head; 23 | while(ival = v[i++]; 25 | tmp=tmp->next; 26 | } 27 | return head; 28 | } 29 | }; -------------------------------------------------------------------------------- /Python/312_Burst_Balloons.py: -------------------------------------------------------------------------------- 1 | from math import inf 2 | 3 | class Solution: 4 | dp=[] 5 | def initDP(self,n): 6 | self.dp=[[-1 for i in range(n+1)] for j in range(n+1)] 7 | def maxCoins(self, nums: List[int]) -> int: 8 | n=len(nums) 9 | self.initDP(n) 10 | return(self.minCost([1]+nums+[1],1,n)) 11 | 12 | 13 | def minCost(self,m,i,j): 14 | 15 | if(i==j): 16 | return m[i-1]*m[i]*m[i+1] 17 | if(i>j): 18 | return 0 19 | 20 | if(self.dp[i][j]!=-1): 21 | return self.dp[i][j] 22 | mini=0 23 | for k in range(i,j+1): 24 | val=self.minCost(m,i,k-1)+self.minCost(m,k+1,j)+m[i-1]*m[k]*m[j+1] 25 | mini=max(mini,val) 26 | self.dp[i][j]=mini 27 | return mini 28 | -------------------------------------------------------------------------------- /C++/LongestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | vector> dp(nums.size()+1,vector(nums.size()+1,0)); 5 | vector a; 6 | vector s=nums; 7 | sort(s.begin(),s.end()); 8 | a.push_back(s[0]); 9 | for(int i=1;i= '0' && str[i] <= '9') { 10 | base = 10 * base + (str[i++] - '0'); 11 | if (base > INT_MAX) { 12 | if (sign == -1) return INT_MIN; 13 | return INT_MAX; 14 | } 15 | } 16 | if (base > INT_MAX) { 17 | if (sign == -1) 18 | return INT_MIN; 19 | else 20 | return INT_MAX; 21 | } 22 | return (int)base * sign; 23 | } 24 | }; -------------------------------------------------------------------------------- /Python/String_to_Integer_atoi.py: -------------------------------------------------------------------------------- 1 | # leetcode problem link: https://leetcode.com/problems/string-to-integer-atoi/ 2 | 3 | class Solution: 4 | def myAtoi(self, str: str) -> int: 5 | num, i = [], 0 6 | while i < len(str) and str[i] == ' ': 7 | i += 1 8 | if i < len(str) and (str[i] == '-' or str[i] == '+'): 9 | num.append(str[i]) 10 | i += 1 11 | while i < len(str) and str[i].isdigit(): 12 | num.append(str[i]) 13 | i += 1 14 | if len(num) == 0: 15 | return 0 16 | if not num[-1].isdigit(): 17 | return 0 18 | ans = int(''.join(num)) 19 | if ans < -(1 << 31): 20 | return -(1 << 31) 21 | if ans > (1 << 31) - 1: 22 | return (1 << 31) - 1 23 | return ans 24 | -------------------------------------------------------------------------------- /1329_Sort_the_Matrix_Diagonally_(Medium).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: 3 | if not mat: return [[]] 4 | m = len(mat) 5 | n = len(mat[0]) 6 | dlen = m + n - 1 7 | diff = n - m 8 | diagonals = [] 9 | for i in range(dlen): 10 | diagonals.append([]) 11 | for i in range(m): 12 | for j in range(n): 13 | diagonals[diff + i-j].append(mat[i][j]) 14 | 15 | for i in range(dlen): 16 | diagonals[i] = sorted(diagonals[i]) 17 | 18 | for i in range(m): 19 | for j in range(n): 20 | i_d = diff + i - j 21 | j_d = min(j, i) 22 | mat[i][j] = diagonals[i_d][j_d] 23 | 24 | return mat 25 | -------------------------------------------------------------------------------- /C++/ShuffleAnArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nums; 4 | Solution(vector& nums) { 5 | this->nums=nums; 6 | } 7 | 8 | /** Resets the array to its original configuration and return it. */ 9 | vector reset() { 10 | return nums; 11 | } 12 | 13 | /** Returns a random shuffling of the array. */ 14 | vector shuffle() { 15 | vector nw(nums); 16 | for(int i=0;i param_1 = obj->reset(); 28 | * vector param_2 = obj->shuffle(); 29 | */ 30 | -------------------------------------------------------------------------------- /C++/Longest_Palindrome_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPalindromeSubseq(string s) { 4 | string s2 = string(s.rbegin(),s.rend()); 5 | int dp[s.size() + 1][s2.size()+1]; 6 | 7 | for(int i = 0 ; i< s.size() + 1 ; i++){ 8 | dp[i][0] = 0; 9 | } 10 | for(int i = 1 ; i< s2.size() + 1 ; i++){ 11 | dp[0][i] = 0; 12 | } 13 | 14 | for(int i = 1 ; i<= s.size() ; i++){ 15 | for(int j = 1 ; j<= s2.size() ; j++){ 16 | if(s[i-1] == s2[j-1]){ 17 | dp[i][j] = dp[i-1][j-1] + 1; 18 | }else{ 19 | dp[i][j] = max(dp[i-1][j] , dp[i][j-1]); 20 | } 21 | } 22 | } 23 | 24 | return dp[s.size()][s2.size()]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/Rotate_List.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-list/ 2 | 3 | class Solution { 4 | public: 5 | ListNode* rotateRight(ListNode* head, int k) { 6 | if (head == NULL) 7 | return head; 8 | else if (head->next == NULL) 9 | return head; 10 | vector address; 11 | ListNode* temp = head; 12 | 13 | while(temp != NULL) 14 | { 15 | address.push_back(temp); 16 | temp = temp->next; 17 | } 18 | 19 | int r = k % address.size(); 20 | cout << r << endl; 21 | if (r > 0) 22 | { 23 | int len = address.size(); 24 | address[len-r-1]->next = NULL; 25 | address[len-1]->next = head; 26 | head = address[len-r]; 27 | } 28 | return head; 29 | } 30 | }; -------------------------------------------------------------------------------- /Javascript/Divide_Two_Integers.js: -------------------------------------------------------------------------------- 1 | // problem link: https://leetcode.com/problems/divide-two-integers/ 2 | 3 | // Runtime: 109 ms, faster than 48.23% of JavaScript online submissions for Divide Two Integers. 4 | 5 | const divide = (dividend, divisor) => { 6 | if (dividend === -2147483648 && divisor === -1) return 2147483647 7 | let ans = 0 8 | let sign = 1 9 | if (dividend < 0) { 10 | dividend = -dividend 11 | sign = -sign 12 | } 13 | if (divisor < 0) { 14 | divisor = -divisor 15 | sign = -sign 16 | } 17 | if (dividend === divisor) return sign 18 | for (let i = 0, val = divisor; dividend >= divisor; i = 0, val = divisor) { 19 | while (val > 0 && val <= dividend) { 20 | val = divisor << ++i 21 | } 22 | dividend -= divisor << (i - 1) 23 | ans += 1 << (i - 1) 24 | } 25 | return sign < 0 ? -ans : ans 26 | } 27 | -------------------------------------------------------------------------------- /Python/Binary_Tree_Inorder_Traversal.py: -------------------------------------------------------------------------------- 1 | #LeetCode problem link: https://leetcode.com/problems/binary-tree-inorder-traversal/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode(object): 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution(object): 10 | def inorderTraversal(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | self.node_list = [] 16 | if root != None: 17 | self.inorder(root) 18 | return self.node_list 19 | 20 | def inorder(self, node): 21 | if node.left: 22 | self.inorder(node.left) 23 | self.node_list.append(node.val) 24 | if node.right: 25 | self.inorder(node.right) 26 | -------------------------------------------------------------------------------- /Java/PalindromicSubstrings647.java: -------------------------------------------------------------------------------- 1 | // This problem was taken from: https://leetcode.com/problems/palindromic-substrings/ 2 | 3 | public class PalindromicSubstrings647 { 4 | 5 | public int cnt_palindrome(String s, int left, int right, int i){ 6 | int cnt = 0; 7 | while (s.charAt(left) == s.charAt(right)){ 8 | cnt ++; 9 | left --; 10 | right ++; 11 | 12 | if (left < 0 || right >= s.length()) 13 | break; 14 | } 15 | return cnt; 16 | } 17 | 18 | public int countSubstrings(String s) { 19 | int cnt = 0; 20 | for(int i = 0; i < s.length(); i++) { 21 | cnt += cnt_palindrome(s, i, i, i); 22 | if (i+1 < s.length()) 23 | cnt += cnt_palindrome(s, i, i+1, i); 24 | } 25 | return cnt; 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /C++/Pow_x,n.cpp: -------------------------------------------------------------------------------- 1 | //Leetcode Problem Link:https://leetcode.com/problems/counting-bits/ 2 | 3 | 4 | 5 | class Solution { 6 | public: 7 | double myPow1(double x,int n){ 8 | 9 | if(n==0){ 10 | return 1; 11 | } 12 | else{ 13 | 14 | double y=myPow1(x,n/2); 15 | //For Even Numbers 16 | if(n%2==0){ 17 | return y*y; 18 | } 19 | //For Odd Numbers 20 | else{ 21 | return x*y*y; 22 | } 23 | } 24 | 25 | 26 | } 27 | 28 | double myPow(double x, int n) { 29 | //Calling myPow1 30 | double ans= myPow1(x,n); 31 | if(n>=0){ 32 | return ans; 33 | } 34 | else{ 35 | return (1/ans); 36 | } 37 | 38 | 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /C++/Permutation_Sequence.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/permutation-sequence/ 2 | class Solution { 3 | public: 4 | string getPermutation(int n, int k) { 5 | vector chck(n+1,false); 6 | vector fac={1,1,2,6,24,120,720,5040,40320,362880}; 7 | string ans; 8 | int len=0; 9 | while(len!=n) 10 | { 11 | int x=(k-1)/fac[n-len-1]; 12 | k-=fac[n-len-1]*x; 13 | int count=0; 14 | for(int i=1;i<=n;i++) 15 | { 16 | if(chck[i]==false) 17 | count++; 18 | if(count==(x+1)) 19 | { 20 | chck[i]=true; 21 | ans+=i+48; 22 | len++; 23 | break; 24 | } 25 | } 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/longest_valid_parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* Problem link -> https://leetcode.com/problems/longest-valid-parentheses/ */ 2 | 3 | 4 | class Solution { 5 | public: 6 | int longestValidParentheses(string s) { 7 | stack st; 8 | 9 | int ans = 0,cur=0; 10 | for(int i =0;i { 6 | candidates.sort((a, b) => a - b) 7 | return helper(candidates, target) 8 | } 9 | const helper = ( 10 | candidates, 11 | target, 12 | start = 0, 13 | sum = 0, 14 | selected = [], 15 | output = [] 16 | ) => { 17 | if (sum >= target) { 18 | if (sum === target) { 19 | output.push([...selected]) 20 | } 21 | return output 22 | } 23 | for (let i = start; i < candidates.length; i++) { 24 | if (sum + candidates[i] > target) break 25 | selected.push(candidates[i]) 26 | helper(candidates, target, i, sum + candidates[i], selected, output) 27 | selected.pop() 28 | } 29 | return output 30 | } 31 | -------------------------------------------------------------------------------- /Python/Next_Permutation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/next-permutation/ 2 | 3 | class Solution: 4 | def nextPermutation(self, nums: List[int]) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | i = len(nums) - 2 9 | while(i >= 0 and nums[i] >= nums[i + 1]): 10 | i -= 1 11 | 12 | if(i == -1): 13 | nums.sort() 14 | return 15 | 16 | j = len(nums) - 1 17 | while(j > i): 18 | if(nums[j] > nums[i]): 19 | nums[j], nums[i] = nums[i], nums[j] 20 | break 21 | j -= 1 22 | 23 | start = i + 1 24 | end = len(nums) -1 25 | while(start < end): 26 | nums[start], nums[end] = nums[end], nums[start] 27 | start += 1 28 | end -= 1 29 | -------------------------------------------------------------------------------- /Python/Spiral_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def spiralOrder(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: List[int] 6 | """ 7 | k, l = 0, 0 8 | m = len(matrix) 9 | n = len(matrix[0]) 10 | res = [] 11 | while (k < m and l < n): 12 | for i in range(l, n): 13 | res.append(matrix[k][i]) 14 | k += 1 15 | for i in range(k, m): 16 | res.append(matrix[i][n-1]) 17 | n -= 1 18 | if (k < m): 19 | for i in range(n-1, (l-1), -1): 20 | res.append(matrix[m-1][i]) 21 | m -= 1 22 | if (l < n): 23 | for i in range(m-1, k-1, -1): 24 | res.append(matrix[i][l]) 25 | l += 1 26 | return res 27 | 28 | 29 | -------------------------------------------------------------------------------- /Python/25. ReverseNodesInK-Group.py: -------------------------------------------------------------------------------- 1 | """ 2 | 25. Reverse Nodes in K-Group 3 | 4 | The program uses a variable(finchk) to check if there are enough(k) nodes remaining to reverse. 5 | If so, it reverses connection(k-1) between each pair of nodes(k) and moves to next group. 6 | If not, it returns the current linked list as answer. 7 | """ 8 | 9 | class Solution: 10 | def reverseKGroup(self, head: ListNode, k: int) -> ListNode: 11 | dummy, dummy.next = ListNode(0), head 12 | prev, cur = dummy, dummy.next 13 | finchk = cur 14 | 15 | while 1: 16 | for _ in range(k): 17 | if not finchk: return dummy.next 18 | finchk = finchk.next 19 | for _ in range(k-1): 20 | cur.next.next, cur.next, prev.next = prev.next, cur.next.next, cur.next 21 | prev, cur = cur, cur.next 22 | return dummy.next 23 | -------------------------------------------------------------------------------- /C++/RemoveNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * ListNode *next; 7 | * ListNode() : val(0), next(nullptr) {} 8 | * ListNode(int x) : val(x), next(nullptr) {} 9 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | ListNode* removeNthFromEnd(ListNode* head, int n) { 15 | ListNode *first,*second; 16 | second=head; 17 | first=new ListNode(-1,head); 18 | ListNode *res=first; 19 | for(int i=0;inext; 21 | } 22 | while(second!=NULL){ 23 | first=first->next; 24 | second=second->next; 25 | } 26 | first->next=first->next->next; 27 | return res->next; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Python/647_Palindromic_Substrings.py: -------------------------------------------------------------------------------- 1 | # Palindromic Substrings 2 | # Problem link: https://leetcode.com/problems/palindromic-substrings/ 3 | # 4 | # Given a string, your task is to count how many palindromic substrings in this string. 5 | # Input: "abc" 6 | # Output: 3 7 | # Explanation: Three palindromic strings: "a", "b", "c". 8 | 9 | ''' 10 | Approach 11 | Iterate through the string character by character 12 | While iterating, check all the palindromes from the current character till the end 13 | ''' 14 | 15 | class Solution: 16 | def isPalindrome(self, sub_s: str) -> bool: 17 | return sub_s == sub_s[::-1] 18 | 19 | def countSubstrings(self, s: str) -> int: 20 | count = len(s) 21 | for index in range(len(s)): 22 | for sub_index in range(index+1, len(s)): 23 | if self.isPalindrome(s[index:sub_index+1]): 24 | count += 1 25 | return count 26 | -------------------------------------------------------------------------------- /GO/add_two_numbers.go: -------------------------------------------------------------------------------- 1 | // Link: https://leetcode.com/problems/add-two-numbers/ 2 | package main 3 | 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 10 | sol := new(ListNode) 11 | var indexSol *ListNode 12 | pass1 := false 13 | 14 | for { 15 | sum := 0 16 | if l1 != nil || l2 != nil { 17 | if l1 != nil { 18 | sum = l1.Val 19 | l1 = l1.Next 20 | } 21 | if l2 != nil { 22 | sum += l2.Val 23 | l2 = l2.Next 24 | } 25 | } else if !pass1 { 26 | break 27 | } 28 | 29 | if pass1 { 30 | sum++ 31 | } 32 | if sum > 9 { 33 | pass1 = true 34 | } else { 35 | pass1 = false 36 | } 37 | 38 | var val = sum % 10 39 | if indexSol == nil { 40 | sol.Val = val 41 | indexSol = sol 42 | } else { 43 | indexSol.Next = &ListNode{Val: val} 44 | indexSol = indexSol.Next 45 | } 46 | } 47 | 48 | return sol 49 | } 50 | -------------------------------------------------------------------------------- /Python/ValidSudoku.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-sudoku/ 2 | class Solution: 3 | def isValidSudoku(self, board: List[List[str]]) -> bool: 4 | column={} 5 | row={} 6 | box={} 7 | for i in range(len(board)): 8 | column[i]=[] 9 | row[i]=[] 10 | box[i]=[] 11 | for i in range(len(board)): 12 | for j in range(len(board)): 13 | row[i].append(board[i][j]) 14 | column[j].append(board[i][j]) 15 | box[(i//3)*3+j//3].append(board[i][j]) 16 | 17 | for i in range(len(board)): 18 | for j in range(1,10): 19 | if row[i].count(str(j))>1: 20 | return False 21 | if column[i].count(str(j))>1: 22 | return False 23 | if box[i].count(str(j))>1: 24 | return False 25 | return True 26 | -------------------------------------------------------------------------------- /Java/48_RotateImage.java: -------------------------------------------------------------------------------- 1 | link: https://leetcode.com/problems/rotate-image/ 2 | 3 | class Solution { 4 | public void rotate(int[][] matrix) { 5 | int n=matrix.length; 6 | for(int layer=0; layer top 14 | matrix[layer][i] = matrix[last-offset][first]; 15 | 16 | //bottom -> left 17 | matrix[last-offset][first] = matrix[last][last-offset]; 18 | 19 | //right -> bottom 20 | matrix[last][last-offset] = matrix[i][last]; 21 | 22 | //top -> right 23 | matrix[i][last] = top; 24 | } 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Python/BinaryTreeLevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-tree-level-order-traversal/ 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, val=0, left=None, right=None): 5 | # self.val = val 6 | # self.left = left 7 | # self.right = right 8 | class Solution: 9 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 10 | if not root: 11 | return list() 12 | levels=[] 13 | q=[(0,root)] 14 | res=[] 15 | while q: 16 | cur=q[0] 17 | if cur[0] not in levels: 18 | levels.append(cur[0]) 19 | res.append([]) 20 | res[cur[0]].append(cur[1].val) 21 | del q[0] 22 | if cur[1].left: 23 | q.append((cur[0]+1,cur[1].left)) 24 | if cur[1].right: 25 | q.append((cur[0]+1,cur[1].right)) 26 | 27 | return res 28 | -------------------------------------------------------------------------------- /Python/LRUCache.py: -------------------------------------------------------------------------------- 1 | class LRUCache: 2 | 3 | def __init__(self, capacity: int): 4 | self.a=[] 5 | self.d={} 6 | self.cap=capacity 7 | 8 | def get(self, key: int) -> int: 9 | if(key in self.a): 10 | self.a.remove(key) 11 | self.a.insert(0,key) 12 | #print("get",self.a) 13 | return self.d[key] 14 | 15 | return -1 16 | 17 | def put(self, key: int, value: int) -> None: 18 | 19 | if key in self.d: 20 | if key in self.a: 21 | self.a.remove(key) 22 | 23 | if (len(self.a)==self.cap): 24 | self.a.pop() 25 | 26 | self.a.insert(0,key) 27 | 28 | self.d[key]=value 29 | #print("put",self.a) 30 | 31 | 32 | 33 | # Your LRUCache object will be instantiated and called as such: 34 | # obj = LRUCache(capacity) 35 | # param_1 = obj.get(key) 36 | # obj.put(key,value) 37 | -------------------------------------------------------------------------------- /C++/Kth_Smallest_Element_BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int find(TreeNode* root,int& cnt,int k) 15 | { 16 | if(root==NULL) 17 | return -1; 18 | int kth=find(root->left,cnt,k); 19 | if(kth!=-1) 20 | { 21 | return kth; 22 | } 23 | cnt+=1; 24 | if(cnt==k) 25 | { 26 | return root->val; 27 | } 28 | return find(root->right,cnt,k); 29 | } 30 | int kthSmallest(TreeNode* root, int k) { 31 | int cnt=0; 32 | return find(root,cnt,k); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Java/ReplaceWords648.java: -------------------------------------------------------------------------------- 1 | public class ReplaceWords648 { 2 | public String replaceWords(List dictionary, String sentence) { 3 | String result = ""; 4 | String[] splitSentence = sentence.split(" "); 5 | for (String word:splitSentence) { 6 | result += " " + getRoot(word, dictionary); 7 | } 8 | return result.substring(1,result.length()); 9 | } 10 | 11 | public String getRoot(String word, List dictionary) { 12 | int len = word.length(); 13 | String rootResult = ""; 14 | for (String root:dictionary) { 15 | if (word.length() < root.length()) 16 | continue; 17 | if ((word.substring(0,root.length())).equals(root) && root.length() < len){ 18 | rootResult = root; 19 | len = root.length(); 20 | } 21 | } 22 | if (rootResult.equals("")) 23 | return word; 24 | return rootResult; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /C++/largest_rectangle_in_histogram.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | 3 | class Solution { 4 | public: 5 | int largestRectangleArea(vector& heights) { 6 | stacks; 7 | int area_with_top=0; 8 | int area=0; 9 | int i=0; 10 | int n=heights.size(); 11 | while(i { 6 | let n1 = num1 7 | let n2 = num2 8 | 9 | if (parseInt(n1) === 0 || parseInt(n2) === 0) { 10 | return '0' 11 | } 12 | 13 | n1 = n1.split('').reverse() 14 | n2 = n2.split('').reverse() 15 | const result = [] 16 | 17 | for (let i = 0; n1[i] >= 0; i++) { 18 | for (let j = 0; n2[j] >= 0; j++) { 19 | if (!result[i + j]) { 20 | result[i + j] = 0 21 | } 22 | 23 | result[i + j] += n1[i] * n2[j] 24 | } 25 | } 26 | 27 | for (let i = 0; result[i] >= 0; i++) { 28 | if (result[i] >= 10) { 29 | if (!result[i + 1]) { 30 | result[i + 1] = 0 31 | } 32 | 33 | result[i + 1] += parseInt(result[i] / 10) 34 | result[i] %= 10 35 | } 36 | } 37 | 38 | return result.reverse().join('') 39 | } 40 | -------------------------------------------------------------------------------- /Python/Reorder_List.py: -------------------------------------------------------------------------------- 1 | # LeetCode link: https://leetcode.com/problems/reorder-list/ 2 | # Issue: https://github.com/noisefilter19/LeetCode_Algorithms/issues/522 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | 9 | class Solution: 10 | def reorderList(self, head: ListNode) -> None: 11 | curr = head 12 | temp_array = [] 13 | while curr: 14 | temp_array.append(curr) 15 | curr = curr.next 16 | left = 0 17 | right = len(temp_array) - 1 18 | curr = head 19 | for _ in range(len(temp_array)): 20 | if _ % 2 == 0: 21 | curr.next = temp_array[left] 22 | left += 1 23 | else: 24 | curr.next = temp_array[right] 25 | right -= 1 26 | curr = curr.next 27 | if left > right: 28 | curr.next = None 29 | 30 | -------------------------------------------------------------------------------- /Python/ZigZag_Conversion.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://leetcode.com/problems/zigzag-conversion/ 2 | 3 | class Solution: 4 | def convert(self, s: str, numRows: int) -> str: 5 | if (numRows <= 1): 6 | return s 7 | 8 | elif (numRows == 2): 9 | output1 = "" 10 | output2 = "" 11 | for i in range(len(s)): 12 | if (i % 2 == 0): 13 | output1 += s[i] 14 | else: 15 | output2 += s[i] 16 | return (output1 + output2) 17 | 18 | else: 19 | output = [] 20 | direction = -1 21 | rowNumber = 0 22 | 23 | for i in range(numRows): 24 | output.append("") 25 | 26 | for j in range(len(s)): 27 | output[rowNumber] += s[j] 28 | if ((rowNumber == 0) or (rowNumber == numRows - 1)): 29 | direction *= -1 30 | rowNumber += direction 31 | 32 | return ("".join(output)) -------------------------------------------------------------------------------- /Java/Linked List Cycle II.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle-ii/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { 9 | * val = x; 10 | * next = null; 11 | * } 12 | * } 13 | */ 14 | public class Solution { 15 | public ListNode detectCycle(ListNode head) { 16 | ListNode fast=head; 17 | ListNode slow=head; 18 | boolean flag=false; 19 | while(fast!=null && fast.next!=null && slow!=null){ 20 | fast=fast.next.next; 21 | slow=slow.next; 22 | if(slow==fast){ 23 | flag=true; 24 | break; 25 | } 26 | } 27 | if(flag){ 28 | slow=head; 29 | while(slow!=fast){ 30 | slow=slow.next; 31 | fast=fast.next; 32 | } 33 | return slow; 34 | }else{ 35 | return null; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /C++/Decode_Ways.cpp: -------------------------------------------------------------------------------- 1 | //LeetCode Problem link - https://leetcode.com/problems/decode-ways/ 2 | class Solution 3 | { 4 | public: 5 | int numDecodings(string s) 6 | { 7 | int size = s.size(); 8 | if (size == 0) 9 | return 0; 10 | if (s[0] == '0') 11 | return 0; 12 | int output[size + 1]; 13 | output[0] = 1; 14 | output[1] = 1; 15 | for (int i = 2; i <= size; i++) 16 | { 17 | if (s[i - 1] == '0') 18 | { 19 | if (s[i - 2] == '1' || s[i - 2] == '2') 20 | output[i] = output[i - 2]; 21 | else 22 | return 0; 23 | } 24 | else 25 | { 26 | output[i] = output[i - 1]; 27 | if ((((s[i - 2] - '0') * 10 + (s[i - 1] - '0')) <= 26) && s[i - 2] != '0') 28 | output[i] = ((output[i]) + (output[i - 2])); 29 | } 30 | } 31 | int ans = output[size]; 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/Longest_Palindromic_Substring.cpp: -------------------------------------------------------------------------------- 1 | //LeetCode Problem link - https://leetcode.com/problems/longest-palindromic-substring/ 2 | 3 | class Solution { 4 | public: 5 | string longestPalindrome(string str) { 6 | int n=str.length(); 7 | vector> dp(n,vector(n,0)); 8 | int maxLen=-10,si=0,ei=0; 9 | for(int gap=0;gapmaxLen) 22 | { 23 | maxLen=dp[i][j]; 24 | si=i; 25 | ei=j; 26 | } 27 | } 28 | } 29 | 30 | return str.substr(si,ei-si+1); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C/Rotate_List.c: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/problems/rotate-list/submissions/ 3 | */ 4 | /** 5 | * Definition for singly-linked list. 6 | * struct ListNode { 7 | * int val; 8 | * struct ListNode *next; 9 | * }; 10 | */ 11 | 12 | 13 | struct ListNode *rotateRight(struct ListNode *head, int k) { 14 | if (!head || k == 0) return head; 15 | 16 | /* 17 | Used to count the size of the array. 18 | */ 19 | struct ListNode* lastNode = head; 20 | int n = 1; 21 | while (lastNode->next) 22 | { 23 | lastNode = lastNode->next; 24 | n++; 25 | } 26 | 27 | /* 28 | Used to remove any complete rotations from the list. 29 | Example: If size of list is n, and no. of rotations = k 30 | if (n==k) 31 | then no rotations is required. 32 | so n = n%k removes all complete roations. 33 | */ 34 | k = k%n; 35 | if (k == 0) return head; 36 | k = n - k; 37 | 38 | lastNode->next = head; 39 | struct ListNode *newHead = head; 40 | 41 | for (int i = 0; i < k - 1; i++) 42 | newHead = newHead->next; 43 | 44 | head = newHead->next; 45 | newHead->next = NULL; 46 | return head; 47 | } 48 | -------------------------------------------------------------------------------- /Python/n_queens_ii.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/n-queens-ii/ 2 | 3 | class Solution: 4 | def totalNQueens(self, n: int) -> int: 5 | self.result = 0 6 | self.backtrack(0, n, []) 7 | 8 | return self.result 9 | 10 | 11 | def isValid(self, i, j, n, positions): 12 | if 0 <= i < n and 0 <= j < n: 13 | for pos in positions: 14 | i1, j1 = pos 15 | 16 | if (i1 == i or j1 == j) or (abs(i-i1) == abs(j-j1)): 17 | return False 18 | 19 | return True 20 | 21 | return False 22 | 23 | def backtrack(self, row, n, qPos): 24 | 25 | if row == n: 26 | self.result += 1 27 | return 28 | 29 | for i in range(n): 30 | if self.isValid(row, i, n, qPos): 31 | 32 | qPos.append((row, i)) 33 | 34 | self.backtrack(row+1, n, qPos) 35 | 36 | qPos.pop(-1) 37 | -------------------------------------------------------------------------------- /Python/Exclusive_Time_Of_Functions.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/exclusive-time-of-functions/ 2 | 3 | class Solution(object): 4 | def exclusiveTime(self, n, logs): 5 | """ 6 | :type n: int 7 | :type logs: List[str] 8 | :rtype: List[int] 9 | """ 10 | 11 | time = [0 for i in range(n)] 12 | stack = [] 13 | last_timestamp = 0 14 | for log in logs: 15 | parts = log.split(":") 16 | function_id = int(parts[0]) 17 | started = parts[1] == "start" 18 | timestamp = int(parts[2]) 19 | if not started: 20 | timestamp += 1 21 | 22 | if stack: 23 | active_id = stack[-1] 24 | time[active_id] = time[active_id] + (timestamp-last_timestamp) 25 | if started: 26 | stack.append(function_id) 27 | else: 28 | stack.pop() 29 | 30 | last_timestamp = timestamp 31 | 32 | return time 33 | -------------------------------------------------------------------------------- /Python/Longest_Palindromic_Substring.py: -------------------------------------------------------------------------------- 1 | # LeetCode Problem link - https://leetcode.com/problems/longest-palindromic-substring/ 2 | 3 | 4 | class Solution: 5 | def longestPalindrome(self, string): 6 | maxLength = 1 7 | 8 | start = 0 9 | length = len(string) 10 | 11 | low = 0 12 | high = 0 13 | 14 | for i in range(1, length): 15 | low = i - 1 16 | high = i 17 | while low >= 0 and high < length and string[low] == string[high]: 18 | if high - low + 1 > maxLength: 19 | start = low 20 | maxLength = high - low + 1 21 | low -= 1 22 | high += 1 23 | 24 | low = i - 1 25 | high = i + 1 26 | while low >= 0 and high < length and string[low] == string[high]: 27 | if high - low + 1 > maxLength: 28 | start = low 29 | maxLength = high - low + 1 30 | low -= 1 31 | high += 1 32 | 33 | return(string[start:start + maxLength]) -------------------------------------------------------------------------------- /C++/3Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | vector> res; 5 | sort(nums.begin(), nums.end()); 6 | for(int i=0;itarget){ 13 | back--; 14 | } 15 | else if(sum bool: 19 | 20 | res = [] 21 | if s in d: 22 | res.append(s) 23 | 24 | for i in range(1,len(s)): 25 | if s[:i] in d: 26 | t1 = s[:i] 27 | t2 = s[i:] 28 | if t2 in self.dp: 29 | tt = self.dp[t2] 30 | else: 31 | tt = self.wordBreak(t2, d) 32 | self.dp[t2] = tt 33 | for k in tt: 34 | res.append(t1 + " " + k) 35 | 36 | return res -------------------------------------------------------------------------------- /C++/Deepest_Leaves_Sum.cpp: -------------------------------------------------------------------------------- 1 | //LeetCode Problem link - https://leetcode.com/problems/deepest-leaves-sum/ 2 | 3 | class Solution { 4 | public: 5 | int maxDepth(TreeNode* node) 6 | { 7 | if (node == NULL) 8 | return 0; 9 | int lDepth = maxDepth(node->left); 10 | int rDepth = maxDepth(node->right); 11 | if (lDepth > rDepth) 12 | return(lDepth + 1); 13 | else return(rDepth + 1); 14 | } 15 | 16 | int deepestLeavesSum(TreeNode* root) { 17 | if(root==NULL) 18 | return 0; 19 | queue>q; 20 | q.push({root,1}); 21 | int d=maxDepth(root); 22 | int sum=0; 23 | while(!q.empty()){ 24 | TreeNode* temp=q.front().first; 25 | int level=q.front().second; 26 | q.pop(); 27 | if(temp->left!=NULL) 28 | q.push({temp->left,level+1}); 29 | if(temp->right!=NULL) 30 | q.push({temp->right,level+1}); 31 | if(level==d) 32 | sum+=temp->val; 33 | } 34 | return sum; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Python/Recover_BST.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/recover-binary-search-tree/ 2 | 3 | class Solution: 4 | 5 | def inorder(self,root,arr): 6 | if root==None: 7 | return 8 | if root.left!=None: 9 | self.inorder(root.left,arr) 10 | arr.append(root.val) 11 | if root.right!=None: 12 | self.inorder(root.right,arr) 13 | 14 | def search(self,root,n1,n2): 15 | if root==None: 16 | return 17 | if root.left!=None: 18 | self.search(root.left,n1,n2) 19 | if root.val==n1: 20 | root.val=n2 21 | elif root.val==n2: 22 | root.val=n1 23 | if root.right!=None: 24 | self.search(root.right,n1,n2) 25 | 26 | 27 | def recoverTree(self, root: TreeNode) -> None: 28 | arr=[] 29 | self.inorder(root,arr) 30 | arr2=arr.copy() 31 | arr2.sort() 32 | n1=n2=0 33 | for i in range(len(arr)): 34 | if arr[i]!=arr2[i]: 35 | n1=arr2[i] 36 | n2=arr[i] 37 | break 38 | self.search(root,n1,n2) -------------------------------------------------------------------------------- /C++/Wildcard_Matching.cpp: -------------------------------------------------------------------------------- 1 | 2 | https://leetcode.com/problems/wildcard-matching/ 3 | 4 | class Solution { 5 | public: 6 | bool isMatch(string s, string p) { 7 | const int a =s.size(); 8 | const int b =p.size(); 9 | bool dp[a+1][b+1]; 10 | dp[0][0]=1; 11 | for(int i=1;i<=s.size();i++){ 12 | dp[i][0]=0; 13 | } 14 | for(int i=1;i<=p.size();i++){ 15 | if(p[i-1]=='*' and dp[0][i-1]==1){ 16 | dp[0][i]=1; 17 | }else{ 18 | dp[0][i]=0; 19 | } 20 | } 21 | for(int j=0;j int: 5 | def fac(n): 6 | if n<=1: 7 | return n 8 | return int(n*(n+1)/2) 9 | 10 | def get(s,nums,k): 11 | for i in range(s,len(nums)): 12 | if nums[i]=k: 31 | product/=nums[start] 32 | start+=1 33 | ans+=(i-start)+1 34 | else: 35 | ans+=fac(i+1-start) 36 | return ans 37 | -------------------------------------------------------------------------------- /C++/Word_Ladder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | using ll = long long; 5 | int ladderLength(string beginWord, string endWord, vector& wordList) { 6 | queue> q; 7 | q.push({beginWord, 0}); 8 | unordered_set s; 9 | unordered_map visited; 10 | 11 | for(auto w : wordList) s.insert(w); 12 | 13 | while(!q.empty()){ 14 | auto from = q.front();q.pop(); 15 | if(from.first == endWord) return from.second+1; 16 | 17 | if(visited[from.first]) continue; 18 | visited[from.first] = true; 19 | for(int i = 0; i< 26; ++i){ 20 | char ch = 'a'+ i; 21 | for(int j = 0; j < from.first.size(); ++j){ 22 | string t = from.first; 23 | char original = t[j]; 24 | t[j]=ch; 25 | //insert new node, if not visited. 26 | if(s.find(t) != s.end() && !visited[t]) q.push({t, from.second+1}); 27 | t[j]=original; 28 | } 29 | } 30 | } 31 | return 0; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Python/MERGE_2_SORTED_LIST.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 8 | if(not l1): 9 | return l2 10 | if(not l2): 11 | return l1 12 | h1,h2=l1,l2 13 | a,b=h1,h2 14 | head,tail=None,None 15 | while(a and b): 16 | if(a.val 0) and (input_list[i] == input_list[i-1])): 12 | continue 13 | 14 | while (j < k): 15 | if ((j-1 > i) and (input_list[j] == input_list[j-1])): 16 | j += 1 17 | print("2",i,j,k) 18 | continue 19 | 20 | if (input_list[i]+input_list[j]+input_list[k] > 0): 21 | k -= 1 22 | elif (input_list[i]+input_list[j]+input_list[k] < 0): 23 | j += 1 24 | else: 25 | temp =[] 26 | temp.append(input_list[i]) 27 | temp.append(input_list[j]) 28 | temp.append(input_list[k]) 29 | result.append(temp) 30 | j += 1 31 | k -= 1 32 | 33 | return result 34 | 35 | -------------------------------------------------------------------------------- /C++/Lexicographically_Smallest_String_After_Applying_Operations.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link - 2 | // https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/ 3 | 4 | class Solution { 5 | public: 6 | string add(string s,int v) 7 | { 8 | int n=s.length(); 9 | for(int i=1;i vis; 20 | queue qu; 21 | qu.push(s); 22 | vis.insert(s); 23 | while(!qu.empty()) 24 | { 25 | string s=qu.front(); qu.pop(); 26 | string ns=add(s,a); 27 | if(!vis.count(ns)) 28 | { 29 | vis.insert(ns); 30 | qu.push(ns); 31 | } 32 | ns=rotate(s,b); 33 | if(!vis.count(ns)) 34 | { 35 | vis.insert(ns); 36 | qu.push(ns); 37 | } 38 | } 39 | return *(vis.begin()); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /C++/binarytree_from_traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* bstFromPreorder(vector& preorder) { 15 | TreeNode *root = new TreeNode(preorder[0]); 16 | for(int i = 1; i < preorder.size(); i++) 17 | { 18 | insertNode(root, preorder[i]); 19 | } 20 | return root; 21 | } 22 | void insertNode(TreeNode *head, int val) 23 | { 24 | if(head->val < val) 25 | { 26 | if(head->right != nullptr) 27 | insertNode(head->right, val); 28 | else 29 | head->right = new TreeNode(val); 30 | } 31 | if(head->val > val) 32 | { 33 | if(head->left != nullptr) 34 | insertNode(head->left, val); 35 | else 36 | head->left = new TreeNode(val); 37 | } 38 | 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/BinaryTreeInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | //PROBLEM-LINK=https://leetcode.com/problems/binary-tree-inorder-traversal/ 2 | //ISSUE-LINK=https://github.com/noisefilter19/LeetCode_Algorithms/issues/795 3 | //Definition for a binary tree node. 4 | /*struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 11 | };*/ 12 | //Recursive solution passing all test cases 13 | class Solution { 14 | //take an vector of integers for storing output 15 | vector soln; 16 | public: 17 | vector inorderTraversal(TreeNode* root) { 18 | //If root is NULL, return. 19 | if(root==NULL) 20 | 21 | return{} ; 22 | //recursively traverse and puch values into ans via the left part of tree 23 | inorderTraversal(root->left); 24 | //push the value of root 25 | soln.push_back(root->val); 26 | //recursively traverse and puch values into ans via the right part of tree 27 | inorderTraversal(root->right); 28 | //return the vector 29 | return soln; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/Furthest_building_you_can_reach.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem link: https://leetcode.com/problems/furthest-building-you-can-reach/ 3 | */ 4 | 5 | class Solution 6 | { 7 | public: 8 | int furthestBuilding(vector &heights, int bricks, int ladders) 9 | { 10 | int n = heights.size(); 11 | int i = 0; 12 | priority_queue, greater> p; 13 | while (i < n - 1 and p.size() < ladders) 14 | { 15 | int t = heights[i + 1] - heights[i]; 16 | if (t > 0) 17 | { 18 | p.push(t); 19 | } 20 | i++; 21 | } 22 | while (i < n - 1) 23 | { 24 | int t = heights[i + 1] - heights[i]; 25 | if (t > 0) 26 | { 27 | if (t > p.top() and !p.empty()) 28 | { 29 | bricks -= p.top(); 30 | p.pop(); 31 | p.push(t); 32 | } 33 | 34 | else 35 | { 36 | bricks -= t; 37 | } 38 | } 39 | if (bricks < 0) 40 | return i; 41 | i++; 42 | } 43 | return i; 44 | } 45 | }; -------------------------------------------------------------------------------- /.github/workflows/python-app.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python application 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up Python 3.8 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: 3.8 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | pip install flake8 pytest 27 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 28 | - name: Lint with flake8 29 | run: | 30 | # stop the build if there are Python syntax errors or undefined names 31 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 32 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 33 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 34 | - name: Test with pytest 35 | run: | 36 | pytest 37 | -------------------------------------------------------------------------------- /Python/Subarray_Sum_Equals_K.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/subarray-sum-equals-k/submissions/ 2 | # Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 3 | 4 | # Example 1: 5 | 6 | # Input:nums = [1,1,1], k = 2 7 | # Output: 2 8 | 9 | 10 | # Constraints: 11 | 12 | # The length of the array is in range [1, 20,000]. 13 | # The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 14 | 15 | # Approach: 16 | # Use additional space as mentioned in hint # 2 to exclude nested loop used in brute force method. 17 | 18 | from collections import defaultdict 19 | 20 | class Solution: 21 | def subarraySum(self, nums: List[int], k: int) -> int: 22 | # Using defaultdict to initialize dictionary with value=0 23 | last_sum = defaultdict(lambda:0) 24 | sum_ = 0 25 | count = 0 26 | for i in range(len(nums)): 27 | sum_ += nums[i] 28 | 29 | if sum_ == k: 30 | count += 1 31 | 32 | # Using additional space (last_sum array) to prevent nested loop. 33 | if sum_ - k in last_sum: 34 | count += last_sum[sum_ - k] 35 | last_sum[sum_] += 1 36 | return count 37 | -------------------------------------------------------------------------------- /.github/workflows/IssueComment.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: CI 4 | 5 | # Controls when the workflow will run 6 | on: 7 | # Triggers the workflow on push or pull request events but only for the main branch 8 | push: 9 | branches: [ main ] 10 | pull_request: 11 | branches: [ main ] 12 | 13 | # Allows you to run this workflow manually from the Actions tab 14 | workflow_dispatch: 15 | 16 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 17 | jobs: 18 | # This workflow contains a single job called "build" 19 | build: 20 | # The type of runner that the job will run on 21 | runs-on: ubuntu-latest 22 | 23 | # Steps represent a sequence of tasks that will be executed as part of the job 24 | steps: 25 | - name: Issue comment 26 | # You may pin to the exact commit or the version. 27 | # uses: kyoncy/issue-comment-actions@1b1e351bee044874171a5dc99598257425f6272c 28 | uses: kyoncy/issue-comment-actions@v1 29 | with: 30 | # GitHub token for use by this action. 31 | token: ${{ secrets.GITHUB_TOKEN }} 32 | # Message 33 | message: Thankyou, for opening the issue. Please wait for the issue to be assigned to you and fo not open anymore issues until this is resolved. 34 | 35 | -------------------------------------------------------------------------------- /C++/Remove_Duplicate_letters.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3491/ 2 | 3 | class Solution 4 | { 5 | public: 6 | string removeDuplicateLetters(string s) 7 | { 8 | vector freq(26, 0); 9 | vector visited(26, false); 10 | vector result; 11 | for (int i = 0; i < s.size(); i++) 12 | { 13 | freq[s[i] - 'a']++; 14 | } 15 | for (char ch : s) 16 | { 17 | if (!visited[ch - 'a']) 18 | { 19 | visited[ch - 'a'] = true; 20 | if (result.size() > 0 && (ch < result[result.size() - 1])) 21 | { 22 | char lastchar = result[result.size() - 1]; 23 | while (result.size() > 0 && ch < lastchar && freq[lastchar - 'a'] > 0) 24 | { 25 | visited[lastchar - 'a'] = false; 26 | result.pop_back(); 27 | if (result.size() > 0) 28 | lastchar = result[result.size() - 1]; 29 | } 30 | } 31 | result.push_back(ch); 32 | } 33 | freq[ch - 'a']--; 34 | } 35 | return string(result.begin(), result.end()); 36 | } 37 | }; -------------------------------------------------------------------------------- /Python/Swap_Nodes_in_Pairs.py: -------------------------------------------------------------------------------- 1 | # LeetCode link: https://leetcode.com/problems/swap-nodes-in-pairs/ 2 | # Issue: https://github.com/noisefilter19/LeetCode_Algorithms/issues/736 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | 9 | 10 | class Solution: 11 | def swapPairs(self, head: ListNode) -> ListNode: 12 | curr = head 13 | if not head: 14 | return head 15 | if not curr.next: 16 | return curr 17 | arr = [] 18 | while curr: 19 | arr.append(curr) 20 | curr = curr.next 21 | ar1 = [arr[i] for i in range(len(arr)) if i % 2 == 0] 22 | ar2 = [arr[i] for i in range(len(arr)) if i % 2 != 0] 23 | full_ar = [] 24 | i = 0 25 | k = 0 26 | m = 0 27 | while m < len(ar1) + len(ar2): 28 | if i < len(ar2): 29 | full_ar.append(ar2[i]) 30 | i += 1 31 | if k < len(ar1): 32 | full_ar.append(ar1[k]) 33 | k += 1 34 | m += 1 35 | head = full_ar[0] 36 | curr = head 37 | for i in full_ar: 38 | curr.next = i 39 | curr = curr.next 40 | curr.next = None 41 | return head 42 | -------------------------------------------------------------------------------- /Python/Merge_k_Sorted_Lists.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://leetcode.com/problems/merge-k-sorted-lists/ 2 | 3 | from heapq import merge 4 | 5 | 6 | # Definition for singly-linked list. 7 | class ListNode: 8 | def __init__(self, val=0, next=None): 9 | self.val = val 10 | self.next = next 11 | 12 | 13 | class Solution: 14 | 15 | def mergeKLists(self, lists: List[ListNode]) -> ListNode: 16 | lists = list(filter(lambda x: x is not None, lists)) 17 | 18 | array_list = [] 19 | array = [] 20 | for l in lists: 21 | node = l 22 | 23 | while node: 24 | array.append(node.val) 25 | node = node.next 26 | 27 | array_list.append(array) 28 | array = [] 29 | 30 | if (len(array_list) > 0): 31 | merge_list = array_list[0] 32 | 33 | for i in range(len(array_list) - 1): 34 | merge_list = list(merge(merge_list, array_list[i + 1])) 35 | 36 | linked_list = output = ListNode(int(merge_list[0])) 37 | 38 | for j in range(len(merge_list) - 1): 39 | output.next = ListNode(int(merge_list[j + 1])) 40 | output = output.next 41 | 42 | return linked_list 43 | else: 44 | linked_list = output = ListNode(None) 45 | return output.next -------------------------------------------------------------------------------- /C++/Remove_Nth_Node_From_End_of_List.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* removeNthFromEnd(ListNode* head, int n) { 16 | int size = 1; 17 | ListNode *temp = head; 18 | while(temp->next != NULL){ 19 | size++; 20 | temp= temp->next; 21 | } 22 | 23 | ListNode* temp2 = head; 24 | 25 | //edge case 26 | if(size == n){ 27 | ListNode* temp4 = head; 28 | head = head->next; 29 | delete temp4; 30 | return head; 31 | } 32 | 33 | int counter = (size - n); 34 | 35 | for(int i=1; inext; 37 | } 38 | 39 | if(temp2->next == NULL){ 40 | 41 | } 42 | 43 | ListNode* temp3 = temp2->next; 44 | temp2->next = temp2->next->next; 45 | delete temp3; 46 | 47 | return head; 48 | } 49 | }; -------------------------------------------------------------------------------- /Python/238_Product_of_Array_Except_Self.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/product-of-array-except-self/ 2 | 3 | # Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 4 | 5 | # Example: 6 | 7 | # Input: [1,2,3,4] 8 | # Output: [24,12,8,6] 9 | 10 | # Constraint: 11 | 12 | # It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 13 | 14 | # Note: Please solve it without division and in O(n). 15 | 16 | # Approach: 17 | 18 | # Multiply all values of nums before and after each index storing the products in an additional array. 19 | # Time Complexity: O(N), Space Complexity: O(N) - where N is length of array. 20 | 21 | class Solution(object): 22 | def productExceptSelf(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: List[int] 26 | """ 27 | prod_arr = [0]*len(nums) 28 | left_prod = 1 29 | for i in range(len(nums)): 30 | prod_arr[i] = left_prod 31 | left_prod = left_prod * nums[i] 32 | 33 | right_prod = 1 34 | for i in range(len(nums)-1, -1, -1): 35 | prod_arr[i] = prod_arr[i] * right_prod 36 | right_prod = right_prod * nums[i] 37 | 38 | return prod_arr 39 | -------------------------------------------------------------------------------- /C++/Contains_duplicate_III.cpp: -------------------------------------------------------------------------------- 1 | /* https://leetcode.com/problems/contains-duplicate-iii/ 2 | 3 | Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. 4 | 5 | Example 1: 6 | 7 | Input: nums = [1,2,3,1], k = 3, t = 0 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: nums = [1,0,1,1], k = 1, t = 2 13 | Output: true 14 | 15 | Example 3: 16 | 17 | Input: nums = [1,5,9,1,5,9], k = 2, t = 3 18 | Output: false 19 | 20 | Constraints: 21 | 0 <= nums.length <= 2 * 104 22 | -231 <= nums[i] <= 231 - 1 23 | 0 <= k <= 104 24 | 0 <= t <= 231 - 1 25 | */ 26 | 27 | 28 | // Runtime : 20 ms 29 | 30 | 31 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 32 | if(nums.size()==1 || nums.size()==0) // If the size of the vector is 0 or 1, false is returned. 33 | return false; 34 | for(int i=0;ik) // Checking every possible pair for the given conditions. 39 | break; 40 | long long l=abs(nums[j]-nums[i]); 41 | if(l<=t) 42 | return true; 43 | } 44 | } 45 | return false; 46 | } 47 | -------------------------------------------------------------------------------- /Java/3_Sum.java: -------------------------------------------------------------------------------- 1 | //Problem Link: https://leetcode.com/problems/3sum/ 2 | 3 | //Solution 4 | 5 | class Solution { 6 | public List> threeSum(int[] nums) { 7 | int i, j; 8 | Arrays.sort(nums); 9 | 10 | List> res = new ArrayList() ; 11 | 12 | for(int k = 0 ; k < nums.length-1 ; k++){ 13 | i =k+1; 14 | j = nums.length-1; 15 | int ele = nums[k]; 16 | 17 | if( k > 0 && nums[k] == nums[k-1]) continue; 18 | 19 | while( i < j){ 20 | 21 | if( i-1 > k && nums[i] == nums[i-1] ){ 22 | i++; 23 | continue; 24 | } 25 | 26 | if( -ele == nums[i] + nums[j] ){ 27 | List list = new ArrayList(); 28 | list.add(ele); 29 | list.add(nums[i]); 30 | list.add(nums[j]); 31 | 32 | res.add( new ArrayList(list) ); 33 | i++; 34 | j--; 35 | } 36 | else if( -ele > nums[i] + nums[j] ) 37 | i++; 38 | else 39 | j--; 40 | } 41 | } 42 | return res; 43 | } 44 | } -------------------------------------------------------------------------------- /C++/merge-intervals.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/merge-intervals/ (Medium) 2 | bool comp(vectora, vectorb) 3 | { 4 | if (a[0] != b[0]) 5 | return a[0] < b[0]; 6 | return a[1] > b[1]; 7 | } 8 | class Solution { 9 | public: 10 | 11 | vector> merge(vector>& intervals) { 12 | sort(intervals.begin(), intervals.end(), comp); 13 | vectorv; vector>ans; 14 | int s = -1, e = -1; 15 | for (int i = 0; i < intervals.size(); i++) 16 | { 17 | if (s == -1) 18 | { 19 | s = intervals[i][0]; 20 | e = intervals[i][1]; 21 | } 22 | else 23 | { 24 | int ss = intervals[i][0]; 25 | int ee = intervals[i][1]; 26 | if (ss >= s and ss <= e) 27 | { 28 | e = max(e, ee); 29 | } 30 | else 31 | { 32 | v.push_back(s); 33 | v.push_back(e); 34 | ans.push_back(v); 35 | v.clear(); 36 | s = ss, e = ee; 37 | } 38 | } 39 | } 40 | v.push_back(s); 41 | v.push_back(e); 42 | ans.push_back(v); 43 | v.clear(); 44 | //s=ss,e=ee; 45 | return ans; 46 | } 47 | }; -------------------------------------------------------------------------------- /Python/Longest_Increasing_Path_in_a_Matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode link: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ 3 | Difficulty: Hard 4 | """ 5 | 6 | class Solution: 7 | def longestIncreasingPath(self, matrix: List[List[int]]) -> int: 8 | if not matrix: 9 | return 0 10 | 11 | height = len(matrix) 12 | width = len(matrix[0]) 13 | 14 | def neighbors(i, j): 15 | if i > 0: 16 | yield i - 1, j 17 | if i < height - 1: 18 | yield i + 1, j 19 | if j > 0: 20 | yield i, j - 1 21 | if j < width - 1: 22 | yield i, j + 1 23 | 24 | longestFrom = [[None] * width for _ in range(height)] 25 | 26 | def findLongestFrom(i, j): 27 | if longestFrom[i][j] is not None: 28 | return longestFrom[i][j] 29 | 30 | value = matrix[i][j] 31 | longestFrom[i][j] = out = max( 32 | (1 + findLongestFrom(r, c) for r, c in neighbors(i, j) if matrix[r][c] > value), 33 | default=1 34 | ) 35 | return out 36 | 37 | 38 | for i in range(height): 39 | for j in range(width): 40 | if longestFrom[i][j] is None: 41 | findLongestFrom(i, j) 42 | 43 | return max(max(row) for row in longestFrom) 44 | -------------------------------------------------------------------------------- /C++/4Sum.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/4sum/ 2 | class Solution { 3 | public: 4 | vector> fourSum(vector& nums, int target) { 5 | sort(nums.begin(),nums.end()); 6 | int i=0; 7 | vector> res; 8 | while(itgt){ 19 | back--; 20 | }else if(smtgt: 24 | bk-=1 25 | else: 26 | tr=[nums[i],nums[j],nums[fr],nums[bk]] 27 | if nums[fr]+nums[bk]==tgt: 28 | a.append(tr) 29 | 30 | while fr a, vector b) { 4 | return a[0]> reconstructQueue(vector>& people) { 9 | vector> ret(people.size()); 10 | sort(people.begin(),people.end(),comp); 11 | for(vector v: people) { 12 | int x = v[1]; 13 | for(int i=0;i where i=height and j=no. of people with height >= height of p 29 | * first we place all the shortest height pairs to position j because they will anyway have someone with height >= their height 30 | * Then we place second shortest height and so on 31 | * suppose the pair p is being processed 32 | * we need to keep p at jth empty position so x=j 33 | * we decrement x whenever we find an empty position or someone with same height because at empty postion there will be someone 34 | * with height >= height of p 35 | * Need not to check for >= condition as we have sorted the array before so no one in ret array would be having height > height * of p 36 | */ 37 | -------------------------------------------------------------------------------- /Python/Largest_Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-number/ 2 | 3 | class Solution: 4 | def largestNumber(self, nums: List[int]) -> str: 5 | for i in range(len(nums)): 6 | nums[i] = str(nums[i]) 7 | new_array = self.merge(nums, 0, len(nums)) 8 | i = 0 9 | while i < len(new_array) and new_array[i] == '0': 10 | i += 1 11 | return '0' if i == len(new_array) else "".join(new_array[i:]) 12 | 13 | def merge_arrays(self, parted_arr1, parted_arr2): 14 | i = j = 0 15 | merged_array = [] 16 | while i < len(parted_arr1) and j < len(parted_arr2): 17 | if int(parted_arr1[i] + parted_arr2[j]) >= int(parted_arr2[j] + parted_arr1[i]): 18 | merged_array.append(parted_arr1[i]) 19 | i += 1 20 | else: 21 | merged_array.append(parted_arr2[j]) 22 | j += 1 23 | while i < len(parted_arr1): 24 | merged_array.append(parted_arr1[i]) 25 | i += 1 26 | while j < len(parted_arr2): 27 | merged_array.append(parted_arr2[j]) 28 | j += 1 29 | return merged_array 30 | 31 | def merge(self, nums, low, high): 32 | if high - low <= 1: 33 | return [nums[low]] 34 | mid = (low + high)//2 35 | parted_subarray1 = self.merge(nums, low, mid) 36 | parted_subarray2 = self.merge(nums, mid, high) 37 | return self.merge_arrays(parted_subarray1, parted_subarray2) 38 | -------------------------------------------------------------------------------- /Python/Permutations.py: -------------------------------------------------------------------------------- 1 | # Given a list e.g. [A, B, C] 2 | # return a list of all permutations => 3 | # [ 4 | # [A,B,C] 5 | # [A,C,B] 6 | # [B,A,C] 7 | # [B,C,A] 8 | # [C,A,B] 9 | # [C,B,A] 10 | # ] 11 | 12 | 13 | class Solution: 14 | def swap(self, indexA: int, indexB: int, nums: List[int]): 15 | temp = nums[indexA] 16 | nums[indexA] = nums[indexB] 17 | nums[indexB] = temp 18 | 19 | def findPermutations(self, nums: List[int], leftIndex: int, rightIndex: int): 20 | 21 | if leftIndex is rightIndex: 22 | self.result.append(nums.copy()) 23 | return 24 | 25 | for index in range(leftIndex, rightIndex): 26 | self.swap(leftIndex, index, nums) 27 | 28 | # we have everything before leftIndex +1 locked in place for this permutation 29 | self.findPermutations(nums, leftIndex + 1, rightIndex) 30 | 31 | # return array to the initial way it was 32 | self.swap(leftIndex, index, nums) 33 | 34 | def permute(self, nums: List[int]) -> List[List[int]]: 35 | self.result = [] 36 | 37 | self.findPermutations(nums, 0, len(nums)) 38 | return self.result 39 | 40 | 41 | # Complexity analysis :) 42 | # 43 | # time complexity: O(n! * n) 44 | # explenation: there are a total of n! permutations and it takes the leftIndex n steps to reach the right index for each of them 45 | # 46 | # space complexity: O(n!) 47 | # explenation: we need to store the resulting permutations until we print them 48 | -------------------------------------------------------------------------------- /Javascript/312_House_Robbers_2.js: -------------------------------------------------------------------------------- 1 | /* 2 | * https://leetcode.com/problems/house-robber-ii/ 3 | */ 4 | 5 | /** 6 | * @param {numbers[]} nums 7 | * @return {number} 8 | */ 9 | const helper = (nums) => { 10 | // init max array with nums length 11 | let max_array = new Array(nums.length); 12 | // max_array = dp 13 | // we iterate through nums and 14 | // we save only the highest value of either the { current house + 2 houses before } or the { house before } 15 | for (i in nums) { 16 | if (i == 0) max_array[i] = nums[i]; 17 | if (i == 1) max_array[i] = Math.max(nums[0], nums[1]); 18 | if (i >= 2) max_array[i] = Math.max(nums[i] + max_array[i - 2], max_array[i - 1]); 19 | } 20 | return max_array[max_array.length - 1]; 21 | }; 22 | 23 | const rob = (nums) => { 24 | if (nums.length === 0) return 0; 25 | if (nums.length === 1) return nums[0]; 26 | let start1 = [...nums]; 27 | let start2 = [...nums]; 28 | 29 | // circular, so the last house touches the first, therefore we do two runs of House Robber 1 (now helper) 30 | start1.pop(); 31 | start2.shift(); 32 | 33 | let max_start1 = helper(start1); 34 | let max_start2 = helper(start2); 35 | 36 | return Math.max(max_start1, max_start2); 37 | }; 38 | 39 | // let nums = [1, 2, 3, 1]; 40 | // let nums = []; 41 | // let nums = []; 42 | // let nums = [11, 2]; 43 | // let nums = [1, 2, 3]; 44 | // let nums = [1, 2, 3, 4]; 45 | // let nums = [15, 2, 3]; 46 | let nums = [2, 7, 9, 3, 1]; 47 | console.log(rob(nums)); 48 | -------------------------------------------------------------------------------- /Python/Reverse_Nodes_in_k-Group.py: -------------------------------------------------------------------------------- 1 | # Problem URL : https://leetcode.com/problems/reverse-nodes-in-k-group/submissions/ 2 | 3 | # Definition for singly-linked list. 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | 10 | class Solution: 11 | def reverseNextK(self, previous, current, k): 12 | 13 | if (current == None): 14 | return None, None 15 | 16 | if (k == 1): 17 | nextNode = current.next 18 | current.next = previous 19 | return (current, nextNode) 20 | 21 | newHead, nextHead = self.reverseNextK(current, current.next, k - 1) 22 | if (newHead == None): 23 | return (None, None) 24 | else: 25 | current.next = previous 26 | return (newHead, nextHead) 27 | 28 | def reverseKGroup(self, head: ListNode, k: int) -> ListNode: 29 | newHead, nextHead = self.reverseNextK(None, head, k) 30 | 31 | if (newHead == None): 32 | return head 33 | else: 34 | result = newHead 35 | 36 | previousTail = head 37 | 38 | while (nextHead != None): 39 | currentNode = nextHead 40 | newHead, nextHead = self.reverseNextK(None, currentNode, k) 41 | if (newHead != None): 42 | previousTail.next = newHead 43 | else: 44 | previousTail.next = currentNode 45 | previousTail = currentNode 46 | return result 47 | -------------------------------------------------------------------------------- /C++/Maximal_Square_Of_Ones.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/maximal-square/ 2 | 3 | 4 | //This algorithm finds the maximum size of square(area of square) that contains all ones in the given m*n matrix. 5 | //This solution takes O(rows*columns) time and O(columns) space (m=rows, n=columns). 6 | 7 | class Solution { 8 | public: 9 | int maximalSquare(vector>& matrix) { 10 | int rows=matrix.size(),cols; 11 | if(rows==0)return 0; 12 | cols=matrix[0].size(); 13 | int ans=0,i,j; 14 | //This solution uses only O(columns) extra space instead of traditional O(rows*columns) space. 15 | int dp[2][cols]; 16 | for(i=0;i& lists) { 14 | ListNode *root=NULL; 15 | for(int i=0;ivalval){ 31 | res=l1; 32 | l1=l1->next; 33 | }else{ 34 | res=l2; 35 | l2=l2->next; 36 | } 37 | root=res; 38 | while(l1&&l2){ 39 | if(l1->valval){ 40 | res->next=l1; 41 | res=res->next; 42 | l1=l1->next; 43 | }else{ 44 | res->next=l2; 45 | res=res->next; 46 | l2=l2->next; 47 | } 48 | } 49 | if(l1){ 50 | res->next=l1; 51 | } 52 | if(l2){ 53 | res->next=l2; 54 | } 55 | return root; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Java/316_Remove_Duplicate_Letters.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Problem No: 316 Remove Duplicate Letters 4 | URI: https://leetcode.com/problems/remove-duplicate-letters/ 5 | Logic: Maintain an array of length 26 to keep note of the index at which the letter in the given string is last observed 6 | Next, build a stack such that the character pushed first is added if and only if it the last occurance and also the ascii value is less than the valuw previous, 7 | Also maintain a visited array to handle multiple additions of same char to the stack. 8 | */ 9 | 10 | class Solution { 11 | public String removeDuplicateLetters(String s) { 12 | int[] result =new int[26]; 13 | for(int i=0;i stack = new Stack <>(); 18 | for(int i=0;ic && result[stack.peek () - 'a']>i){ 24 | visited[stack.peek () - 'a'] = false; 25 | stack.pop (); 26 | } 27 | // System.out.println(stack+"\t"+c); 28 | stack.push(c); 29 | visited[c-'a']=true; 30 | 31 | } 32 | StringBuilder ans = new StringBuilder (); 33 | 34 | while (!stack.isEmpty ()) { 35 | ans.append (stack.pop()); 36 | } 37 | 38 | return ans.reverse().toString (); 39 | } 40 | } -------------------------------------------------------------------------------- /Python/0420_Strong_Password_Checker.py: -------------------------------------------------------------------------------- 1 | class Solution(): 2 | def strongPasswordChecker(self, s: str) -> int: 3 | 4 | #Alphabet reach check 5 | count = 3 6 | if any('a' <= c <= 'z' for c in s): 7 | count -= 1 8 | if any('A' <= c <= 'Z' for c in s): 9 | count -= 1 10 | if any(c.isdigit() for c in s): 11 | count-= 1 12 | 13 | #length check 14 | change = 0 15 | a = 0 16 | b = 0 17 | #consecutive 3 letters check 18 | c = 2 19 | while c < len(s): 20 | if s[c] == s[c-1] == s[c-2]: 21 | length = 2 22 | while c < len(s) and s[c] == s[c-1]: 23 | length += 1 24 | c += 1 25 | 26 | change += length // 3 27 | if length % 3 == 0: a += 1 28 | elif length % 3 == 1: b += 1 29 | else: 30 | c += 1 31 | 32 | 33 | if len(s) < 6: 34 | return max(count, 6 - len(s)) 35 | elif len(s) <= 20: 36 | return max(count, change) 37 | else: 38 | delete = len(s) - 20 39 | change -= min(delete, a) 40 | change -= min(max(delete - a, 0), b * 2) // 2 41 | change -= max(delete - a - 2 * b, 0) // 3 42 | 43 | return delete + max(count, change) 44 | 45 | obj = Solution() 46 | password = "" 47 | output = obj.strongPasswordChecker(password) 48 | print(output) 49 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to the repository 2 | 3 | Welcome to the repository! Before sending your pull requests, make sure that you read the whole guidelines. If you have any doubt on the contributing guide, please feel free to state it clearly in an issue. 4 | 5 | Reference/Mention the issue being fixed in the PR. 6 | 7 | **Only assigned issue will be reviewed** 8 | 9 | We accept only **Medium/Hard problem**. So, don't raise an issue for Easy problems. 10 | 11 | ### Before raising a pullrequest 12 | 13 | To contribute an algorithm, please raise an issue for the problem using the following title 14 | 15 | Problem No. | Problem name | Language 16 | 17 | Please don't raise the PR until the issue is assigned to you. PR's raised without assignment may lead to PR being marked invalid 18 | 19 | ### Raising a PR 20 | 21 | - Follow [How to raise a PR?](https://www.digitalocean.com/community/tutorials/how-to-create-a-pull-request-on-github) to raise a PR 22 | - Please don't copy editorial solutions, if found doing so - the PR might be marked invalid, 23 | - Please publish only genuine solutions written by you. 24 | - All the solutions should give expected solution and pass all tests in Leetcode. 25 | - Please don't spam any file with useless comments and unwanted changes. Make the Hacktoberfest worth it. 26 | - Place the solution to a problem within the folder of the implementation language. 27 | - Comment the link to the problem on top of the code 28 | - Name the algorithm by the name of the problem separated by underscores 29 | 30 | 31 | ## PLEASE LINK YOUR PRS TO THE ISSUE, IT'll HELP FAST-FORWARD THE REVIEW PROCESS 32 | -------------------------------------------------------------------------------- /Java/LongestPalindromeSubstring5.java: -------------------------------------------------------------------------------- 1 | // The problem was taken from : https://leetcode.com/problems/longest-palindromic-substring/ 2 | // 3 | // Created by Ricky Benkovich 13/10/2020 4 | // 5 | public class LongestPalindromeSubstring5 { 6 | 7 | public String expandPalindrome(String s, int left, int right, String curr_pali, int i){ 8 | while (s.charAt(left) == s.charAt(right)){ 9 | 10 | if (curr_pali.length() == 0) 11 | if (left == right) 12 | curr_pali = s.charAt(i) + ""; 13 | else 14 | curr_pali = s.charAt(left) + "" + s.charAt(right); 15 | else 16 | curr_pali = s.charAt(left) + curr_pali + s.charAt(right); 17 | left --; 18 | right ++; 19 | 20 | if (left < 0 || right >= s.length()) 21 | break; 22 | } 23 | return curr_pali; 24 | } 25 | 26 | 27 | public String longestPalindrome(String s) { 28 | String max_Pali = ""; 29 | 30 | for(int i = 0; i < s.length(); i++) { 31 | String pali_odd= ""; 32 | String pali_even = ""; 33 | 34 | pali_odd = expandPalindrome(s, i, i, pali_odd, i); 35 | if (i+1 < s.length()) 36 | pali_even = expandPalindrome(s, i, i+1, pali_even, i); 37 | 38 | if (pali_odd.length() > max_Pali.length()) 39 | max_Pali = pali_odd; 40 | 41 | if (pali_even.length() > max_Pali.length()) 42 | max_Pali = pali_even; 43 | } 44 | return max_Pali; 45 | } 46 | } 47 | 48 | 49 | -------------------------------------------------------------------------------- /C++/Shortest_Common_Supersequence.cpp: -------------------------------------------------------------------------------- 1 | //Problem Link 2 | // https://leetcode.com/problems/shortest-common-supersequence/ 3 | 4 | class Solution { 5 | public: 6 | string shortestCommonSupersequence(string str1, string str2) { 7 | string s=find_SCS(str1,str2); 8 | reverse(s.begin(),s.end()); 9 | return s; 10 | } 11 | 12 | string find_SCS(string str1,string str2){ 13 | vector> lcs(str1.size()+1,vector(str2.size()+1,0)); 14 | for(int i=1;i<=str1.size();i++){ 15 | for(int j=1;j<=str2.size();j++){ 16 | if(str1[i-1]==str2[j-1]) 17 | lcs[i][j]=lcs[i-1][j-1]+1; 18 | else 19 | lcs[i][j]=max(lcs[i-1][j],lcs[i][j-1]); 20 | } 21 | } 22 | 23 | int i=str1.size(); 24 | int j=str2.size(); 25 | string s; 26 | 27 | while(i>0 && j>0){ 28 | if(str1[i-1]==str2[j-1]){ 29 | s.push_back(str1[i-1]); 30 | i--;j--; 31 | } 32 | else{ 33 | if(lcs[i-1][j]>lcs[i][j-1]){ 34 | s.push_back(str1[i-1]); 35 | i--; 36 | } 37 | else{ 38 | s.push_back(str2[j-1]); 39 | j--; 40 | } 41 | } 42 | } 43 | 44 | while(i>0){ 45 | s.push_back(str1[i-1]); 46 | i--; 47 | } 48 | while(j>0){ 49 | s.push_back(str2[j-1]); 50 | j--; 51 | } 52 | return s; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Python/1007_Minimum_Domino_Rotations_For_Equal_Row.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ 2 | 3 | # In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. 4 | # (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) 5 | # We may rotate the ith domino, so that A[i] and B[i] swap values. 6 | # Return the minimum number of rotations so that all the values in A are the same, 7 | # or all the values in B are the same. 8 | # If it cannot be done, return -1. 9 | 10 | # Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] 11 | # Output: 2 12 | # Explanation: 13 | # The first figure represents the dominoes as given by A and B: before we do any rotations. 14 | # If we rotate the second and fourth dominoes, 15 | # we can make every value in the top row equal to 2, as indicated by the second figure. 16 | 17 | ''' 18 | Approach: 19 | Figure out if any one particular number is present on either side of each dice. 20 | Compute minimum rotations required. 21 | ''' 22 | class Solution: 23 | def minDominoRotations(self, a: List[int], b: List[int]) -> int: 24 | size = len(a) 25 | x,y = None,None 26 | if all([a[0] in (a[i], b[i]) for i in range(size)]): 27 | x = min(size-a.count(a[0]), size - b.count(a[0])) 28 | elif all([b[0] in (a[i], b[i]) for i in range(len(b))]): 29 | y = min(size-a.count(b[0]), size - b.count(b[0])) 30 | # print(x,y) 31 | if x is None: 32 | if y is None: 33 | return -1 34 | else: 35 | return y 36 | else: 37 | if y is None: 38 | return x 39 | else: 40 | return min(x,y) -------------------------------------------------------------------------------- /C++/Maximum_Nesting_Depth_of_Two_Valid_Parentheses_Strings.cpp: -------------------------------------------------------------------------------- 1 | /*Leetcode link: https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/ */ 2 | 3 | //The Question itself is simple but the wording makes it difficult 4 | //What the question asks is, we have to make two VPS strings out of a parent string which is also VPS such that there depth of parantheses is minimum 5 | 6 | class Solution { 7 | public: 8 | vector maxDepthAfterSplit(string seq) { 9 | 10 | int n=0,m=0; //assuming n,m denoting the size A,B [for understanding take it as size of stack A,B] 11 | vector res; //vector representing result 12 | for(int i=0;im){ 25 | n--; //whenever the size of B>A we decrement count of A 26 | res.push_back(0); //here in ques, B is said to represent 0 in ans 27 | } 28 | else { 29 | m--; //whenever the size of A>=B we decrement count of A 30 | res.push_back(1); //here in ques, A is said to represent 1 in ans 31 | } 32 | } 33 | return res; 34 | 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /C++/Valid_Number.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/valid-number 2 | class Solution { 3 | public: 4 | bool isNumber(string s) { 5 | int n=s.length(); 6 | if(n==0) 7 | return false; 8 | if(n==1&&(s[0]<'0'||s[0]>'9')) 9 | return false; 10 | int i=0; 11 | while(s[i]==' '&&i=0) 16 | n--; 17 | if(s[i]=='+'||s[i]=='-') 18 | i++; 19 | if(i==n) 20 | return false; 21 | bool chcke=false; 22 | bool chckdec=false; 23 | if(s[i]=='e') 24 | return false; 25 | if(s[i]=='.'&&i+1='0'&&s[i+1]<='9') 26 | { 27 | i++; 28 | chckdec=true; 29 | } 30 | for(i;i='0'&&s[i]<='9') 33 | { 34 | if(i+1 int: 44 | if n%2 ==0: 45 | return int((n/2)**2) 46 | else: 47 | return int(((n-1)*(n+1)/4)) 48 | 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /Python/Integer_To_Roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, num: int) -> str: 3 | dic={4:"IV",9:"IX",40:"XL",90:"XC",400:"CD",900:"CM"} 4 | h=1 5 | 6 | s1="" 7 | s2="" 8 | s3="" 9 | s4="" 10 | while(num!=0): 11 | dig=num%10 12 | if h==1: 13 | if dig==9: 14 | s1+=dic[9] 15 | elif dig>=5: 16 | s1+="V" 17 | for i in range(dig-5): 18 | s1+="I" 19 | elif dig==4: 20 | s1+=dic[4] 21 | else: 22 | for i in range(dig): 23 | s1+="I" 24 | h+=1 25 | 26 | elif h==2: 27 | if dig==9: 28 | s2+=dic[90] 29 | elif dig>=5: 30 | s2+="L" 31 | for i in range(dig-5): 32 | s2+="X" 33 | elif dig==4: 34 | s2+=dic[40] 35 | else: 36 | for i in range(dig): 37 | s2+="X" 38 | h+=1 39 | 40 | elif h==3: 41 | if dig==9: 42 | s3+=dic[900] 43 | elif dig>=5: 44 | s3+="D" 45 | for i in range(dig-5): 46 | s3+="C" 47 | elif dig==4: 48 | s3+=dic[400] 49 | else: 50 | for i in range(dig): 51 | s3+="C" 52 | h+=1 53 | 54 | else: 55 | for i in range(dig): 56 | s4+="M" 57 | num=num//10 58 | return s4+s3+s2+s1 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /Python/Rotting_Oranges.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/rotting-oranges/ 3 | 4 | Comments included with the code. 5 | 6 | The idea is to go a BFS level order traversal from each rotting orange, then 7 | add 1 to minutes elapsed after each level. Keep a count of how many pure oranges 8 | remained at each point, and when they reach zero, return minutes elapsed. 9 | 10 | """ 11 | 12 | class Solution(object): 13 | def orangesRotting(self, grid): 14 | """ 15 | :type grid: List[List[int]] 16 | :rtype: int 17 | """ 18 | dirs = [(0,1),(1,0), (-1,0), (0,-1)] 19 | q = [] 20 | rows, cols = len(grid), len(grid[0]) 21 | pure_count =0 22 | # we will do a bfs from a rotten orange 23 | 24 | # first, get the number of pure oranges 25 | # then add all the rotten oranges in a queue 26 | for i in range(rows): 27 | for j in range(cols): 28 | if grid[i][j]==2: 29 | q.append((i,j)) 30 | if grid[i][j]==1: 31 | pure_count+=1 32 | if pure_count==0: 33 | return 0 34 | if not q: 35 | return -1 36 | 37 | # making minutes start from -1, for convenience, 38 | # as at the next (0th) minute, we will just add 39 | # the neighbors to the queue, not rot them until the minute after that. 40 | minutes=-1 41 | 42 | while q: 43 | next_level = [] 44 | for i, j in q: 45 | for dx, dy in dirs: 46 | x,y = i+dx, j+dy 47 | if x>=0 and y>=0 and x 0 the value of k is updated as k-length. Swap the next pointers for the rotation point and last node of the listarray 8 | to length-k node and start respectively 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode() {} 17 | * ListNode(int val) { this.val = val; } 18 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 19 | * } 20 | */ 21 | class Solution { 22 | public ListNode rotateRight(ListNode head, int k) { 23 | if(head==null | k==0){ 24 | return head; 25 | } 26 | int length = 0; 27 | int pivotPoint; 28 | List store = new ArrayList<>(); 29 | while(true){ 30 | length++; 31 | store.add(head); 32 | head=head.next; 33 | if(head==null){ 34 | break; 35 | } 36 | } 37 | ListNode newHead = head; 38 | while(k>length){ 39 | k-=length; 40 | } 41 | if(length==k){ 42 | return store.get(0); 43 | } 44 | newHead = store.get(length-k); 45 | ListNode curr = newHead; 46 | while(curr.next!=null){ 47 | curr=curr.next; 48 | } 49 | curr.next = store.get(0); 50 | if(length-k!=0) 51 | store.get(length-k-1).next=null; 52 | else 53 | store.get(store.size()-1).next=null; 54 | return newHead; 55 | } 56 | } -------------------------------------------------------------------------------- /Python/123. Best Time to Buy and Sell Stock III.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 2 | # 123. Best Time to Buy and Sell Stock III(Hard) Solution 3 | # Say you have an array for which the ith element is the price of a given stock on day i. 4 | 5 | # Design an algorithm to find the maximum profit. You may complete at most two transactions. 6 | 7 | # Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 8 | 9 | 10 | class Solution(object): 11 | def maxProfit(self, prices): 12 | """ 13 | :type prices: List[int] 14 | :rtype: int 15 | """ 16 | l = len(prices) 17 | 18 | # helper function that finds maxrise and the lowcations of maxrise in prices[b:e:step] 19 | def helper(b, e, step): 20 | max_rise, tmp_low, low, hi = 0, b, 0, 0 21 | for i in range(b, e, step): 22 | rise = prices[i] - prices[tmp_low] 23 | if rise <= 0: 24 | tmp_low = i 25 | elif rise > max_rise: 26 | max_rise, low, hi = rise, tmp_low, i 27 | return max_rise, low, hi 28 | 29 | # For the first pass, we identify the indices for "at most 1 transaction" problem, so that we find low, hi 30 | max_rise, low, hi = helper(0, l, 1) 31 | # Then there are three possibilities: 1, use (low, hi) and another rise before low; 2, (low, hi) and another rise after hi; 3, use (low, x) and (y, hi). 32 | # In the third case, it is equivalent to finding the max_rise in the sequence prices[hi:low:-1] 33 | m1, m2, m3 = helper(0, low, 1)[0], helper( 34 | hi+1, l, 1)[0], helper(hi-1, low, -1)[0] 35 | return max_rise + max(m1, m2, m3) 36 | 37 | # Driver code 38 | # test = [3, 3, 5, 0, 0, 3, 1, 4] 39 | # p = Solution() 40 | # result = p.maxProfit(test) 41 | # print(result) 42 | -------------------------------------------------------------------------------- /Java/449_Serialize_deserialize_BST.java: -------------------------------------------------------------------------------- 1 | //Leetcode link : https://leetcode.com/problems/serialize-and-deserialize-bst/ 2 | 3 | public class Codec { 4 | 5 | // Encodes a tree to a single string. 6 | public String serialize(TreeNode root) { 7 | if (root == null) 8 | return ""; 9 | return bfs(root); 10 | } 11 | 12 | // returns a comma separated BFS traversal of the tree. 13 | public String bfs(TreeNode root) { 14 | Queue q = new LinkedList(); 15 | List vals = new ArrayList(); 16 | q.add(root); 17 | 18 | while (!q.isEmpty()) { 19 | TreeNode node = q.remove(); 20 | vals.add(String.valueOf(node.val)); 21 | if (node.left != null) 22 | q.add(node.left); 23 | if (node.right != null) 24 | q.add(node.right); 25 | } 26 | return String.join(",", vals); 27 | } 28 | 29 | // Decodes your encoded data to tree. 30 | public TreeNode deserialize(String data) { 31 | if (data.length() < 1) 32 | return null; 33 | 34 | String[] vals; 35 | vals = data.split(","); 36 | TreeNode root = new TreeNode(Integer.valueOf(vals[0])); 37 | 38 | for (int i = 1; i < vals.length; i++) { 39 | int val = Integer.valueOf(vals[i]); 40 | insertIntoBST(root, val); 41 | } 42 | 43 | return root; 44 | } 45 | 46 | // inserts a value into the BST at the correct position. 47 | public void insertIntoBST(TreeNode root, int val) { 48 | TreeNode node = root; 49 | TreeNode prev = root; 50 | while (node != null) { 51 | prev = node; 52 | if (val > node.val) 53 | node = node.right; 54 | else 55 | node = node.left; 56 | } 57 | 58 | node = new TreeNode(val); 59 | if (val > prev.val) 60 | prev.right = node; 61 | else 62 | prev.left = node; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /C/LongestPalindromicSubstring.c: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Ofek Mula on 14/10/2020. 3 | // 4 | 5 | #include 6 | #include 7 | 8 | char* get_substring(char* s,int start_index,int end_index){ 9 | char* substring=(char*)malloc(sizeof(char)*(end_index-start_index+2)); 10 | for ( int i=start_index;i<=end_index;i++){ 11 | substring[i-start_index]=s[i]; 12 | } 13 | substring[end_index-start_index+1]='\0'; 14 | return substring; 15 | } 16 | 17 | char* get_palindrome(char* s,int left_index,int right_index){ 18 | char* palindrome; 19 | if (left_index>=0 && right_index = strlen(s)){ 25 | break; 26 | } 27 | } 28 | } 29 | return palindrome; 30 | } 31 | 32 | char* longestPalindrome(char *s){ 33 | 34 | char* max_palindrome=""; 35 | char* even_palindrome=""; 36 | char* odd_palindrome=""; 37 | int left_index; 38 | int right_index; 39 | int counter=0; 40 | for (int j=1;j strlen(max_palindrome)) { 59 | max_palindrome=odd_palindrome; 60 | } 61 | if (strlen(even_palindrome) > strlen(max_palindrome) ){ 62 | max_palindrome=even_palindrome; 63 | } 64 | } 65 | return max_palindrome; 66 | } 67 | -------------------------------------------------------------------------------- /C++/RottingOranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int orangesRotting(vector>& grid) { 4 | 5 | bool flag=false; 6 | int minutes_counter=0; 7 | if(is_all_rotten(grid)){ 8 | minutes_counter= 0; 9 | return minutes_counter; 10 | } 11 | while(!flag && minutes_counter<=grid.size()*grid[0].size()){ 12 | update(grid,flag); 13 | minutes_counter++; 14 | } 15 | if(flag==false){ 16 | return -1; 17 | } 18 | return minutes_counter; 19 | 20 | 21 | } 22 | void update(vector>& grid,bool& flag){ 23 | vector> updated_grid(grid); 24 | for ( int i=0;i0){ 32 | near_rotten_function(updated_grid[i-1][j]); 33 | } 34 | if(j0){ 38 | near_rotten_function(updated_grid[i][j-1]); 39 | } 40 | 41 | } 42 | } 43 | } 44 | grid=updated_grid; 45 | if(is_all_rotten(grid)){ 46 | flag=true; 47 | } 48 | } 49 | void near_rotten_function(int& cell){ 50 | if (cell==0){ 51 | cell= 0; 52 | return; 53 | } 54 | cell=2; 55 | } 56 | bool is_all_rotten(vector>& grid){ 57 | for (int i=0;i1: #check for row 35 | return False 36 | c=0 37 | for k in range(len(board)): 38 | if board[k][j]==board[i][j]: #check for column 39 | c+=1 40 | if c>1: 41 | return False 42 | # Now check for sinlge-single 3x3 matrix if it contain all different elemnts or not 43 | for i in range(0,len(board),3): 44 | for j in range(0,len(board),3): 45 | nums = [0]*10 46 | for ii in range(i,i+3): 47 | for jj in range(j,j+3): 48 | if board[ii][jj] != '.': 49 | if nums[int(board[ii][jj])] <1: 50 | nums[int(board[ii][jj])] = int(board[ii][jj]) 51 | else: 52 | return False 53 | return True -------------------------------------------------------------------------------- /Python/firstAndLastIndexOfAnElementInSortedArray.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 2 | 3 | def searchRange(arr, target): 4 | 5 | n = len(arr) 6 | 7 | # find leftIndex 8 | leftIndex = -1 9 | 10 | # start is the first index of the array 11 | start = 0 12 | 13 | # end is the last index of the array 14 | end = n-1 15 | 16 | while(start <= end): 17 | # mid = (start+end)//2 18 | # (start + end) might exceed the range of integers 19 | 20 | # better way to do this 21 | mid = start + (end - start)//2 22 | 23 | # if target element is equal to the middle element 24 | if arr[mid] == target: 25 | 26 | # potential answer is found 27 | leftIndex = mid 28 | 29 | # continue searching in left of mid 30 | end = mid - 1 31 | 32 | # target element is less than middle element 33 | # search in the left 34 | elif target < arr[mid]: 35 | end = mid - 1 36 | 37 | # target element is greater than middle element 38 | # search in the right 39 | elif target > arr[mid]: 40 | start = mid + 1 41 | 42 | 43 | # find rightIndex 44 | rightIndex = -1 45 | 46 | # start is the first index of the array 47 | start = 0 48 | 49 | # end is the last index of the array 50 | end = n-1 51 | 52 | while(start <= end): 53 | # mid = (start+end)//2 54 | # (start + end) might exceed the range of integers 55 | 56 | # better way to do this 57 | mid = start + (end - start)//2 58 | 59 | # if target element is equal to the middle element 60 | if arr[mid] == target: 61 | # potential answer is found 62 | rightIndex = mid 63 | 64 | # continue searching in right of mid 65 | start = mid + 1 66 | 67 | # target element is less than middle element 68 | # search in the left 69 | elif target < arr[mid]: 70 | end = mid - 1 71 | 72 | # target element is greater than middle element 73 | # search in the right 74 | elif target > arr[mid]: 75 | start = mid + 1 76 | 77 | return [leftIndex,rightIndex] 78 | 79 | 80 | -------------------------------------------------------------------------------- /Python/Binary_Tree_Zigzag_Level_Order_Traversal.py: -------------------------------------------------------------------------------- 1 | # Problem link: 2 | # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 3 | 4 | ''' 5 | Approach - the idea here is to print each level, but the direction changes at 6 | each level. While adding nodes to a queue (like in BFS), we add a delimiter 7 | that helps us track when a level is ending, and change the direction of 8 | traversal for a level. 9 | We use a deque since appending and popping on either end is O(1). More on 10 | deque: https://docs.python.org/3/library/collections.html#collections.deque 11 | ''' 12 | 13 | from collections import deque 14 | # Definition for a binary tree node. 15 | # class TreeNode: 16 | # def __init__(self, val=0, left=None, right=None): 17 | # self.val = val 18 | # self.left = left 19 | # self.right = right 20 | 21 | 22 | class Solution: 23 | def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: 24 | # empty binary tree (edge case) 25 | if not root: 26 | return [] 27 | # we want to do bfs here, but the direction of traversal will change 28 | # after every level (use delimiter for that), using a variable to 29 | # track direction 30 | zigzagLevelOrderTraversal = [] 31 | # a deque supports faster append operation from both sides 32 | zigzagLevel = deque() 33 | bfsQueue = deque() 34 | leftToRight = True # change at every level 35 | # using an integer delimiter since all other elements in deque will be 36 | # TreeNode objects 37 | delimiter = -1 38 | bfsQueue.append(root) 39 | bfsQueue.append(delimiter) 40 | while bfsQueue: 41 | node = bfsQueue.popleft() 42 | if node == delimiter: 43 | zigzagLevelOrderTraversal.append(zigzagLevel) 44 | # we only proceed further if bfsQueue is not empty 45 | if bfsQueue: 46 | # change leftToRight since level is changing 47 | leftToRight = False if leftToRight else True 48 | zigzagLevel = deque() # empty current level elements 49 | bfsQueue.append(delimiter) 50 | else: 51 | if leftToRight: 52 | zigzagLevel.append(node.val) 53 | else: 54 | zigzagLevel.appendleft(node.val) 55 | if node.left: 56 | bfsQueue.append(node.left) 57 | if node.right: 58 | bfsQueue.append(node.right) 59 | return zigzagLevelOrderTraversal 60 | -------------------------------------------------------------------------------- /Python/median_of_two_sorted_arrays.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMedianSortedArrays(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: float 7 | """ 8 | 9 | def getIndices(rightShortArray, shortArray, longArray): 10 | midIndex = (len(shortArray) + len(longArray)) / 2 11 | rightLongArray = midIndex - rightShortArray 12 | return (rightShortArray - 1, rightShortArray, rightLongArray - 1, rightLongArray) 13 | 14 | 15 | def getDirection(leftShortArray, rightShortArray, leftLongArray, rightLongArray, shortArray, longArray): 16 | if getVal(shortArray, leftShortArray) > getVal(longArray, rightLongArray): 17 | return -1 18 | elif getVal(longArray, leftLongArray) > getVal(shortArray, rightShortArray): 19 | return 1 20 | else: 21 | return 0 22 | 23 | def getVal(array, i): 24 | if i == -1: 25 | return float('-inf') 26 | if i == len(array): 27 | return float('inf') 28 | return array[i] 29 | 30 | 31 | def getResult(leftShortArray, rightShortArray, leftLongArray, rightLongArray, shortArray, longArray): 32 | odd = (len(shortArray) + len(longArray)) % 2 33 | if odd: 34 | return min(getVal(longArray, rightLongArray), getVal(shortArray, rightShortArray)) 35 | else: 36 | return (max(getVal(shortArray, leftShortArray), getVal(longArray, leftLongArray)) 37 | + min(getVal(shortArray, rightShortArray), getVal(longArray, rightLongArray))) / 2.0 38 | 39 | 40 | shortArray = nums1 41 | longArray = nums2 42 | if len(nums1) > len(nums2): 43 | shortArray = nums2 44 | longArray = nums1 45 | 46 | 47 | leftShortArray = rightShortArray = leftLongArray = rightLongArray = t = 1 48 | 49 | 50 | l = 0 51 | r = len(shortArray) 52 | while t != 0: 53 | m = (l + r) / 2 54 | 55 | leftShortArray, rightShortArray, leftLongArray, rightLongArray = getIndices(m, shortArray, longArray) 56 | 57 | t = getDirection(leftShortArray, rightShortArray, leftLongArray, rightLongArray, shortArray, longArray) 58 | if t < 0: 59 | r = m - 1 60 | elif t > 0: 61 | l = m + 1 62 | 63 | return getResult(leftShortArray, rightShortArray, leftLongArray, rightLongArray, shortArray, longArray) -------------------------------------------------------------------------------- /C++/Course_schedule.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link: https://leetcode.com/problems/course-schedule/ 3 | 4 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. 5 | 6 | Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] 7 | 8 | Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: numCourses = 2, prerequisites = [[1,0]] 15 | Output: true 16 | Explanation: There are a total of 2 courses to take. 17 | To take course 1 you should have finished course 0. So it is possible. 18 | Example 2: 19 | 20 | Input: numCourses = 2, prerequisites = [[1,0],[0,1]] 21 | Output: false 22 | Explanation: There are a total of 2 courses to take. 23 | To take course 1 you should have finished course 0, and to take course 0 you should 24 | also have finished course 1. So it is impossible. 25 | 26 | 27 | Constraints: 28 | 29 | The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. 30 | You may assume that there are no duplicate edges in the input prerequisites. 31 | 1 <= numCourses <= 10^5 32 | 33 | */ 34 | 35 | class Solution { 36 | public: 37 | 38 | void addEdge(vector adj[], int u, int v){ 39 | 40 | adj[u].push_back(v); 41 | } 42 | 43 | bool tropoSort(vector adj[],int n){ 44 | 45 | queue q; 46 | vector inDeg(n,0); 47 | for(int i=0;i>& A) { 75 | 76 | if(n==1) 77 | return true; 78 | int m = A.size(); 79 | if(m==0) 80 | return true; 81 | 82 | vector adj[n]; 83 | 84 | for(int i=0;i int: 41 | dsu1, dsu2 = DSU(n), DSU(n) 42 | d = {} 43 | 44 | for t, x, y in a: 45 | x -= 1 46 | y -= 1 47 | if t in d: 48 | d[t].append([x, y]) 49 | else: 50 | d[t] = [[x,y]] 51 | 52 | ans = 0 53 | 54 | if 3 in d: 55 | for i in d[3]: 56 | x, y = i 57 | dsu2.union(x, y) 58 | if not dsu1.union(x, y): 59 | ans += 1 60 | 61 | if 1 in d: 62 | for i in d[1]: 63 | x, y = i 64 | if not dsu1.union(x, y): 65 | ans += 1 66 | 67 | if 2 in d: 68 | for i in d[2]: 69 | x, y = i 70 | if not dsu2.union(x, y): 71 | ans += 1 72 | 73 | if dsu1.size(0) != n or dsu2.size(0) != n: 74 | return -1 75 | return ans -------------------------------------------------------------------------------- /Python/Integer_to_English_Words.py: -------------------------------------------------------------------------------- 1 | # LeetCode Problem Link - https://leetcode.com/problems/integer-to-english-words/ 2 | 3 | class Solution(object): 4 | def numberToWords(self, num): 5 | """ 6 | :type num: int 7 | :rtype: str 8 | """ 9 | def decode(triple_str): 10 | final_list = [] 11 | 12 | numbers = { "1": "One", 13 | "2": "Two", 14 | "3": "Three", 15 | "4": "Four", 16 | "5": "Five", 17 | "6": "Six", 18 | "7": "Seven", 19 | "8": "Eight", 20 | "9": "Nine", 21 | "10": "Ten", 22 | "11": "Eleven", 23 | "12": "Twelve", 24 | "13": "Thirteen", 25 | "14": "Fourteen", 26 | "15": "Fifteen", 27 | "16": "Sixteen", 28 | "17": "Seventeen", 29 | "18": "Eighteen", 30 | "19": "Nineteen"} 31 | 32 | tens = { "2": "Twenty", 33 | "3": "Thirty", 34 | "4": "Forty", 35 | "5": "Fifty", 36 | "6": "Sixty", 37 | "7": "Seventy", 38 | "8": "Eighty", 39 | "9": "Ninety"} 40 | 41 | if int(triple_str[0]) != 0: 42 | final_list.append("{} Hundred".format(numbers[triple_str[0]])) 43 | if int(triple_str[1]) == 1: 44 | final_list.append("{}".format(numbers[triple_str[1:3]])) 45 | else: 46 | if int(triple_str[1]) != 0: 47 | final_list.append("{}".format(tens[triple_str[1]])) 48 | if int(triple_str[2]) != 0: 49 | final_list.append("{}".format(numbers[triple_str[2]])) 50 | 51 | return final_list 52 | 53 | 54 | num_str = "{:0>12}".format(str(num)) 55 | num_list = [] 56 | final_num = "" 57 | digit_dict = { 0: "Billion", 58 | 3: "Million", 59 | 6: "Thousand"} 60 | 61 | for x in range(0, 12, 3): 62 | the_triple = num_str[x:x+3] 63 | if the_triple == "000": 64 | continue 65 | else: 66 | num_list.extend(decode(the_triple)) 67 | if x == 9: break 68 | num_list.append(digit_dict[x]) 69 | 70 | final_num = " ".join(num_list) 71 | if final_num == "": 72 | final_num = "Zero" 73 | 74 | return final_num 75 | -------------------------------------------------------------------------------- /Python/Letter_Combinations_Of_A_Phone_Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 2 | 3 | 4 | class Solution: 5 | class Node: 6 | def __init__(self, val=None, nextNode=None): 7 | self.val = val 8 | self.nextNode = nextNode 9 | 10 | def constructMappings(self): 11 | letterZ = self.Node("z") 12 | letterY = self.Node("y", letterZ) 13 | letterX = self.Node("x", letterY) 14 | letterW = self.Node("w", letterX) 15 | letterV = self.Node("v") 16 | letterU = self.Node("u", letterV) 17 | letterT = self.Node("t", letterU) 18 | letterS = self.Node("s") 19 | letterR = self.Node("r", letterS) 20 | letterQ = self.Node("q", letterR) 21 | letterP = self.Node("p", letterQ) 22 | letterO = self.Node("o") 23 | letterN = self.Node("n", letterO) 24 | letterM = self.Node("m", letterN) 25 | letterL = self.Node("l") 26 | letterK = self.Node("k", letterL) 27 | letterJ = self.Node("j", letterK) 28 | letterI = self.Node("i") 29 | letterH = self.Node("h", letterI) 30 | letterG = self.Node("g", letterH) 31 | letterF = self.Node("f") 32 | letterE = self.Node("e", letterF) 33 | letterD = self.Node("d", letterE) 34 | letterC = self.Node("c") 35 | letterB = self.Node("b", letterC) 36 | letterA = self.Node("a", letterB) 37 | 38 | numberDict = dict() 39 | numberDict["2"] = letterA 40 | numberDict["3"] = letterD 41 | numberDict["4"] = letterG 42 | numberDict["5"] = letterJ 43 | numberDict["6"] = letterM 44 | numberDict["7"] = letterP 45 | numberDict["8"] = letterT 46 | numberDict["9"] = letterW 47 | 48 | return numberDict 49 | 50 | def getCombinations( 51 | self, currentIndex: int, digitNodes: List[Node], accumulatedString: str 52 | ): 53 | if currentIndex is len(digitNodes): 54 | self.answer.append(accumulatedString) 55 | return 56 | 57 | combinations = [] 58 | currentNode = digitNodes[currentIndex] 59 | while currentNode is not None: 60 | 61 | self.getCombinations( 62 | currentIndex + 1, digitNodes, accumulatedString + currentNode.val 63 | ) 64 | currentNode = currentNode.nextNode 65 | 66 | return 67 | 68 | def letterCombinations(self, digits: str) -> List[str]: 69 | 70 | self.answer = [] 71 | numberDict = self.constructMappings() 72 | 73 | if len(digits) is 0: 74 | return [] 75 | 76 | digitNodes = list() 77 | for index in range(0, len(digits)): 78 | digitNodes.append(numberDict[digits[index]]) 79 | 80 | self.getCombinations(0, digitNodes, "") 81 | return self.answer 82 | -------------------------------------------------------------------------------- /Python/Basic_Calculator_II.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/basic-calculator-ii/ 2 | 3 | # Implement a basic calculator to evaluate a simple expression string. 4 | # The expression string contains only non-negative integers and 5 | # +, -, *, / operators and empty spaces. 6 | # The integer division should truncate toward zero. 7 | 8 | # Example 1: 9 | # Input: "3+2*2" 10 | # Output: 7 11 | 12 | # Example 2: 13 | # Input: " 3/2 " 14 | # Output: 1 15 | 16 | # Example 3: 17 | # Input: " 3+5 / 2 " 18 | # Output: 5 19 | 20 | # Note: 21 | # You may assume that the given expression is always valid. 22 | # Do not use the eval built-in library function. 23 | 24 | 25 | """ 26 | Approach: 27 | 1. Segregate the string into a list with the digits and operations. 28 | 1.1 Count the operations along the way. 29 | 2. Go through the list twice. 30 | 2.1 Once to compute all "*" and "/". 31 | 2.2 Second to compute all "+" and "-". 32 | 3. Return the final element left in the expression. 33 | """ 34 | 35 | 36 | class Solution: 37 | def segregate(self, s): 38 | result = list() 39 | operator_count = {"+": 0, "-": 0, "*": 0, "/": 0} 40 | item = "" 41 | for index, char in enumerate(s): 42 | if char.isspace(): 43 | if item != "": 44 | result.append(int(item)) 45 | item = "" 46 | if char in ["+", "-", "*", "/"]: 47 | operator_count[char] += 1 48 | if item != "": 49 | result.append(int(item)) 50 | item = "" 51 | result.append(char) 52 | if char.isnumeric(): 53 | item += char 54 | if item != "": 55 | result.append(int(item)) 56 | return result, operator_count 57 | 58 | def calculate(self, s: str) -> int: 59 | exp, operator_count = self.segregate(s) 60 | # print("Initial", exp) 61 | # print(operator_count) 62 | ops = { 63 | "+": (lambda x, y: x + y), 64 | "-": (lambda x, y: x - y), 65 | "*": (lambda x, y: x * y), 66 | "/": (lambda x, y: x // y), 67 | } 68 | index = 0 69 | while index < len(exp): 70 | if exp[index] in ["/", "*"]: 71 | exp[index - 1] = ops[exp[index]]( 72 | exp[index - 1], exp[index + 1]) 73 | exp.pop(index) 74 | exp.pop(index) 75 | index -= 1 76 | index += 1 77 | index = 0 78 | while index < len(exp): 79 | if exp[index] in ["-", "+"]: 80 | exp[index - 1] = ops[exp[index]]( 81 | exp[index - 1], exp[index + 1]) 82 | exp.pop(index) 83 | exp.pop(index) 84 | index -= 1 85 | index += 1 86 | return exp[0] 87 | -------------------------------------------------------------------------------- /Python/singleElementInSortedArray.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/single-element-in-a-sorted-array/ 2 | 3 | # Algorithm - Binary Search 4 | 5 | # apply binary search 6 | # if mid is a non extreme element (mid!=0 and mid!=len(arr)) => arr[mid]!=arr[mid-1] and arr[mid]!=arr[mid+1] =>return arr[mid] 7 | # if mid==0, if arr[mid] != arr[mid +1] => return arr[mid] 8 | # if mid==n-1, if arr[mid] != arr[mid-1] => return arr[mid] 9 | # if mid is even, move to the side of the element same as mid 10 | # if mid is odd, move to side of the element different from mid 11 | 12 | class Solution: 13 | def singleNonDuplicate(self, nums) -> int: 14 | 15 | # n represents the size of the array 16 | n = len(nums) 17 | 18 | # if the size of the array is 1, the only element available is our answer 19 | if n == 1: 20 | return nums[0] 21 | 22 | # initially start is the first index of the array 23 | start = 0 24 | 25 | # initially end is the last index of the array 26 | end = n - 1 27 | 28 | while start <= end: 29 | mid = start + (end-start)//2 30 | 31 | # if mid is the start index and if element at mid is different from element at mid+1 32 | # then element at mid is our answer 33 | if mid == 0 and nums[mid]!=nums[mid+1]: 34 | return nums[mid] 35 | 36 | # if mid is the last index of the array and if element at mid is different from element at mid-1 37 | # then element at mid is our answer 38 | if mid == n - 1 and nums[mid] != nums[mid-1]: 39 | return nums[mid] 40 | 41 | # if mid is an index somewhere in the middle of the array 42 | # if element at mid is different from elements at mid-1 and mid+1 43 | # then mid is our answer 44 | if nums[mid] != nums[mid-1] and nums[mid] != nums[mid+1]: 45 | return nums[mid] 46 | 47 | # now we have cases to move the start and end pointers 48 | 49 | # if mid is even - even number of elements to the left of mid 50 | if mid%2 == 0: 51 | # if element at mid is equal to element at mid+1 52 | # ans will lie to the right of mid 53 | # start = mid + 1 54 | # else end = mid - 1 55 | if nums[mid] == nums[mid+1]: 56 | start = mid + 1 57 | else: 58 | end = mid - 1 59 | 60 | # if mid is odd - odd number of elements to the left of mid 61 | else: 62 | # if element at mid is not equal to element at mid-1 63 | # then our ans lies to the right side of mid 64 | # so start = mid + 1 65 | # else end = mid - 1 66 | if nums[mid] != nums[mid + 1]: 67 | start = mid + 1 68 | else: 69 | end = mid - 1 -------------------------------------------------------------------------------- /Python/449_Serialize_and_Deserialize_BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Codec: 9 | 10 | def inord(self, root, arr): 11 | if not root: 12 | return 13 | self.inord(root.left,arr) 14 | arr.append(str(root.val)) 15 | self.inord(root.right,arr) 16 | 17 | def postord(self, root, arr): 18 | if not root: 19 | return 20 | self.postord(root.left,arr) 21 | self.postord(root.right,arr) 22 | arr.append(str(root.val)) 23 | 24 | 25 | def serialize(self, root: TreeNode) -> str: 26 | """Encodes a tree to a single string. 27 | """ 28 | inorder = [] 29 | postorder = [] 30 | 31 | self.inord(root, inorder) 32 | self.postord(root, postorder) 33 | 34 | string = ",".join(inorder) + '$' + ','.join(postorder) 35 | print(string) 36 | return string 37 | 38 | def deserialize(self, data: str) -> TreeNode: 39 | """Decodes your encoded data to tree. 40 | """ 41 | if data == "$": 42 | return None 43 | inorder, postorder = data.split('$') 44 | inorder = [int(i) for i in inorder.split(',')] 45 | postorder = [int(i) for i in postorder.split(',')] 46 | 47 | return self.buildTree(inorder,postorder) 48 | 49 | 50 | def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: 51 | inorderDict = {} 52 | n = len(inorder) 53 | for i in range(n): 54 | inorderDict[inorder[i]] = i 55 | 56 | start = 0 57 | end = n-1 58 | 59 | self.head = None 60 | 61 | self.build(inorder, postorder, inorderDict, None, start, end, False, n-1) 62 | 63 | return self.head 64 | 65 | 66 | def build(self, inorder, postorder, inorderDict, head, start, end, left, rootIndex ): 67 | if start > end: 68 | return rootIndex 69 | nodeVal = postorder[rootIndex] 70 | index = inorderDict[nodeVal] 71 | rootIndex -= 1 72 | if head == None: 73 | head = TreeNode(nodeVal) 74 | self.head = head 75 | elif left: 76 | head.left = TreeNode(nodeVal) 77 | head = head.left 78 | else: 79 | head.right = TreeNode(nodeVal) 80 | head = head.right 81 | 82 | rootIndex = self.build(inorder, postorder, inorderDict, head, index+1, end, False, rootIndex) 83 | rootIndex = self.build(inorder, postorder, inorderDict, head, start, index-1, True, rootIndex) 84 | 85 | return rootIndex 86 | 87 | # Your Codec object will be instantiated and called as such: 88 | # Your Codec object will be instantiated and called as such: 89 | # ser = Codec() 90 | # deser = Codec() 91 | # tree = ser.serialize(root) 92 | # ans = deser.deserialize(tree) 93 | # return ans 94 | -------------------------------------------------------------------------------- /Python/Number_of_Islands.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-islands/ 2 | 3 | # class Graph defined here which contains node_count and adjacency_matrix 4 | class Graph: 5 | def __init__(self): 6 | self.node_count=0 7 | self.adjacency_list=[] 8 | 9 | # exploring every unexplored node of the graph recursively in a depth first way 10 | def explore(graph,node,explored): 11 | if explored[node] ==False : 12 | explored[node]=True 13 | for adjacent_node in graph.adjacency_list[node]: 14 | explore(graph,adjacent_node,explored) 15 | 16 | # checking for total no of connected components in the graph (water is exluded ) 17 | def dfs(graph,explored): 18 | connnected_components=0 19 | for i in range(0,graph.node_count): 20 | if explored[i] ==False : 21 | explore(graph,i,explored) 22 | connnected_components+=1 23 | return connnected_components 24 | 25 | #returns the list of nodes that are connected to nodes(i,j) 26 | def adjacent_elements(grid,i,j): 27 | al=[] 28 | rows=len(grid) 29 | cols=len(grid[0]) 30 | 31 | #checks if grid[i][j] is water or not, if it is water than a vacant list is returned else valid connected nodes are appended to the list and returned 32 | if grid[i][j] == '1' : 33 | if i-1>=0 : 34 | if grid[i-1][j] != '0': 35 | al.append((i-1)*cols+j) 36 | if i+1=0: 40 | if grid[i][j-1] != '0': 41 | al.append(i*cols+j-1) 42 | if j+1 dictT = new HashMap(); 15 | for (int i = 0; i < t.length(); i++) { 16 | int count = dictT.getOrDefault(t.charAt(i), 0); 17 | dictT.put(t.charAt(i), count + 1); 18 | } 19 | 20 | // Number of unique characters in t, which need to be present in the desired window. 21 | int required = dictT.size(); 22 | 23 | // Left and Right pointer 24 | int l = 0, r = 0; 25 | 26 | // formed is used to keep track of how many unique characters in t 27 | // are present in the current window in its desired frequency. 28 | // e.g. if t is "AABC" then the window must have two A's, one B and one C. 29 | // Thus formed would be = 3 when all these conditions are met. 30 | int formed = 0; 31 | 32 | // Dictionary which keeps a count of all the unique characters in the current window. 33 | Map windowCounts = new HashMap(); 34 | 35 | // ans list of the form (window length, left, right) 36 | int[] ans = {-1, 0, 0}; 37 | 38 | while (r < s.length()) { 39 | // Add one character from the right to the window 40 | char c = s.charAt(r); 41 | int count = windowCounts.getOrDefault(c, 0); 42 | windowCounts.put(c, count + 1); 43 | 44 | // If the frequency of the current character added equals to the 45 | // desired count in t then increment the formed count by 1. 46 | if (dictT.containsKey(c) && windowCounts.get(c).intValue() == dictT.get(c).intValue()) { 47 | formed++; 48 | } 49 | 50 | // Try and contract the window till the point where it ceases to be 'desirable'. 51 | while (l <= r && formed == required) { 52 | c = s.charAt(l); 53 | // Save the smallest window until now. 54 | if (ans[0] == -1 || r - l + 1 < ans[0]) { 55 | ans[0] = r - l + 1; 56 | ans[1] = l; 57 | ans[2] = r; 58 | } 59 | 60 | // The character at the position pointed by the 61 | // `Left` pointer is no longer a part of the window. 62 | windowCounts.put(c, windowCounts.get(c) - 1); 63 | if (dictT.containsKey(c) && windowCounts.get(c).intValue() < dictT.get(c).intValue()) { 64 | formed--; 65 | } 66 | 67 | // Move the left pointer ahead, this would help to look for a new window. 68 | l++; 69 | } 70 | 71 | // Keep expanding the window once we are done contracting. 72 | r++; 73 | } 74 | 75 | return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /C++/Text_Justification.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/text-justification/ 2 | #define ff first 3 | #define ss second 4 | class Solution { 5 | public: 6 | vector fullJustify(vector& words, int maxWidth) { 7 | int n=words.size(); 8 | if(n==1) 9 | { 10 | vector ans(1); 11 | ans[0]+=words[0]; 12 | while(ans[0].length()!=maxWidth) 13 | ans[0]+=" "; 14 | return ans; 15 | } 16 | vector> len(n); 17 | len[0].first=words[0].length(); 18 | len[0].second=len[0].first; 19 | int i; 20 | for(i=1;i ans(1); 28 | ans[0]+=words[0]; 29 | for(int i=1;i> help(1); 36 | int check=0; 37 | help[0].ff=0; 38 | int j=0; 39 | for(i=0;i ans(j,""); 58 | int sum=len[help[0].ss].ss; 59 | int space=help[0].ss; 60 | i=0; 61 | while(i!=help[0].ss) 62 | { 63 | ans[0]+=words[i]; 64 | i++; 65 | int xx=maxWidth-sum; 66 | int j; 67 | for(j=0;j version2, return 1. 11 | Otherwise, return 0. 12 | 13 | 14 | Example 1: 15 | Input: version1 = "1.01", version2 = "1.001" 16 | Output: 0 17 | Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". 18 | 19 | Example 2: 20 | Input: version1 = "1.0", version2 = "1.0.0" 21 | Output: 0 22 | Explanation: version1 does not specify revision 2, which means it is treated as "0". 23 | 24 | Example 3: 25 | Input: version1 = "0.1", version2 = "1.1" 26 | Output: -1 27 | Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. 28 | 29 | Example 4: 30 | Input: version1 = "1.0.1", version2 = "1" 31 | Output: 1 32 | 33 | Example 5: 34 | Input: version1 = "7.5.2.4", version2 = "7.5.3" 35 | Output: -1 36 | 37 | 38 | Constraints: 39 | 1 <= version1.length, version2.length <= 500 40 | version1 and version2 only contain digits and '.'. 41 | version1 and version2 are valid version numbers. 42 | All the given revisions in version1 and version2 can be stored in a 32-bit integer. 43 | 44 | */ 45 | 46 | #include 47 | #include 48 | int compareVersion(std::string version1, std::string version2) 49 | { 50 | std::size_t found1,found2; 51 | if(version1==version2) 52 | return 0; 53 | found1=version1.find('.'); 54 | found2=version2.find('.'); 55 | while(found1!=std::string::npos||found2!=std::string::npos) // npos is to detect end of string. 56 | { 57 | if(std::stoi(version1.substr(0,found1))>std::stoi(version2.substr(0,found2))) 58 | return 1; 59 | else if(std::stoi(version1.substr(0,found1))std::stof(version2)) 72 | return 1; 73 | else 74 | return -1; 75 | } 76 | 77 | // the code below does not change 78 | int main(int argc, char const *argv[]) 79 | { 80 | std::string s1,s2; 81 | int answer; 82 | std::cout << "Enter first version number.\n" ; 83 | std::cin>>s1; 84 | std::cout << "Enter second version number.\n" ; 85 | std::cin>>s2; 86 | answer = compareVersion(s1,s2); 87 | if(answer==0) 88 | { 89 | std::cout<<"The version numbers are the same. \n"; 90 | } 91 | else if(answer == 1) 92 | { 93 | std::cout<<"Version 1 is bigger. \n"; 94 | } 95 | else 96 | { 97 | std::cout<<"Version 2 is bigger. \n"; 98 | } 99 | return 0; 100 | } 101 | /* this solution was 0ms */ 102 | -------------------------------------------------------------------------------- /Java/The_Skyline_Problem.java: -------------------------------------------------------------------------------- 1 | /* 2 | LeetCode link: https://leetcode.com/problems/the-skyline-problem/ 3 | Difficulty: hard 4 | 5 | Solution author: Gianluca Gippetto 6 | */ 7 | import java.util.*; 8 | 9 | 10 | class Solution { 11 | static int LEFT = 0; 12 | static int RIGHT = 1; 13 | static int HEIGHT = 2; 14 | 15 | static class Corner { 16 | int x; 17 | int height; 18 | boolean isRightCorner; 19 | 20 | Corner(int x, int height, boolean isRightCorner) { 21 | this.x = x; 22 | this.height = height; 23 | this.isRightCorner = isRightCorner; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return String.format("Corner(x: %d, height: %d, isRightCorner: %d)", x, height, isRightCorner); 29 | } 30 | } 31 | 32 | static T last(List list) { 33 | return list.get(list.size() - 1); 34 | } 35 | 36 | static void heapPop(PriorityQueue heap, Map> heightToItems) { 37 | Corner removed = heap.poll(); 38 | heightToItems.get(removed.height).remove(removed); 39 | } 40 | 41 | static void heapPush(PriorityQueue heap, Map> heightToItems, Corner corner) { 42 | heap.add(corner); 43 | if (!heightToItems.containsKey(corner.height)) 44 | heightToItems.put(corner.height, new LinkedList()); 45 | heightToItems.get(corner.height).push(corner); 46 | } 47 | 48 | public List> getSkyline(int[][] buildings) { 49 | if (buildings.length == 0) 50 | return new ArrayList<>(1); 51 | 52 | List corners = new ArrayList<>(buildings.length * 2); 53 | int lastHeight = -1; 54 | for (int[] b : buildings) { 55 | if (b[HEIGHT] == lastHeight) { 56 | last(corners).x = b[RIGHT]; 57 | } else { 58 | corners.add(new Corner(b[LEFT], b[HEIGHT], false)); 59 | corners.add(new Corner(b[RIGHT], b[HEIGHT], true)); 60 | lastHeight = b[HEIGHT]; 61 | } 62 | } 63 | corners.sort((a, b) -> a.x - b.x); 64 | 65 | List> skyline = new ArrayList<>(); 66 | Corner firstCorner = corners.get(0); 67 | skyline.add(Arrays.asList(firstCorner.x, firstCorner.height)); 68 | 69 | // heap.poll() returns the Corner with maximum height 70 | PriorityQueue heap = 71 | new PriorityQueue<>(64, (a, b) -> b.height - a.height); 72 | 73 | // Useful to remove items from the priority queue: 74 | Map> heightToItems = new HashMap<>(); 75 | 76 | for (Corner corner : corners) { 77 | int currentHeight = (!heap.isEmpty()) ? heap.peek().height : 0; 78 | 79 | if (corner.isRightCorner) { 80 | assert (corner.height <= currentHeight); 81 | if (corner.height == currentHeight) { 82 | heapPop(heap, heightToItems); 83 | int newHeight = (!heap.isEmpty()) ? heap.peek().height : 0; 84 | List lastKeyPoint = last(skyline); 85 | if (corner.x == lastKeyPoint.get(0)) 86 | lastKeyPoint.set(1, newHeight); 87 | else 88 | skyline.add(Arrays.asList(corner.x, newHeight)); 89 | } 90 | else { 91 | Corner item = heightToItems.get(corner.height).pop(); 92 | heap.remove(item); 93 | } 94 | } 95 | else { // left corner of a building 96 | if (corner.height > currentHeight) { 97 | List lastKeyPoint = last(skyline); 98 | if (corner.x == lastKeyPoint.get(0)) 99 | lastKeyPoint.set(1, corner.height); 100 | else 101 | skyline.add(Arrays.asList(corner.x, corner.height)); 102 | } 103 | heapPush(heap, heightToItems, corner); 104 | } 105 | } 106 | return skyline; 107 | } 108 | } -------------------------------------------------------------------------------- /Python/Basic_Calculator.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/basic-calculator/ 2 | 3 | # Implement a basic calculator to evaluate a simple expression string. 4 | # The expression string may contain open '(' and closing parentheses ')', 5 | # the plus '+' or minus sign '-', non-negative integers and empty spaces . 6 | 7 | # Example 1: 8 | # Input: "1 + 1" 9 | # Output: 2 10 | 11 | # Example 2: 12 | # Input: " 2-1 + 2 " 13 | # Output: 3 14 | 15 | # Example 3: 16 | # Input: "(1+(4+5+2)-3)+(6+8)" 17 | # Output: 23 18 | 19 | # Note: 20 | # You may assume that the given expression is always valid. 21 | # Do not use the eval built-in library function. 22 | 23 | """ 24 | Approach: 25 | 1. Segregate the string into a list with the digits, operations 26 | and parenthesis. 27 | 1. To make sure that there could be any 2,3,4... no. of digits in a number: 28 | 1. If char is a numeric, appending it to item string. 29 | 2. Else append item to list if not empty and then 30 | append what was encountered. 31 | 2. Adding parenthesis to both sides before passing the string to segregator 32 | since our algorithm computes only when a ")" is encountered. 33 | 2. We have a dictionary to use for the operations. 34 | 3. Now iterate through the list. (enumerate gives index,item pairs.) 35 | 1. Append until ")" is encountered. 36 | 2. When ")" is encountered: 37 | 1. Find the index of the correcponding "(". 38 | 2. pop and operate on the numbers staring from that index, 39 | appending them at the same index. 40 | (Hence making it in-place operation(kind of)) 41 | 3. Finally when only a single number is left to compute, 42 | stack[-2] would be "(", so store number in temp, 43 | pop the "(", and add number back to stack. 44 | 4. For eg, this makes - 45 | stack = ["(", 1, "+", "(", 1, "+", 2 ] 46 | become - 47 | stack = ["(", 1, "+", 3 ] 48 | 4. Finally return the last item of the stack, the computed answer. 49 | """ 50 | 51 | 52 | class Solution: 53 | def segregate(self, s: str) -> list: 54 | """ 55 | Separetes elements of the equation from string to list. 56 | 57 | >>>segregate("(1+(4+5+2)-3)+(6+8)") 58 | ['(', '(', 1, '+', '(', 4, '+', 5, '+', 2, ')', '-', 3, ')', '+', 59 | '(', 6, '+', 8, ')', ')'] 60 | >>>segregate("( 11 + ( 41 + 51 + 21 ) - 31 ) + ( 16 + 18 )") 61 | ['(', '(', 11, '+', '(', 41, '+', 51, '+', 21, ')', '-', 31, ')', 62 | '+', '(', 16, '+', 18, ')', ')'] 63 | 64 | """ 65 | result = [] 66 | item = "" 67 | for char in s: 68 | if char.isspace(): 69 | if item != "": 70 | result.append(int(item)) 71 | item = "" 72 | if char in ["(", ")", "+", "-"]: 73 | if item != "": 74 | result.append(int(item)) 75 | item = "" 76 | result.append(char) 77 | if char.isnumeric(): 78 | item += char 79 | return result 80 | 81 | def calculate(self, s: str) -> int: 82 | """ 83 | Returns the computed value of the expression. 84 | 85 | >>>calculate("(1+(4+5+2)-3)+(6+8)") 86 | 23 87 | >>>calculate("( 11 + ( 41 + 51 + 21 ) - 31 ) + ( 16 + 18 )") 88 | 127 89 | 90 | """ 91 | list_of_expression = self.segregate("(" + s + ")") 92 | # print("initial",list_of_expression) 93 | ops = { 94 | "+": (lambda x, y: x + y), 95 | "-": (lambda x, y: x - y), 96 | } 97 | stack = [] 98 | for index, item in enumerate(list_of_expression): 99 | if item != ")": 100 | stack.append(item) 101 | # print(stack) 102 | else: 103 | open_brac = len(stack) - 1 104 | while stack[open_brac - 1] != "(": 105 | open_brac -= 1 106 | while stack[-2] != "(": 107 | x, op, y = ( 108 | stack.pop(open_brac), 109 | stack.pop(open_brac), 110 | stack.pop(open_brac), 111 | ) 112 | stack.insert(open_brac, int(ops[op](x, y))) 113 | temp = stack.pop() 114 | stack.pop() 115 | stack.append(temp) 116 | return stack.pop() 117 | --------------------------------------------------------------------------------