├── .github ├── FUNDING.yml └── workflows │ ├── codeql.yml │ └── greetings.yml ├── .gitignore ├── 0072-edit-distance.cpp ├── 0202-happy-number.cpp ├── 1-two-sums.cpp ├── 108_Convert_Sorted_Array_to_Binary_Search_Tree.cpp ├── 1207_Unique_Number_Of_Occurrences.cpp ├── 1232. Check If It Is a Straight Line.cpp ├── 125-Valid-Palindrome.cpp ├── 127. Word_Ladder ├── 1329.Sort_the_Matrix_Diagonally.cpp ├── 1338. Reduce Array Size to The Half.cpp ├── 136-single-number ├── 1512. Number of Good Pairs.cpp ├── 152._Maximum_Product_Subarray.java ├── 1531. String Compression II.cpp ├── 1539. Kth Missing Positive Number.cpp ├── 1547._Minimum_Cost_to_Cut_a_Stick.java ├── 16. 3Sum Closest ├── 1636_Sort_Array_By_Increasing_Frequency.cpp ├── 1662. Check If Two String Arrays are Equivalent ├── 1752_Check_If_Array_Is_Sorted_And_Rotated.cpp ├── 19-remove-nth-node-from-end-of-list.cpp ├── 1_bfs.cpp ├── 200.Number_of_Islands.cpp ├── 2095-Delete-the-Middle-Node-of-a-Linked-List.cpp ├── 2095_Delete_the_Middle_Node_of_a_Linked_List.java ├── 20_Valid_Parentheses.cpp ├── 21. Merge Two Sorted Lists.cpp ├── 234. Palindrome Linked List.cpp ├── 235. Lowest Common Ancestor of a Binary Search Tree.cpp ├── 2365-Task-scheduler-ii.cpp ├── 24.Swap_Nodes_in_Pairs.cpp ├── 2421. Number of Good Paths ├── 2427. N509. Fibonacci Numberumber of Common Factors.cpp ├── 2427. Number of Common Factors.cpp ├── 2428. Maximum Sum of an Hourglass.cpp ├── 2433.FindTheOriginalArrayofPrefixXor ├── 2433.FindTheOriginalArrayofPrefixXor.cpp ├── 268_Missing_Number.cpp ├── 26_Remove_Duplicates_From_Sorted_Array.cpp ├── 274. H-Index.cpp ├── 27_Remove_Element.cpp ├── 309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown.cpp ├── 326. Power of Three.cpp ├── 342. Power of Four.cpp ├── 35-search-insert-position.cpp ├── 394. Decode String.cpp ├── 412. Fizz Buzz.cpp ├── 46. Permutations.cpp ├── 48.Rotate_Image.cpp ├── 4Sum.cpp ├── 4_prims.cpp ├── 53. Maximum Subarray.java ├── 62. Unique Paths.cpp ├── 62. Unique paths.js ├── 659. Split Array into Consecutive Subsequences.cpp ├── 66_Plus_One.cpp ├── 674. Longest Continuous Increasing Subsequence.cpp ├── 692. Top K Frequent Words.cpp ├── 69_Sqrt(x).cpp ├── 704_Binary_Search.cpp ├── 713_Subarray_Product_Less_Than_K.cpp ├── 72._Edit_Distance.cpp ├── 72._Edit_Distance.java ├── 74. Search a 2D Matrix.java ├── 773. Sliding_Puzzle ├── 778. Swim_in_Rising_Water ├── 804. Unique Morse Code Words.cpp ├── 869.Reordered_Power_of_2.cpp ├── 871. Minimum Number of Refueling Stops.cpp ├── 88-Merge-Sorted-Array.cpp ├── 88. Merge Sorted Array.cpp ├── 887.Super_Egg_Drop.java ├── 936. Stamping The Sequence.cpp ├── 98. Validate Binary Search Tree.cpp ├── 99. Recover Binary Search Tree.cpp ├── 994. Rotting Oranges.cpp ├── 9_Palindrome_Number.cpp ├── ASCII.cpp ├── ActivitySelection.cpp ├── Add two nos.cpp ├── AllocateBooks.cpp ├── Armstrong number.cpp ├── Autobot Youtube clipper.py ├── BFS.cpp ├── BFS_2.cpp ├── Balanced Paranthesis.cpp ├── Best Time to Buy and Sell Stock.cpp ├── BigCountries.sql ├── Binary_and_Modular_Exponentiation.cpp ├── Binary_search.cpp ├── Bubble Sorting an Array using pointers.cpp ├── Bubble_sort.cpp ├── CARCG.C ├── CLosestPAirOfPoints.cpp ├── CODE_OF_CONDUCT.md ├── Calculator application ├── Calculator.py ├── ClimbingStairs.cpp ├── Coin_Change_2_DP.cpp ├── CombinationSum.java ├── Combination_Sum.cpp ├── Concatenation_Array.cpp ├── Container With Most Water.cpp ├── Count_Number_Of_Texts.cpp ├── Count_Reverse_Pairs.java ├── Counting Bits.cpp ├── CourseSchedular.cpp ├── Create Grading Students problem.py ├── DFA.py ├── DFS.cpp ├── Delete Node in a Linked List.cpp ├── Design_A_Text_Editor.cpp ├── Disjisktra.cpp ├── Distance of nearest cell having 1 ├── EditDistance.cpp ├── Eventual_safe_states ├── FCFS.java ├── Factorial ├── Fibonacci Series without recursion ├── FindCustomerReferee.sql ├── Find_whether_an_array_is_a_subset_of_another_array.cpp ├── First_Non_Repeating_Number.cpp ├── Flood_fill_algo.cpp ├── Flower Planting With No Adjacent.cpp ├── Fractional Knapsack ├── GCD in single line ├── GFG-Sets_Problem.cpp ├── Goal Parser.cpp ├── H-index.cpp ├── Height_Of_A_Binary_Tree.cpp ├── Hexadecimal_to_decimal_counter.cpp ├── Huffman_encoding.py ├── IntegerToRoman.py ├── Integet to Roman ├── JewelsAndStones.java ├── Kids_With_the_Greatest_Number_of_Candies.java ├── Kruskal.cpp ├── KthSymbol.java ├── Length_of_Longest_Substring_without_any_Repeating_Character.java ├── Linked-List-Cycle-Detection.cpp ├── Linkedlist_Implementation.cpp ├── Longest Increasing Subsequence ├── Longest Valid Parenthesis ├── Longest_Common_Subsequence.cpp ├── Longest_Palindromic_Subsequence.cpp ├── Majority Element ├── Make A and B equal.cpp ├── Matrix_Diagonal_Sum.java ├── Max Area of Island.cpp ├── Merge Intervals ├── MergeArray.java ├── MergeInterval.cpp ├── Minimize_XOR.cpp ├── Missingnumber.cpp ├── Mouseactivity.java ├── N-Queen.py ├── NQueen.cpp ├── NQueens.cpp ├── Next Permutation.java ├── Number of Islands.cpp ├── Number of Pairs Satisfying Inequality.cpp ├── OverlappingABBA.cpp ├── PartitionProblem.cpp ├── Pascal.cpp ├── Payroll Management System ├── PeakElement.java ├── Postevent_feedback_with_parallaxeffect.html ├── Postevent_update_2.html ├── Power_Set_trie.cpp ├── QuizGame.py ├── README.md ├── Radixsort.cpp ├── RatInMaze.cpp ├── Rearrange array elements by sign.cpp ├── Rectangle.cpp ├── Remove Duplicates from Sorted List.cpp ├── Remove duplicates for subarray ll.java ├── RemoveDuplicatesfromSortedArray.cpp ├── Reverse alternate levels of a perfect binary tree ├── ReverseLinkedList.cpp ├── RichestCustomerWealth.java ├── RodCutting.cpp ├── Rotate image ├── Russian_Doll.cpp ├── SalesPerson.sql ├── SearchInsertPosition.cpp ├── SearchRowColumnSortedMatrix.cpp ├── Search_2DMatrix_II.cpp ├── SetMatrixZero.java ├── Smallest Subtree with all the Deepest Nodes ├── Spiral Matrix II.java ├── SquareRoot.cpp ├── SquaresOfSortedArray.java ├── Subarray_With_Given_Sum.cpp ├── Subtract 12 Operation.cpp ├── Sudoku python.py ├── SudokuSolver.cpp ├── Sum of Prefix Scores of Strings.cpp ├── Sum of nodes at level k.cpp ├── SumofTwoArray.cpp ├── TargetSum.java ├── TemperatureConversion.cpp ├── Time2BurnTree.cpp ├── TrainglePattern.java ├── Trapping Rain Water.cpp ├── Trie.cpp ├── Trie.exe ├── Trim given Binary Tree for any subtree containing only 0s ├── Two Sum IV - Input is a BST.cpp ├── Twosums.cpp ├── Ugly Number II.cpp ├── Ugly_Number_II.cpp ├── Ugly_numbers.java ├── Unique Paths III.cpp ├── Valid Parentheses.cpp ├── ValidPair ├── ValidPair.cpp ├── Vending Machine ├── Word Break II.py ├── addOneRowtoTree.cpp ├── binarySearch.cpp ├── bst.c ├── bst_linked.c ├── bubble_sort.cpp ├── bubblesort.cpp ├── calculateDigit.cpp ├── calculator_application.py ├── check-if-there-is-a-valid-partition-of-array.cpp ├── check_star_graph.cpp ├── circular_delete.c ├── clone_graph.cpp ├── combination sum.cpp ├── concatenationofConsecutiveBinaryNumbers.cpp ├── countSmallerNumber.cpp ├── countSolutions.cpp ├── count_dispaly.c ├── cutRod.cpp ├── deleteNode.java ├── designCircularQueue.cpp ├── diagonal_matrix.c ├── digit.cpp ├── dijkstras.cpp ├── double_triangle_pattern.c ├── duplicates.c++ ├── even or odd.cpp ├── findPermutations.cpp ├── findTriplets.cpp ├── fixedPoint.cpp ├── floodfill.cpp ├── fourSum.java ├── frequenciesOfElementsInArray.cpp ├── frequencyofcharacters_string.java ├── generate_paranthesis.cpp ├── get maze.cpp ├── gravityflipProblem.cpp ├── guessing_the_number.c ├── happynumber_taniaban2712.cpp ├── help_classmates.cpp ├── increasing_triplet_subsequence.cpp ├── javascript clock └── project.html ├── kadaneAlgorithm ├── kadaneAlgorithm.cpp ├── korasuls_strongly_connected.cpp ├── ladder prob.cpp ├── linked_list_ circular.cpp ├── longest cycle in graph.cpp ├── longest-increasing-subsequence-ii.cpp ├── longestMountain.cpp ├── longest_substring_without_repeating_characters.cpp ├── majority_element2.cpp ├── matrix_chain_mult.cpp ├── matrix_to_spiral_matrix.cpp ├── maxMinWindow.cpp ├── maxSubarraySum.cpp ├── maxXorQueries.cpp ├── maxfreqofelement.cpp ├── maximize_array.cpp ├── maximum-score-words-formed-by-letters ├── maximumMeetings.cpp ├── maximumSubarraySum.cpp ├── merge two sorted array.cpp ├── merge_sort.cs ├── merge_two_ll.cpp ├── missingnumber.cpp ├── n queens problem ├── onoffBULB.HTML ├── pascal's triangle.cpp ├── passwordGenrator.cpp ├── passwordgenerator.py ├── prime-or-not.cpp ├── primenumber.cpp ├── prims algo.cpp ├── quiz.cpp ├── removeString.cpp ├── reverse integers.cpp ├── rootToLeafSum.cpp ├── rotate_bits ├── searchRotatedSortedArr.cpp ├── segregate_even_and_odd_nodes_in_LL.cpp ├── shortestPathUnweightedGraph.cpp ├── single_file_program.cpp ├── single_num_2.cpp ├── sortStack.cpp ├── sparse_create.c ├── sqrt(x).java ├── square_pattern.c ├── stack_next_greater_element.cpp ├── star_pattern.c ├── strongnum.cpp ├── sudoko.cpp ├── table_program ├── tempCodeRunnerFile.cpp ├── tower_of_honoi.java ├── traping rain water.cpp ├── tree.c ├── trie_Maximum_XOR.cpp ├── two sum.cpp ├── two_sum.cpp ├── using_robot_to_print_lexicographically_smallest_string.cpp └── wildcard_matching.cpp /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # [@kasakvaish] 4 | patreon: # @kasakvaish 5 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request_target, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | with: 14 | repo-token: ${{ secrets.GITHUB_TOKEN }} 15 | issue-message: "Message that will be displayed on users' first issue" 16 | pr-message: "Message that will be displayed on users' first pull request" 17 | -------------------------------------------------------------------------------- /0072-edit-distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int f(string word1, string word2,int i,int j,vector>&dp){ 5 | if(i<0) return j+1; 6 | if(j<0) return i+1; 7 | if(dp[i][j]!=-1) return dp[i][j]; 8 | if(word1[i]==word2[j]){ 9 | return dp[i][j] = 0 + f(word1,word2,i-1,j-1,dp); 10 | } 11 | return dp[i][j] = 1 + min(f(word1,word2,i-1,j,dp),min(f(word1,word2,i-1,j-1,dp),f(word1,word2,i,j-1,dp))); 12 | } 13 | 14 | 15 | int minDistance(string word1, string word2) { 16 | int n= word1.size(); 17 | int m = word2.size(); 18 | vector>dp(word1.size()+1,vector(word2.size()+1,-1)); 19 | for(int i=0;i<=n;i++){ 20 | dp[i][0]=i; 21 | } 22 | for(int j=0;j<=m;j++){ 23 | dp[0][j]=j; 24 | } 25 | for(int i=1;i<=n;i++){ 26 | for(int j=1;j<=m;j++){ 27 | if(word1[i-1]==word2[j-1]){ 28 | dp[i][j] = 0 + dp[i-1][j-1]; 29 | } 30 | else 31 | dp[i][j] = 1 + min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1])); 32 | } 33 | } 34 | return dp[n][m]; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /0202-happy-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isHappy(int n) { 4 | if(n == 1) 5 | return true; 6 | if(n > 1 && n <= 4) 7 | return false; 8 | 9 | int sum = 0; 10 | while(n > 0) { 11 | int m = n % 10; 12 | sum = sum + (m * m); 13 | n = n / 10; 14 | } 15 | 16 | return isHappy(sum); 17 | } 18 | }; -------------------------------------------------------------------------------- /1-two-sums.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | vectorresult; 5 | for(int i =0;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | TreeNode *sortedArrayToBST(vector &nums) 11 | { 12 | return helper(nums, 0, nums.size() - 1); 13 | } 14 | 15 | TreeNode *helper(vector &nums, int left, int right) 16 | { 17 | 18 | // base case 19 | // If the left pointer crosses right return null; 20 | if (left > right) 21 | { 22 | return NULL; 23 | } 24 | 25 | // as middle of the array will be the root node 26 | int mid = (left + right) / 2; 27 | TreeNode *temp = new TreeNode(nums[mid]); 28 | 29 | // left part from middle will be left subtree 30 | temp->left = helper(nums, left, mid - 1); 31 | 32 | // right part of array will be right subtree 33 | temp->right = helper(nums, mid + 1, right); 34 | return temp; 35 | } 36 | }; -------------------------------------------------------------------------------- /1207_Unique_Number_Of_Occurrences.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-number-of-occurrences/ 2 | 3 | class Solution { 4 | public: 5 | bool uniqueOccurrences(vector& arr) { 6 | bool flag{true}; 7 | map m; 8 | for(int i{0}; i count; 12 | for(auto val : m){ 13 | count.push_back(val.second); 14 | } 15 | sort(count.begin(),count.end()); 16 | for(int i{0}; i>& a) { 4 | int i, n, val, x, y; 5 | n = a.size(); 6 | x = a[1][0] - a[0][0]; 7 | y = a[1][1] - a[0][1]; 8 | for(i=0; i'Z')&&(s[i]<'a'|| s[i]>'z')&&(s[i]<'0' || s[i]>'9')){ 7 | s.erase(i,1); 8 | i--; 9 | } 10 | } 11 | if(s.compare("")==0){ 12 | return true; 13 | } 14 | //all small 15 | for(int i =0;i& wordList) { 4 | 5 | unordered_map> mp; 6 | unordered_map bank,visited; 7 | vector mywordList; 8 | 9 | mywordList.push_back(beginWord); 10 | bank[beginWord]=true; 11 | for(auto it:wordList){ 12 | bank[it]=true; 13 | mywordList.push_back(it); 14 | } 15 | 16 | for(int i=0;i q; 30 | q.push(beginWord); 31 | visited[beginWord]=true; 32 | int level=2; 33 | 34 | while(!q.empty()) 35 | { 36 | int n=q.size(); 37 | for(int i=0;i& a) { 4 | int i, n=a.size(), size=n, ans=1; 5 | unordered_map mp; 6 | priority_queue> pq; 7 | for(auto x: a) mp[x]++; 8 | for(auto x: mp) { 9 | pq.push({x.second, x.first}); 10 | } 11 | while(size-pq.top().first > (n/2)) { 12 | size -= pq.top().first; pq.pop(); 13 | ans++; 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /136-single-number: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | public: 4 | int singleNumber(vector& nums) { 5 | //approach 1 6 | int xorresult = 0; 7 | for(int i =0;i& nums) { 4 | int ans = 0; 5 | for(int i = 0; i < nums.size(); i++){ 6 | for(int j = i+1; j < nums.size(); j++){ 7 | if(nums[i] == nums[j]){ 8 | ans++; 9 | } 10 | } 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /152._Maximum_Product_Subarray.java: -------------------------------------------------------------------------------- 1 | // Problem link 2 | // https://leetcode.com/problems/maximum-product-subarray/ 3 | 4 | 5 | 6 | // Basically to undertand this solution, one should have idea on Kadanes Algorithm which is a DP approach to solve Maximum Subarray Sum. 7 | // This question just replaced sum with product and we know that we got headache with the negative values if you have understood the question properly. 8 | // So I swapped min and max values at current iteration of negative value. 9 | 10 | 11 | class Solution { 12 | public int maxProduct(int[] nums) { 13 | int max=nums[0], min=nums[0],prod=max; 14 | for(int i=1;i>>> &dp, string &s) 5 | { 6 | if(k < 0) return 100000000; 7 | if(currIdx >= s.size()) return 0; 8 | 9 | if(curFreq >= 10) curFreq = 10; 10 | if(dp[currIdx][prevchar][curFreq][k] != -1) return dp[currIdx][prevchar][curFreq][k]; 11 | 12 | // // exclude 13 | int res = 100000000; 14 | res = min(res, helper(currIdx + 1, prevchar, curFreq, k - 1, dp, s)); 15 | 16 | // // include 17 | if(s[currIdx] - 'a' != prevchar) 18 | { 19 | res = min(res, 1 + helper(currIdx + 1, s[currIdx] - 'a', 1, k, dp, s)); 20 | } 21 | else 22 | { 23 | if(curFreq == 1 || curFreq == 9) 24 | { 25 | res = min(res, 1 + helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s)); 26 | } 27 | else res = min(res, helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s)); 28 | } 29 | 30 | return dp[currIdx][prevchar][curFreq][k] = res; 31 | } 32 | 33 | int getLengthOfOptimalCompression(string s, int k) 34 | { 35 | int n = s.size(); 36 | cout<>>> dp 45 | (n+1,vector>>(28,vector>(11,vector(n+1,-1)))); 46 | return helper(0, 27, 0, k, dp, s); 47 | } 48 | 49 | }; 50 | -------------------------------------------------------------------------------- /1539. Kth Missing Positive Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthPositive(vector& a, int k) { 4 | int i,n=a.size(),ans; 5 | unordered_map A; 6 | for(i=0;i(); 9 | for (int cut : cuts) 10 | c.add(cut); 11 | c.addAll(Arrays.asList(0, n)); 12 | Collections.sort(c); 13 | int[][] dp = new int[c.size()][c.size()]; 14 | for (int i = c.size() - 1; i >= 0; --i) 15 | for (int j = i + 1; j < c.size(); ++j) { 16 | for (int k = i + 1; k < j; ++k) 17 | dp[i][j] = Math.min(dp[i][j] == 0 ? Integer.MAX_VALUE : dp[i][j], 18 | c.get(j) - c.get(i) + dp[i][k] + dp[k][j]); 19 | } 20 | return dp[0][c.size() - 1]; 21 | } 22 | -------------------------------------------------------------------------------- /1636_Sort_Array_By_Increasing_Frequency.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sort-array-by-increasing-frequency/ 2 | 3 | class Solution { 4 | public: 5 | bool static compare(pair a,pair b){ 6 | if(a.second == b.second){ 7 | return a>b; 8 | } 9 | else{ 10 | return a.second frequencySort(vector& nums) { 14 | map mp; 15 | for(int i{0}; i> vec; 19 | for(auto val : mp){ 20 | vec.push_back(val); 21 | } 22 | sort(vec.begin(),vec.end(),compare); 23 | vector answer; 24 | for(int i{0}; i0){ 26 | answer.push_back(vec.at(i).first); 27 | vec.at(i).second--; 28 | } 29 | } 30 | return answer; 31 | } 32 | 33 | }; 34 | -------------------------------------------------------------------------------- /1662. Check If Two String Arrays are Equivalent: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool arrayStringsAreEqual(vector& word1, vector& word2) { 4 | string sol1=""; 5 | string sol2=""; 6 | for(auto i:word1) 7 | sol1+=i; 8 | for(auto i:word2) 9 | sol2+=i; 10 | return sol1==sol2; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /1752_Check_If_Array_Is_Sorted_And_Rotated.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ 2 | 3 | class Solution { 4 | public: 5 | bool check(vector& nums) { 6 | int count{0}; 7 | for(int i{0}; i nums.at(i+1)){ 9 | count++; 10 | } 11 | } 12 | if(nums.at(nums.size()-1) > nums.at(0)){ 13 | count++; 14 | } 15 | if(count <= 1){ 16 | return true; 17 | } 18 | else{ 19 | return false; 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /19-remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | 12 | // *********************************************************************************** 13 | // Problem link : https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 14 | 15 | class Solution { 16 | public: 17 | ListNode* removeNthFromEnd(ListNode* head, int n) { 18 | ListNode *dummy = new ListNode(0); 19 | dummy->next = head; 20 | ListNode *slow = dummy, *fast = dummy; 21 | while(n && fast->next) 22 | { 23 | fast = fast->next; 24 | n--; 25 | } 26 | while(fast->next) 27 | { 28 | slow = slow->next; 29 | fast = fast->next; 30 | } 31 | ListNode *temp = slow->next; 32 | slow->next = slow->next->next; 33 | delete temp; 34 | return dummy->next; 35 | } 36 | }; -------------------------------------------------------------------------------- /1_bfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void bfs(int g[][7],int i,int n) 6 | { 7 | queueq; 8 | int arr[7]={0}; 9 | // start ka index 1 10 | arr[i]=1; 11 | cout<>&grid,int i,int j,int m,int n){ 9 | 10 | if(i<0||j<0||i>=m||j>=n||grid[i][j]!='1'){ 11 | return; 12 | } 13 | grid[i][j] = '2'; 14 | checkIslands(grid,i-1,j,m,n); 15 | checkIslands(grid,i,j-1,m,n); 16 | checkIslands(grid,i+1,j,m,n); 17 | checkIslands(grid,i,j+1,m,n); 18 | 19 | 20 | } 21 | 22 | 23 | 24 | int countIslands(vector> &grid){ 25 | 26 | int m = grid.size(); 27 | int n = grid[0].size(); 28 | int count = 0; 29 | for(int i = 0 ; i < m ;i++){ 30 | for(int j = 0 ;j < n ;j++){ 31 | if(grid[i][j]=='1'){ 32 | count++; 33 | checkIslands(grid,i,j,m,n); 34 | } 35 | } 36 | } 37 | 38 | return count; 39 | 40 | 41 | } 42 | 43 | 44 | int numIslands(vector>& grid) { 45 | return countIslands(grid); 46 | } 47 | }; -------------------------------------------------------------------------------- /2095-Delete-the-Middle-Node-of-a-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteMiddle(ListNode* head) { 4 | ListNode *slow=head; 5 | ListNode *fast=head; 6 | ListNode *prev=NULL; 7 | if(head->next==NULL) return NULL; 8 | while(fast!=NULL and fast->next!=NULL){ 9 | prev=slow; 10 | slow=slow->next; 11 | fast=fast->next->next; 12 | } 13 | prev->next=slow->next; 14 | return head; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /2095_Delete_the_Middle_Node_of_a_Linked_List.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode deleteMiddle(ListNode head) { 3 | if(head.next == null){ 4 | return head.next; 5 | } 6 | ListNode slow = head; 7 | ListNode fast = head; 8 | ListNode prev = null; 9 | while(fast != null && fast.next != null){ 10 | prev = slow; 11 | slow = slow.next; 12 | fast = fast.next.next; 13 | } 14 | prev.next = prev.next.next; 15 | return head; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /20_Valid_Parentheses.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-parentheses/ 2 | 3 | class Solution { 4 | public: 5 | bool isValid(string s) { 6 | stack Stack; 7 | for(int i{0}; ival < b->val) { 9 | temp->next = a; 10 | a = a->next; 11 | temp = temp->next; 12 | } 13 | else { 14 | temp->next = b; 15 | b = b->next; 16 | temp = temp->next; 17 | } 18 | } 19 | if(a) temp->next = a; 20 | if(b) temp->next = b; 21 | return dummy->next; 22 | } 23 | }; -------------------------------------------------------------------------------- /234. Palindrome Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *reverse(ListNode *head){ 4 | ListNode *curr=head, *next=NULL, *prev=NULL; 5 | while(curr){ 6 | next=curr->next; 7 | curr->next=prev; 8 | prev=curr; 9 | curr=next; 10 | } 11 | return head=prev; 12 | } 13 | bool isPalindrome(ListNode* head) { 14 | ListNode *curr=head, *slow=head, *fast=head; 15 | while(fast->next && fast->next->next) { 16 | slow=slow->next; 17 | fast=fast->next->next; 18 | } 19 | slow->next=reverse(slow->next); 20 | slow=slow->next; 21 | while(slow){ 22 | if(slow->val != curr->val) return 0; 23 | slow=slow->next; 24 | curr=curr->next; 25 | } 26 | return 1; 27 | } 28 | }; -------------------------------------------------------------------------------- /235. Lowest Common Ancestor of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | if(root==NULL) 5 | return root; 6 | if(root==p || root==q) 7 | return root; 8 | TreeNode* lca1=lowestCommonAncestor(root->left,p,q); 9 | TreeNode* lca2=lowestCommonAncestor(root->right,p,q); 10 | if(lca1 && lca2) 11 | return root; 12 | if(lca1) 13 | return lca1; 14 | if(lca2) 15 | return lca2; 16 | return NULL; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /2365-Task-scheduler-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long taskSchedulerII(vector& tasks, int space) { 4 | unordered_mapmapp; 5 | long long res=tasks.size(); 6 | 7 | vectorarr(tasks.size()); 8 | long long c=0; 9 | 10 | for(int i=0;inext; 23 | current->next = prev; 24 | prev = current; 25 | current = next; 26 | 27 | i++; 28 | } 29 | if(next!=NULL){ 30 | head->next = swapPairs(next); 31 | } 32 | return prev; 33 | } 34 | }; -------------------------------------------------------------------------------- /2427. N509. Fibonacci Numberumber of Common Factors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int n) { 4 | if(n == 1) 5 | return 1; 6 | 7 | int first = 0; 8 | int second = 1; 9 | int ans = 0; 10 | for(int i = 1; i < n; i++){ 11 | ans = first + second; 12 | first = second; 13 | second = ans; 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /2427. Number of Common Factors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int commonFactors(int a, int b) { 4 | int mini = min(a,b); 5 | int ans = 0; 6 | for(int i = 1; i <= mini; i++){ 7 | if(a % i ==0 && b % i == 0) 8 | ans++; 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /2428. Maximum Sum of an Hourglass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution 4 | { 5 | public: 6 | int maxSum(vector> &grid) 7 | { 8 | // vector> pos = {{0,0},{0,1},{0,2},{1,1},{2,0},{2,1},{2,2}}; 9 | int sum = 0; 10 | for (int i = 0; i < grid.size(); i++) 11 | { 12 | for (int j = 0; j < grid[0].size(); j++) 13 | { 14 | if (i + 2 < grid.size() && j + 2 < grid[0].size()) 15 | { 16 | int temp = grid[i][j] + grid[i][j + 1] + grid[i][j + 2] + grid[i + 1][j + 1] + grid[i + 2][j] + grid[i + 2][j + 1] + grid[i + 2][j + 2]; 17 | sum = max(sum, temp); 18 | } 19 | } 20 | } 21 | return sum; 22 | } 23 | }; 24 | int main() 25 | { 26 | Solution b; 27 | vector> grid = {{6, 2, 1, 3}, {4, 2, 1, 5}, {9, 2, 8, 7}, {4, 1, 2, 9}}; 28 | cout << b.maxSum(grid) << endl; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /2433.FindTheOriginalArrayofPrefixXor: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/strang3-r/Leetcode75/c8e5de0ac282d7cc53cc5d9a548f23ef1ae13984/2433.FindTheOriginalArrayofPrefixXor -------------------------------------------------------------------------------- /2433.FindTheOriginalArrayofPrefixXor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution 4 | { 5 | public: 6 | vector findArray(vector &A) 7 | { 8 | for (int i = A.size() - 1; i > 0; --i) 9 | A[i] ^= A[i - 1]; 10 | return A; 11 | } 12 | }; 13 | 14 | int main() 15 | { 16 | Solution b; 17 | vector arr = {5, 2, 0, 3, 1}; 18 | auto ans = b.findArray(arr); 19 | for (int x : ans) 20 | cout << x << endl; 21 | return 0; 22 | } -------------------------------------------------------------------------------- /268_Missing_Number.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/missing-number/ 2 | 3 | class Solution { 4 | public: 5 | int missingNumber(vector& nums) { 6 | sort(nums.begin(),nums.end()); 7 | int ans{}; 8 | for(int i{0}; i& nums) { 6 | for(int i{0}; i& a) { 4 | int lo = 0, hi = a.size() - 1, mid; 5 | sort(a.begin(), a.end()); 6 | while(lo <= hi) { 7 | mid = (lo + hi) >> 1; 8 | if(a[mid] < a.size() - mid) lo = mid + 1; 9 | else hi = mid - 1; 10 | } 11 | return a.size() - lo; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /27_Remove_Element.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-element/ 2 | 3 | class Solution { 4 | public: 5 | int removeElement(vector& nums, int val) { 6 | for(int i{0}; i&prices,vector>&dp) 4 | { 5 | if(ind>=prices.size())return 0; 6 | int profit=0; 7 | if(dp[ind][buy]!=-1)return dp[ind][buy]; 8 | if(buy) 9 | { 10 | profit=max(-prices[ind]+find(ind+1,0,prices,dp),find(ind+1,1,prices,dp)); 11 | } 12 | else 13 | profit=max(prices[ind]+find(ind+2,1,prices,dp),find(ind+1,0,prices,dp)); 14 | return dp[ind][buy]=profit; 15 | } 16 | int maxProfit(vector& prices) { 17 | vector>dp(prices.size(),vector(2,-1)); 18 | int a=find(0,1,prices,dp); 19 | return a; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /326. Power of Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | if(n<=0) return 0; 5 | return ((1162261467%n) == 0); 6 | } 7 | }; 8 | 9 | 10 | -------------------------------------------------------------------------------- /342. Power of Four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | return ((n > 0) && ((n&(n-1)) == 0) && (n%3 == 1)); 5 | } 6 | }; -------------------------------------------------------------------------------- /35-search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int indx; 5 | if(nums[0]>target){ 6 | indx = 0; 7 | } 8 | else if(nums[nums.size()-1]target){ 17 | indx = i+1; 18 | } 19 | } 20 | } 21 | return indx; 22 | } 23 | }; -------------------------------------------------------------------------------- /394. Decode String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeString(const string& s, int& i) { 4 | string res; 5 | 6 | while (i < s.length() && s[i] != ']') { 7 | if (!isdigit(s[i])) 8 | res += s[i++]; 9 | else { 10 | int n = 0; 11 | while (i < s.length() && isdigit(s[i])) 12 | n = n * 10 + s[i++] - '0'; 13 | 14 | i++; // '[' 15 | string t = decodeString(s, i); 16 | i++; // ']' 17 | 18 | while (n-- > 0) 19 | res += t; 20 | } 21 | } 22 | 23 | return res; 24 | } 25 | 26 | string decodeString(string s) { 27 | int i = 0; 28 | return decodeString(s, i); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /412. Fizz Buzz.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fizzBuzz(int n) { 4 | vector ans; 5 | for(int i = 1; i <= n; i++){ 6 | if(i % 3 == 0 && i % 5 == 0) 7 | ans.push_back("FizzBuzz"); 8 | else if(i % 3 == 0) 9 | ans.push_back("Fizz"); 10 | else if(i % 5 == 0) 11 | ans.push_back("Buzz"); 12 | else 13 | ans.push_back(to_string(i)); 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /46. Permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | leetcode problem no 46 Permutations 3 | 4 | Input: nums = [1,2,3] 5 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 6 | */ 7 | 8 | class Solution { 9 | public: 10 | void backtrack(vector>& pers, vector& per, vector& nums){ 11 | if(per.size() == nums.size()){ 12 | pers.push_back(per); 13 | }else{ 14 | for(int e : nums){ 15 | if(find(per.begin(), per.end(), e) != per.end()){ 16 | continue; 17 | } 18 | per.push_back(e); 19 | backtrack(pers, per, nums); 20 | per.pop_back(); 21 | } 22 | } 23 | }; 24 | 25 | vector> permute(vector& nums) { 26 | vector> pers; 27 | vector per; 28 | 29 | backtrack(pers, per, nums); 30 | 31 | return pers; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /48.Rotate_Image.cpp: -------------------------------------------------------------------------------- 1 | // Solution to the Problem : Rotate Image 2 | // https://leetcode.com/problems/rotate-image/ 3 | 4 | class Solution { 5 | public: 6 | void rotate(vector>& matrix) { 7 | int m = matrix.size(); 8 | int n = matrix[0].size(); 9 | 10 | for(int i = 0 ; i < m ; i++){ 11 | 12 | for(int j = i ; j < n ; j++){ 13 | swap(matrix[i][j],matrix[j][i]); 14 | } 15 | 16 | } 17 | 18 | for(int i = 0 ; i < m ; i++){ 19 | for(int j = 0 ; j < n /2 ;j++){ 20 | swap(matrix[i][j],matrix[i][n-j-1]); 21 | } 22 | } 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /4Sum.cpp: -------------------------------------------------------------------------------- 1 | vector> fourSum(vector& nums, int target) { 2 | int n = nums.size(); 3 | sort(nums.begin() , nums.end()); // sort the array to use the two pointers method 4 | vector> ans; 5 | set> store; // to store and remove the duplicate answers 6 | 7 | for(int i = 0 ; i < n; i++){ 8 | 9 | for(int j = i + 1; j < n ; j++){ 10 | 11 | int new_target = target - nums[i] - nums[j]; 12 | 13 | int x = j+1 , y = n-1; 14 | 15 | while(x < y){ 16 | 17 | int sum = nums[x] + nums[y]; 18 | 19 | if(sum > new_target) y--; 20 | else if(sum < new_target ) x++; 21 | else { 22 | store.insert({nums[i] , nums[j] , nums[x] , nums[y]}); 23 | x++; 24 | y--; 25 | }; 26 | } 27 | } 28 | } 29 | 30 | for(auto i : store){ 31 | ans.push_back(i); // store the answers in an array(ans) 32 | } 33 | 34 | return ans; 35 | } 36 | -------------------------------------------------------------------------------- /4_prims.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define I INT_MAX 3 | #define V 8 4 | using namespace std; 5 | 6 | void prime_mst(int cost[][V], int n) 7 | { 8 | int u, v, i, j, k, min = I; 9 | vector near; 10 | for (i = 1; i <= n; i++) 11 | { 12 | for (j = i; j <= n; j++) 13 | { 14 | if (cost[i][j] < min) 15 | { 16 | u = i; 17 | v = j; 18 | } 19 | } 20 | } 21 | 22 | 23 | } 24 | 25 | int main() 26 | { 27 | 28 | int cost[V][V]{ 29 | {I, I, I, I, I, I, I, I}, 30 | {I, I, 25, I, I, I, 5, I}, 31 | {I, 25, I, 12, I, I, I, 10}, 32 | {I, I, 12, I, 8, I, I, I}, 33 | {I, I, I, 8, I, 16, I, 14}, 34 | {I, I, I, I, 16, I, 20, 18}, 35 | {I, 5, I, I, I, 20, I, I}, 36 | {I, I, 10, I, 14, 18, I, I}, 37 | }; 38 | 39 | int n = sizeof(cost[0]) / sizeof(cost[0][0]) - 1; 40 | 41 | prime_mst(cost, n); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /53. Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | public int maxSubArray(int[] nums) { 2 | int maxsofar=nums[0]; 3 | int sum=0; 4 | for(int i=0;imaxsofar) 7 | { 8 | maxsofar=sum; 9 | } 10 | if(sum<0) 11 | { 12 | sum=0; 13 | } 14 | } 15 | return maxsofar; 16 | } 17 | -------------------------------------------------------------------------------- /62. Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | if(m& a) { 4 | unordered_map mp; 5 | for(auto x: a) mp[x]++; 6 | for(auto x: a) { 7 | if(mp[x] == 0) continue; 8 | int freq = mp[x], count = 0, currElement = x; 9 | while(mp.count(currElement) && mp[currElement] >= freq) { 10 | freq = max( freq, mp[currElement]); 11 | mp[currElement]--; 12 | currElement++; 13 | count++; 14 | } 15 | if(count < 3) return 0; 16 | } 17 | return 1; 18 | } 19 | }; -------------------------------------------------------------------------------- /66_Plus_One.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/plus-one/ 2 | 3 | class Solution { 4 | public: 5 | vector plusOne(vector& digits) { 6 | int end{}; 7 | end = digits.size()-1; 8 | int carry_back{1}; 9 | for(int i{end}; i>=0; --i){ 10 | digits.at(i) += carry_back; 11 | carry_back = 0; 12 | if(digits.at(i) == 10){ 13 | digits.at(i) = 0; 14 | carry_back = 1; 15 | } 16 | } 17 | if(carry_back == 1){ 18 | digits.insert(digits.begin(),1); 19 | } 20 | return digits; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /674. Longest Continuous Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLengthOfLCIS(vector& nums) { 4 | int prev=INT_MIN, cnt=0, ans=0; 5 | for(auto x: nums) { 6 | if(x > prev) { 7 | cnt++; 8 | ans = max(ans, cnt); 9 | prev=x; 10 | } 11 | else { 12 | cnt=1; 13 | ans=max(ans, cnt); 14 | prev=x; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /692. Top K Frequent Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& words, int k) { 4 | unordered_map freq; 5 | for(auto w : words){ 6 | freq[w]++; 7 | } 8 | 9 | auto comp = [&](const pair& a, const pair& b) { 10 | return a.second > b.second || (a.second == b.second && a.first < b.first); 11 | }; 12 | typedef priority_queue< pair, vector>, decltype(comp) > my_priority_queue_t; 13 | my_priority_queue_t pq(comp); 14 | 15 | for(auto w : freq ){ 16 | pq.emplace(w.first, w.second); 17 | if(pq.size()>k) pq.pop(); 18 | } 19 | 20 | vector output; 21 | while(!pq.empty()){ 22 | output.insert(output.begin(), pq.top().first); 23 | pq.pop(); 24 | } 25 | return output; 26 | 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /69_Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/ 2 | 3 | class Solution { 4 | public: 5 | int mySqrt(int x) { 6 | return sqrt(x); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /704_Binary_Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int search(vector &nums, int target) 11 | { 12 | int low = 0; // Least element 13 | int high = nums.size() - 1; // Highest element 14 | 15 | // Loop while low and high intersect 16 | while (low <= high) 17 | { 18 | int mid = low + (high - low) / 2; 19 | // Mid value to check target is left side of mid or right side of mid 20 | 21 | if (nums[mid] < target) 22 | { 23 | // If target > nums[mid] value 24 | // ==> target is on right side so we should search in the range (mid+1 to high) so change low to mid + 1; 25 | low = mid + 1; 26 | } 27 | else if (nums[mid] > target) 28 | { 29 | // If target < nums[mid] value 30 | // ==> target is on left side so we should search in the range (low to mid-1) so change high to mid - 1; 31 | high = mid - 1; 32 | } 33 | else 34 | { 35 | // Found the target !!! 36 | return mid; 37 | } 38 | } 39 | // Target is not present in array 40 | return -1; 41 | } 42 | }; -------------------------------------------------------------------------------- /713_Subarray_Product_Less_Than_K.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-product-less-than-k/ 2 | 3 | class Solution { 4 | public: 5 | int numSubarrayProductLessThanK(vector& nums, int k) { 6 | if(k <= 1){ 7 | return 0; 8 | } 9 | int left{0},right{0},product{1},ans{0}; 10 | while(right= k){ 13 | product /= nums.at(left); 14 | left++; 15 | } 16 | ans += (right-left+1); 17 | right++; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /72._Edit_Distance.java: -------------------------------------------------------------------------------- 1 | // Problem Link 2 | // https://leetcode.com/problems/edit-distance/ 3 | 4 | 5 | public class Solution { 6 | int[][] dp; 7 | 8 | public int minDistance(String word1, String word2) { 9 | dp = new int[word1.length()][word2.length()]; 10 | 11 | return minDistanceHelper(word1, word2, 0, 0); 12 | } 13 | 14 | private int minDistanceHelper(String word1, String word2, int index1, int index2) { 15 | if (index1 == word1.length()) return word2.length() - index2; 16 | if (index2 == word2.length()) return word1.length() - index1; 17 | 18 | if (dp[index1][index2] > 0) return dp[index1][index2]; 19 | 20 | int result; 21 | if (word1.charAt(index1) == word2.charAt(index2)) { 22 | result = minDistanceHelper(word1, word2, index1+1, index2+1); 23 | } else { 24 | // replace char 25 | result = 1 + minDistanceHelper(word1, word2, index1+1, index2+1); 26 | 27 | // delete char from word1 28 | result = Math.min(result, 1 + minDistanceHelper(word1, word2, index1+1, index2)); 29 | 30 | // delete char from word2 31 | result = Math.min(result, 1 + minDistanceHelper(word1, word2, index1, index2+1)); 32 | } 33 | 34 | dp[index1][index2] = result; 35 | return result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /74. Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | for (int r=0; r>& board) { 10 | string expected="123450"; 11 | string cur=""; 12 | vector> swaps={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}}; 13 | int z; 14 | 15 | for(int i=0;i<2;i++) 16 | for(int j=0;j<3;j++){ 17 | cur+=board[i][j]+'0'; 18 | if(board[i][j]==0) 19 | z=(i*3)+j; 20 | } 21 | 22 | queue> q; 23 | unordered_map visited; 24 | visited[cur]=true; 25 | q.push({cur,z}); 26 | int level=0; 27 | 28 | while(!q.empty()) 29 | { 30 | int n=q.size(); 31 | for(int i=0;i>& grid) { 4 | 5 | int n=grid.size(),ans=0; 6 | priority_queue,vector>,greater>> q; 7 | unordered_map visited; 8 | vector d={1,0,-1,0,1}; 9 | 10 | q.push({grid[0][0],0,0}); 11 | visited[0]=true; 12 | 13 | while(!q.empty()) 14 | { 15 | auto p=q.top(); 16 | q.pop(); 17 | // ans=max(ans,p[0]); 18 | for(int i=0;i<4;i++) 19 | { 20 | int X=p[1]+d[i]; 21 | int Y=p[2]+d[i+1]; 22 | if(X>=0&&Y>=0&&X& words) { 4 | vector A = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 5 | unordered_set st; 6 | for(auto x : words) { 7 | string str = ""; 8 | for(auto ch : x) str += A[ch - 'a']; 9 | st.insert(str); 10 | } 11 | return st.size(); 12 | } 13 | }; -------------------------------------------------------------------------------- /869.Reordered_Power_of_2.cpp: -------------------------------------------------------------------------------- 1 | // Solution to : Reordered Power Of 2 2 | // https://leetcode.com/problems/reordered-power-of-2/ 3 | 4 | // This Solution has very minimal runtime 5 | 6 | class Solution { 7 | public: 8 | bool reorderedPowerOf2(int n) { 9 | string s = to_string(n); 10 | sort(s.begin(),s.end()); 11 | 12 | vector power; 13 | for(int i=0;i<=30;i++){ 14 | int p = pow(2,i); 15 | power.push_back(to_string(p)); 16 | } 17 | 18 | for(int i=0;i<=30;i++){ 19 | sort(power[i].begin(),power[i].end()); 20 | } 21 | 22 | for(int i=0;i<=30;i++){ 23 | if(power[i] == s ) return true; 24 | } 25 | return false; 26 | } 27 | }; -------------------------------------------------------------------------------- /871. Minimum Number of Refueling Stops.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minRefuelStops(int target, int startFuel, vector>& stations) { 4 | int i=0, ans=0; 5 | priority_queue pq; 6 | while(startFuel < target) { 7 | while(i < stations.size() && stations[i][0] <= startFuel) { 8 | pq.push(stations[i][1]); 9 | i++; 10 | } 11 | if(pq.size()==0) return -1; 12 | startFuel += pq.top(); pq.pop(); 13 | ans++; 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /88-Merge-Sorted-Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | nums1.resize(m); 5 | for(int i =0;i& a, int m, vector& b, int n) { 4 | int ind = m + n - 1, i = m - 1, j = n - 1; 5 | while(i >= 0 && j >= 0) { 6 | if(a[i] >= b[j]) a[ind--] = a[i--]; 7 | else a[ind--] = b[j--]; 8 | } 9 | while(i >= 0) a[ind--] = a[i--]; 10 | while(j >= 0) a[ind--] = b[j--]; 11 | } 12 | }; -------------------------------------------------------------------------------- /887.Super_Egg_Drop.java: -------------------------------------------------------------------------------- 1 | // Problem Link 2 | // https://leetcode.com/problems/super-egg-drop/ 3 | 4 | class Solution { 5 | Integer dp[][]=new Integer[101][10001]; 6 | //Declared wrapper class because no need to initialise values, will be null defaultly 7 | 8 | public int superEggDrop(int K, int N) { 9 | 10 | if(K==1)//when there is only one egg 11 | return N; 12 | 13 | if(N==0 || N==1)//when no. of floors are 0 or 1 14 | return N; 15 | 16 | if(dp[K][N]!=null)//checking if it is filled 17 | return dp[K][N]; 18 | 19 | int i,l=1,h=N; 20 | int ans=Integer.MAX_VALUE; 21 | 22 | while(l<=h) 23 | { 24 | int mid=(l+h)/2; 25 | 26 | int down_temp=superEggDrop(K-1,mid-1);//If egg breaks go down 27 | 28 | int up_temp=superEggDrop(K,N-mid);//if egg doesn't break go up 29 | 30 | int temp=1+Math.max(down_temp,up_temp); 31 | //adding one because we have used 1 attempt and max of up and down because 32 | //we need worst case attempts from both 33 | 34 | if(down_temp movesToStamp(string stamp, string target) { 4 | vector res; 5 | int n = stamp.size(), total = 0; 6 | while (true) { 7 | bool isStamped = false; 8 | for (int size = n; size > 0; --size) { 9 | for (int i = 0; i <= n - size; ++i) { 10 | string t = string(i, '*') + stamp.substr(i, size) + string(n - size - i, '*'); 11 | auto pos = target.find(t); 12 | while (pos != string::npos) { 13 | res.push_back(pos); 14 | isStamped = true; 15 | total += size; 16 | fill(begin(target) + pos, begin(target) + pos + n, '*'); 17 | pos = target.find(t); 18 | } 19 | } 20 | } 21 | if (!isStamped) break; 22 | } 23 | reverse(res.begin(), res.end()); 24 | return total == target.size() ? res : vector(); 25 | } 26 | }; -------------------------------------------------------------------------------- /98. Validate Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool valid(TreeNode* root,long long Left,long long Right){ 4 | if(root==NULL){ 5 | return true; 6 | } 7 | if(root->val<=Left || root->val>=Right){ 8 | return false; 9 | } 10 | return valid(root->left,Left,root->val) && valid(root->right,root->val,Right); 11 | 12 | 13 | 14 | } 15 | bool isValidBST(TreeNode* root) { 16 | if(root->left==NULL && root->right==NULL){ 17 | return true; 18 | } 19 | return valid(root,-3147483648,3147483647); 20 | 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /99. Recover Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> v; 4 | void ans(TreeNode* root){ 5 | if(root==NULL){ 6 | return; 7 | } 8 | ans(root->left); 9 | v.push_back({root->val,root}); 10 | ans(root->right); 11 | 12 | } 13 | void recoverTree(TreeNode* root) { 14 | ans(root); 15 | vector b; 16 | for(int i=0;ival; 32 | change1->val=change2->val; 33 | change2->val=a; 34 | return ; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /994. Rotting Oranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool ispos(int a,int b,int m,int n,vector>& grid){ 4 | if(a<0||a>=m||b<0||b>=n){ 5 | return false; 6 | } 7 | if(grid[a][b]==1){ 8 | return true; 9 | } 10 | return false; 11 | } 12 | int orangesRotting(vector>& grid) { 13 | queue> q; 14 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | char c = 'A'; 6 | cout << "The ASCII value of " << c << " is " << int(c); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /ActivitySelection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | struct Activitiy 5 | { 6 | int start, end; 7 | }; 8 | bool comp(Activitiy act1, Activitiy act2) 9 | { 10 | return (act1.end < act2.end); 11 | } 12 | void maxActivity(Activitiy act[], int n) 13 | { 14 | sort(act, act + n, comp); // sort activities using compare function 15 | 16 | cout << "Selected Activities are: " << endl; 17 | int i = 0; // first activity as 0 is selected 18 | cout << "Activity: " << i << " , Start: " << act[i].start << " End: " << act[i].end << endl; 19 | for (int j = 1; j < n; j++) 20 | { // for all other activities 21 | if (act[j].start >= act[i].end) 22 | { // when start time is >= endtime, print the activity 23 | cout << "Activity: " << j << " , Start: " << act[j].start << " End: " << act[j].end << endl; 24 | i = j; 25 | } 26 | } 27 | } 28 | int main() 29 | { 30 | Activitiy actArr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}}; 31 | int n = 6; 32 | maxActivity(actArr, n); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Add two nos.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/add-two-numbers/ 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* addTwoNumbers(ListNode* l1, ListNode* l2) { 16 | ListNode *p=l1; 17 | ListNode *q=l2; 18 | ListNode *newna=new ListNode(); 19 | ListNode *temp=newna; 20 | int c=0; 21 | while(l1!=NULL||l2!=NULL||c!=0){ 22 | int sum=0,dig=0; 23 | if(l1!=NULL){ 24 | sum+=l1->val; 25 | l1=l1->next;} 26 | 27 | if(l2!=NULL){ 28 | sum+=l2->val; 29 | l2=l2->next; 30 | } 31 | if(c!=0) sum+=c; 32 | c=sum/10; 33 | dig=sum%10; 34 | ListNode *newn=new ListNode(dig); 35 | temp->next=newn; 36 | temp=temp->next; 37 | 38 | 39 | } 40 | // if(l1!=NULL){ 41 | // p=l1; 42 | 43 | // } 44 | // if(l2!=NULL){ 45 | // if(c!=0){ 46 | // l2->val=l2->val+1; 47 | 48 | // } 49 | // temp->next=l2; 50 | // } 51 | return newna->next; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Armstrong number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int num, originalNum, remainder, result = 0; 8 | 9 | cout << "Enter a three-digit integer: "; 10 | 11 | cin >> num; 12 | 13 | originalNum = num; 14 | 15 | while (originalNum != 0) { 16 | 17 | 18 | 19 | remainder = originalNum % 10; 20 | 21 | 22 | 23 | result += remainder * remainder * remainder; 24 | 25 | 26 | 27 | 28 | 29 | originalNum /= 10; 30 | 31 | } 32 | 33 | if (result == num) 34 | 35 | cout << num << " is an Armstrong number."; 36 | 37 | else 38 | 39 | cout << num << " is not an Armstrong number."; 40 | 41 | return 0; 42 | 43 | } -------------------------------------------------------------------------------- /BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bfs(vector> &graph, int source, vector &vis) 5 | { 6 | queue q; 7 | q.push(source); 8 | vis[source] = true; 9 | while (!q.empty()) 10 | { 11 | int curr = q.front(); 12 | q.pop(); 13 | cout << curr << " "; 14 | for (int neigh : graph[curr]) 15 | if (!vis[neigh]) 16 | { 17 | q.push(neigh); 18 | vis[neigh] = true; 19 | } 20 | } 21 | } 22 | 23 | int main() 24 | { 25 | int n, e; 26 | cout << "Enter the Number of Nodes : " << endl; 27 | cin >> n; 28 | cout << "Enter the number of Edges : " << endl; 29 | cin >> e; 30 | vector> graph(n); 31 | vector vis(n, false); 32 | for (int i = 0; i < e; i++) 33 | { 34 | int u, v; 35 | cin >> u >> v; 36 | graph[u].push_back(v); 37 | graph[v].push_back(u); 38 | } 39 | for (int i = 0; i < n; i++) 40 | { 41 | if (!vis[i]) 42 | bfs(graph, i, vis); 43 | } 44 | return 0; 45 | } -------------------------------------------------------------------------------- /BFS_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Graph 4 | { 5 | int V; 6 | vector> adj; 7 | public: 8 | Graph(int V); 9 | void addEdge(int v, int w); 10 | void BFS(int s); 11 | }; 12 | 13 | Graph::Graph(int V) 14 | { 15 | this->V = V; 16 | adj.resize(V); 17 | } 18 | 19 | void Graph::addEdge(int v, int w) 20 | { 21 | adj[v].push_back(w); 22 | } 23 | 24 | void Graph::BFS(int s) 25 | { 26 | vector visited; 27 | visited.resize(V,false); 28 | list queue; 29 | visited[s] = true; 30 | queue.push_back(s); 31 | 32 | while(!queue.empty()) 33 | { 34 | s = queue.front(); 35 | cout << s << " "; 36 | queue.pop_front(); 37 | for (auto adjecent: adj[s]) 38 | { 39 | if (!visited[adjecent]) 40 | { 41 | visited[adjecent] = true; 42 | queue.push_back(adjecent); 43 | } 44 | } 45 | } 46 | } 47 | int main() 48 | { 49 | Graph g(4); 50 | g.addEdge(0, 1); 51 | g.addEdge(0, 2); 52 | g.addEdge(1, 2); 53 | g.addEdge(2, 0); 54 | g.addEdge(2, 3); 55 | g.addEdge(3, 3); 56 | 57 | cout << "Following is Breadth First Traversal " 58 | << "(starting from vertex 2) \n"; 59 | g.BFS(2); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Balanced Paranthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | unordered_mapsymbol={ {'[',-1},{'(',-2},{'{',-3},{']',1},{')',2},{'}',3}}; 5 | void solve() 6 | { 7 | string s; 8 | cin >> s; 9 | stackst; 10 | for(auto bracket : s) 11 | { 12 | if(symbol[bracket]<0) 13 | { 14 | st.push(bracket); 15 | } 16 | else 17 | { 18 | if(st.empty()) 19 | { 20 | cout << "NO\n"; 21 | return; 22 | } 23 | char top=st.top(); 24 | st.pop(); 25 | if(symbol[top]+symbol[bracket]!=0) 26 | { 27 | cout << "NO\n"; 28 | return; 29 | } 30 | } 31 | } 32 | if(st.empty()) 33 | { 34 | cout << "YES\n"; 35 | return; 36 | } 37 | cout << "NO\n"; 38 | return; 39 | 40 | } 41 | 42 | int main() 43 | { 44 | int t; 45 | cin >> t; 46 | while(t--) 47 | { 48 | solve(); 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 121. Best Time to Buy and Sell Stock 4 | Easy 5 | 6 | 20587 7 | 8 | 660 9 | 10 | Add to List 11 | 12 | Share 13 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 14 | 15 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 16 | 17 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 18 | 19 | 20 | 21 | Example 1: 22 | 23 | Input: prices = [7,1,5,3,6,4] 24 | Output: 5 25 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 26 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 27 | Example 2: 28 | 29 | Input: prices = [7,6,4,3,1] 30 | Output: 0 31 | Explanation: In this case, no transactions are done and the max profit = 0. 32 | 33 | 34 | Constraints: 35 | 36 | 1 <= prices.length <= 105 37 | 0 <= prices[i] <= 104 38 | 39 | 40 | */ 41 | 42 | 43 | class Solution { 44 | public: 45 | int maxProfit(vector& prices) { 46 | int ans = 0; 47 | int n = prices.size(); 48 | int mini = prices[0]; 49 | for(int i = 1 ;i= 3000000 OR population >= 25000000; 8 | -------------------------------------------------------------------------------- /Binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int bin_search(int arr[],int n, int s){ 4 | int mid=n/2; 5 | int temp[mid]; 6 | if (arr[mid]==s){ 7 | cout<<"Element found at position "<>n; 18 | int arr[n]; 19 | for(int i=0; i>arr[i]; 21 | } 22 | cin>>s; 23 | bin_search(arr,n,s); 24 | } 25 | -------------------------------------------------------------------------------- /Bubble Sorting an Array using pointers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void main(){ 3 | int *a,i,j,t,n; 4 | printf("Size of Array : "); 5 | scanf("%d",&n); 6 | printf("Give Array Elements: "); 7 | for(i=0;i *(a+j)){ 13 | t = *(a+i);*(a+i) = *(a+j); 14 | *(a+j) = t; 15 | } 16 | } 17 | } 18 | printf("Sorted array is: "); 19 | for(i=0;i 2 | using namespace std; 3 | 4 | // A function to implement bubble sort 5 | void bubbleSort(int arr[], int n) 6 | { 7 | int i, j; 8 | for (i = 0; i < n - 1; i++) 9 | 10 | // Last i elements are already 11 | // in place 12 | for (j = 0; j < n - i - 1; j++) 13 | if (arr[j] > arr[j + 1]) 14 | swap(arr[j], arr[j + 1]); 15 | /* 16 | //can also be done using a temporary varibale 17 | 18 | temp = arr[j]; 19 | arr[j] = arr[j+1]; 20 | arr[j+1] = temp 21 | */ 22 | } 23 | 24 | // Function to print an array 25 | void printArray(int arr[], int size) 26 | { 27 | int i; 28 | for (i = 0; i < size; i++) 29 | cout << arr[i] << " "; 30 | cout << endl; 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | int arr[] = { 5, 1, 4, 2, 8}; 37 | int N = sizeof(arr) / sizeof(arr[0]); 38 | bubbleSort(arr, N); 39 | cout << "Sorted array: \n"; 40 | printArray(arr, N); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Calculator application: -------------------------------------------------------------------------------- 1 | #include 2 | void main() 3 | { char ch; 4 | float p,q; 5 | 6 | printf("enter the type of operation you want to perform="); 7 | scanf("%c",&ch); 8 | printf(" enter the two numbers "); 9 | scanf("%f %f",&p,&q); 10 | 11 | if(ch=='+') 12 | { 13 | printf("p +q=%f",p+q); 14 | } 15 | else if(ch=='-') 16 | { 17 | printf("p -q=%f",p-q); 18 | } 19 | else if(ch=='*') 20 | { 21 | printf("p*q=%f",p*q); 22 | } 23 | else if(ch=='/') 24 | { 25 | printf(" p/q=%f",p/q); 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Calculator.py: -------------------------------------------------------------------------------- 1 | 2 | a=int(input("Enter First Number:")) 3 | b=int(input("Enter Second Number:")) 4 | c=input("Enter The sign:") 5 | if c=='*': 6 | print("Multiplication:",a*b) 7 | if c=='+': 8 | print("Addition:",a+b) 9 | if c=='-': 10 | print("Substraction:",a-b) 11 | if c=='/': 12 | print("Division:",a/b) 13 | if c=='%': 14 | print("Moduls:",a%b) 15 | if c=='**': 16 | print("Power:",a**b) 17 | if c=='//': 18 | print("Floor Division:",a//b) 19 | -------------------------------------------------------------------------------- /ClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | int arr[46]; // array for 1 <= n <= 45 5 | arr[1] = 1; // only one way 6 | arr[2] = 2; // two ways 1->1 or directly 2 7 | 8 | 9 | // from n = 3 ==> calculate from last two steps 10 | for(int i = 3; i <= n; i++){ 11 | arr[i] = arr[i-1]+arr[i-2]; 12 | } 13 | return arr[n]; 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Coin_Change_2_DP.cpp: -------------------------------------------------------------------------------- 1 | //problem-statement 2 | //You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 3 | //Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 4 | //You may assume that you have an infinite number of each kind of coin. 5 | #include 6 | 7 | using namespace std; 8 | 9 | long countWaysToMakeChange(vector& arr, int n, int T){ 10 | 11 | vector> dp(n,vector(T+1,0)); 12 | 13 | 14 | //Initializing base condition 15 | for(int i=0;i<=T;i++){ 16 | if(i%arr[0]==0) 17 | dp[0][i]=1; 18 | // Else condition is automatically fulfilled, 19 | // as dp array is initialized to zero 20 | } 21 | 22 | for(int ind=1; ind arr ={1,2,3}; 40 | int target=4; 41 | 42 | int n =arr.size(); 43 | 44 | cout<<"The total number of ways is " <> combinationSum2(vector& candidates, int target) { 4 | vector> ans; 5 | vector sum; 6 | sort(candidates.begin(),candidates.end()); 7 | combination(candidates, target, sum, 0, ans); 8 | return ans; 9 | } 10 | 11 | void combination(vector & nums, int target, vector &sum, int idx, vector>& ans) 12 | { 13 | if(target==0) 14 | { 15 | return ans.push_back(sum); 16 | } 17 | 18 | if(target<0) 19 | { 20 | return; 21 | } 22 | 23 | for(int i=idx;iidx && nums[i]==nums[i-1]) 26 | continue; 27 | 28 | sum.push_back(nums[i]); 29 | combination(nums,target-nums[i],sum,i+1,ans); 30 | sum.pop_back(); 31 | } 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Concatenation_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getConcatenation(vector& nums) { 4 | vector ans = nums; 5 | 6 | for(int i=0; i& height) { 10 | int water = 0; 11 | int i = 0, j = height.size() - 1; 12 | while (i < j) { 13 | int h = min(height[i], height[j]); 14 | water = max(water, (j - i) * h); 15 | while (height[i] <= h && i < j) i++; 16 | while (height[j] <= h && i < j) j--; 17 | } 18 | return water; 19 | } 20 | -------------------------------------------------------------------------------- /Count_Number_Of_Texts.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countTexts(string s) { 4 | int n = s.size(); 5 | int mod = 1e9 + 7; 6 | vector dp(n + 1); 7 | dp[0] = 1; 8 | for (int i = 0; i < n; i++) 9 | { 10 | dp[i + 1] = dp[i]; 11 | if (i > 0 and s[i] == s[i - 1]) 12 | { 13 | dp[i + 1] = (dp[i + 1] + dp[i - 1]) % mod; 14 | if (i > 1 and s[i] == s[i - 2]) 15 | { 16 | dp[i + 1] = (dp[i + 1] + dp[i - 2]) % mod; 17 | if (i > 2 and s[i] == s[i - 3] and (s[i] == '7' or s[i] == '9')) 18 | dp[i + 1] = (dp[i + 1] + dp[i - 3]) % mod; 19 | } 20 | } 21 | } 22 | return dp[n]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Counting Bits 4 | 5 | 6 | Share 7 | Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 8 | 9 | */ 10 | 11 | vector countBits(int n) { 12 | vector answer; 13 | for(int i = 0; i <=n; i++){ 14 | int m = __builtin_popcount(i); 15 | answer.push_back(m); 16 | } 17 | return answer; 18 | } 19 | -------------------------------------------------------------------------------- /CourseSchedular.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findOrder(int V, vector>& a) { 4 | 5 | 6 | 7 | vectoradj[V+1]; 8 | for(int i=0;iindegree(V,0); 16 | 17 | for(int i=0;iq; 27 | for(int i=0;iv; 36 | while(!q.empty()){ 37 | 38 | 39 | 40 | 41 | int x=q.front(); 42 | v.push_back(x); 43 | q.pop(); 44 | 45 | for(auto it : adj[x]){ 46 | 47 | indegree[it]--; 48 | if(indegree[it]==0)q.push(it); 49 | } 50 | 51 | 52 | } 53 | if(v.size()!=V){ 54 | 55 | return {}; 56 | } 57 | return v; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Create Grading Students problem.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | def gradingStudents(grades): 10 | 11 | for i in range(0,len(grades)): 12 | 13 | if grades[i] < 38: #grade is less than 38 , no rounding occurs as the result will still be a failing grade 14 | continue 15 | else: 16 | temp = grades[i] 17 | te = temp % 5 #If the difference between grade and the next multiple of 5 is less than 3 , round up to the next multiple of 5 18 | if te == 3: 19 | temp = temp + 2 20 | grades[i] = temp 21 | elif te == 4: 22 | temp = temp + 1 23 | grades[i] = temp 24 | else: 25 | continue 26 | return grades 27 | 28 | 29 | 30 | if __name__ == '__main__': 31 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 32 | 33 | grades_count = int(input().strip()) 34 | 35 | grades = [] 36 | 37 | for _ in range(grades_count): 38 | grades_item = int(input().strip()) 39 | grades.append(grades_item) 40 | 41 | result = gradingStudents(grades) 42 | 43 | fptr.write('\n'.join(map(str, result))) 44 | fptr.write('\n') 45 | 46 | fptr.close() -------------------------------------------------------------------------------- /DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void dfs(vector> &graph, int source, vector &vis) 5 | { 6 | cout << source << " "; 7 | vis[source] = true; 8 | for (int neigh : graph[source]) 9 | if (!vis[neigh]) 10 | dfs(graph, neigh, vis); 11 | } 12 | 13 | int main() 14 | { 15 | int n, e; 16 | cin >> n >> e; 17 | vector> graph(n); 18 | vector vis(n, false); 19 | for (int i = 0; i < e; i++) 20 | { 21 | int u, v; 22 | cin >> u >> v; 23 | graph[u].push_back(v); 24 | graph[v].push_back(u); 25 | } 26 | for (int i = 0; i < n; i++) 27 | { 28 | if (!vis[i]) 29 | dfs(graph, i, vis); 30 | } 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Delete Node in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void deleteNode(ListNode* node) { 4 | ListNode* temp = node -> next; 5 | node -> val = temp -> val; 6 | node -> next = temp -> next; 7 | delete temp; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Disjisktra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void dijisktra(vector>> &adj, int source) 5 | { 6 | int n = adj.size(); 7 | vector vis(n, false); 8 | vector dis(n, INT_MAX); 9 | set> st; 10 | 11 | st.insert({0, source}); 12 | dis[source] = 0; 13 | 14 | while (st.size() > 0) 15 | { 16 | auto node = *st.begin(); 17 | int v = node.second; 18 | int v_dis = node.first; 19 | st.erase(st.begin()); 20 | if (vis[v]) 21 | continue; 22 | vis[v] = true; 23 | for (auto neigh : adj[v]) 24 | { 25 | int neigh_v = neigh.first; 26 | int neigh_wt = neigh.second; 27 | if (dis[v] + neigh_wt < dis[neigh_v]) 28 | { 29 | dis[neigh_v] = dis[v] + neigh_wt; 30 | st.insert({dis[neigh_v], neigh_v}); 31 | } 32 | } 33 | } 34 | for (int i = 0; i < n; i++) 35 | cout << "distance from " << source << " to " << i << " is : - > " << dis[i] << endl; 36 | } 37 | int main() 38 | { 39 | int n, m; 40 | cout << "Enter Number of Nodes" << endl; 41 | cin >> n; 42 | cout << "Enter number of edges" << endl; 43 | cin >> m; 44 | vector>> adj(n); 45 | for (int i = 0; i < m; i++) 46 | { 47 | int u, v, w; 48 | cin >> u >> v >> w; 49 | adj[u].push_back({v, w}); 50 | } 51 | int source; 52 | cin >> source; 53 | dijisktra(adj, source); 54 | return 0; 55 | } 56 | // 0 1 4 0 7 8 1 2 8 1 7 1 2 3 7 2 8 2 2 5 4 3 4 9 3 5 1 4 5 1 5 6 2 6 7 1 6 8 6 7 8 7 -------------------------------------------------------------------------------- /Distance of nearest cell having 1: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #define N 3 4 | #define M 4 5 | using namespace std; 6 | 7 | void printDistance(int mat[N][M]) 8 | { 9 | int ans[N][M]; 10 | 11 | for (int i = 0; i < N; i++) 12 | for (int j = 0; j < M; j++) 13 | ans[i][j] = INT_MAX; 14 | 15 | for (int i = 0; i < N; i++) 16 | for (int j = 0; j < M; j++) { 17 | // Traversing the whole matrix 18 | // to find the minimum distance. 19 | for (int k = 0; k < N; k++) 20 | for (int l = 0; l < M; l++) { 21 | // If cell contain 1, check 22 | // for minimum distance. 23 | if (mat[k][l] == 1) 24 | ans[i][j] 25 | = min(ans[i][j], 26 | abs(i - k) + abs(j - l)); 27 | } 28 | } 29 | 30 | for (int i = 0; i < N; i++) { 31 | for (int j = 0; j < M; j++) 32 | cout << ans[i][j] << " "; 33 | 34 | cout << endl; 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | int mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; 41 | 42 | // Function call 43 | printDistance(mat); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /EditDistance.cpp: -------------------------------------------------------------------------------- 1 | /*Name -:Jai Sinha 2 | Date-:03-10-2022 */ 3 | 4 | //Question 5 | //to convert one string to another by deleting,updating,replacing the characters of the first string in minimum moves 6 | 7 | 8 | #include 9 | using namespace std; 10 | int editDistance(string str1, string str2) 11 | { 12 | //doing space optimization 13 | int n=str1.length(); 14 | int m=str2.length(); 15 | vector pre(m+1,0); //creating a pre vector 16 | for(int i=0;i<=m;i++) 17 | pre[i]=i; //initializing the pre vector by i 18 | for(int i=1;i<=n;i++) 19 | { 20 | vector temp(m+1,0); //making a temperorary vector 21 | temp[0]=i; 22 | for(int j=1;j<=m;j++) 23 | { 24 | if(str1[i-1]==str2[j-1]) //if the previous elements are equal 25 | temp[j]= pre[j-1]; store the value 26 | else 27 | temp[j]=1+min(pre[j],min(temp[j-1],pre[j-1])); //else store the minimum of the elements 28 | } 29 | pre=temp; //now==>previous vector becomes temp vector 30 | } 31 | return pre[m]; 32 | } 33 | //main function 34 | int main() 35 | { 36 | string s; 37 | cin>>s; 38 | string s2; 39 | cin>>s2; 40 | return editDistance(s,s2); //calling function 41 | } 42 | -------------------------------------------------------------------------------- /FCFS.java: -------------------------------------------------------------------------------- 1 | import java.text.ParseException; 2 | class FCFS{ 3 | static void findWaitingTime(int processes[], int n, 4 | int bt[], int wt[]) { 5 | wt[0] = 0; 6 | for (int i = 1; i < n; i++) { 7 | wt[i] = bt[i - 1] + wt[i - 1]; 8 | } 9 | } 10 | 11 | static void findTurnAroundTime(int processes[], int n, 12 | int bt[], int wt[], int tat[]) { 13 | for (int i = 0; i < n; i++) { 14 | tat[i] = bt[i] + wt[i]; 15 | } 16 | } 17 | 18 | static void findavgTime(int processes[], int n, int bt[]) { 19 | int wt[] = new int[n], tat[] = new int[n]; 20 | int total_wt = 0, total_tat = 0; 21 | findWaitingTime(processes, n, bt, wt); 22 | findTurnAroundTime(processes, n, bt, wt, tat); 23 | System.out.printf("Processes Burst time Waiting" 24 | +" time Turn around time\n"); 25 | for (int i = 0; i < n; i++) { 26 | total_wt = total_wt + wt[i]; 27 | total_tat = total_tat + tat[i]; 28 | System.out.printf(" %d ", (i + 1)); 29 | System.out.printf(" %d ", bt[i]); 30 | System.out.printf(" %d", wt[i]); 31 | System.out.printf(" %d\n", tat[i]); 32 | } 33 | float s = (float)total_wt /(float) n; 34 | int t = total_tat / n; 35 | System.out.printf("Average waiting time = %f", s); 36 | System.out.printf("\n"); 37 | System.out.printf("Average turn around time = %d ", t); 38 | } 39 | public static void main(String[] args) throws ParseException { 40 | int processes[] = {1, 2, 3}; 41 | int n = processes.length; 42 | int burst_time[] = {9, 10, 6}; 43 | 44 | findavgTime(processes, n, burst_time); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Factorial: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int fact(int); 4 | int main() 5 | { 6 | int ans, n; 7 | printf("enter n:"); 8 | scanf("%d",&n); 9 | ans = fact(n); 10 | printf("Factorial of %d is %d", n,ans); 11 | return 0; 12 | } 13 | int fact(int n) 14 | { 15 | for(int i=0; i<=n; i++) 16 | { 17 | if(n==0 || n==1) 18 | { 19 | return 1; 20 | } 21 | else if(n>1) 22 | { 23 | return(fact(n-1)*n); 24 | } 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Fibonacci Series without recursion: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { int t1=0,t2=1,t3,term,n; 4 | printf("Enter the no of term = "); 5 | scanf("%d",&n); 6 | printf("%d\t%d\t",t1,t2); 7 | for(term=3;term<=n;term++) 8 | { 9 | t3=t1+t2; 10 | printf("%d\t",t3); 11 | t1=t2; 12 | t2=t3; 13 | 14 | } 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /FindCustomerReferee.sql: -------------------------------------------------------------------------------- 1 | # MySQL query for problem of Finding Customer Referee 2 | 3 | # Problem link : https://leetcode.com/problems/find-customer-referee/ 4 | 5 | SELECT name 6 | From Customer 7 | WHERE id NOT IN (SELECT id 8 | WHERE referee_id = 2); 9 | 10 | 11 | -------------------------------------------------------------------------------- /Find_whether_an_array_is_a_subset_of_another_array.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | bool isSubset(int arr1[], int arr2[], int m, int n) 4 | { 5 | int i = 0; 6 | int j = 0; 7 | for (i = 0; i < n; i++) { 8 | for (j = 0; j < m; j++) { 9 | if (arr2[i] == arr1[j]) 10 | break; 11 | } 12 | if (j == m) 13 | return 0; 14 | } 15 | return 1; 16 | } 17 | int main() 18 | { 19 | int arr1[] = { 11, 1, 13, 21, 3, 7 }; 20 | int arr2[] = { 11, 3, 7, 1 }; 21 | 22 | int m = sizeof(arr1) / sizeof(arr1[0]); 23 | int n = sizeof(arr2) / sizeof(arr2[0]); 24 | 25 | if (isSubset(arr1, arr2, m, n)) 26 | printf("arr2[] is subset of arr1[] "); 27 | else 28 | printf("arr2[] is not a subset of arr1[]"); 29 | 30 | getchar(); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /First_Non_Repeating_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int firstNonRepeating(int arr[], int n) 5 | { 6 | 7 | unordered_map mp; 8 | for (int i = 0; i < n; i++) 9 | mp[arr[i]]++; 10 | 11 | 12 | for (int i = 0; i < n; i++) 13 | if (mp[arr[i]] == 1) 14 | return arr[i]; 15 | return -1; 16 | } 17 | 18 | 19 | int main() 20 | { 21 | int arr[] = { 9, 4, 9, 6, 7, 4 }; 22 | int n = sizeof(arr) / sizeof(arr[0]); 23 | cout << firstNonRepeating(arr, n); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Flower Planting With No Adjacent.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bool apply(vector>& adj, vector& colors, int u, int n, int par) { 3 | for (int c = 1; c <= 4; c++) { 4 | if (c != par) { 5 | colors[u] = c; 6 | bool safe = true; 7 | for (int v : adj[u]) { 8 | if (colors[v] == c) { 9 | safe = false; 10 | break; 11 | } 12 | if (colors[v] == -1 && !apply(adj, colors, v, n, c)) { 13 | safe = false; 14 | break; 15 | } 16 | } 17 | if (safe) 18 | break; 19 | colors[u] = -1; 20 | } 21 | } 22 | return colors[u] != -1; 23 | } 24 | 25 | public: 26 | vector gardenNoAdj(int N, vector>& paths) { 27 | vector> adj(N); 28 | for (auto e : paths) { 29 | adj[e[0]-1].push_back(e[1]-1); 30 | adj[e[1]-1].push_back(e[0]-1); 31 | } 32 | 33 | vector colors(N, -1); 34 | for (int i = 0; i < N; i++) { 35 | if (colors[i] == -1) 36 | apply(adj, colors, i, N, -1); 37 | } 38 | return colors; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Fractional Knapsack: -------------------------------------------------------------------------------- 1 | /* 2 | struct Item{ 3 | int value; 4 | int weight; 5 | }; 6 | */ 7 | 8 | bool comp(Item a,Item b){ 9 | double r1=(double)a.value/(double)a.weight; 10 | double r2=(double)b.value/(double)b.weight; 11 | return r1>r2; 12 | } 13 | 14 | class Solution 15 | { 16 | public: 17 | //Function to get the maximum total value in the knapsack. 18 | double fractionalKnapsack(int W, Item arr[], int n) 19 | { 20 | // Your code here 21 | sort(arr,arr+n,comp); 22 | int currWeight=0; 23 | double finalValue=0.0; 24 | for(int i=0;i 4 | using namespace std; 5 | 6 | // Recursive function to return gcd of a and b in single line 7 | 8 | int gcd(int a, int b) 9 | { 10 | 11 | return b == 0 ? a : gcd(b, a % b); 12 | } 13 | 14 | 15 | // Driver program to test above function 16 | 17 | int main() 18 | { 19 | 20 | int a , b ; 21 | cin>>a>>b; 22 | 23 | cout<<"GCD of "< 17 | using namespace std; 18 | 19 | int main() { 20 | int n,m; 21 | cin>>n>>m; 22 | int arr1[n]; 23 | int arr2[m]; 24 | for(int i=0;i>arr1[i]; 26 | for(int i=0;i>arr2[i]; 28 | unordered_set s; 29 | for (int i = 0; i < m; i++) 30 | s.insert(arr2[i]); 31 | for (int i = 0; i < n; i++) 32 | if (s.find(arr1[i]) == s.end()) 33 | cout << arr1[i] << " "; 34 | // Agr element set me nahi hota hai to set ka end point return krdeta hai 35 | // Aur agr element hota hai to wo s.end ke equal nahi hoga wo us element ka pointer dedega 36 | // s.find(element) returns an iterator pointing to the element, if the iterator reaches s.end() 37 | // that means if it reaches the end of set s, which actually means that the element is not in the set 38 | // and we had reached the end searching the whole set, then cout<& citations) { 4 | const auto n = citations.size(); 5 | vector count(n + 1, 0); 6 | for (const auto& x : citations) { 7 | // Put all x >= n in the same bucket. 8 | if (x >= n) { 9 | ++count[n]; 10 | } else { 11 | ++count[x]; 12 | } 13 | } 14 | 15 | int h = 0; 16 | for (int i = n; i >= 0; --i) { 17 | h += count[i]; 18 | if (h >= i) { 19 | return i; 20 | } 21 | } 22 | return h; 23 | } 24 | }; 25 | 26 | 27 | // Time complexity: O(n) 28 | // Space complexity: O(n) 29 | -------------------------------------------------------------------------------- /Height_Of_A_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node { 5 | public: 6 | int data; 7 | node* left; 8 | node* right; 9 | }; 10 | 11 | int maxHeight(node* node) 12 | { 13 | if (node == NULL) 14 | return 0; 15 | else 16 | { 17 | int lHeight = mmaxHeight(node->left); 18 | int rHeight = maxHeight(node->right); 19 | 20 | return max(lHeight+1,rHeight+1); 21 | 22 | } 23 | } 24 | 25 | 26 | node* newNode(int data) 27 | { 28 | node* Node = new node(); 29 | Node->data = data; 30 | Node->left = NULL; 31 | Node->right = NULL; 32 | 33 | return (Node); 34 | } 35 | 36 | // Driver code 37 | int main() 38 | { 39 | node* root = newNode(1); 40 | root->left = newNode(2); 41 | root->right = newNode(3); 42 | root->left->left = newNode(4); 43 | root->left->right = newNode(5); 44 | 45 | cout<<"Height of tree is "< 1: 40 | (key1, c1) = nodes[-1] 41 | (key2, c2) = nodes[-2] 42 | nodes = nodes[:-2] 43 | node = NodeTree(key1, key2) 44 | nodes.append((node, c1 + c2)) 45 | 46 | nodes = sorted(nodes, key=lambda x: x[1], reverse=True) 47 | 48 | huffmanCode = huffman_code_tree(nodes[0][0]) 49 | 50 | print(' Char | Huffman code ') 51 | print('----------------------') 52 | for (char, frequency) in freq: 53 | print(' %-4r |%12s' % (char, huffmanCode[char])) 54 | -------------------------------------------------------------------------------- /IntegerToRoman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, num: int) -> str: 3 | valueSymbols = [(1000, 'M'), (900, 'CM'), 4 | (500, 'D'), (400, 'CD'), 5 | (100, 'C'), (90, 'XC'), 6 | (50, 'L'), (40, 'XL'), 7 | (10, 'X'), (9, 'IX'), 8 | (5, 'V'), (4, 'IV'), 9 | (1, 'I')] 10 | ans = [] 11 | 12 | for value, symbol in valueSymbols: 13 | if num == 0: 14 | break 15 | count, num = divmod(num, value) 16 | ans.append(symbol * count) 17 | 18 | return ''.join(ans) 19 | 20 | -------------------------------------------------------------------------------- /Integet to Roman: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string intToRoman(int num) { 4 | int numm[]={1000,900,500,400,100,90,50,40,10,9,5,4,1}; 5 | string ans[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 6 | string s; 7 | for(int i=0;i<13;i++) 8 | { 9 | while(num>=numm[i]) 10 | { 11 | s=s+ans[i]; 12 | num=num-numm[i]; 13 | } 14 | } 15 | return s; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | //Problem Link:- https://leetcode.com/problems/jewels-and-stones/ 2 | 3 | //Problem Solution in Java: 4 | 5 | class Solution { 6 | public int numJewelsInStones(String jewels, String stones) { 7 | int count=0; 8 | for(int i=0;i kidsWithCandies(int[] candies, int extraCandies) { 8 | ArrayList list = new ArrayList(); 9 | int max = Integer.MIN_VALUE; 10 | for(int i=0;i= max){ 18 | list.add(true); 19 | }else{ 20 | list.add(false); 21 | } 22 | } 23 | 24 | return list; 25 | } 26 | } -------------------------------------------------------------------------------- /KthSymbol.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/k-th-symbol-in-grammar/ 2 | class Solution { 3 | public int kthGrammar(int n, int k) { 4 | if(n==1 || k==1){ 5 | return 0; 6 | } 7 | if(k%2==0){ 8 | return 1 - kthGrammar(n-1, (k+1)/2); 9 | }else{ 10 | return kthGrammar(n-1, (k+1)/2); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Length_of_Longest_Substring_without_any_Repeating_Character.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Main { 3 | static int solve(String str) { 4 | 5 | if(str.length()==0) 6 | return 0; 7 | int maxans = Integer.MIN_VALUE; 8 | for (int i = 0; i < str.length(); i++) // outer loop for traversing the string 9 | { 10 | Set < Character > se = new HashSet < > (); 11 | for (int j = i; j < str.length(); j++) // nested loop for getting different 12 | string starting with str[i] 13 | { 14 | if (se.contains(str.charAt(j))) // if element if found so mark it as ans 15 | and break from the loop 16 | { 17 | maxans = Math.max(maxans, j - i); 18 | break; 19 | } 20 | se.add(str.charAt(j)); 21 | } 22 | } 23 | return maxans; 24 | } 25 | 26 | public static void main(String args[]) { 27 | String str = "takeUforward"; 28 | System.out.println("The length of the longest substring without repeating 29 | characters is " + solve(str)); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Linked-List-Cycle-Detection.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasCycle(ListNode *head) { 4 | ListNode *fast = head; 5 | ListNode *slow = head; 6 | 7 | while(fast!=NULL && fast->next!=NULL){ 8 | slow = slow->next; 9 | fast = fast->next->next; 10 | if(fast==slow){ 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | }; -------------------------------------------------------------------------------- /Longest Increasing Subsequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int solve(vector& nums) 4 | { 5 | int n=nums.size(); 6 | vector> dp(nums.size()+1,vector (nums.size()+1,0)); 7 | for(int curr=n-1;curr>=-0;curr--) 8 | { 9 | for(int prev=curr-1;prev>=-1;prev--) 10 | { 11 | int include=0; 12 | if(prev==-1 || nums[prev]& nums) { 23 | 24 | return solve(nums); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Longest Valid Parenthesis: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestValidParentheses(string s) { 4 | int n = s.length(), longest = 0; 5 | stack st; 6 | for (int i = 0; i < n; i++) { 7 | if (s[i] == '(') st.push(i); 8 | else { 9 | if (!st.empty()) { 10 | if (s[st.top()] == '(') st.pop(); 11 | else st.push(i); 12 | } 13 | else st.push(i); 14 | } 15 | } 16 | if (st.empty()) longest = n; 17 | else { 18 | int a = n, b = 0; 19 | while (!st.empty()) { 20 | b = st.top(); st.pop(); 21 | longest = max(longest, a-b-1); 22 | a = b; 23 | } 24 | longest = max(longest, a); 25 | } 26 | return longest; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Longest_Common_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int solve(string& s, string& t, int i, int j, vector>& dp){ 4 | if(i==s.size()) return 0; 5 | if(j==t.size()) return 0; 6 | if(dp[i][j]!=-1) return dp[i][j]; 7 | int ans=0; 8 | if(s[i]==t[j]) ans=1+solve(s,t,i+1,j+1,dp); 9 | else ans=max(solve(s,t,i+1,j,dp), solve(s,t,i,j+1,dp)); 10 | dp[i][j]=ans; 11 | return dp[i][j]; 12 | } 13 | int longestCommonSubsequence(string text1, string text2) { 14 | int n=text1.size(), m=text2.size(); 15 | vector> dp(n, vector(m, -1)); 16 | int ans=solve(text1,text2,0,0,dp); 17 | return ans; 18 | } 19 | int main(){ 20 | string s,t; 21 | cin>>s>>t; 22 | int ans=longestCommonSubsequence(s,t); 23 | cout< 2 | using namespace std; 3 | 4 | int lps(string& s1, string& s2, int n1, int n2) 5 | { 6 | if (n1 == 0 || n2 == 0) { 7 | return 0; 8 | } 9 | if (dp[n1][n2] != -1) { 10 | return dp[n1][n2]; 11 | } 12 | if (s1[n1 - 1] == s2[n2 - 1]) { 13 | return dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1); 14 | } 15 | else { 16 | return dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2),lps(s1, s2, n1, n2 - 1)); 17 | } 18 | } 19 | 20 | 21 | int main() 22 | { 23 | string seq = "CARORCAR"; 24 | int n = seq.size(); 25 | int dp[n][n]; 26 | memset(dp, -1, sizeof(dp)); 27 | string s2 = seq; 28 | reverse(s2.begin(), s2.end()); 29 | cout<<"The length of the LPS is "< 3 | using namespace std; 4 | 5 | int findCandidate(int a[], int size) 6 | { 7 | int maj_index = 0, count = 1; 8 | for (int i = 1; i < size; i++) { 9 | if (a[maj_index] == a[i]) 10 | count++; 11 | else 12 | count--; 13 | if (count == 0) { 14 | maj_index = i; 15 | count = 1; 16 | } 17 | } 18 | return a[maj_index]; 19 | } 20 | 21 | /* Function to check if the candidate 22 | occurs more than n/2 times */ 23 | bool isMajority(int a[], int size, int cand) 24 | { 25 | int count = 0; 26 | for (int i = 0; i < size; i++) 27 | 28 | if (a[i] == cand) 29 | count++; 30 | 31 | if (count > size / 2) 32 | return 1; 33 | 34 | else 35 | return 0; 36 | } 37 | 38 | void printMajority(int a[], int size) 39 | { 40 | int cand = findCandidate(a, size); 41 | 42 | if (isMajority(a, size, cand)) 43 | cout << " " << cand << " "; 44 | 45 | else 46 | cout << "No Majority Element"; 47 | } 48 | 49 | int main() 50 | { 51 | int a[] = { 1, 3, 3, 1, 2 }; 52 | int size = (sizeof(a)) / sizeof(a[0]); 53 | 54 | printMajority(a, size); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Make A and B equal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | typedef long long int ll; 5 | 6 | int main() { 7 | // your code goes here 8 | ll p; 9 | cin>>p; 10 | while(p--){ 11 | ll m,a=0,b=0; 12 | cin>>m; 13 | vector x(m,0),y(m,0); 14 | for(ll i=0;i>x[i]; 15 | for(ll i=0;i>y[i]; 17 | a+=(x[i]-y[i]); 18 | b= b+abs(x[i]-y[i]); 19 | } 20 | 21 | if(a!=0)cout<<-1<>& grid) { 4 | int ans = 0; 5 | n = grid.size(), m = grid[0].size(); 6 | for (int i = 0; i < n; i++) 7 | for (int j = 0; j < m; j++) 8 | if (grid[i][j]) ans = max(ans, trav(i, j, grid)); 9 | return ans; 10 | } 11 | private: 12 | int n, m; 13 | int trav(int i, int j, vector>& grid) { 14 | if (i < 0 || j < 0 || i >= n || j >= m || !grid[i][j]) return 0; 15 | grid[i][j] = 0; 16 | return 1 + trav(i-1, j, grid) + trav(i, j-1, grid) + trav(i+1, j, grid) + trav(i, j+1, grid); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Merge Intervals: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& interval) { 4 | vector> res; 5 | if(interval.size()==0) 6 | { 7 | return res; 8 | } 9 | int n=interval.size(); 10 | sort(interval.begin(),interval.end()); 11 | res.push_back(interval[0]); 12 | int j=0; 13 | for(int i=1;i=interval[i][0]) 16 | { 17 | res[j][1]=max(res[j][1],interval[i][1]); 18 | } 19 | else 20 | { 21 | j++; 22 | res.push_back(interval[i]); 23 | } 24 | } 25 | return res; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /MergeArray.java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | public class MergeArrayExample2 3 | { 4 | public static void main(String[] args) 5 | { 6 | int firstArray[] = { 11,22,33,44,55,98,76,54,60}; 7 | int secondArray[] = {66,77,88,99,22,67,21,90,80,70}; 8 | int source_arr[], sourcePos, dest_arr[], destPos, len; 9 | source_arr = firstArray; 10 | dest_arr = secondArray; 11 | sourcePos = 2; 12 | destPos = 4; 13 | len = 3; 14 | // Print elements of source 15 | System.out.print("source_array : "); 16 | for (int i = 0; i < firstArray.length; i++) 17 | System.out.print(firstArray[i] + " "); 18 | System.out.println(""); 19 | System.out.println("sourcePos : " + sourcePos); 20 | // Print elements of destination 21 | System.out.print("dest_array : "); 22 | for (int i = 0; i < secondArray.length; i++) 23 | System.out.print(secondArray[i] + " "); 24 | System.out.println(""); 25 | System.out.println("destPos : " + destPos); 26 | System.out.println("len : " + len); 27 | //invoking arraycopy() method 28 | System.arraycopy(source_arr, sourcePos, dest_arr,destPos, len); 29 | // Print elements of destination after 30 | System.out.print("Resultant array : "); 31 | for (int i = 0; i < secondArray.length; i++) 32 | System.out.print(secondArray[i] + " "); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Minimize_XOR.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimizeXor(int num2, int num1) { 4 | int g = __builtin_popcount(num1); 5 | int ans = num2; 6 | map a; 7 | for (int i = 0; i <= 30; i++) 8 | if ((num2 >> i) & 1) 9 | a[i] = 1; 10 | if (g <= a.size()){ 11 | g = a.size() - g; 12 | for (auto &e : a){ 13 | if (!g) 14 | break; 15 | --g; 16 | ans -= (1 << e.first); 17 | } 18 | return ans; 19 | } 20 | g -= a.size(); 21 | for (int i = 0; g > 0 and i <= 30; i++){ 22 | if (!a[i]){ 23 | --g; 24 | ans += (1 << i); 25 | } 26 | } 27 | return ans; 28 | } 29 | /* 30 | Solution to Miniminze XOR (https://leetcode.com/contest/weekly-contest-313/problems/minimize-xor/) 31 | */ 32 | -------------------------------------------------------------------------------- /Missingnumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findMissingNo (int arr[], int len){ 5 | int temp; 6 | temp = ((len+1)*(len+2))/2; 7 | for (int i = 0; i>n; 15 | int arr[n-1]; 16 | for(int i=0; i>arr[i]; 18 | } 19 | int missingNo = findMissingNo(arr,5); 20 | cout<<"Missing Number is: "<= 0 && A[i] >= A[i + 1]) 7 | i--; // Find 1st id i that breaks descending order 8 | if (i >= 0) { // If not entirely descending 9 | int j = A.length - 1; // Start from the end 10 | while (A[j] <= A[i]) 11 | j--; // Find rightmost first larger id j 12 | swap(A, i, j); // Switch i and j 13 | } 14 | reverse(A, i + 1, A.length - 1); // Reverse the descending sequence 15 | } 16 | 17 | public void swap(int[] A, int i, int j) { 18 | int tmp = A[i]; 19 | A[i] = A[j]; 20 | A[j] = tmp; 21 | } 22 | 23 | public void reverse(int[] A, int i, int j) { 24 | while (i < j) 25 | swap(A, i++, j--); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Number of Islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | int ans=0; 5 | for(int i=0;i>& grid,int i, int j){ 16 | if(i<0||j<0||i==grid.size()||j==grid[0].size()||grid[i][j]=='0') 17 | return; 18 | grid[i][j]='0'; 19 | help(grid,i+1,j); 20 | help(grid,i,j+1); 21 | help(grid,i-1,j); 22 | help(grid,i,j-1); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /PartitionProblem.cpp: -------------------------------------------------------------------------------- 1 | // A recursive C++ program for partition problem 2 | #include 3 | using namespace std; 4 | 5 | // A utility function that returns true if there is 6 | // a subset of arr[] with sum equal to given sum 7 | bool isSubsetSum(int arr[], int n, int sum) 8 | { 9 | // Base Cases 10 | if (sum == 0) 11 | return true; 12 | if (n == 0 && sum != 0) 13 | return false; 14 | 15 | // If last element is greater than sum, then 16 | // ignore it 17 | if (arr[n - 1] > sum) 18 | return isSubsetSum(arr, n - 1, sum); 19 | 20 | /* else, check if sum can be obtained by any of 21 | the following 22 | (a) including the last element 23 | (b) excluding the last element 24 | */ 25 | return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); 26 | } 27 | 28 | // Returns true if arr[] can be partitioned in two 29 | // subsets of equal sum, otherwise false 30 | bool findPartiion(int arr[], int n) 31 | { 32 | // Calculate sum of the elements in array 33 | int sum = 0; 34 | for (int i = 0; i < n; i++) 35 | sum += arr[i]; 36 | 37 | // If sum is odd, there cannot be two subsets 38 | // with equal sum 39 | if (sum % 2 != 0) 40 | return false; 41 | 42 | // Find if there is subset with sum equal to 43 | // half of total sum 44 | return isSubsetSum(arr, n, sum / 2); 45 | } 46 | int main() 47 | { 48 | int arr[] = {3, 1, 5, 9, 12}; 49 | int n = sizeof(arr) / sizeof(arr[0]); 50 | 51 | // Function call 52 | if (findPartiion(arr, n) == true) 53 | cout << "Can be divided into two subsets " 54 | "of equal sum"; 55 | else 56 | cout << "Can not be divided into two subsets" 57 | " of equal sum"; 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Pascal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const int N=42; 4 | int main() 5 | { 6 | int t; 7 | cin>>t; 8 | 9 | long long int a[N][N]; 10 | a[0][0] = 1; 11 | 12 | for(int i = 1 ; i < N; i++) 13 | { 14 | a[i][0] = 1; 15 | a[i][i] = 1; 16 | 17 | for(int j=1; j>n; 27 | 28 | for(int i=0; i 11 | using namespace std; 12 | void solve(int i, string s, string &f) { 13 | if (i == s.length()) { 14 | cout << f << " "; 15 | return; 16 | } 17 | //picking 18 | f = f + s[i]; 19 | solve(i + 1, s, f); 20 | //poping out while backtracking 21 | f.pop_back(); 22 | solve(i + 1, s, f); 23 | } 24 | int main() { 25 | string s = "abc"; 26 | string f = ""; 27 | cout<<"All possible subsequences are: "< rearrangeArray(vector& nums) { 4 | int x= nums.size(); 5 | vector a(x); 6 | int i=0,j=1; 7 | for(int k=0;k0){ 9 | a[i]=nums[k]; 10 | i+=2; 11 | } 12 | else{ 13 | a[j]=nums[k]; 14 | j+=2; 15 | } 16 | } 17 | return a; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Rectangle.cpp: -------------------------------------------------------------------------------- 1 | /*Divide the stick in 4 parts codeforces "Pasha and Stick" problem. 2 | Note 3 | There is only one way to divide the stick in the first sample {1, 1, 2, 2}. 4 | 5 | Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work. 6 | 7 | 8 | 9 | 10 | EXAMPLE:- 11 | INPUT 1: 12 | 6 13 | 14 | OUTPUT 1: 15 | 1 //divide like(1, 1, 2, 2) 16 | 17 | INPUT 2: 18 | 20 19 | 20 | OUTPUT: 21 | 4 //divide like {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7}, {4, 4, 6, 6} 22 | 23 | 24 | stick = l+l+b+b 25 | stick = 2(l+b) 26 | stick/2 = l+b 27 | 28 | */ 29 | 30 | 31 | 32 | //SOLUTION 1: 33 | #include 34 | using namespace std; 35 | 36 | int main() 37 | { 38 | long int n; 39 | cin>>n; 40 | 41 | if(n%2==1) // here by default is 1. Not needed to write ==1 42 | { 43 | cout<<0; 44 | } 45 | n=n/2; 46 | 47 | if(n%2==1) // here by default is 1. Not needed to write ==1 48 | { 49 | cout< 67 | 68 | int main(){ 69 | int i, n, p, k; 70 | long t; 71 | 72 | scanf("%ld", &t); 73 | if(t%2 !=0){ 74 | printf("0\n"); 75 | } 76 | else{ 77 | if(t%4==0){ 78 | printf("%ld\n", (t/4)-1); 79 | } 80 | else printf("%ld\n", t/4); 81 | } 82 | 83 | return 0; 84 | } 85 | */ 86 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteDuplicates(ListNode* head) { 4 | 5 | if(head==NULL || head->next==NULL) 6 | return head; 7 | 8 | ListNode* tmp = head; 9 | ListNode* curr = head->next; 10 | 11 | while(curr!=NULL) { 12 | 13 | if(tmp->val == curr->val) { 14 | 15 | curr=curr->next; 16 | } 17 | 18 | else { 19 | tmp->next = curr; 20 | tmp = curr; 21 | curr = tmp->next; 22 | } 23 | } 24 | tmp->next = NULL; 25 | return head; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Remove duplicates for subarray ll.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) extends Exception { 3 | if(nums.length==0){ 4 | return 0; 5 | } 6 | int x=1,index=0; 7 | for(int i=0;i& nums) { 4 | if(nums.size() == 0) return 0; 5 | int left = 0; 6 | for(int right =1; right< nums.size(); right++){ 7 | if(nums[left] != nums[right]) 8 | left++; 9 | nums[left] = nums[right]; 10 | } 11 | return left+1; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverseList(ListNode* head) { 4 | ListNode* current = head; 5 | ListNode *prev = NULL, *next = NULL; 6 | 7 | while (current != NULL) { 8 | next = current->next; 9 | current->next = prev; 10 | prev = current; 11 | current = next; 12 | } 13 | head = prev; 14 | return head; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /RichestCustomerWealth.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximumWealth(int[][] accounts) { 3 | int m = accounts.length; 4 | int n = accounts[0].length; 5 | int arr[] = new int[m]; 6 | int sum = 0; 7 | for(int i = 0 ; i < m ; i++) { 8 | for(int j = 0 ; j < n ; j++) { 9 | sum+=accounts[i][j]; 10 | } 11 | arr[i] = sum; 12 | sum=0; 13 | } 14 | int max = arr[0]; 15 | for(int i = 0 ; i < m ; i++) { 16 | if(arr[i]>max) { 17 | max = arr[i]; 18 | } 19 | } 20 | return max; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /RodCutting.cpp: -------------------------------------------------------------------------------- 1 | // A recursive solution for Rod cutting problem 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // A utility function to get the maximum of two integers 8 | int max(int a, int b) { return (a > b) ? a : b; } 9 | 10 | /* Returns the best obtainable price for a rod of length n 11 | and price[] as prices of different pieces */ 12 | int cutRod(int price[], int index, int n) 13 | { 14 | // base case 15 | if (index == 0) 16 | { 17 | return n * price[0]; 18 | } 19 | // At any index we have 2 options either 20 | // cut the rod of this length or not cut 21 | // it 22 | int notCut = cutRod(price, index - 1, n); 23 | int cut = INT_MIN; 24 | int rod_length = index + 1; 25 | 26 | if (rod_length <= n) 27 | cut = price[index] + cutRod(price, index, n - rod_length); 28 | 29 | return max(notCut, cut); 30 | } 31 | int main() 32 | { 33 | int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; 34 | int size = sizeof(arr) / sizeof(arr[0]); 35 | cout << "Maximum Obtainable Value is " 36 | << cutRod(arr, size - 1, size); 37 | getchar(); 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Rotate image: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | 5 | for(int i=0;i<(matrix.size()/2);i++) 6 | { 7 | for(int j=0;j& nums, int target) { 4 | int start = 0; 5 | int end = nums.size() - 1; 6 | 7 | while(start <=end){ 8 | int mid = start + (end - start)/2; 9 | 10 | if(nums[mid] < target) 11 | start = mid + 1; 12 | else 13 | end = mid - 1; 14 | 15 | } 16 | return start; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Search_2DMatrix_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | 5 | int row = matrix.size(); 6 | int col = matrix[0].size(); 7 | 8 | int rowIndex = 0; 9 | int colIndex = col-1; 10 | 11 | while(rowIndex=0){ 12 | 13 | int element = matrix[rowIndex][colIndex]; 14 | 15 | if(element == target){ 16 | return 1; 17 | } 18 | 19 | if(element < target){ 20 | rowIndex++; 21 | } 22 | else{ 23 | colIndex--; 24 | } 25 | } 26 | return 0; 27 | } 28 | }; -------------------------------------------------------------------------------- /SetMatrixZero.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | int col0 = 1, rows = matrix.length, cols = matrix[0].length; 4 | 5 | for (int i = 0; i < rows; i++) { 6 | if (matrix[i][0] == 0) col0 = 0; 7 | for (int j = 1; j < cols; j++) 8 | if (matrix[i][j] == 0) 9 | matrix[i][0] = matrix[0][j] = 0; 10 | } 11 | 12 | for (int i = rows - 1; i >= 0; i--) { 13 | for (int j = cols - 1; j >= 1; j--) 14 | if (matrix[i][0] == 0 || matrix[0][j] == 0) 15 | matrix[i][j] = 0; 16 | if (col0 == 0) matrix[i][0] = 0; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Smallest Subtree with all the Deepest Nodes: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | // Structure of a Node 6 | struct TreeNode { 7 | 8 | int val; 9 | TreeNode* left; 10 | TreeNode* right; 11 | 12 | TreeNode(int data) 13 | { 14 | this->val = data; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | int find_ht(TreeNode* root) 21 | { 22 | if (!root) 23 | return 0; 24 | 25 | // If current node is a leaf node 26 | if (root->left == NULL 27 | && root->right == NULL) 28 | return 1; 29 | 30 | return max(find_ht(root->left), 31 | find_ht(root->right)) 32 | + 1; 33 | } 34 | 35 | void find_node(TreeNode* root, TreeNode*& req_node) 36 | { 37 | if (!root) 38 | return; 39 | 40 | // Stores height of left subtree 41 | int left_ht = find_ht(root->left); 42 | 43 | // Stores height of right subtree 44 | int right_ht = find_ht(root->right); 45 | 46 | // If height of left subtree exceeds 47 | // that of the right subtree 48 | if (left_ht > right_ht) { 49 | 50 | // Traverse left subtree 51 | find_node(root->left, req_node); 52 | } 53 | 54 | // If height of right subtree exceeds 55 | // that of the left subtree 56 | else if (right_ht > left_ht) { 57 | find_node(root->right, req_node); 58 | } 59 | 60 | // Otherwise 61 | else { 62 | 63 | // Return current node 64 | req_node = root; 65 | return; 66 | } 67 | } 68 | 69 | // Driver Code 70 | int main() 71 | { 72 | struct TreeNode* root 73 | = new TreeNode(1); 74 | root->left = new TreeNode(2); 75 | root->right = new TreeNode(3); 76 | 77 | TreeNode* req_node = NULL; 78 | 79 | find_node(root, req_node); 80 | 81 | cout << req_node->val; 82 | 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /Spiral Matrix II.java: -------------------------------------------------------------------------------- 1 | class Matrix { 2 | public int[][] generateMatrix(int n) { 3 | int[][] result = new int[n][n]; 4 | int cnt = 1; 5 | int dir[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 6 | int d = 0; 7 | int row = 0; 8 | int col = 0; 9 | while (cnt <= n * n) { 10 | result[row][col] = cnt++; 11 | int r = Math.floorMod(row + dir[d][0], n); 12 | int c = Math.floorMod(col + dir[d][1], n); 13 | 14 | // change direction if next cell is non zero 15 | if (result[r][c] != 0) d = (d + 1) % 4; 16 | 17 | row += dir[d][0]; 18 | col += dir[d][1]; 19 | } 20 | return result; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /SquaresOfSortedArray.java: -------------------------------------------------------------------------------- 1 | //Problem Link:- https://leetcode.com/problems/squares-of-a-sorted-array/ 2 | 3 | //Solution Of the Problem: 4 | 5 | class Solution { 6 | public int[] sortedSquares(int[] nums) { 7 | for(int i=0;i=0 && nums[k]>key){ 15 | nums[k+1] = nums[k]; 16 | k=k-1; 17 | } 18 | nums[k+1] = key; 19 | } 20 | return nums; 21 | } 22 | } -------------------------------------------------------------------------------- /Subarray_With_Given_Sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int subArraySum(int arr[], int n, int sum) 5 | { 6 | 7 | int currentSum = arr[0], start = 0, i; 8 | 9 | 10 | for (i = 1; i <= n; i++) { 11 | 12 | while (currentSum > sum && start < i - 1) { 13 | currentSum = currentSum - arr[start]; 14 | start++; 15 | } 16 | 17 | 18 | if (currentSum == sum) { 19 | cout << "Sum found between indexes " << start 20 | << " and " << i - 1; 21 | return 1; 22 | } 23 | 24 | 25 | if (i < n) 26 | currentSum = currentSum + arr[i]; 27 | } 28 | 29 | 30 | cout << "No subarray found"; 31 | return 0; 32 | } 33 | 34 | 35 | int main() 36 | { 37 | int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | int sum = 23; 40 | subArraySum(arr, n, sum); 41 | return 0; 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /Subtract 12 Operation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define int long long 5 | 6 | 7 | int n,a[20000],s; 8 | void solve(){ 9 | cin>> n;s=0; 10 | for(int i=1;i<=n;++i) cin >> a[i]; 11 | for(int i=n;i>1;--i) 12 | if(a[i]>0){ 13 | a[i-1]-=a[i]/2; 14 | a[i]=a[i]%2; 15 | if(a[i]==1&&(a[i-1]%2==1||((i==2)&&a[1]>0))){ 16 | a[i]=-1; 17 | a[i-1]--; 18 | } 19 | } 20 | for(int i=1;i<=n;++i) s+=abs(a[i]); 21 | cout << s << endl; 22 | } 23 | 24 | signed main(){ 25 | int T; 26 | cin >> T; 27 | while(T--) solve(); 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Sudoku python.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValidSudoku(self, board): 3 | """ 4 | :type board: List[List[str]] 5 | :rtype: bool 6 | """ 7 | for i in range(9): 8 | row = {} 9 | column = {} 10 | block = {} 11 | row_cube = 3 * (i//3) 12 | column_cube = 3 * (i%3) 13 | for j in range(9): 14 | if board[i][j]!='.' and board[i][j] in row: 15 | return False 16 | row[board[i][j]] = 1 17 | if board[j][i]!='.' and board[j][i] in column: 18 | return False 19 | column[board[j][i]] = 1 20 | rc= row_cube+j//3 21 | cc = column_cube + j%3 22 | if board[rc][cc] in block and board[rc][cc]!='.': 23 | return False 24 | block[board[rc][cc]]=1 25 | return True 26 | ob1 = Solution() 27 | print(ob1.isValidSudoku([ 28 | ["5","3",".",".","7",".",".",".","."], 29 | ["6",".",".","1","9","5",".",".","."], 30 | [".","9","8",".",".",".",".","6","."], 31 | ["8",".",".",".","6",".",".",".","3"], 32 | ["4",".",".","8",".","3",".",".","1"], 33 | ["7",".",".",".","2",".",".",".","6"], 34 | [".","6",".",".",".",".","2","8","."], 35 | [".",".",".","4","1","9",".",".","5"], 36 | [".",".",".",".","8",".",".","7","9"]])) 37 | -------------------------------------------------------------------------------- /TargetSum.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/target-sum/ 2 | public class TargetSum { 3 | static int count; 4 | public static void main(String[] args) { 5 | int[] nums = {1, 1, 1, 1, 1}; 6 | System.out.println(findTargetSumWays(nums, 3)); 7 | } 8 | public static int findTargetSumWays(int[] nums, int target){ 9 | count = 0; 10 | TargetSum(nums, target, 0, 0); 11 | 12 | return count; 13 | } 14 | public static void TargetSum(int[] nums, int target, int index, int val){ 15 | if(index == nums.length){ 16 | if(target == val){ 17 | count++; 18 | } 19 | return; 20 | } 21 | 22 | TargetSum(nums, target, index+1, val+nums[index]); 23 | TargetSum(nums, target, index+1, val-nums[index]); 24 | } 25 | } -------------------------------------------------------------------------------- /TemperatureConversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | float kelvin; 5 | int celcuis; 6 | int c; 7 | 8 | cout << "Please enter if you want to enter the value of temp in 1(for Kelvin " 9 | "to celsuis) and 2(for celcuis to kelvin)"; 10 | cin >> c; 11 | 12 | switch (c) { 13 | case 1: 14 | cout << "Please Enter The Tempratue in Kelvin : "; 15 | cin >> kelvin; 16 | 17 | cout << "The Tempratue in Celsius is : " << kelvin - 274.15 << 'C' << endl; 18 | cout << "The approx value in int is : " << int(kelvin - 274.15) << 'C'; 19 | break; 20 | 21 | case 2: 22 | cout << "Please Enter The Tempratue in Celsius : "; 23 | cin >> celcuis; 24 | 25 | cout << "The Tempratue in Kelvin is : " << celcuis + 274.15 << 'k' << endl; 26 | cout << "The approx value in Celcuis is : " << int(celcuis + 274.15) << 'k'; 27 | break; 28 | default: 29 | cout << "Please Enter A valid value : "; 30 | break; 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /TrainglePattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * 4 | * * 5 | * * 6 | * * 7 | */ 8 | public class TrianglePattern { 9 | public static void main(String[] args) { 10 | // Write code here 11 | int rows = 5; 12 | for (int i = 1; i <= rows; i++) { 13 | for (int j = rows; j > i; j--) { 14 | System.out.print(" "); 15 | } 16 | System.out.print("*"); 17 | for (int j = 1; j < (i - 1) * 2; j++) { 18 | System.out.print(" "); 19 | } 20 | if (i == 1) { 21 | System.out.print("\n"); 22 | } else { 23 | System.out.print("*" + "\n"); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { // 4 ms, faster than 89.31% 2 | public: 3 | int trap(vector& height) { 4 | int n = height.size(); 5 | vector leftMax(n), rightMax(n); 6 | for (int i = 1; i < n; ++i) 7 | leftMax[i] = max(height[i-1], leftMax[i-1]); 8 | for (int i = n-2; i >= 0; --i) 9 | rightMax[i] = max(height[i+1], rightMax[i+1]); 10 | 11 | int ans = 0; 12 | for (int i = 0; i < n; ++i) { 13 | int waterLevel = min(leftMax[i], rightMax[i]); 14 | if (waterLevel >= height[i]) ans += waterLevel - height[i]; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Trie.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/strang3-r/Leetcode75/c8e5de0ac282d7cc53cc5d9a548f23ef1ae13984/Trie.exe -------------------------------------------------------------------------------- /Trim given Binary Tree for any subtree containing only 0s: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class TreeNode { 6 | 7 | public: 8 | int data; 9 | TreeNode* left; 10 | TreeNode* right; 11 | TreeNode(int val) 12 | { 13 | data = val; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | void inorderPrint(TreeNode* root) 20 | { 21 | if (root == NULL) 22 | return; 23 | inorderPrint(root->left); 24 | cout << root->data << " "; 25 | inorderPrint(root->right); 26 | } 27 | 28 | TreeNode* TrimTree(TreeNode* root) 29 | { 30 | if (!root) 31 | return nullptr; 32 | 33 | root->left = TrimTree(root->left); 34 | root->right = TrimTree(root->right); 35 | 36 | // We only trim if the node's value is 0 37 | // and children are null 38 | if (root->data == 0 && root->left == nullptr 39 | && root->right == nullptr) { 40 | 41 | // We trim the subtree by returning nullptr 42 | return nullptr; 43 | } 44 | 45 | // Otherwise we leave the node the way it is 46 | return root; 47 | } 48 | 49 | // Driver code 50 | int main() 51 | { 52 | /* 53 | 1 54 | / \ 55 | 0 1 56 | / \ / \ 57 | 0 0 0 1 58 | */ 59 | 60 | TreeNode* root = new TreeNode(1); 61 | root->left = new TreeNode(0); 62 | root->right = new TreeNode(1); 63 | root->left->left = new TreeNode(0); 64 | root->left->right = new TreeNode(0); 65 | root->right->left = new TreeNode(0); 66 | root->right->right = new TreeNode(1); 67 | 68 | TreeNode* ReceivedRoot = TrimTree(root); 69 | cout << endl; 70 | inorderPrint(ReceivedRoot); 71 | 72 | } 73 | -------------------------------------------------------------------------------- /Twosums.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | vectorresult; 5 | for(int i =0;i a(n); 5 | int p2=0,p3=0,p5=0; 6 | a[0]=1; 7 | 8 | for(int i=1;i dp(n); 8 | dp[0] = 1; 9 | int x = 0, y = 0, z = 0; 10 | for (int i = 1; i < n; i++) 11 | { 12 | dp[i] = min({2 * dp[x], 3 * dp[y], 5 * dp[z]}); 13 | x += (dp[i] == 2 * dp[x]); 14 | y += (dp[i] == 3 * dp[y]); 15 | z += (dp[i] == 5 * dp[z]); 16 | } 17 | return dp[n - 1]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Ugly_numbers.java: -------------------------------------------------------------------------------- 1 | // Java program to find nth ugly number 2 | class GFG { 3 | 4 | /*This function divides a by greatest 5 | divisible power of b*/ 6 | static int maxDivide(int a, int b) 7 | { 8 | while (a % b == 0) 9 | a = a / b; 10 | return a; 11 | } 12 | 13 | /* Function to check if a number 14 | is ugly or not */ 15 | static int isUgly(int no) 16 | { 17 | no = maxDivide(no, 2); 18 | no = maxDivide(no, 3); 19 | no = maxDivide(no, 5); 20 | 21 | return (no == 1) ? 1 : 0; 22 | } 23 | 24 | /* Function to get the nth ugly 25 | number*/ 26 | static int getNthUglyNo(int n) 27 | { 28 | int i = 1; 29 | 30 | // ugly number count 31 | int count = 1; 32 | 33 | // check for all integers 34 | // until count becomes n 35 | while (n > count) { 36 | i++; 37 | if (isUgly(i) == 1) 38 | count++; 39 | } 40 | return i; 41 | } 42 | 43 | /* Driver Code*/ 44 | public static void main(String args[]) 45 | { 46 | int no = getNthUglyNo(150); 47 | 48 | // Function call 49 | System.out.println("150th ugly " 50 | + "no. is " + no); 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /Unique Paths III.cpp: -------------------------------------------------------------------------------- 1 | #define sz(x) int(x.size()) 2 | vector>grid2; 3 | vector>visited; 4 | int n , m; 5 | int startsi,startsj; 6 | int empty_cnt_l = 0,empty_cnt_g = 0; 7 | bool is_valid(int i , int j) 8 | { 9 | return i >= 0 && i < n && j >=0 && j < m && grid2[i][j] != -1 && (!visited[i][j]); 10 | } 11 | 12 | int rec2(int r ,int c) 13 | { 14 | if(!is_valid(r , c)) 15 | return 0; 16 | 17 | 18 | if(grid2[r][c] == 2) 19 | return empty_cnt_l == empty_cnt_g; 20 | 21 | visited[r][c] = 1; 22 | empty_cnt_l++; 23 | int ans = rec2(r , c + 1) + rec2(r , c - 1) + rec2(r + 1 , c) + rec2(r - 1 ,c); 24 | empty_cnt_l-- ,visited[r][c] = 0; 25 | return ans; 26 | } 27 | class Solution { 28 | public: 29 | int uniquePathsIII(vector>& grid){ 30 | n = sz(grid),m=sz(grid[0]); 31 | empty_cnt_l = 0,empty_cnt_g = 0; 32 | grid2.assign(n,vector(m,0)); 33 | 34 | grid2 = grid; 35 | 36 | visited.assign(n,vector(m,0)); 37 | 38 | grid2=grid; 39 | 40 | for(int i = 0 ; i < n;i++) 41 | { 42 | for(int j = 0 ; j < m ;j++) 43 | { 44 | if(grid[i][j] == 1) 45 | startsi =i,startsj = j; 46 | 47 | else if(grid[i][j] == 0) 48 | empty_cnt_g++; 49 | } 50 | } 51 | empty_cnt_g++; 52 | //cout_2d(grid2); 53 | return rec2(startsi, startsj); 54 | } 55 | }; -------------------------------------------------------------------------------- /Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector my_stack; 3 | public: 4 | bool isValid(string s) { 5 | if (s.size() % 2 != 0) 6 | return false; 7 | if (s.size() == 0) 8 | return true; 9 | for (int i = 0; i < s.size(); i++) 10 | { 11 | my_stack.push_back(s[i]); 12 | if (my_stack[my_stack.size() - 1] == '}') 13 | { 14 | if (my_stack.size() > 1){ 15 | if(my_stack[my_stack.size() - 2] == '{') 16 | { 17 | my_stack.pop_back(); 18 | my_stack.pop_back(); 19 | } 20 | } 21 | } 22 | else if (my_stack[my_stack.size() - 1] == ')') 23 | { 24 | if (my_stack.size() > 1){ 25 | if(my_stack[my_stack.size() - 2] == '(') 26 | { 27 | my_stack.pop_back(); 28 | my_stack.pop_back(); 29 | } 30 | } 31 | } 32 | else if (my_stack[my_stack.size() - 1] == ']') 33 | { 34 | if (my_stack.size() > 1){ 35 | if(my_stack[my_stack.size() - 2] == '[') 36 | { 37 | my_stack.pop_back(); 38 | my_stack.pop_back(); 39 | } 40 | } 41 | } 42 | } 43 | if (!my_stack.empty()) 44 | return false; 45 | return true; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /ValidPair: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/strang3-r/Leetcode75/c8e5de0ac282d7cc53cc5d9a548f23ef1ae13984/ValidPair -------------------------------------------------------------------------------- /Vending Machine: -------------------------------------------------------------------------------- 1 | #include 2 | void main() 3 | { 4 | int a; 5 | printf(" Code \t Products \n 106 - Haldiram Ratmali Sev \n 206 - Haldiram instant bhel \n 306 - Fuse chocolate \n 406 - Mixed Fruit Juice \n 506 - Lassi"); 6 | printf("\n Enter the code = "); 7 | scanf("%d",&a); 8 | 9 | switch(a) 10 | { 11 | case 106: 12 | 13 | printf("\n Haldiram Ratmali Sev"); 14 | 15 | break; 16 | 17 | case 206: 18 | 19 | printf("\n Haldiram instant bhel"); 20 | 21 | break; 22 | case 306: 23 | 24 | printf("\n Fuse chocolate"); 25 | 26 | 27 | break; 28 | case 406: 29 | 30 | printf("\n Mixed Fruit Juice"); 31 | break; 32 | case 506: 33 | 34 | printf("\n Lassi"); 35 | break; 36 | default:printf("\n The coin is lost"); 37 | break; 38 | 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Word Break II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/word-break-ii/description/ 2 | 3 | class Solution: 4 | def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: 5 | 6 | def recur(idx, str_): 7 | if idx >= len(s): 8 | recur.res.append(str_.strip()) 9 | return 10 | 11 | for i in range(idx, len(s)): 12 | if s[idx:i+1] in wordDict: 13 | temp = str_ 14 | str_ += s[idx:i+1] + ' ' 15 | recur(i+1, str_) 16 | str_ = temp 17 | 18 | return 19 | 20 | recur.res = [] 21 | 22 | recur(0, '') 23 | return recur.res -------------------------------------------------------------------------------- /addOneRowtoTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* addOneRow(TreeNode* root, int v, int d) { 4 | if (d == 1) { 5 | TreeNode* newRoot = new TreeNode(v); 6 | newRoot->left = root; 7 | return newRoot; 8 | } 9 | 10 | int depth = 0; 11 | queue q{{root}}; 12 | 13 | while (!q.empty()) { 14 | ++depth; 15 | for (int sz = q.size(); sz > 0; --sz) { 16 | TreeNode* node = q.front(); 17 | q.pop(); 18 | if (node->left) 19 | q.push(node->left); 20 | if (node->right) 21 | q.push(node->right); 22 | if (depth == d - 1) { 23 | TreeNode* cachedLeft = node->left; 24 | TreeNode* cachedRight = node->right; 25 | node->left = new TreeNode(v); 26 | node->right = new TreeNode(v); 27 | node->left->left = cachedLeft; 28 | node->right->right = cachedRight; 29 | } 30 | } 31 | if (depth == d - 1) 32 | break; 33 | } 34 | 35 | return root; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /binarySearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool searchMatrix(vector> &matrix, int target) 5 | { 6 | // nrows---> Number of rows, mcols---> Number of columns 7 | int nrows = matrix.size(); 8 | int mcols = matrix[0].size(); // Because, No. of columns = length of any particular row 9 | 10 | int start = 0; 11 | int end = nrows * mcols - 1; 12 | int mid = (start + end) / 2; // Finding mid index 13 | 14 | while (start <= end) 15 | { 16 | mid = (start + end) / 2; 17 | 18 | int element = matrix[mid / mcols][mid % mcols]; // Finding the element at mid index 19 | 20 | if (element == target) 21 | { 22 | return true; 23 | } 24 | else if (element < target) 25 | { 26 | start = mid + 1; 27 | } 28 | else //(element > target) 29 | { 30 | end = mid - 1; 31 | } 32 | } 33 | return 0; 34 | } 35 | }; -------------------------------------------------------------------------------- /bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int arr[50], tot, i, j, k, elem, index; 6 | cout<<"Enter the Size for Array: "; 7 | cin>>tot; 8 | cout<<"Enter "<>arr[i]; 11 | for(i=1; ij; k--) 22 | arr[k] = arr[k-1]; 23 | break; 24 | } 25 | } 26 | } 27 | else 28 | continue; 29 | arr[index] = elem; 30 | } 31 | cout<<"\nThe New Array (Sorted Array):\n"; 32 | for(i=0; i 5 | using namespace std; 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | int a[n]; 11 | for (int i = 0; i < n; ++i) 12 | cin >> a[i]; 13 | 14 | for (int i = 0; i < n; i++) 15 | { 16 | bool swapped = false; 17 | for (int j = 0; j < n - i - 1; j++) 18 | { 19 | if (a[j + 1] < a[j]) 20 | { 21 | swapped = true; 22 | swap(a[j + 1], a[j]); 23 | } 24 | } 25 | if (!swapped) 26 | { 27 | break; 28 | } 29 | } 30 | for (int i = 0; i < n; i++) 31 | cout << a[i] << " "; 32 | } -------------------------------------------------------------------------------- /calculateDigit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | cin>>t; 8 | 9 | while(t--) 10 | { 11 | 12 | int n; 13 | cin>>n; 14 | 15 | int digit_sum=0; 16 | while(n > 0) 17 | { 18 | int last_digit=n%10; 19 | digit_sum += last_digit; 20 | n=n / 10; 21 | } 22 | /* Use can use also the folowing while loop 23 | while👎 24 | { 25 | digit_sum+=n%10; 26 | n=n/10; 27 | } 28 | 29 | */ 30 | cout<& nums) { 3 | int n = nums.size(); 4 | int dp[n+1]; 5 | dp[0] = 0; 6 | dp[1] = 0; 7 | dp[2] = (nums[0]==nums[1]); 8 | if(n>=3){ 9 | if(nums[0]==nums[1] && nums[1]==nums[2]){ 10 | dp[3] = true; 11 | } 12 | else if(nums[2] == nums[1]+1 && nums[1] == nums[0] + 1){ 13 | dp[3] = true; 14 | }else{ 15 | dp[3] = false; 16 | } 17 | 18 | } 19 | 20 | if(n>=4){ 21 | for(int i = 4;i<=n;i++){ 22 | bool a=false,b=false,c=false; 23 | if(nums[i-1]==nums[i-2]) a = dp[i-2]; 24 | if(nums[i-1]==nums[i-2] && nums[i-2] == nums[i-3]) b = dp[i-3]; 25 | if(nums[i-1]-1==nums[i-2] && nums[i-2]-1 == nums[i-3]) c = dp[i-3]; 26 | 27 | dp[i] = a||b||c; 28 | } 29 | } 30 | return dp[n]; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /check_star_graph.cpp: -------------------------------------------------------------------------------- 1 | // CPP to find whether given graph is star or not 2 | #include 3 | using namespace std; 4 | 5 | // define the size of incidence matrix 6 | #define size 4 7 | 8 | // function to find star graph 9 | bool checkStar(int mat[][size]) 10 | { 11 | // initialize number of vertex 12 | // with deg 1 and n-1 13 | int vertexD1 = 0, vertexDn_1 = 0; 14 | 15 | // check for S1 16 | if (size == 1) 17 | return (mat[0][0] == 0); 18 | 19 | // check for S2 20 | if (size == 2) 21 | return (mat[0][0] == 0 && mat[0][1] == 1 && 22 | mat[1][0] == 1 && mat[1][1] == 0 ); 23 | 24 | // check for Sn (n>2) 25 | for (int i = 0; i < size; i++) 26 | { 27 | int degreeI = 0; 28 | for (int j = 0; j < size; j++) 29 | if (mat[i][j]) 30 | degreeI++; 31 | 32 | if (degreeI == 1) 33 | vertexD1++; 34 | else if (degreeI == size-1) 35 | vertexDn_1++; 36 | } 37 | 38 | return (vertexD1 == (size-1) && 39 | vertexDn_1 == 1); 40 | } 41 | 42 | // driver code 43 | int main() 44 | { 45 | int mat[size][size] = { {0, 1, 1, 1}, 46 | {1, 0, 0, 0}, 47 | {1, 0, 0, 0}, 48 | {1, 0, 0, 0}}; 49 | 50 | checkStar(mat) ? cout << "Star Graph" : 51 | cout << "Not a Star Graph"; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /clone_graph.cpp: -------------------------------------------------------------------------------- 1 | // runtime 22ms 2 | // author -> Sarthak Aggarwal 3 | 4 | class Solution { 5 | public: 6 | Node* cloneGraph(Node* node) { 7 | if (!node) { 8 | return NULL; 9 | } 10 | if (copies.find(node) == copies.end()) { 11 | copies[node] = new Node(node -> val, {}); 12 | for (Node* neighbor : node -> neighbors) { 13 | copies[node] -> neighbors.push_back(cloneGraph(neighbor)); 14 | } 15 | } 16 | return copies[node]; 17 | } 18 | public: 19 | unordered_map copies; 20 | }; -------------------------------------------------------------------------------- /combination sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void findNumbers(vector& ar, int sum, 6 | vector >& res, vector& r, 7 | int i) 8 | { 9 | 10 | if (sum == 0) { 11 | res.push_back(r); 12 | return; 13 | } 14 | 15 | 16 | while (i < ar.size() && sum - ar[i] >= 0) { 17 | 18 | 19 | r.push_back(ar[i]); 20 | 21 | 22 | findNumbers(ar, sum - ar[i], res, r, i); 23 | i++; 24 | 25 | // Remove number from list (backtracking) 26 | r.pop_back(); 27 | } 28 | } 29 | 30 | 31 | vector > combinationSum(vector& ar, 32 | int sum) 33 | { 34 | sort(ar.begin(), ar.end()); 35 | 36 | 37 | ar.erase(unique(ar.begin(), ar.end()), ar.end()); 38 | 39 | vector r; 40 | vector > res; 41 | findNumbers(ar, sum, res, r, 0); 42 | 43 | return res; 44 | } 45 | 46 | int main() 47 | { 48 | vector ar; 49 | ar.push_back(2); 50 | ar.push_back(4); 51 | ar.push_back(6); 52 | ar.push_back(8); 53 | int n = ar.size(); 54 | 55 | int sum = 8; 56 | vector > res = combinationSum(ar, sum); 57 | 58 | 59 | if (res.size() == 0) { 60 | cout << "Empty"; 61 | return 0; 62 | } 63 | 64 | 65 | for (int i = 0; i < res.size(); i++) { 66 | if (res[i].size() > 0) { 67 | cout << " ( "; 68 | for (int j = 0; j < res[i].size(); j++) 69 | cout << res[i][j] << " "; 70 | cout << ")"; 71 | } 72 | } 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /concatenationofConsecutiveBinaryNumbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int concatenatedBinary(int n) { 4 | long ans = 0, mod = 1e9+7; 5 | for (int i = 1; i <= n; ++i) { 6 | int len = 0; 7 | for (int j = i; j; j >>= 1, ++len); 8 | ans = ((ans << len) % mod + i) % mod; 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /count_dispaly.c: -------------------------------------------------------------------------------- 1 | // Count and Sum Linked List 2 | #include 3 | #include 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | } *first = NULL; 9 | void create(int A[], int n) 10 | { 11 | int i; 12 | struct Node *t, *last; 13 | first = (struct Node *)malloc(sizeof(struct Node)); 14 | first->data = A[0]; 15 | first->next = NULL; 16 | last = first; 17 | for (i = 1; i < n; i++) 18 | { 19 | t = (struct Node *)malloc(sizeof(struct Node)); 20 | t->data = A[i]; 21 | t->next = NULL; 22 | last->next = t; 23 | last = t; 24 | } 25 | } 26 | int count(struct Node *p) 27 | { 28 | int l = 0; 29 | while (p) 30 | { 31 | l++; 32 | p = p->next; 33 | } 34 | return l; 35 | } 36 | int Rcount(struct Node *p) 37 | { 38 | if (p != NULL) 39 | return Rcount(p->next) + 1; 40 | else 41 | return 0; 42 | } 43 | int sum(struct Node *p) 44 | { 45 | int s = 0; 46 | while (p != NULL) 47 | { 48 | s += p->data; 49 | p = p->next; 50 | } 51 | return s; 52 | } 53 | int Rsum(struct Node *p) 54 | { 55 | if (p == NULL) 56 | return 0; 57 | else 58 | return Rsum(p->next) + p->data; 59 | } 60 | int main() 61 | { 62 | int A[] = {3, 5, 7, 10, 25, 8, 32, 2}; 63 | create(A, 8); 64 | printf("Count %d\n", count(first)); 65 | printf("Sum %d\n", sum(first)); 66 | return 0; 67 | } -------------------------------------------------------------------------------- /deleteNode.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void deleteNode(ListNode node) { 3 | ListNode nextNode = node.next; 4 | 5 | node.val = nextNode.val; 6 | 7 | node.next = nextNode.next; 8 | nextNode.next = null; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /designCircularQueue.cpp: -------------------------------------------------------------------------------- 1 | struct Node { 2 | public: 3 | int val; 4 | Node* next; 5 | Node(int v, Node* n=nullptr) { 6 | val = v; 7 | next = n; 8 | } 9 | }; 10 | class MyCircularQueue { 11 | public: 12 | MyCircularQueue(int k) { 13 | maxSize = k; 14 | } 15 | bool enQueue(int val) { 16 | if (isFull()) return false; 17 | Node* newNode = new Node(val); 18 | if (isEmpty()) head = newNode, tail = newNode; 19 | else tail->next = newNode, tail = tail->next; 20 | size++; 21 | return true; 22 | } 23 | bool deQueue() { 24 | if (isEmpty()) return false; 25 | head = head->next; 26 | size--; 27 | return true; 28 | } 29 | int Front() { 30 | return isEmpty() ? -1 : head->val; 31 | } 32 | int Rear() { 33 | return isEmpty() ? -1 : tail->val; 34 | } 35 | bool isEmpty() { 36 | return size == 0; 37 | } 38 | bool isFull() { 39 | return size == maxSize; 40 | } 41 | private: 42 | int maxSize, size = 0; 43 | Node *head = new Node(0), *tail = new Node(0); 44 | }; 45 | -------------------------------------------------------------------------------- /diagonal_matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | struct Matrix 3 | { 4 | int A[10]; 5 | int n; 6 | }; 7 | void Set(struct Matrix *m, int i, int j, int x) 8 | { 9 | if (i == j) 10 | m->A[i - 1] = x; 11 | } 12 | int Get(struct Matrix m, int i, int j) 13 | { 14 | if (i == j) 15 | return m.A[i - 1]; 16 | else 17 | return 0; 18 | } 19 | void Display(struct Matrix m) 20 | { 21 | int i, j; 22 | for (i = 0; i < m.n; i++) 23 | { 24 | for (j = 0; j < m.n; j++) 25 | { 26 | if (i == j) 27 | printf("%d ", m.A[i]); 28 | else 29 | printf("0 "); 30 | } 31 | printf("\n"); 32 | } 33 | } 34 | int main() 35 | { 36 | struct Matrix m; 37 | m.n = 4; 38 | 39 | Set(&m, 1, 1, 5); 40 | Set(&m, 2, 2, 8); 41 | Set(&m, 3, 3, 9); 42 | Set(&m, 43 | 4, 4, 12); 44 | printf("%d \n", Get(m, 2, 2)); 45 | Display(m); 46 | return 0; 47 | } -------------------------------------------------------------------------------- /digit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | public: 4 | int singleNumber(vector& nums) { 5 | //approach 1 6 | int xorresult = 0; 7 | for(int i =0;i 2 | void main() 3 | { 4 | int i,j,n,s,a,b,l,p,t,num=0; 5 | printf("enter the odd number of rows:"); 6 | scanf("%d",&n); 7 | if(n%2==0) 8 | { 9 | printf("invalid input"); 10 | } 11 | else 12 | { 13 | a=(n+1)/2; 14 | b=a+1; 15 | for(i=a;i>=1;i--) 16 | { 17 | for(s=(a-i);s>=1;s--) 18 | { 19 | printf(" "); 20 | } 21 | for(j=(2*i-1);j>=1;j--) 22 | { 23 | printf("*"); 24 | } 25 | printf("\n"); 26 | } 27 | for(l=b;l<=n;l++) 28 | { 29 | for(p=(n-l);p>=1;p--) 30 | { 31 | printf(" "); 32 | } 33 | for(t=l;t>=(l-2*num-2);t--) 34 | { 35 | printf("*"); 36 | 37 | } 38 | num++; 39 | printf("\n"); 40 | } 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /duplicates.c++: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | map m; 4 | int main() 5 | { 6 | int n,a,ans=0; 7 | cin>>n; 8 | while(n--) 9 | { 10 | cin>>a; 11 | if(m[a]==0) 12 | { 13 | m[a]++; 14 | ans++; 15 | } 16 | } 17 | cout< 2 | #include 3 | using namespace std; 4 | 5 | void printfloodfill(int[][] maze, int row, int col, string psf, bool visited[][]) 6 | { 7 | //base case 8 | if ((row < 0) || (col < 0) || row >= n || col >= m || maze[row][col] == 1 || visited[row][col] == true) 9 | { 10 | return; 11 | } 12 | if (row == size() && col ==) 13 | { 14 | cout << psf << endl; 15 | return; 16 | } 17 | 18 | visited[row][col] = true; 19 | printfloodfill(maze, row - 1, col, psf + "T", visited); 20 | printfloodfill(maze, row, col - 1, psf + "L", visited); 21 | printfloodfill(maze, row + 1, col, psf + "D", visited); 22 | printfloodfill(maze, row, col + 1, psf + "R", visited); 23 | visited[row][col] = false; 24 | } 25 | 26 | int main() 27 | { 28 | int n, m; 29 | cin >> n >> m; 30 | int arr[n][m]; 31 | vector> arr(n, vector(m)); 32 | 33 | for (int i = 0; i < n; i++) 34 | { 35 | for (int j = 0; j < m; j++) 36 | 37 | { 38 | cin >> arr[i][j]; 39 | } 40 | } 41 | 42 | bool visited[n][m]; 43 | printfloodfill(arr, 0, 0, "", visited); 44 | } 45 | -------------------------------------------------------------------------------- /fourSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class fourSum { 4 | public List> fourSumLC(int[] nums, int target) { 5 | ArrayList> result = new ArrayList>(); 6 | 7 | if (nums == null || nums.length == 0) 8 | return result; 9 | 10 | int l = nums.length; 11 | 12 | Arrays.sort(nums); 13 | 14 | for (int i = 0; i < l; i++) { 15 | 16 | int target_3 = target - nums[i]; 17 | 18 | for (int j = i + 1; j < l; j++) { 19 | 20 | int target_2 = target_3 - nums[j]; 21 | 22 | int front = j + 1; 23 | int back = l - 1; 24 | 25 | while(front < back) { 26 | 27 | int two_sum = nums[front] + nums[back]; 28 | 29 | if (two_sum < target_2) front++; 30 | 31 | else if (two_sum > target_2) back--; 32 | 33 | else { 34 | 35 | List quad = new ArrayList<>(); 36 | quad.add(nums[i]); 37 | quad.add(nums[j]); 38 | quad.add(nums[front]); 39 | quad.add(nums[back]); 40 | result.add(quad); 41 | 42 | while (front < back && nums[front] == quad.get(2)) ++front; 43 | 44 | while (front < back && nums[back] == quad.get(3)) --back; 45 | } 46 | } 47 | while(j + 1 < l && nums[j + 1] == nums[j]) ++j; 48 | } 49 | while (i + 1 < l && nums[i + 1] == nums[i]) ++i; 50 | } 51 | return result; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /frequenciesOfElementsInArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printFrequencies (int arr[], int n) { 5 | int frequency = 1, i = 1; 6 | while (i < n) { 7 | while (i < n && arr[i-1] == arr[i]) { 8 | frequency++; 9 | i++; 10 | } 11 | cout << arr[i-1] <<' ' << frequency << '\n'; 12 | i++; 13 | frequency = 1; 14 | if (n == 1 || arr[n-1] != arr[n-2]) { 15 | cout << arr[n-1] <<' ' << '1' << '\n'; 16 | } 17 | } 18 | } 19 | 20 | int main() { 21 | int n; cin >> n; 22 | int arr[n]; 23 | for (int i = 0; i < n; i++) { 24 | cin >> arr[i]; 25 | } 26 | printFrequencies (arr, n); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /frequencyofcharacters_string.java: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string str = "C++ Programming is awesome"; 7 | char checkCharacter = 'a'; 8 | int count = 0; 9 | 10 | for (int i = 0; i < str.size(); i++) 11 | { 12 | if (str[i] == checkCharacter) 13 | { 14 | ++ count; 15 | } 16 | } 17 | 18 | cout << "Number of " << checkCharacter << " = " << count; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /generate_paranthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | class Solution { 5 | public: 6 | vector generateParenthesis(int n) { 7 | int obc=0; 8 | int cbc=0; 9 | vectorv; 10 | ans(v,n,obc,cbc,""); 11 | return v; 12 | 13 | } 14 | void ans(vector&v,int n,int obc,int cbc,string s){ 15 | 16 | if(obc==n&&(cbc==n)){ 17 | 18 | v.push_back(s); 19 | return ; 20 | } 21 | 22 | if(obccbc){ 26 | 27 | ans(v,n,obc,cbc+1,s+")"); 28 | } 29 | 30 | } 31 | }; -------------------------------------------------------------------------------- /get maze.cpp: -------------------------------------------------------------------------------- 1 | 2 | //use eulers tree to understand 3 | // sc=starting col 4 | // sr=starting row 5 | // dc =destination col 6 | // dr =destination row 7 | // v & h= vertical and horizontal 8 | 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | vector getpath(int sr, int sc, int dr, int dc) 14 | { 15 | if (sr == dr && sc == dc) //base case 16 | { 17 | vector base; 18 | base.push_back(""); 19 | return base; 20 | } 21 | vector ans; 22 | if (sc + 1 <= dc) // condition to not go outside the maze 23 | { 24 | vector hpath = getpath(sr, sc + 1, dr, dc); //moving in horizontsl means rigth side 25 | for (string s : hpath) 26 | { 27 | ans.push_back("h" + s); 28 | } 29 | } 30 | if (sr + 1 <= dr) // condition to not go outside the maze 31 | { 32 | vector vpath = getpath(sr + 1, sc, dr, dc); //moving in vertical direction means downwards 33 | for (string s : vpath) 34 | { 35 | ans.push_back("v" + s); 36 | } 37 | } 38 | return ans; 39 | } 40 | void display(vector &a) //display the output 41 | { 42 | 43 | for (int i = 0; i < a.size(); i++) 44 | { 45 | cout << a[i]; 46 | cout << " "; 47 | } 48 | } 49 | 50 | int main() 51 | { 52 | int n, m; 53 | cin >> n >> m; 54 | vector answer = getpath(0, 0, n - 1, m - 1); 55 | display(answer); 56 | } -------------------------------------------------------------------------------- /gravityflipProblem.cpp: -------------------------------------------------------------------------------- 1 | //codeforces problem 405-A Gravity Flip Solution 2 | #include 3 | using namespace std; 4 | 5 | int main (){ 6 | int n; 7 | cin>>n; 8 | int a[n]; 9 | for (int i=0;i>a[i]; 11 | sort(a,a+n); 12 | for (int i=0;i 2 | #include 3 | #include 4 | int main() 5 | { 6 | int guess,nguess=1,num; 7 | srand(time(0)); 8 | num=rand()%100+1; 9 | do 10 | { 11 | printf("Guess the right number between 1 to 100 : \n"); 12 | scanf("%d",&guess); 13 | if(guess>num) 14 | { 15 | printf("LOWER NUMBER PLEASE : \n"); 16 | } 17 | else if(num>guess) 18 | { 19 | printf("GREATER NUMBER PLEASE : \n"); 20 | } 21 | else 22 | { 23 | printf("*CONGRATULATION !!! YOU GUESS THE RIGHT NUMBER. \n"); 24 | printf("*YOU GUESS THE RIGHT NUMBER IN %d ATTEMPTS \n",nguess); 25 | } 26 | nguess++; 27 | } 28 | while(guess!=num); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /happynumber_taniaban2712.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isHappy(int n) { 4 | int tmp = 0; 5 | set visited; 6 | 7 | while(true){ 8 | tmp = 0; 9 | while(n > 0){ 10 | tmp += pow((n%10), 2); 11 | n/=10; 12 | } 13 | n = tmp; 14 | if(n == 1){ 15 | break; 16 | }else if(visited.find(n)!=visited.end()){ 17 | return false; 18 | } 19 | visited.insert(n); 20 | } 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /increasing_triplet_subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool increasingTriplet(vector& nums) { 10 | int l=nums.size(); 11 | if(l<3) return false; 12 | int min1=INT_MAX,min2=INT_MAX; 13 | 14 | for(int i=0;i 7 | using namespace std; 8 | 9 | int largestSubarraySum(int *arr, int n) 10 | { 11 | int currentSum = 0; 12 | int largestSum = 0; 13 | for (int i = 0; i < n; i++) 14 | { 15 | currentSum += arr[i]; 16 | if (currentSum < 0) // Does not calculates negative as it will only cause reduction in maximum sum 17 | currentSum = 0; // Instead of -ve it adds 0 for it 18 | largestSum = max(largestSum, currentSum); 19 | } 20 | 21 | return largestSum; 22 | } 23 | 24 | int main() 25 | { 26 | system("CLS"); 27 | int arr[] = {-10, 20, -30, 40, 50, 60, -70, 80, -90}; 28 | int n = sizeof(arr) / sizeof(int); 29 | cout << largestSubarraySum(arr, n); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /ladder prob.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ladderLength(string beginWord, string endWord, vector& wordList) { 4 | 5 | unordered_map> mp; 6 | unordered_map bank,visited; 7 | vector mywordList; 8 | 9 | mywordList.push_back(beginWord); 10 | bank[beginWord]=true; 11 | for(auto it:wordList){ 12 | bank[it]=true; 13 | mywordList.push_back(it); 14 | } 15 | 16 | for(int i=0;i q; 30 | q.push(beginWord); 31 | visited[beginWord]=true; 32 | int level=2; 33 | 34 | while(!q.empty()) 35 | { 36 | int n=q.size(); 37 | for(int i=0;i &edges,int si,vector& visit,vector& store){ 7 | if(si == -1)return ; 8 | if(visit[si]){ 9 | int count = -1; 10 | for(int i =0;i& edges) { 34 | 35 | vector visit(edges.size(),0); 36 | 37 | for(int i =0;i store; 41 | getcycle(edges,i,visit,store); 42 | 43 | } 44 | 45 | return maxLength; 46 | 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /longest-increasing-subsequence-ii.cpp: -------------------------------------------------------------------------------- 1 | template 2 | class SegmentTree{ 3 | private: 4 | int n; 5 | vector segtree; 6 | public: 7 | SegmentTree(int n){ 8 | this->n = n; 9 | segtree.resize(4 * n + 1); 10 | } 11 | T op(T x, T y){ 12 | return max(x, y); 13 | } 14 | void updateVal(int x, int l, int r, int idx, T val){ 15 | if (l > idx or r < idx) 16 | return; 17 | if (l == r) 18 | { 19 | segtree[x] = val; 20 | return; 21 | } 22 | int mid = (l + r) / 2LL; 23 | updateVal(2 * x, l, mid, idx, val); 24 | updateVal(2 * x + 1, mid + 1, r, idx, val); 25 | segtree[x] = op(segtree[2 * x], segtree[2 * x + 1]); 26 | } 27 | void update(int idx, T val){ 28 | updateVal(1, 1, n, idx, val); 29 | } 30 | T cal(int x, int l, int r, int L, int R){ 31 | if (L <= l and R >= r) 32 | return segtree[x]; 33 | if (L > r or R < l) 34 | return 0; 35 | int mid = (l + r) / 2LL; 36 | return op(cal(2 * x, l, mid, L, R), cal(2 * x + 1, mid + 1, r, L, R)); 37 | } 38 | T query(int l, int r){ 39 | return l > r ? 0 : cal(1, 1, n, l, r); 40 | } 41 | }; 42 | class Solution { 43 | public: 44 | int lengthOfLIS(vector& nums, int k) { 45 | const int M = 1e5 + 1; 46 | SegmentTree dp(M); 47 | for (auto &e : nums) 48 | { 49 | int x = dp.query(e - k, e - 1) + 1; 50 | int y = dp.query(e, e); 51 | if (y < x) 52 | dp.update(e, x); 53 | } 54 | return dp.query(1, M); 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /longest_substring_without_repeating_characters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // This function returns true if all characters in str[i..j] 5 | // are distinct, otherwise returns false 6 | bool areDistinct(string str, int i, int j) 7 | { 8 | 9 | // Note : Default values in visited are false 10 | vector visited(26); 11 | 12 | for (int k = i; k <= j; k++) { 13 | if (visited[str[k] - 'a'] == true) 14 | return false; 15 | visited[str[k] - 'a'] = true; 16 | } 17 | return true; 18 | } 19 | 20 | // Returns length of the longest substring 21 | // with all distinct characters. 22 | int longestUniqueSubsttr(string str) 23 | { 24 | int n = str.size(); 25 | int res = 0; // result 26 | for (int i = 0; i < n; i++) 27 | for (int j = i; j < n; j++) 28 | if (areDistinct(str, i, j)) 29 | res = max(res, j - i + 1); 30 | return res; 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | string str = "geeksforgeeks"; 37 | cout << "The input string is " << str << endl; 38 | int len = longestUniqueSubsttr(str); 39 | cout << "The length of the longest non-repeating " 40 | "character substring is " 41 | << len; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /majority_element2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector majorityElement(vector& nums) { 8 | vectorans; 9 | int n=nums.size(); 10 | unordered_mapmp; 11 | for(int i=0;i(n/3)){ 16 | ans.push_back(x.first); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /matrix_chain_mult.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int MatrixChainOrder(int p[], int i, int j) 5 | { 6 | if (i == j) 7 | return 0; 8 | int k; 9 | int mini = INT_MAX; 10 | int count; 11 | 12 | for (k = i; k < j; k++) 13 | { 14 | count = MatrixChainOrder(p, i, k) 15 | + MatrixChainOrder(p, k + 1, j) 16 | + p[i - 1] * p[k] * p[j]; 17 | 18 | mini = min(count, mini); 19 | } 20 | 21 | return mini; 22 | } 23 | 24 | // Driver Code 25 | int main() 26 | { 27 | int arr[] = { 1, 2, 3, 4, 3 }; 28 | int N = sizeof(arr) / sizeof(arr[0]); 29 | 30 | // Function call 31 | cout << "Minimum number of multiplications is "<< MatrixChainOrder(arr, 1, N - 1); 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /maxfreqofelement.cpp: -------------------------------------------------------------------------------- 1 | #include //in this we have created a map to store the freq..and created a minheap and output the elemnts having more freq 2 | using namespace std; 3 | 4 | typedef pair pi; 5 | 6 | void PrintTopKfrequentNums(vector &arr, int k) 7 | { 8 | 9 | //created a map becoz numbers r repeating ... map stores the the freq of a particular number 10 | 11 | /* input: (10->no. of ele 12 | 2 2 2 1 1 1 3 3 4 13 | 2->key) 14 | Map will store the input like this ...with which it will be easier to store freq 15 | 16 | no. freq 17 | 1 -> 3 18 | 2 -> 3 19 | 3 -> 2 20 | 4 -> 1 21 | 22 | */ 23 | 24 | unordered_map mp; 25 | for (auto e : arr) 26 | { 27 | mp[e]++; 28 | } 29 | 30 | priority_queue, greater> minh; 31 | for (auto e : mp) //iterating the map from 1st to last 32 | { 33 | minh.push(make_pair(e.second, e.first)); // pair becoz we r pushing both freq and no. 34 | 35 | if (minh.size() > k) 36 | minh.pop(); 37 | } 38 | 39 | while (!minh.empty()) 40 | { 41 | cout << minh.top().second << " "; //printing the no. with highest freq 42 | minh.pop(); 43 | } 44 | cout << endl; 45 | } 46 | 47 | int main() 48 | { 49 | int n, k; 50 | cin >> n >> k; 51 | vector arr(n); 52 | 53 | for (int i = 0; i < n; ++i) 54 | cin >> arr[i]; 55 | 56 | PrintTopKfrequentNums(arr, k); 57 | return 0; 58 | } -------------------------------------------------------------------------------- /maximize_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | class Solution { 5 | public: 6 | int maxSubArray(vector& nums) { 7 | 8 | int n=nums.size(); 9 | int sum=0; 10 | int maxi=INT_MIN; 11 | for(int i=0;i&w,unordered_map&m,vector&score){ 4 | if(n<0) return 0; 5 | bool flag=true; 6 | int sr=0; 7 | for(auto x:w[n]){ 8 | if(!m[x]) flag=false; 9 | m[x]--;sr+=score[x-'a']; 10 | } 11 | int a=0,b=0; 12 | if(flag) a=sr+solve(n-1,w,m,score); 13 | for(auto x:w[n]) m[x]++; 14 | b=solve(n-1,w,m,score); 15 | return max(a,b); 16 | } 17 | int maxScoreWords(vector& words, vector& letters, vector& score) { 18 | unordered_mapm; 19 | for(auto x: letters) m[x]++; 20 | return solve(words.size()-1,words,m,score); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /maximumSubarraySum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxSum (int arr[], int n) { 5 | int maxEnding = arr[0], result = arr[0]; 6 | for (int i = 1; i < n; i++) { 7 | maxEnding = max (maxEnding + arr[i], arr[i]); 8 | result = max (maxEnding, result); 9 | } 10 | return result; 11 | } 12 | 13 | int main() { 14 | int n; cin >> n; 15 | int arr[n]; 16 | for (int i = 0; i < n; i++) { 17 | cin >> arr[i]; 18 | } 19 | int result = maxSum (arr, n); 20 | cout << result << '\n'; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /merge two sorted array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void mergeArrays(int arr1[], int arr2[], int n1, 5 | int n2, int arr3[]) 6 | { 7 | int i = 0, j = 0, k = 0; 8 | 9 | while(i < n1){ 10 | arr3[k++] = arr1[i++]; 11 | } 12 | 13 | 14 | while(j < n2){ 15 | arr3[k++] = arr2[j++]; 16 | } 17 | 18 | 19 | sort(arr3, arr3+n1+n2); 20 | } 21 | int main() 22 | { 23 | int arr1[] = {1, 3, 5, 7}; 24 | int n1 = sizeof(arr1) / sizeof(arr1[0]); 25 | 26 | int arr2[] = {2, 4, 6, 8}; 27 | int n2 = sizeof(arr2) / sizeof(arr2[0]); 28 | 29 | int arr3[n1+n2]; 30 | mergeArrays(arr1, arr2, n1, n2, arr3); 31 | 32 | cout << "Array after merging" <& nums) { 4 | int ans = nums.size(); 5 | int mask = 0; 6 | 7 | for(auto i : nums){ 8 | ans = ans ^ i; 9 | ans = ans ^ mask; 10 | mask++; 11 | } 12 | 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /onoffBULB.HTML: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | On Off Bulb 6 | 10 | 11 | 12 | 13 |
14 |
15 |
16 |
17 |
18 |
19 | 20 | 21 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /pascal's triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binomialCoeff(int n, int k); 5 | 6 | 7 | void printPascal(int n) 8 | { 9 | for (int line = 0; line < n; line++) 10 | { 11 | 12 | for (int i = 0; i <= line; i++) 13 | cout <<" "<< binomialCoeff(line, i); 14 | cout <<"\n"; 15 | } 16 | } 17 | 18 | 19 | int binomialCoeff(int n, int k) 20 | { 21 | int res = 1; 22 | if (k > n - k) 23 | k = n - k; 24 | for (int i = 0; i < k; ++i) 25 | { 26 | res *= (n - i); 27 | res /= (i + 1); 28 | } 29 | 30 | return res; 31 | } 32 | 33 | 34 | int main() 35 | { 36 | int n = 7; 37 | printPascal(n); 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /passwordGenrator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | static const char alphanum[] = 7 | "0123456789" 8 | "!@#$%^&*" 9 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 10 | "abcdefghijklmnopqrstuvwxyz"; 11 | int size = sizeof(alphanum) - 1; 12 | 13 | int main() 14 | { 15 | //password length 16 | int length = 8; 17 | 18 | srand(time(0)); 19 | for (int i = 0; i < length; i++) 20 | { 21 | cout << alphanum[rand() % ::size]; 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /passwordgenerator.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | pass1 = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 4 | 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 5 | 't', 'u', 'v', 'x', 'y', 'z', 'A', 'B', 'C', 6 | 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 7 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 8 | 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', 9 | '7', '8', '9', '0', '@', '#', '$', '_', '*', 10 | '.', '!', '(', ')', '%', '^', '/', '|', ' '] 11 | password = " " 12 | for x in range(16): 13 | password = password + random.choice(pass1)[0] 14 | 15 | print('your new password is:\n', password) 16 | -------------------------------------------------------------------------------- /prime-or-not.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | 7 | { 8 | 9 | int n, i, m=0, flag=0; 10 | 11 | cout << "Enter the Number to check Prime: "; 12 | 13 | cin >> n; 14 | 15 | m=n/2; 16 | 17 | for(i = 2; i <= m; i++) 18 | 19 | { 20 | 21 | if(n % i == 0) 22 | 23 | { 24 | 25 | cout<<"Number is not Prime."< sieve; 46 | void prime(int n){ 47 | sieve.resize(n+1,true); 48 | sieve[0]=sieve[1]=false; 49 | for(int i=2;(long long)i*i<=n;++i){ 50 | if(sieve[i]) 51 | for(int j=i*i;j<=n;j+=i) 52 | sieve[j]=false; 53 | } 54 | } 55 | 56 | int main{ 57 | cout<<"Enter total numbers you wanted to check for prime: "; 58 | int t; 59 | cin>>t; 60 | 61 | // Initialise the sieve upto the maximum number 62 | prime(100005); 63 | while(t--){ 64 | int n; 65 | cin>>n; 66 | if(sieve[n]==true) 67 | cout<<"Number "< 4 | using namespace std; 5 | 6 | bool isPrime(int n) 7 | { 8 | // Corner case 9 | if (n <= 1) 10 | return false; 11 | 12 | // Check from 2 to n-1 13 | for (int i = 2; i < n; i++) 14 | if (n % i == 0) 15 | return false; 16 | 17 | return true; 18 | } 19 | 20 | // Driver Program to test above function 21 | int main() 22 | { 23 | isPrime(11) ? cout << " true\n" : cout << " false\n"; 24 | isPrime(15) ? cout << " true\n" : cout << " false\n"; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /reverse integers.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-integer/ 2 | class Solution { 3 | public: 4 | int reverse(int x) { 5 | long long int rev=0; 6 | if(x==0) return 0; 7 | else if(x>0){ 8 | while(x!=0){ 9 | int rem=x%10; 10 | rev=rev*10+rem; 11 | x/=10; 12 | if(rev>INT_MAX||revINT_MAX||rev 2 | using namespace std; 3 | 4 | int INT_BITS = 32; 5 | 6 | 7 | int leftRotate(int n, unsigned int d) { 8 | return (n << d)|(n >> (INT_BITS - d)); 9 | } 10 | 11 | 12 | int rightRotate(int n, unsigned int d) { 13 | return (n >> d)|(n << (INT_BITS - d)); 14 | } 15 | 16 | int main() { 17 | 18 | int n = 4; 19 | 20 | 21 | int d = 2; 22 | 23 | 24 | cout << "Left Rotation of " << n << " by " << d << " is " << leftRotate(n, d)<<"\n"; 25 | 26 | cout << "Right Rotation of " << n <<" by " << d << " is "<< rightRotate(n, d); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /single_file_program.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int tc, n , m, k; 7 | scanf("%d",&tc); 8 | while(tc--) { 9 | scanf("%d %d %d",&n,&m,&k); 10 | int ar[n+1] = {0}; 11 | int sum = 0,ans = 0 ; 12 | for(int i = 0; i < n; i++) scanf("%d",&ar[i]); 13 | for(int i = 0, j = 0; i < n*m; i++) { 14 | j = i + 1; 15 | sum = 0; 16 | if(ar[i%n] <= k){ 17 | ans++; 18 | sum = ar[i%n] + ar[j%n]; 19 | 20 | while(j < n*m and sum <= k) { 21 | ans++;j++; 22 | sum += ar[j%n]; 23 | } 24 | } 25 | } 26 | cout << ans << endl; 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /single_num_2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | int x=0,x1=0,x2=0,pos=-1; 5 | for(int i=0;i vect; 24 | vect.push_back(x1); 25 | vect.push_back(x2); 26 | return vect; 27 | } 28 | }; -------------------------------------------------------------------------------- /sqrt(x).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int BinarySearch(int n){ 3 | long s = 0; 4 | long e = n ; 5 | long mid = s + (e-s)/2; 6 | long ans = -1; 7 | while(s<=e){ 8 | long sq = mid*mid; 9 | 10 | if(sq==n){ 11 | return (int)mid; 12 | } 13 | 14 | if(sq < n){ 15 | ans = mid; 16 | s = mid + 1; 17 | } 18 | else{ 19 | e = mid - 1; 20 | } 21 | mid = s + (e-s)/2; 22 | } 23 | return (int)ans ; 24 | } 25 | public int mySqrt(int x) { 26 | return BinarySearch(x); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /square_pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int i,j,k,l,m,n,o=2,a,b,c,d,g,h; 5 | printf("enter the last digit of square"); 6 | scanf("%d",&n); 7 | b=n-1; 8 | for(i=n;i>=1;i--) 9 | { 10 | m=n; 11 | for(l=1;l<=n-i;l++) 12 | { 13 | printf("%d ",m); 14 | m--; 15 | } 16 | for(j=1;j<=2*i-1;j++) 17 | { 18 | printf("%d ",i); 19 | } 20 | o=i+1; 21 | for(k=1;k<=n-i;k++) 22 | { 23 | printf("%d ",o); 24 | o++; 25 | } 26 | printf("\n"); 27 | } 28 | for(a=1;a<=b;a++) 29 | { 30 | d=n; 31 | for(c=1;c<=b-a;c++) 32 | { 33 | printf("%d ",d); 34 | d--; 35 | } 36 | for(g=1;g<=2*a+1;g++) 37 | { 38 | printf("%d ",a+1); 39 | } 40 | for(h=1;h<=b-a;h++) 41 | { 42 | printf("%d ",a+h+1); 43 | } 44 | 45 | printf("\n"); 46 | } 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /stack_next_greater_element.cpp: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/contests/second/challenges/next-greater-element/problem 2 | // problem 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main() { 9 | int n; 10 | cin>>n; 11 | int nums[n]; 12 | for(int i=0;i>nums[i]; 14 | } 15 | int nge[n]; 16 | for(int i=0;ist; 20 | for (int i = n - 1; i >= 0; i--) { 21 | while (!st.empty() && st.top() <= nums[i]) { 22 | st.pop(); 23 | } 24 | 25 | if (i < n) { 26 | if (!st.empty()) 27 | nge[i] = st.top(); 28 | } 29 | st.push(nums[i]); 30 | } 31 | for(int i=0;i 2 | int main() 3 | { 4 | int a,b,mod=5,k,i,z,c; 5 | a=1; 6 | printf("\n\n\n"); 7 | while(a<=6) 8 | { 9 | printf("\t\t"); 10 | b=0; 11 | printf(" "); 12 | while(b<6-a) 13 | { 14 | printf(" "); 15 | b=b+1; 16 | } 17 | b=0; 18 | while(b0;z--){ 35 | printf(" "); 36 | } 37 | for(k;k>=0;k--){ 38 | printf("* "); 39 | } 40 | printf("\n"); 41 | i = i+1; 42 | b = b-2; 43 | a = a+1; 44 | } 45 | while(mod>=0){ 46 | printf("\t\t"); 47 | z=mod+3; 48 | while(z>0){ 49 | printf(" "); 50 | z = z-1; 51 | } 52 | printf(" "); 53 | for(k=1;k<=mod;k++){ 54 | printf("* "); 55 | } 56 | for(i=1;i<=2*(a-2*mod);i++){ 57 | printf(" "); 58 | } 59 | for(k=1;k<=mod;k++){ 60 | printf("* "); 61 | } 62 | printf("\n"); 63 | mod=mod-1; 64 | a = a+1; 65 | } 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /strongnum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // function to calculate factorial 5 | int factorial(int n){ 6 | int fact = 1; 7 | 8 | for(int i = 1; i <= n; i++) 9 | fact = fact * i; 10 | 11 | return fact; 12 | } 13 | 14 | int Strongnum(int num){ 15 | 16 | int digit, sum = 0; 17 | int temp = num; 18 | 19 | // calculate 1! + 4! + 5! 20 | while(temp!=0){ 21 | digit = temp % 10; 22 | 23 | sum = sum + factorial(digit); 24 | temp /= 10; 25 | } 26 | 27 | 28 | return sum == num; 29 | 30 | } 31 | int main () 32 | { 33 | int num = 120; 34 | 35 | if(Strongnum(num)) 36 | cout << num << " is Strong Number"; 37 | else 38 | cout << num << " is Not Strong Number"; 39 | 40 | } 41 | -------------------------------------------------------------------------------- /table_program: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | printf("Table Program (Using Loop) \n\n\n"); 5 | printf("Enter A Number That You want the Table : \n"); 6 | int num; 7 | scanf("%d", &num); 8 | 9 | for (int i = 1; i <= 10; i++) 10 | { 11 | printf("%d * %d = %d \n", num, i, num * i); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tempCodeRunnerFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution 4 | { 5 | public: 6 | vector findArray(vector &A) 7 | { 8 | for (int i = A.size() - 1; i > 0; --i) 9 | A[i] ^= A[i - 1]; 10 | return A; 11 | } 12 | }; 13 | 14 | int main() 15 | { 16 | Solution b; 17 | vector arr = {5, 2, 0, 3, 1}; 18 | cout << b.findArray(arr) << endl; 19 | return 0; 20 | } -------------------------------------------------------------------------------- /tower_of_honoi.java: -------------------------------------------------------------------------------- 1 | // Java recursive program to solve tower of hanoi puzzle 2 | 3 | class Codespeedy 4 | { 5 | 6 | static void result(long n, char source, char destination, char auxiliary) 7 | { 8 | if (n == 1) 9 | { 10 | System.out.println("Move disk 1 from " + source + " to " + destination); // print the task 11 | return; 12 | } 13 | 14 | result(n-1, source, auxiliary, destination); 15 | 16 | System.out.println("Move disk " + n + " from " + source + " to " + destination); // print the task 17 | 18 | result(n-1, auxiliary, destination, source); 19 | } 20 | 21 | 22 | public static void main(String args[]) 23 | { 24 | long n = 3; // Number of disks 25 | result(n,'A','C','B'); // A, B and C are names of rods 26 | } } -------------------------------------------------------------------------------- /traping rain water.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int maxWater(int arr[], int n) 6 | { 7 | 8 | int res = 0; 9 | 10 | 11 | for (int i = 1; i < n - 1; i++) { 12 | 13 | 14 | int left = arr[i]; 15 | for (int j = 0; j < i; j++) 16 | left = max(left, arr[j]); 17 | 18 | 19 | int right = arr[i]; 20 | for (int j = i + 1; j < n; j++) 21 | right = max(right, arr[j]); 22 | 23 | 24 | res = res + (min(left, right) - arr[i]); 25 | } 26 | 27 | return res; 28 | } 29 | 30 | 31 | int main() 32 | { 33 | int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; 34 | int n = sizeof(arr) / sizeof(arr[0]); 35 | 36 | cout << maxWater(arr, n); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /two_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector twoSum(vector& nums, int target) { 8 | 9 | 10 | 11 | int n=nums.size(); 12 | 13 | unordered_setst; 14 | // for(int i=0;ians; 18 | for(int i=0;i &freq) 7 | { 8 | for(int i=0;i freq(26); 21 | for(auto ch:s) 22 | { 23 | freq[ch-'a']++; 24 | } 25 | 26 | stack st; 27 | string ans = ""; 28 | 29 | for(auto ch:s) 30 | { 31 | st.push(ch); 32 | freq[ch-'a']--; 33 | //bhai terse chota koi nahi h ans me add hoja -> st ka top , min in freq se bhi minimum hai 34 | while(!st.empty() && st.top()<=getMinChar(freq)) 35 | { 36 | ans.push_back(st.top()); 37 | st.pop(); 38 | } 39 | 40 | } 41 | 42 | 43 | while(!st.empty()) 44 | { 45 | ans.push_back(st.top()); 46 | st.pop(); 47 | } 48 | 49 | 50 | return ans; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /wildcard_matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string a, string b) { 4 | int n=a.size(),m=b.size(); 5 | bool dp[n+1][m+1]; 6 | memset(dp,false,sizeof(dp)); 7 | if(m==0) 8 | return n==0; 9 | 10 | dp[0][0]=true; 11 | for(int i=1;i<=m;i++) 12 | if(b[i-1]=='*') 13 | dp[0][i]=dp[0][i-1]; 14 | 15 | 16 | for(int i=1;i<=n;i++) 17 | { 18 | for(int j=1;j<=m;j++) 19 | { 20 | if(b[j-1]=='?' || b[j-1]==a[i-1]) 21 | dp[i][j]=dp[i-1][j-1]; 22 | else if(b[j-1]=='*') 23 | dp[i][j]=dp[i-1][j] || dp[i][j-1]; 24 | else if(b[j-1]!=a[i-1]) 25 | dp[i][j]=false; 26 | } 27 | } 28 | if(dp[n][m]) 29 | return 1; 30 | return 0; 31 | 32 | } 33 | }; --------------------------------------------------------------------------------