├── Adhoc problems ├── Circular List of Students.cpp ├── Interesting Sequences.cpp ├── Light Up the Bulbs.cpp └── winning strategy.cpp ├── Advanced Graphs ├── AIRPORTS.cpp ├── BOTTOM.cpp ├── Connected horses.cpp ├── Dominos.cpp ├── FILLMTR.cpp ├── Kingdom Of Monkeys.cpp ├── Monk and the Islands.cpp ├── New Year Transportation.cpp ├── Permutation Swaps.cpp └── connected components.cpp ├── Advanced Recursion ├── Merge sort.cpp ├── Print Keypad Combinations Code.cpp ├── Quick sort.cpp ├── Remove Duplicates Recursively.cpp ├── Replace Character Recursively.cpp ├── Return Keypad Code.cpp └── Return Subsequences of string.cpp ├── Applications Of NT - 1 ├── Advanced GCD.cpp ├── Card Game.cpp ├── Divisors Of Factorial.cpp ├── Find The Cube Free Number.cpp ├── Find the good sets.cpp ├── Number Of Factors.cpp ├── Sachin And Varun Problem.cpp └── Strange order.cpp ├── Assignment - Backtracking , Binary Search And Merge Sort Problems ├── Collecting the balls.cpp ├── Find power of a number.cpp ├── Sorting the Skills.cpp └── Sudoku Solver.cpp ├── Backtracking ├── Crossword Problem.cpp ├── N-Queen Problem.cpp ├── Rat In A Maze Problem.cpp └── sudoku.cpp ├── Basics of resursion ├── Number of digits.cpp ├── all indices of number.cpp ├── check number.cpp ├── first index of number.cpp ├── last index of number.cpp ├── power.cpp ├── print numbers.cpp └── sum of array.cpp ├── Binary Tree and Binary Search Tree ├── Averages of Levels in Binary Tree.cpp ├── Binary Tree.cpp ├── Construct the binary tree from inorder and preorder.cpp ├── Serialize and Deserialize The Binary Tree.cpp ├── Tree Views Top Right Left Bottom.cpp └── Tree traversals and height.cpp ├── Bit manipulation ├── CheckEvenOdd.cpp ├── Clear All Bits From MSB.cpp ├── Find first set bit.cpp ├── Set ith bit.cpp ├── Turn off 1st set bit.cpp ├── Unset ith bit.cpp ├── clearLSBbits.cpp ├── flip_ith_bit.cpp └── powerof2.cpp ├── Commonly Asked Problems Practice ├── Arrays : Minimum number of increment-other operations to make all array elements equal.cpp ├── Backtracking : M - Coloring problem.cpp ├── Backtracking : Permutations.cpp ├── Backtracking : Rat in maze.cpp ├── Backtracking and DP : count number of subsets with given sum.cpp ├── Binary Search : Search in Rotated Sorted Array.cpp ├── Binary Search : Find Minimum in Rotated Sorted Array.cpp ├── Binary Search : Find Smallest Letter Greater Than Target.cpp ├── Binary Search : Find minimum absolute difference in sorted array.cpp ├── Binary Search : Floor in a Sorted Array.cpp ├── Binary Search : K-th element of two sorted Arrays.cpp ├── Binary Search : Meeting rooms.cpp ├── Binary Search : Search in an almost sorted array.cpp ├── Binary search : Allocate minimum number of pages .cpp ├── Binary search : Find Nth root of M.cpp ├── Binary search : Find maximum element in Bitonic Array.cpp ├── Binary search : Minimum removals from array to make max – min <= K.cpp ├── Contruct Height balanced BST from sorted array.cpp ├── Count Binary Substrings.cpp ├── Count number of binary strings without consecutive 1’s.cpp ├── DP : Coin game winner where every player has three choices.cpp ├── DP : Partition Equal Subset Sum.cpp ├── Dp : number of subsequences having product smaller than or equal to K..cpp ├── Dp : Count common subsequence in two strings.cpp ├── Dp : Count of subsets with sum equal to X.cpp ├── Dp : Edit distance.cpp ├── Dp : Egg dropping problem.cpp ├── Dp : Largest Rectangle in Histogram.cpp ├── Dp : Longest Common Subsequence.cpp ├── Dp : Longest Palindromic Subsequence.cpp ├── Dp : Longest repeating subsequence.cpp ├── Dp : MCM.cpp ├── Dp : Maximum Sum Circular Subarray.cpp ├── Dp : Maximum subsequence sum such that no three are consecutive.cpp ├── Dp : Maximum sum Increasing subsequence.cpp ├── Dp : Minimum Difference Subsets.cpp ├── Dp : Minimum number of deletions OR insertions to make a string palindrome.cpp ├── Dp : Number of ways to make coin change.cpp ├── Dp : Painting the Fence.cpp ├── Dp : Regular Expression Matching.cpp ├── Dp : Rod cutting problem.cpp ├── Dp : Russian Doll Envelopes.cpp ├── Dp : Shortest Common Supersequence.cpp ├── Dp : Subset Sum Problem.cpp ├── Dp : Trapping Rain Water.cpp ├── Dp : Uncrossed Lines.cpp ├── Dp : Unique paths in a Grid with Obstacles.cpp ├── Dp : Wildcard Matching.cpp ├── Dp : Word Wrap.cpp ├── Dp : count number subsets S1 and S2 with given given difference.cpp ├── Geometry : Minimum distance from a point to the line segment.cpp ├── Graphs : Number of Operations to Make Network Connected.cpp ├── Graphs : Alien Dictionary ( Topo sort ).cpp ├── Graphs : BFS - Snake and Ladder.cpp ├── Graphs : Cheapest Flights Within K Stops.cpp ├── Graphs : Critical Connections in a Network.cpp ├── Graphs : Cycle detection in directed graph.cpp ├── Graphs : Cycle detection in undirected graph.cpp ├── Graphs : Dijkstras single source shortest path.cpp ├── Graphs : Find the celebrity.cpp ├── Graphs : Minimum time taken by each job to be completed given by a Directed Acyclic Graph.cpp ├── Graphs : Network Delay Time.cpp ├── Graphs : Number of islands.cpp ├── Graphs : Prims algorithm for MST.cpp ├── Graphs : Rotting Oranges.cpp ├── Graphs : Strongly connected components in graph (kosaraju algo).cpp ├── Graphs : course schedule 2 .cpp ├── Graphs : topological sorting.cpp ├── Graphs : words ladder.cpp ├── Greedy : Job sequencing.cpp ├── Greedy : Maximum trains for which stoppage can be provided.cpp ├── HashMap Implementation.cpp ├── Hashmaps : Count subarrays with Given XOR.cpp ├── Hashmaps : Largest subarray with 0 sum.cpp ├── Heap : Sort a nearly sorted (or K sorted) array.cpp ├── LRU Cache Implementation O(1) .cpp ├── LRU Cache Implementation O(n) .cpp ├── Largest subarray with equal number of 0s and 1s.cpp ├── Linked List : Flattening a Linked List.cpp ├── Linked List Cycle detection approach : Find the Duplicate Number.cpp ├── Majority Element II.cpp ├── Maximum points on straight line.cpp ├── Merge Sort : Count inversion.cpp ├── Merge Without Extra Space.cpp ├── Minimum cost to cover the given positions in a N*M grid.cpp ├── Minimum cost to make string valid.cpp ├── Minimum number of coins to make change to amount.cpp ├── Minimum operations to make strings equal.cpp ├── Moores : Majority Element.cpp ├── Next Greater Element.cpp ├── Optimal Strategy for a Game.cpp ├── Priority Queue : Min Heap Implementation.cpp ├── Queue : Double ended queue.cpp ├── Queue : implementation using array.cpp ├── Queue Using Two Stacks.cpp ├── Recursion : Return all susequences of string.cpp ├── Return Keypad Code.cpp ├── Search In Rotated Sorted Array.cpp ├── Sliding window : First negative integer in every window of size k.cpp ├── Sliding window : Longest K unique characters substring.cpp ├── Sliding window : Longest Substring Without Repeating Characters.cpp ├── Sliding window : Max Sum Subarray of size K .cpp ├── Sliding window : Minimum Window Substring.cpp ├── Sort Stack Recursively.cpp ├── Sorting : Merge sort.cpp ├── Sorting : Quicksort.cpp ├── Stack : Largest Rectangle in Histogram.cpp ├── Stack : Merge Intervals leetcode.cpp ├── Stack : Online Stock Span.cpp ├── Stack : Stack using single queue.cpp ├── String : Partition Labels.cpp ├── Strings : Minimum Swaps for Bracket Balancing.cpp ├── Strings : Rabin carp (string matching).cpp ├── Subsets.cpp ├── Trees : Check Identical and Mirror trees.cpp ├── Trees : Convert Binary tree to BST.cpp ├── Trees : Convert a given tree to its Sum Tree.cpp ├── Trees : Largest BST in Binary Tree.cpp ├── Trees : Left view of binary tree.cpp ├── Trees : Minimal Tree ( construct BST ) .cpp ├── Trees : Predecessor and Successor.cpp ├── Trees : sum of all elements in leaf nodes.cpp ├── Treess : Convert Binary Tree to DLL.cpp └── Trie : Implement Trie (Prefix Tree).cpp ├── Computational Geometry ├── Area Of Convex Polygon.cpp ├── Convex Hull.cpp ├── Surveyor.cpp └── Warehouse.cpp ├── DP & Bitmasking ├── Candy.cpp ├── Counting Strings.cpp ├── Dilemma.cpp ├── Ghost Type.cpp ├── Mehta And Bank Robbery.cpp ├── N jobs Bitmask.cpp ├── Number of APs.cpp └── String Maker.cpp ├── Dynamic Programming - 1 ├── Adjacent Bit Counts.cpp ├── AlphaCode-Question.cpp ├── Alyona and Spreadsheet.cpp ├── Angry Children.cpp ├── Boredom.cpp ├── Coin Change Problem.cpp ├── Count BSTs.cpp ├── Hasan and Trip.cpp ├── Jon Snow and his favourite number.cpp ├── Largest Bitonic Subarray.cpp ├── Longest Increasing subsequence.cpp ├── Loot Houses.cpp ├── Magic Grid Problem.cpp ├── Maximum Square Matrix With All Zeros.cpp ├── Maximum Sum Rectangle.cpp ├── Minimum Count.cpp ├── Minimum Number of Chocolates.cpp ├── Roy and Coin Boxes.cpp ├── StairCase Problem.cpp ├── Vanya and GCD.cpp ├── mincost.cpp └── sam ans substring.cpp ├── Dynamic Programming - 2 ├── Balika Vadhu- Problem.cpp ├── Charlie and Pilots.cpp ├── Distinct Subsequences.cpp ├── Edit Distance - Problem.cpp ├── Knapsnack - Problem.cpp ├── LCS - Problem.cpp ├── Miser Man.cpp ├── PARTY - Problem.cpp ├── Shortest Subsequence.cpp ├── Smallest Super-Sequence.cpp ├── Square Brackets.cpp ├── Subset Sum - Problem.cpp └── Trader Profit.cpp ├── FFT └── FFT.cpp ├── Fenwick Tree ├── Coder's Rating.cpp ├── Distinct Query Problem.cpp ├── Fenwick Tree Demo Sum.cpp ├── INCSEQ.cpp ├── KQUERY.cpp ├── OrderSet - Problem.cpp └── Shil and Wave Sequence.cpp ├── Game Theory ├── Calculate Grundy Number.cpp └── Optimal Move In Tic Tac Toe.cpp ├── Graphs 1 ├── 3 Cycle.cpp ├── Code : All connected components.cpp ├── Code : BFS Traversal.cpp ├── Code : Get Path - BFS.cpp ├── Code : Get Path - DFS.cpp ├── Code : Has Path.cpp ├── Code : Is Connected.cpp ├── Coding Ninjas.cpp ├── Connecting Dots.cpp ├── Graph BFS and DFS.cpp ├── Islands.cpp ├── Largest Piece.cpp └── Lowest Common Ancestor.cpp ├── Graphs 2 ├── Dijkstra's Algorithm.cpp ├── Floyd Warshall Algorithm .cpp ├── Kruskal's Algorithm.cpp ├── Prim's Algorithm.cpp └── Union find algorithm to detect cycle in graph.cpp ├── Greedy Problems ├── Activity Selection.cpp ├── Fractional Knapsack ( original ).cpp ├── Fractional Knapsack.cpp ├── Gold Robbry.cpp ├── Min. Absolute Difference In Array.cpp ├── Nikunj and Donuts.cpp ├── Perimeter with conditions.cpp ├── Problem discussion.cpp ├── Save Energy.cpp ├── Weighted Job Scheduling.cpp ├── Winning Lottery.cpp └── original fractional knapsack.cpp ├── Langauage tools ├── Exercise - Different names.cpp ├── Exercise - Extract unique characters.cpp ├── Exercise - Love for characters.cpp ├── Exercise - tell the positions.cpp ├── Exercise - warm reception.cpp ├── Permutation and Palindrome.cpp ├── STL functions.cpp ├── STL.cpp ├── char frequency.cpp ├── codechef - hussainset.cpp ├── remove duplicates.cpp └── voterslist.cpp ├── Language Tools + Time and Complexity Assignment ├── Duplicate in array.cpp ├── Find unique element.cpp ├── Longest consecutive sequence.cpp ├── Rotate array.cpp ├── Triplet sum.cpp ├── pair sum to 0.cpp └── sum me up.cpp ├── Linked List ├── Find the middle of a given linked list.cpp └── single linked list.cpp ├── Modulo arithmetic └── Number Of Balanced BTs.cpp ├── Number Theory - 1 ├── Extended Euclid algorithm.cpp ├── Find Prime Numbers From 1 to N(sieve of eratosthenes).cpp ├── GCD(euclid).cpp ├── multiplicative modulo inverse.cpp └── return count of prime numbers.cpp ├── Number Theory - 2 ├── Euler Totient.cpp ├── LCM SUM.cpp └── Segmented Sieve Problem.cpp ├── Number Theory - 3 ├── Boring Factorials.cpp ├── Cubic Square.cpp ├── Fibonacci Sum.cpp ├── GCD Extreme.cpp ├── Income On Nth Day.cpp ├── Innocent Swaps and His Emotions.cpp ├── Sanchit And Nuclear Reactor.cpp ├── Sehwag And ETF.cpp └── modular-exponentiation.cpp ├── Pre-requisites ├── Even and Odd Indexes.cpp ├── Matrix Diagonal and Boundaries sum.cpp ├── PRE4.cpp ├── Target Marbles.cpp └── chakri.cpp ├── Searching & Sorting Applications ├── Aggressive Cows Problem.cpp ├── Binary Search.cpp ├── Distribute Candies.cpp ├── Inversion Count.cpp ├── Momos shop.cpp ├── Murder.cpp └── variation.cpp ├── Segment Tree ├── 2 vs 3.cpp ├── Counting Even or Odd.cpp ├── Horrible Queries.cpp ├── Lazy propogation demo.cpp ├── Maximum Pair Sum.cpp ├── Maximum Sum In Subarray.cpp ├── Minimum In SubArray.cpp ├── Vasya vs Rhezo.cpp └── sum segment tree demo.cpp ├── String Algorithms ├── Brute Force String Matching.cpp ├── KMP.cpp ├── Longest Palindrome Substring.cpp ├── Longest prefix suffix code.cpp ├── Palindromic Substrings.cpp ├── String Search.cpp └── Z-algorithm.cpp ├── Time and Space complexity ├── k-concatenation.cpp ├── kadane.cpp ├── max product subarray.cpp └── mind bending.cpp ├── Tries ├── Help Me Pradyumana!.cpp ├── Max XOR pair.cpp ├── Maximum XOR Subarray.cpp ├── SUBXOR.cpp └── Search Engine.cpp └── pointers ├── Reference and pass by reference.cpp ├── datatype and pointer sizes.cpp └── pointers.pdf /Adhoc problems/Circular List of Students.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a circular list of students as follows: 3 | 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 4 | This list is circular, means that 11 will follow 0 again. You will be given the student number ‘i’ and some position ‘p’. You will have to tell that if the list will start 5 | from (i+1)th student, then which student will be at pth position. 6 | Input Format: 7 | First line will have an integer ‘t’, denoting the number of test cases. 8 | Next line will have two space separated integers denoting the value of ‘i’ and ‘p’ respectively. 9 | Output Format: 10 | Print ‘t’ lines containing single integer denoting the student number. 11 | Constraints: 12 | 1 <= t <= 10^5 13 | 0 <= i <= 11 14 | 1 <= p <= 12 15 | Sample Input: 16 | 2 17 | 2 3 18 | 5 8 19 | Sample Output: 20 | 5 21 | 1 22 | 23 | Explanation: 24 | First, list will start at 3. 3 -> 4 -> 5. Hence, 5 will be at third position. 25 | Second, list will start at 6. 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 0 -> 1. Hence, 1 will be at 8th position. 26 | */ 27 | 28 | #include 29 | using namespace std; 30 | int main() 31 | { 32 | int t; 33 | cin >> t; 34 | int k = 0; 35 | 36 | while(t--){ 37 | int i,p; 38 | cin >> i >> p; 39 | int pos = i + 1; 40 | while(p--){ 41 | if(pos > 11){ 42 | pos = 0; 43 | } 44 | pos ++; 45 | } 46 | pos --; 47 | if(pos == -1){ 48 | pos = 11; 49 | } 50 | cout << pos << endl; 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Advanced Graphs/connected components.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void dfs(int start, vector* edges, int n, unordered_set& visited, unordered_set * component) { 7 | visited.insert(start); 8 | component->insert(start); 9 | vector::iterator it = edges[start].begin(); 10 | for (;it != edges[start].end(); it++) { 11 | int i = *it; 12 | if (visited.count(i) > 0) { 13 | continue; 14 | } 15 | dfs(i, edges,n, visited, component); 16 | } 17 | } 18 | 19 | unordered_set*>* getComponents(vector* edges, int n) { 20 | unordered_set visited; 21 | unordered_set*>* output = new unordered_set*>(); 22 | for (int i = 0; i < n; i++) { 23 | if (visited.count(i) == 0) { 24 | unordered_set * component = new unordered_set(); 25 | dfs(i, edges,n, visited, component); 26 | output->insert(component); 27 | } 28 | } 29 | return output; 30 | } 31 | 32 | int main() { 33 | int n; 34 | cin >> n; 35 | vector* edges = new vector[n]; 36 | int m; 37 | cin >> m; 38 | for (int i = 0; i < m; i++) { 39 | int j, k; 40 | cin >> j >> k; 41 | edges[j - 1].push_back(k - 1); 42 | edges[k - 1].push_back(j - 1); 43 | } 44 | unordered_set*>* components = getComponents(edges, n); 45 | unordered_set*>::iterator it = components->begin(); 46 | while (it != components->end()) { 47 | unordered_set* component = *it; 48 | unordered_set::iterator it2 = component->begin(); 49 | while (it2 != component->end()) { 50 | cout << *it2 + 1 << " "; 51 | it2++; 52 | } 53 | cout << endl; 54 | delete component; 55 | it++; 56 | } 57 | delete components; 58 | delete edges; 59 | } 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /Advanced Recursion/Merge sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort an array A using Merge Sort. 3 | Change in the input array itself. So no need to return or print anything. 4 | 5 | Input format : 6 | Line 1 : Integer n i.e. Array size 7 | Line 2 : Array elements (separated by space) 8 | 9 | Output format : 10 | Array elements in increasing order (separated by space) 11 | 12 | Constraints : 13 | 1 <= n <= 10^3 14 | 15 | Sample Input 1 : 16 | 6 17 | 2 6 8 5 4 3 18 | 19 | Sample Output 1 : 20 | 2 3 4 5 6 8 21 | 22 | Sample Input 2 : 23 | 5 24 | 2 1 5 2 3 25 | 26 | Sample Output 2 : 27 | 1 2 2 3 5 28 | 29 | */ 30 | 31 | 32 | #include 33 | using namespace std; 34 | 35 | void merge(int* arr1,int n1,int* arr2,int n2,int* input,int size){ 36 | int i = 0; 37 | int j = 0; 38 | int k = 0; 39 | while(i> length; 81 | int* input = new int[length]; 82 | for(int i=0; i < length; i++) 83 | cin >> input[i]; 84 | mergeSort(input, length); 85 | for(int i = 0; i < length; i++) { 86 | cout << input[i] << " "; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Advanced Recursion/Print Keypad Combinations Code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n. 4 | Note : The order of strings are not important. Just print different strings in new lines. 5 | Input Format : 6 | Integer n 7 | Output Format : 8 | All possible strings in different lines 9 | Constraints : 10 | 1 <= n <= 10^6 11 | Sample Input: 12 | 23 13 | Sample Output: 14 | ad 15 | ae 16 | af 17 | bd 18 | be 19 | bf 20 | cd 21 | ce 22 | cf 23 | 24 | */ 25 | 26 | 27 | 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | #include 34 | #include 35 | using namespace std; 36 | string output[1000]; 37 | const char key[10][5]={{},{},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}; 38 | 39 | void helper(int n,string output){ 40 | if(n==0){ 41 | 42 | cout<> num; 66 | 67 | printKeypad(num); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Advanced Recursion/Remove Duplicates Recursively.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, remove consecutive duplicates from it recursively. 3 | Input Format : 4 | String S 5 | Output Format : 6 | Output string 7 | Constraints : 8 | 1 <= |S| <= 10^3 9 | where |S| represents the length of string 10 | Sample Input 1 : 11 | aabccba 12 | Sample Output 1 : 13 | abcba 14 | Sample Input 2 : 15 | xxxyyyzwwzzz 16 | Sample Output 2 : 17 | xyzwz 18 | */ 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | #include 27 | using namespace std; 28 | 29 | 30 | void removeConsecutiveDuplicates(char *input) { 31 | 32 | if(input[0] == '\0'){ 33 | return; 34 | } 35 | char temp = input[0]; 36 | if(input[1] == temp){ 37 | int i=2; 38 | for(;input[i]!='\0';i++){ 39 | input[i-1] = input[i]; 40 | } 41 | input[i-1] = '\0'; 42 | removeConsecutiveDuplicates(input); 43 | } 44 | removeConsecutiveDuplicates(input+1); 45 | 46 | } 47 | 48 | int main() { 49 | char s[100000]; 50 | cin >> s; 51 | removeConsecutiveDuplicates(s); 52 | cout << s << endl; 53 | } 54 | -------------------------------------------------------------------------------- /Advanced Recursion/Replace Character Recursively.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 4 | Given an input string S and two characters c1 and c2, you need to replace every occurrence of character c1 with character c2 in the given string. 5 | Do this recursively. 6 | Input Format : 7 | Line 1 : Input String S 8 | Line 2 : Character c1 and c2 (separated by space) 9 | Output Format : 10 | Updated string 11 | Constraints : 12 | 1 <= Length of String S <= 10^6 13 | Sample Input : 14 | abacd 15 | a x 16 | Sample Output : 17 | xbxcd 18 | */ 19 | 20 | 21 | #include 22 | using namespace std; 23 | 24 | void replaceCharacter(char input[], char c1, char c2) { 25 | if(input[0] == '\0'){ 26 | return; 27 | } 28 | if(input[0] == c1){ 29 | input[0] = c2; 30 | replaceCharacter(input+1,c1,c2); 31 | } 32 | replaceCharacter(input+1,c1,c2); 33 | 34 | } 35 | 36 | int main() { 37 | char input[1000000]; 38 | char c1, c2; 39 | cin >> input; 40 | cin >> c1 >> c2; 41 | replaceCharacter(input, c1, c2); 42 | cout << input << endl; 43 | } 44 | -------------------------------------------------------------------------------- /Advanced Recursion/Return Subsequences of string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string we need to find all subsequences and total count of subsequences 3 | example : abc 4 | output : 5 | total count = 2^3 =8 6 | subsequences = "",a,b,c,ab,ac,bc,abc 7 | */ 8 | 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | long subSeq(string str,string output[]){ 15 | if(str.size() == 0){ 16 | output[0] = ""; 17 | return 1; 18 | } 19 | string smallString = str.substr(1); //calling except first character ie if "abc" call on "bc" 20 | long smallOutputSize = subSeq(smallString,output); 21 | for(long i=0;i> str; 30 | string* output = new string[1000]; 31 | long count = subSeq(str,output); 32 | cout << " Number of subsequences is : " << count << endl; 33 | for(long i=0;i 28 | using namespace std; 29 | 30 | long long getPower(int x,int n){ 31 | if(n == 0){ 32 | return 1; 33 | } 34 | return x * getPower(x,n-1); 35 | } 36 | 37 | int main() { 38 | // Write your code here 39 | int x,n; 40 | cin >> x >> n; 41 | long long ans = getPower(x,n); 42 | cout << ans << endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Basics of resursion/Number of digits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the code to find out and return the number of digits present in a number recursively. But it contains few bugs, that you need to rectify such that all the test cases 3 | should pass. 4 | Input Format : 5 | Integer n 6 | Output Format : 7 | Count of digits 8 | Constraints : 9 | 1 <= n <= 10^6 10 | Sample Input 1 : 11 | 156 12 | Sample Output 1 : 13 | 3 14 | Sample Input 2 : 15 | 7 16 | Sample Output 2 : 17 | 1 18 | 19 | */ 20 | 21 | 22 | 23 | 24 | #include 25 | #include "Solution.h" 26 | using namespace std; 27 | 28 | int count(int n){ 29 | if(n == 0){ 30 | return 0; 31 | } 32 | int smallAns = count(n / 10); 33 | return smallAns + 1; 34 | } 35 | 36 | int main(){ 37 | int n; 38 | cin >> n; 39 | 40 | cout << count(n) << endl; 41 | } 42 | -------------------------------------------------------------------------------- /Basics of resursion/check number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false. 3 | Do this recursively. 4 | Input Format : 5 | Line 1 : An Integer N i.e. size of array 6 | Line 2 : N integers which are elements of the array, separated by spaces 7 | Line 3 : Integer x 8 | Output Format : 9 | 'true' or 'false' 10 | Constraints : 11 | 1 <= N <= 10^3 12 | Sample Input 1 : 13 | 3 14 | 9 8 10 15 | 8 16 | Sample Output 1 : 17 | true 18 | Sample Input 2 : 19 | 3 20 | 9 8 10 21 | 2 22 | Sample Output 2 : 23 | false 24 | */ 25 | 26 | 27 | #include 28 | #include "Solution.h" 29 | using namespace std; 30 | 31 | 32 | 33 | bool checkNumber(int input[], int n, int x) { 34 | if (n==0){ 35 | return false; 36 | } 37 | if(n==1){ 38 | if(x== input[n]){ 39 | return true; 40 | }else{ 41 | return false; 42 | } 43 | } 44 | 45 | //CHACKING FOR FIRST ELEMENT = X FOR EVERY RECURSION 46 | if(input[0] == x){ 47 | return true; 48 | }else{ 49 | return checkNumber(input+1,n-1,x); 50 | } 51 | 52 | 53 | //CHACKING FOR LAST ELEMENT = X FOR EVERY RECURSION 54 | // if(input[n-1] == x){ 55 | // return true; 56 | // }else{ 57 | // return checkNumber(input,n-1,x); 58 | // } 59 | } 60 | 61 | 62 | 63 | 64 | int main(){ 65 | int n; 66 | cin >> n; 67 | 68 | int *input = new int[n]; 69 | 70 | for(int i = 0; i < n; i++) { 71 | cin >> input[i]; 72 | } 73 | 74 | int x; 75 | 76 | cin >> x; 77 | 78 | if(checkNumber(input, n, x)) { 79 | cout << "true" << endl; 80 | } 81 | else { 82 | cout << "false" << endl; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Basics of resursion/first index of number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. 3 | First index means, the index of first occurrence of x in the input array. 4 | Do this recursively. Indexing in the array starts from 0. 5 | Input Format : 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Line 3 : Integer x 9 | Output Format : 10 | first index or -1 11 | Constraints : 12 | 1 <= N <= 10^3 13 | Sample Input : 14 | 4 15 | 9 8 10 8 16 | 8 17 | Sample Output : 18 | 1 19 | */ 20 | 21 | 22 | 23 | 24 | 25 | #include 26 | #include "Solution.h" 27 | using namespace std; 28 | 29 | 30 | int count = 0; 31 | 32 | int firstIndex(int input[], int n, int x) { 33 | 34 | if(n==0){ 35 | return -1; 36 | } 37 | if(n==1){ 38 | if(input[n] == x){ 39 | return 0; 40 | }else{ 41 | return -1; 42 | } 43 | } 44 | if(input[0] == x){ 45 | return count; 46 | }else{ 47 | count++; 48 | return firstIndex(input+1,n-1,x); 49 | } 50 | } 51 | 52 | int main(){ 53 | int n; 54 | cin >> n; 55 | 56 | int *input = new int[n]; 57 | 58 | for(int i = 0; i < n; i++) { 59 | cin >> input[i]; 60 | } 61 | 62 | int x; 63 | 64 | cin >> x; 65 | 66 | cout << firstIndex(input, n, x) << endl; 67 | 68 | } 69 | -------------------------------------------------------------------------------- /Basics of resursion/last index of number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. 3 | Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. 4 | You should start traversing your array from 0, not from (N - 1). 5 | Do this recursively. Indexing in the array starts from 0. 6 | Input Format : 7 | Line 1 : An Integer N i.e. size of array 8 | Line 2 : N integers which are elements of the array, separated by spaces 9 | Line 3 : Integer x 10 | Output Format : 11 | last index or -1 12 | Constraints : 13 | 1 <= N <= 10^3 14 | Sample Input : 15 | 4 16 | 9 8 10 8 17 | 8 18 | Sample Output : 19 | 3 20 | 21 | */ 22 | 23 | 24 | #include 25 | #include "Solution.h" 26 | using namespace std; 27 | 28 | int count = 0; 29 | 30 | int firstIndex(int input[], int n, int x) { 31 | /* Don't write main(). 32 | Don't read input, it is passed as function argument. 33 | Return output and don't print it. 34 | Taking input and printing output is handled automatically. 35 | */ 36 | if(n==0){ 37 | return -1; 38 | } 39 | if(n==1){ 40 | if(input[n] == x){ 41 | return 0; 42 | }else{ 43 | return -1; 44 | } 45 | } 46 | if(input[0] == x){ 47 | return count; 48 | }else{ 49 | count++; 50 | return firstIndex(input+1,n-1,x); 51 | } 52 | } 53 | 54 | int main(){ 55 | int n; 56 | cin >> n; 57 | 58 | int *input = new int[n]; 59 | 60 | for(int i = 0; i < n; i++) { 61 | cin >> input[i]; 62 | } 63 | 64 | int x; 65 | 66 | cin >> x; 67 | 68 | cout << lastIndex(input, n, x) << endl; 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Basics of resursion/power.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to return the answer. 3 | Do this recursively. 4 | Input format : 5 | Two integers x and n (separated by space) 6 | Output Format : 7 | x^n (i.e. x raise to the power n) 8 | Constraints : 9 | 1 <= x <= 30 10 | 0 <= n <= 30 11 | 12 | */ 13 | 14 | 15 | 16 | 17 | 18 | #include 19 | #include "Solution.h" 20 | using namespace std; 21 | 22 | 23 | int power(int x, int n) { 24 | /* Don't write main(). 25 | Don't read input, it is passed as function argument. 26 | Return output and don't print it. 27 | Taking input and printing output is handled automatically. 28 | */ 29 | if(n==0){ 30 | return 1; 31 | } 32 | int smallOutput = power(x,n-1); 33 | return x * smallOutput; 34 | 35 | } 36 | 37 | int main(){ 38 | int x, n; 39 | cin >> x >> n; 40 | 41 | cout << power(x, n) << endl; 42 | } 43 | -------------------------------------------------------------------------------- /Basics of resursion/print numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given is the code to print numbers from 1 to n in increasing order recursively. But it contains few bugs that you need to rectify such that all the test cases pass. 3 | Input Format : 4 | Integer n 5 | Output Format : 6 | Numbers from 1 to n (separated by space) 7 | Constraints : 8 | 1 <= n <= 10000 9 | Sample Input 1 : 10 | 6 11 | Sample Output 1 : 12 | 1 2 3 4 5 6 13 | Sample Input 2 : 14 | 4 15 | Sample Output 2 : 16 | 1 2 3 4 17 | */ 18 | 19 | 20 | 21 | 22 | 23 | 24 | #include 25 | using namespace std; 26 | #include "Solution.h" 27 | 28 | void print(int n){ 29 | if(n == 1){ 30 | cout << n << " "; 31 | return; 32 | } 33 | print(n - 1); 34 | cout << n << " "; 35 | } 36 | 37 | 38 | int main(){ 39 | int n; 40 | cin >> n; 41 | 42 | print(n); 43 | } 44 | -------------------------------------------------------------------------------- /Basics of resursion/sum of array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an array of length N, you need to find and return the sum of all elements of the array. 4 | Do this recursively. 5 | Input Format : 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Output Format : 9 | Sum 10 | Constraints : 11 | 1 <= N <= 10^3 12 | Sample Input 1 : 13 | 3 14 | 9 8 9 15 | Sample Output 1 : 16 | 26 17 | Sample Input 2 : 18 | 3 19 | 4 2 1 20 | Sample Output 2 : 21 | 7 22 | */ 23 | #include 24 | #include "Solution.h" 25 | using namespace std; 26 | 27 | 28 | int sum(int input[], int n) { 29 | /* Don't write main(). 30 | Don't read input, it is passed as function argument. 31 | Return output and don't print it. 32 | Taking input and printing output is handled automatically. 33 | 34 | */ 35 | if(n == 0){ 36 | return 0; 37 | } 38 | if (n== 1){ 39 | return input[0]; 40 | } 41 | return input[0] + sum(input+1,n-1); 42 | // return input[n-1] + sum(input,n-1); 43 | } 44 | 45 | 46 | int main(){ 47 | int n; 48 | cin >> n; 49 | 50 | int *input = new int[n]; 51 | 52 | for(int i = 0; i < n; i++) { 53 | cin >> input[i]; 54 | } 55 | 56 | cout << sum(input, n) << endl; 57 | } 58 | -------------------------------------------------------------------------------- /Bit manipulation/CheckEvenOdd.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 7 : 0111 3 | 0111 & 0001 = 0001 (!= 0) hence odd 4 | 5 | 6 : 0110 6 | 0110 & 0001 = 0000 (= 0) hence even 7 | */ 8 | 9 | 10 | #include 11 | using namespace std; 12 | int main(){ 13 | int n; 14 | cin >> n; 15 | if((n & 1) == 0){ 16 | cout << "even" << endl; 17 | }else{ 18 | cout << "odd" << endl; 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Bit manipulation/Clear All Bits From MSB.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integers N and i. You need to clear all bits from MSB to ith bit (start i from right to left) and return the updated N. 3 | Counting of bits starts from 0 from right to left. 4 | 5 | Input Format : 6 | Two integers N and i (separated by space) 7 | Output Format : 8 | Updated N 9 | Sample Input 1 : 10 | 15 2 11 | Sample Output 1 : 12 | 3 13 | Sample Output 1 Explanation : 14 | We need to clear all bits from MSB to ith bit i.e. clear all bits except 0th and 1st. 15 | Sample Input 2 : 16 | 4 4 17 | Sample Output 2 : 18 | 4 19 | */ 20 | 21 | 22 | /* 23 | ex: n = 15 : 00001111 ; i = 2 24 | out: 00000011 = 3 25 | 26 | approach : a = left shift by (1 << i) 00000100 27 | b = a - 1 = 00000011 28 | ans = n & b = 00001111 & 00000011 = 00000011 29 | */ 30 | 31 | 32 | 33 | 34 | #include 35 | using namespace std; 36 | 37 | int clearAllBits(int n, int i){ 38 | 39 | if(i == 0){ 40 | return 0; 41 | } 42 | int a = (1 << i); 43 | int b = a-1; 44 | int ans = n & b; 45 | return ans; 46 | } 47 | 48 | int main() { 49 | int n, i; 50 | 51 | cin >> n >> i; 52 | 53 | cout<< clearAllBits(n, i) < 18 | using namespace std; 19 | 20 | #include 21 | int returnFirstSetBit(int n){ 22 | int i=0; 23 | if(n == 0){ 24 | return 0; 25 | } 26 | while(1){ 27 | if((n & (1 << i)) == 0 ){ 28 | i++; 29 | }else{ 30 | return pow(2,i); 31 | } 32 | } 33 | } 34 | 35 | 36 | 37 | int main() { 38 | int n; 39 | 40 | cin >> n; 41 | 42 | cout<< returnFirstSetBit(n) < 20 | using namespace std; 21 | 22 | int turnOnIthBit(int n, int i){ 23 | /* Don't write main(). 24 | * Don't read input, it is passed as function argument. 25 | * Return output and don't print it. 26 | * Taking input and printing output is handled automatically. 27 | */ 28 | int z; 29 | z = n | (1 << i); 30 | return z; 31 | } 32 | 33 | 34 | 35 | int main() { 36 | int n, i; 37 | 38 | cin >> n >> i; 39 | 40 | cout<< turnOnIthBit(n, i) < 19 | using namespace std; 20 | 21 | #include 22 | int turnOffFirstSetBit(int n){ 23 | 24 | if(n == 0){ 25 | return 0; 26 | } 27 | if((n & n-1) == 0){ 28 | return 0; 29 | } 30 | int i=0; 31 | while(1){ 32 | 33 | if((n & (1 << i)) == 0){ 34 | i++; 35 | }else{ 36 | int z; 37 | z = n^(1 << i); 38 | return z; 39 | 40 | } 41 | } 42 | // int i=0; 43 | // while((n & (1<> n; 55 | 56 | cout<< turnOffFirstSetBit(n) < 21 | using namespace std; 22 | 23 | int turnOffIthBit(int n, int i){ 24 | 25 | int z ; 26 | z = n & ~(1 << i); 27 | return z; 28 | 29 | } 30 | 31 | 32 | 33 | int main() { 34 | int n, i; 35 | 36 | cin >> n >> i; 37 | 38 | cout<< turnOffIthBit(n, i) < 27 | using namespace std; 28 | 29 | int main(){ 30 | int n,i; 31 | cin >> n >> i; 32 | int a = (1 << i+1); 33 | int b = a-1; 34 | int c = ~b; 35 | int ans = n & c; 36 | cout << ans << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Bit manipulation/flip_ith_bit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 14 : 1110 ; flipbit = 2 3 | 1110 ^ 0100 = 1010 4 | (14,2) = 10 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int n; 12 | cin >> n; 13 | int i; 14 | cin >> i; 15 | int z; 16 | z = n ^ (1 << i); 17 | cout << z << endl; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Bit manipulation/powerof2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 8 : 1000 3 | 7 : 0111 4 | 8 & 7 : 0000 5 | power of two 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | int main(){ 12 | int n; 13 | cin >> n; 14 | if((n & n-1) == 0){ 15 | cout << "Yes" << endl; 16 | }else{ 17 | cout << "No" << endl; 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Arrays : Minimum number of increment-other operations to make all array elements equal.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | We are given an array consisting of n elements. At each operation you can select any one element 4 | and increase rest of n-1 elements by 1. You have to make all elements equal performing 5 | such operation as many times you wish. Find the minimum number of operations needed for this. 6 | 7 | 8 | Input : arr[] = {1, 2, 3} 9 | Output : Minimum Operation = 3 10 | Explanation : 11 | operation | increased elements | after increment 12 | 1 | 1, 2 | 2, 3, 3 13 | 2 | 1, 2 | 3, 4, 3 14 | 3 | 1, 3 | 4, 4, 4 15 | 16 | 17 | Input : arr[] = {4, 3, 4} 18 | Output : Minimum Operation = 2 19 | Explanation : 20 | operation | increased elements | after increment 21 | 1 | 1, 2 | 5, 4, 4 22 | 2 | 2, 3 | 5, 5, 5 23 | 24 | 25 | 26 | Brute force : A simple way to make all elements equal is that at each step find the largest elements 27 | and then increase all rest n-1 elements by 1. We should keep doing this operation till all 28 | elements become equal. Time Complexity : O(n^2) 29 | */ 30 | 31 | #include 32 | using namespace std; 33 | 34 | /* 35 | approach : 36 | O(N^2) 37 | 38 | loop 39 | select largest element from array 40 | increment all other element except larger element 41 | do this until all elements equal 42 | end loop 43 | 44 | O(N) 45 | 46 | if we think in reverse direction 47 | above approach is equivalent to 48 | selecting smaller element from array , reducing all other element to this value 49 | 50 | */ 51 | int main(){ 52 | int n; 53 | cin >> n; 54 | vector arr(n); 55 | for(int i=0;i> arr[i]; 57 | } 58 | int mini = INT_MAX; 59 | for(int i=0;i &nums,int start,vector> &res){ 11 | if(start == nums.size()){ 12 | res.push_back(nums); 13 | return; 14 | } 15 | 16 | for(int i=start;i> permute(vector& nums) { 25 | vector> res; 26 | int start = 0; 27 | helper(nums,start,res); 28 | return res; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Backtracking : Rat in maze.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print(int** sol,int n) 5 | { 6 | for(int i=0;i= n || col >= n || row < 0 || col < 0 || arr[row][col] == 0 || sol[row][col]){ 17 | return false; 18 | } 19 | return true; 20 | } 21 | 22 | 23 | 24 | bool helper(int** arr,int** &sol,int row,int col,int n) 25 | { 26 | 27 | if(row == n-1 && col == n-1){ 28 | sol[row][col] = 1; 29 | print(sol,n); 30 | return true; 31 | } 32 | 33 | if(isSafe(row,col,n,arr,sol)){ 34 | sol[row][col] = 1; 35 | if(helper(arr,sol,row+1,col,n)){ 36 | return true; 37 | } 38 | if(helper(arr,sol,row,col+1,n)){ 39 | return true; 40 | } 41 | sol[row][col] = 0; 42 | return false; 43 | } 44 | return false; 45 | 46 | } 47 | 48 | int main() 49 | { 50 | int n; 51 | cin >> n; 52 | int** arr = new int*[n]; 53 | for(int i=0;i> arr[i][j]; 59 | } 60 | } 61 | int** sol = new int*[n]; 62 | for(int i=0;i 2 | using namespace std; 3 | vector> ans; 4 | 5 | 6 | //RECURSION 7 | int helper(vector &arr,int start,int n,int k) 8 | { 9 | if(start == n){ 10 | if(k==0){ 11 | return 1; 12 | } 13 | return 0; 14 | } 15 | 16 | if(k < 0){ 17 | return 0; 18 | } 19 | 20 | if(k == 0){ 21 | return 1; 22 | } 23 | 24 | int count = 0; 25 | count += helper(arr,start+1,n,k); 26 | count += helper(arr,start+1,n,k-arr[start]); 27 | return count; 28 | 29 | } 30 | 31 | 32 | 33 | //DP 34 | int helper(vector arr,int start,int n,int k){ 35 | int** dp = new int*[n+1]; 36 | for(int i=0;i<=n;i++){ 37 | dp[i] = new int[k+1]; 38 | } 39 | 40 | for(int i=0;i<=n;i++){ 41 | dp[i][0] = 1; 42 | } 43 | 44 | for(int i=1;i<=k;i++){ 45 | dp[0][i] = 0; 46 | } 47 | 48 | for(int i=1;i<=n;i++){ 49 | for(int j=1;j<=k;j++){ 50 | if(j-arr[i-1] >=0){ 51 | dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]]; 52 | }else{ 53 | dp[i][j] = dp[i-1][j]; 54 | } 55 | } 56 | } 57 | 58 | return dp[n][k]; 59 | } 60 | 61 | 62 | int main(){ 63 | 64 | // write your code here 65 | int t; 66 | cin>>t; 67 | while(t--){ 68 | int n; 69 | cin >> n; 70 | int k; 71 | cin >> k; 72 | vector arr; 73 | for(int i=0;i> temp; 76 | arr.push_back(temp); 77 | } 78 | cout << helper(arr,0,n,k) << endl; 79 | } 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary Search : Search in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There is an integer array nums sorted in ascending order (with distinct values). 3 | 4 | Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., 5 | nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. 6 | 7 | Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 8 | 9 | You must write an algorithm with O(log n) runtime complexity. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: nums = [4,5,6,7,0,1,2], target = 0 16 | Output: 4 17 | Example 2: 18 | 19 | Input: nums = [4,5,6,7,0,1,2], target = 3 20 | Output: -1 21 | Example 3: 22 | 23 | Input: nums = [1], target = 0 24 | Output: -1 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= nums.length <= 5000 30 | -104 <= nums[i] <= 104 31 | All values of nums are unique. 32 | nums is guaranteed to be rotated at some pivot. 33 | -104 <= target <= 104 34 | */ 35 | 36 | class Solution { 37 | public: 38 | int search(vector& arr, int target) { 39 | int n = arr.size(); 40 | int start = 0; 41 | int end= n-1; 42 | int idx = -1; 43 | while(start<=end){ 44 | int mid = (start+end)/2; 45 | if(arr[mid] == target){ 46 | idx = mid; 47 | return idx; 48 | }else if(arr[start] <= arr[mid]){ 49 | if( target <= arr[mid] && target >= arr[start]){ 50 | end = mid-1; 51 | }else{ 52 | start = mid+1; 53 | } 54 | }else{ 55 | if(target >= arr[mid] && target <= arr[end]){ 56 | start = mid+1; 57 | }else{ 58 | end = mid-1; 59 | } 60 | } 61 | } 62 | 63 | return idx; 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary Search : Find Smallest Letter Greater Than Target.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target. 3 | 4 | Note that the letters wrap around. 5 | 6 | For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'. 7 | 8 | 9 | Example 1: 10 | 11 | Input: letters = ["c","f","j"], target = "a" 12 | Output: "c" 13 | Example 2: 14 | 15 | Input: letters = ["c","f","j"], target = "c" 16 | Output: "f" 17 | Example 3: 18 | 19 | Input: letters = ["c","f","j"], target = "d" 20 | Output: "f" 21 | Example 4: 22 | 23 | Input: letters = ["c","f","j"], target = "g" 24 | Output: "j" 25 | Example 5: 26 | 27 | Input: letters = ["c","f","j"], target = "j" 28 | Output: "c" 29 | 30 | 31 | Constraints: 32 | 33 | 2 <= letters.length <= 104 34 | letters[i] is a lowercase English letter. 35 | letters is sorted in non-decreasing order. 36 | letters contains at least two different characters. 37 | target is a lowercase English letter. 38 | */ 39 | 40 | class Solution { 41 | public: 42 | char nextGreatestLetter(vector& arr, char target) { 43 | int n = arr.size(); 44 | int start = 0; 45 | int end = n-1; 46 | int ans = -1; 47 | while(start<=end){ 48 | int mid = (start+end)/2; 49 | if(arr[mid] > target){ 50 | ans = arr[mid]; 51 | end = mid-1; 52 | }else{ 53 | start = mid+1; 54 | } 55 | } 56 | 57 | if(ans == -1){ //if target is last element in array , wrap it 58 | ans = arr[0]; 59 | } 60 | 61 | return (char)ans; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary Search : Find minimum absolute difference in sorted array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | /* 6 | Find minimum absolute difference element in given array 7 | 8 | given array [1,3,5,8,9] and key = 7 9 | answer = 8 - 7 = 1 10 | 11 | if key = 8 then ans = 8 - 8 = 0 12 | 13 | */ 14 | 15 | 16 | //find two elements between which key lies and take one one with less diff in neighbours 17 | //in binary search at last after loops breaks ,start and end are pointing to neighbours of key (end < key and start > key) 18 | 19 | 20 | void binary_search(int* arr,int start,int end,int key,int n) 21 | { 22 | int ans = -1; 23 | while(start<=end){ 24 | int mid = (start+end)/2; 25 | if(arr[mid] == key){ 26 | ans = 0; 27 | break; 28 | }else if(arr[mid] > key){ 29 | end = mid - 1; 30 | }else{ 31 | start = mid+1; 32 | } 33 | } 34 | if(ans == -1){ 35 | cout << min(abs(arr[start] - key) , abs(arr[end] - key)) << endl; 36 | }else{ 37 | cout << 0 << endl; 38 | } 39 | return; 40 | } 41 | 42 | int main() 43 | { 44 | int n; 45 | cin >> n; 46 | int* arr = new int[n]; 47 | for(int i=0;i> arr[i]; 49 | } 50 | int key; 51 | cout << "enter key" << endl; 52 | cin >> key; 53 | binary_search(arr,0,n-1,key,n); 54 | return 0; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary Search : Floor in a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | Given a sorted array and a value x, the floor of x is the largest element in array smaller than or equal to x. Write efficient functions to find floor of x. 5 | Examples: 6 | 7 | 8 | Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 5 9 | Output : 2 10 | 2 is the largest element in 11 | arr[] smaller than 5. 12 | 13 | Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 20 14 | Output : 19 15 | 19 is the largest element in 16 | arr[] smaller than 20. 17 | 18 | Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 0 19 | Output : -1 20 | Since floor doesn't exist, 21 | output is -1. 22 | */ 23 | 24 | 25 | 26 | #include 27 | using namespace std; 28 | 29 | void binary_search(int* arr,int start,int end,int key,int n) 30 | { 31 | int floor = -1; 32 | while(start <= end){ 33 | int mid = (start+end)/2; 34 | if(arr[mid] == key){ 35 | floor = arr[mid]; 36 | break; 37 | }else if(arr[mid] < key){ 38 | floor = arr[mid]; 39 | start = mid+1; 40 | }else{ 41 | end = mid-1; 42 | } 43 | } 44 | 45 | cout << "floor of element " << floor << endl; 46 | } 47 | 48 | int main() 49 | { 50 | int n; 51 | cin >> n; 52 | int* arr = new int[n]; 53 | for(int i=0;i> arr[i]; 55 | } 56 | int key; 57 | cout << "enter key" << endl; 58 | cin >> key; 59 | binary_search(arr,0,n-1,key,n); 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary Search : Search in an almost sorted array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., 3 | arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. 4 | Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1]. 5 | 6 | For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position. 7 | 8 | Example : 9 | 10 | Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40 11 | Output: 2 12 | Output is index of 40 in given array 13 | 14 | Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90 15 | Output: -1 16 | -1 is returned to indicate element is not present 17 | 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | 23 | void binary_search(int* arr,int start,int end,int key,int n) 24 | { 25 | int idx = -1; 26 | while(start <= end){ 27 | int mid = (start+end)/2; 28 | if(arr[mid] == key){ 29 | idx = mid; 30 | break; 31 | }else if(mid+1 < n && arr[mid+1] == key){ 32 | idx = mid+1; 33 | break; 34 | }else if(mid-1 > 0 && arr[mid-1] == key){ 35 | idx = mid-1; 36 | break; 37 | }else if(key <= arr[mid]){ 38 | end = mid-2; 39 | }else{ 40 | start = mid+2; 41 | } 42 | } 43 | 44 | if(idx == -1){ 45 | cout << "not found" << endl; 46 | }else{ 47 | cout << "present at index " << idx << endl; 48 | } 49 | 50 | 51 | } 52 | 53 | int main() 54 | { 55 | int n; 56 | cin >> n; 57 | int* arr = new int[n]; 58 | for(int i=0;i> arr[i]; 60 | } 61 | int key; 62 | cout << "enter key" << endl; 63 | cin >> key; 64 | binary_search(arr,0,n-1,key,n); 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary search : Find maximum element in Bitonic Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array arr of n elements which is first increasing and then may be decreasing, find the maximum element in the array. 3 | Note: If the array is increasing then just print then last element will be the maximum value. 4 | 5 | Example 1: 6 | 7 | Input: 8 | n = 9 9 | arr[] = {1,15,25,45,42,21,17,12,11} 10 | Output: 45 11 | Explanation: Maximum element is 45. 12 | Example 2: 13 | 14 | Input: 15 | n = 5 16 | arr[] = {1, 45, 47, 50, 5} 17 | Output: 50 18 | Explanation: Maximum element is 50. 19 | Your Task: 20 | You don't need to read input or print anything. Your task is to complete the function findMaximum() which takes the array arr[], 21 | and n as parameters and returns an integer denoting the answer. 22 | 23 | Expected Time Complexity: O(logn) 24 | Expected Auxiliary Space: O(1) 25 | 26 | Constraints: 27 | 3 ≤ n ≤ 106 28 | 1 ≤ arri ≤ 106 29 | 30 | */ 31 | 32 | 33 | class Solution{ 34 | public: 35 | 36 | int findMaximum(int arr[], int n) { 37 | // code here 38 | int start = 0; 39 | int end = n-1; 40 | int ans = -1; 41 | while(start <= end){ 42 | int mid = (start+end)/2; 43 | int left = mid-1; 44 | int right = mid+1; 45 | int leftval,rightval; 46 | if(right >= n){ 47 | rightval = INT_MIN; 48 | }else{ 49 | rightval = arr[right]; 50 | } 51 | if(left < 0){ 52 | leftval = INT_MIN; 53 | }else{ 54 | leftval = arr[left]; 55 | } 56 | 57 | if(arr[mid] > leftval and arr[mid] > rightval){ 58 | return arr[mid]; 59 | }else if(arr[mid] > rightval){ 60 | end = mid-1; 61 | }else{ 62 | start = mid+1; 63 | } 64 | 65 | } 66 | 67 | return ans; 68 | } 69 | }; 70 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Binary search : Minimum removals from array to make max – min <= K.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given N integers and K, find the minimum number of elements that should be removed, such that Amax-Amin<=K. 3 | After the removal of elements, Amax and Amin is considered among the remaining elements 4 | 5 | 6 | Input : a[] = {1, 3, 4, 9, 10, 11, 12, 17, 20} 7 | k = 4 8 | Output : 5 9 | Explanation: Remove 1, 3, 4 from beginning 10 | and 17, 20 from the end. 11 | 12 | Input : a[] = {1, 5, 6, 2, 8} K=2 13 | Output : 3 14 | Explanation: There are multiple ways to 15 | remove elements in this case. 16 | One among them is to remove 5, 6, 8. 17 | The other is to remove 1, 2, 5 18 | */ 19 | 20 | 21 | #include 22 | using namespace std; 23 | 24 | int helper(vector &arr,int start,int end,int key,int k){ 25 | int idx = end; 26 | while(start <= end){ 27 | int mid = (start+end)/2; 28 | if(arr[mid]-key <= k){ 29 | idx = mid; 30 | start = mid+1; 31 | }else{ 32 | end = mid-1; 33 | } 34 | } 35 | return idx; 36 | } 37 | 38 | int main(){ 39 | int n,k; 40 | cin >> n >> k; 41 | vector arr(n); 42 | for(int i=0;i> arr[i]; 44 | } 45 | //consider each element as minimum element find in the right half of array such that arr[i] - arr[index] <= k 46 | sort(arr.begin(),arr.end()); 47 | vector dp(n,0); 48 | int mini = INT_MAX; 49 | for(int i=0;i 5 | using namespace std; 6 | class node{ 7 | public: 8 | int data; 9 | node* left; 10 | node* right; 11 | node(int data){ 12 | this->data = data; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | 19 | //construct Height balanced BST from sorted array 20 | 21 | node* constructBST(int arr[],int start,int end) 22 | { 23 | if(start > end){ 24 | return NULL; 25 | } 26 | int mid = (start+end)/2; 27 | node* root = new node(arr[mid]); 28 | root->left = constructBST(arr,start,mid-1); 29 | root->right = constructBST(arr,mid+1,end); 30 | 31 | return root; 32 | } 33 | 34 | void inorder(node* root) 35 | { 36 | if(root == NULL){ 37 | return; 38 | } 39 | inorder(root->left); 40 | cout << root->data << " "; 41 | inorder(root->right); 42 | } 43 | 44 | void preorder(node* root) 45 | { 46 | if(root == NULL){ 47 | return; 48 | } 49 | 50 | cout << root->data << " "; 51 | preorder(root->left); 52 | preorder(root->right); 53 | 54 | } 55 | 56 | int main() 57 | { 58 | node* root = NULL; 59 | int arr[6]= {1,2,3,4,5,6}; 60 | cout << "Height Balanced tree : " << endl; 61 | root = constructBST(arr,0,5); 62 | cout << "Inorder traversal" << endl; 63 | inorder(root); 64 | 65 | cout << "preorder traversal" << endl; 66 | preorder(root); 67 | return 0; 68 | } 69 | 70 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Count number of binary strings without consecutive 1’s.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s. 4 | Eg 5 | 6 | Input: N = 2 7 | Output: 3 8 | // The 3 strings are 00, 01, 10 9 | 10 | Input: N = 3 11 | Output: 5 12 | // The 5 strings are 000, 001, 010, 100, 101 13 | 14 | 15 | APPROACH : 16 | Let a[i] be the number of binary strings of length i which do not contain any two consecutive 1’s and which end in 0. 17 | Similarly, let b[i] be the number of such strings which end in 1. 18 | 19 | Note : We can append either 0 or 1 to a string ending in 0, 20 | but we can only append 0 to a string ending in 1. 21 | 22 | */ 23 | #include 24 | using namespace std; 25 | 26 | int countStrings(int n) 27 | { 28 | int* dp1 = new int[n](); 29 | int* dp2 = new int[n](); 30 | dp1[0] = 1; //number of binary strings with length of i which ends with 0 31 | dp2[0] = 1; // number of binary strings of length of i which ends with 1 32 | 33 | for(int i=1;i 21 | using namespace std; 22 | 23 | int main(){ 24 | int n,x,y; 25 | cin >> n >> x >> y; 26 | 27 | vector dp(n+1,false); 28 | 29 | dp[0] = false;//given that if player didnt collect any point , he is loser 30 | dp[1] = true;//player A can always make 1 move 31 | 32 | //dp[i] : wether player can win till 'i' 33 | 34 | //if player A lose at any of the dp[i-1] or dp[i-x] or dp[i-y] then definetely he wins at i 35 | //since both are playing optimally "B" would have chosen that move in which dp[i-1] or dp[i-x] or dp[i-y] is false 36 | 37 | for(int i=2;i<=n;i++){ 38 | if(i-1 >= 0 and !dp[i-1]){ 39 | dp[i] = true; 40 | }else if(i-x >=0 and !dp[i-x]){ 41 | dp[i-x] = true; 42 | }else if(i-y >=0 and !dp[i-y]){ 43 | dp[i-y] = true; 44 | } 45 | } 46 | 47 | cout << "winner " << endl; 48 | if(dp[n]){ 49 | cout << "A"; 50 | }else{ 51 | cout << "B"; 52 | } 53 | return 0; 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/DP : Partition Equal Subset Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both 3 | subsets is equal. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [1,5,11,5] 10 | Output: true 11 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 12 | Example 2: 13 | 14 | Input: nums = [1,2,3,5] 15 | Output: false 16 | Explanation: The array cannot be partitioned into equal sum subsets. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= nums.length <= 200 22 | 1 <= nums[i] <= 100 23 | */ 24 | 25 | class Solution { 26 | public: 27 | bool canPartition(vector& nums) { 28 | int sum = 0; 29 | int n = nums.size(); 30 | for(int i=0;i= nums[i-1]){ 54 | dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i-1]]; 55 | }else{ 56 | dp[i][j] = dp[i-1][j]; 57 | } 58 | } 59 | } 60 | 61 | return dp[n][w]; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : number of subsequences having product smaller than or equal to K..cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive array, find the number of subsequences having product smaller than or equal to K. 3 | Examples: 4 | 5 | 6 | Input : [1, 2, 3, 4] 7 | k = 10 8 | Output :11 9 | The subsequences are {1}, {2}, {3}, {4}, 10 | {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, 11 | {1, 2, 3}, {1, 2, 4} 12 | 13 | Input : [4, 8, 7, 2] 14 | k = 50 15 | Output : 9 16 | */ 17 | 18 | #include 19 | using namespace std; 20 | 21 | int main(){ 22 | int n; 23 | cin >> n; 24 | vector arr(n); 25 | for(int i=0;i> arr[i]; 27 | } 28 | int k; 29 | cin >> k; 30 | 31 | vector> dp(n+1,vector(k+1,0)); 32 | 33 | for(int i=1;i<=n;i++){ 34 | for(int j=1;j<=k;j++){ 35 | if(arr[i-1] <= j){ 36 | dp[i][j] = dp[i-1][j] + dp[i-1][j/arr[i-1]] + 1; //+1 since current element alone can make a subsequence 37 | }else{ 38 | dp[i][j] = dp[i-1][j]; 39 | } 40 | } 41 | } 42 | cout << dp[n][k] << endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Count common subsequence in two strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | To find the number of common subsequences in two string, say S and T, 3 | we use Dynamic Programming by defining a 2D array dp[][], 4 | where dp[i][j] is the number of common subsequences in the string S[0…i-1] and T[0….j-1]. 5 | Now, we can define dp[i][j] as 6 | = dp[i][j-1] + dp[i-1][j] + 1, when S[i-1] is equal to T[j-1] 7 | This is because when S[i-1] == S[j-1], using the above fact all the previous 8 | common sub-sequences are doubled as they get appended by one more character. 9 | Both dp[i][j-1] and dp[i-1][j] contain dp[i-1][j-1] and 10 | hence it gets added two times in our recurrence which takes care of 11 | doubling of count of all previous common sub-sequences. 12 | Addition of 1 in recurrence is for the latest character match : 13 | common sub-sequence made up of s1[i-1] and s2[j-1] 14 | = dp[i-1][j] + dp[i][j-1] – dp[i-1][j-1], when S[i-1] is not equal to T[j-1] 15 | Here we subtract dp[i-1][j-1] once because it is present in both dp[i][j – 1] and dp[i – 1][j] 16 | and gets added twice. 17 | */ 18 | #include 19 | using namespace std; 20 | 21 | int main(){ 22 | string str1,str2; 23 | cin >> str1 >> str2; 24 | vector> dp(str1.size()+1,vector(str2.size()+1,0)); 25 | 26 | 27 | //dp[i-1][j] contains dp[i-1][j-1] and dp[i][j-1] also contains dp[i-1][j-1] 28 | for(int i=1;i<=str1.length();i++){ 29 | for(int j=1;j<=str2.length();j++){ 30 | if(str1[i-1] == str2[j-1]){ //all prev counts are doubled (dont explicity double dp[i-1][j-1] as they are included in dp[i-1][j] and dp[i][j-1]) 31 | dp[i][j] = 1 + dp[i-1][j] + dp[i][j-1]; // 1 + 2*dp[i-1][j-1] + dp[i-1][j] + dp[i][j-1] - 2*dp[i-1][j-1] 32 | }else{ 33 | dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1];//dp[i-1][j-1] added two times , hence subtracting 34 | } 35 | } 36 | } 37 | cout << dp[str1.length()][str2.length()]; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Count of subsets with sum equal to X.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X. 3 | 4 | Examples: 5 | 6 | Input: arr[] = {1, 2, 3, 3}, X = 6 7 | Output: 3 8 | All the possible subsets are {1, 2, 3}, 9 | {1, 2, 3} and {3, 3} 10 | 11 | 12 | Input: arr[] = {1, 1, 1, 1}, X = 1 13 | Output: 4 14 | */ 15 | 16 | 17 | //count all subsets with given sum 18 | #include 19 | using namespace std; 20 | int main() 21 | { 22 | int n; 23 | cin >> n; 24 | int sum; 25 | cin >> sum; 26 | int* arr = new int[n]; 27 | for(int i=0;i> arr[i]; 29 | } 30 | 31 | int** dp = new int*[n+1]; 32 | for(int i=0;i<=n;i++){ 33 | dp[i] = new int[sum+1]; 34 | for(int j=0;j<=sum;j++){ 35 | dp[i][j] = 0; 36 | } 37 | } 38 | 39 | for(int i=0;i<=n;i++){ 40 | dp[i][0] = 1; 41 | } 42 | 43 | for(int i=1;i<=n;i++){ 44 | for(int j=1;j<=sum;j++){ 45 | if(j >= arr[i-1]){ 46 | dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]]; 47 | }else{ 48 | dp[i][j] = dp[i-1][j]; 49 | } 50 | } 51 | } 52 | 53 | 54 | cout << dp[n][sum] << endl; 55 | } 56 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Edit distance.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. 4 | 5 | You have the following three operations permitted on a word: 6 | 7 | Insert a character 8 | Delete a character 9 | Replace a character 10 | 11 | 12 | Example 1: 13 | 14 | Input: word1 = "horse", word2 = "ros" 15 | Output: 3 16 | Explanation: 17 | horse -> rorse (replace 'h' with 'r') 18 | rorse -> rose (remove 'r') 19 | rose -> ros (remove 'e') 20 | Example 2: 21 | 22 | Input: word1 = "intention", word2 = "execution" 23 | Output: 5 24 | Explanation: 25 | intention -> inention (remove 't') 26 | inention -> enention (replace 'i' with 'e') 27 | enention -> exention (replace 'n' with 'x') 28 | exention -> exection (replace 'n' with 'c') 29 | exection -> execution (insert 'u') 30 | 31 | 32 | Constraints: 33 | 34 | 0 <= word1.length, word2.length <= 500 35 | word1 and word2 consist of lowercase English letters. 36 | 37 | */ 38 | 39 | class Solution { 40 | public: 41 | int minDistance(string word1, string word2) { 42 | int n1 = word1.length(); 43 | int n2 = word2.length(); 44 | int** dp = new int*[n1+1]; 45 | for(int i=0;i<=n1;i++){ 46 | dp[i] = new int[n2+1]; 47 | for(int j=0;j<=n2;j++){ 48 | dp[i][j] = 0; 49 | } 50 | } 51 | 52 | for(int i=1;i<=n1;i++){ 53 | dp[i][0] = i; 54 | } 55 | 56 | for(int i=1;i<=n2;i++){ 57 | dp[0][i] = i; 58 | } 59 | 60 | for(int i=1;i<=n1;i++){ 61 | for(int j=1;j<=n2;j++){ 62 | if(word1[i-1] == word2[j-1]){ 63 | dp[i][j] = dp[i-1][j-1]; 64 | }else{ 65 | dp[i][j] = min({1 + dp[i][j-1] , 1 + dp[i-1][j] , 1 + dp[i-1][j-1]}); //delete , insert , replace 66 | } 67 | } 68 | } 69 | 70 | return dp[n1][n2]; 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Longest Palindromic Subsequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given a string s, find the longest palindromic subsequence's length in s. 4 | 5 | A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "bbbab" 12 | Output: 4 13 | Explanation: One possible longest palindromic subsequence is "bbbb". 14 | Example 2: 15 | 16 | Input: s = "cbbd" 17 | Output: 2 18 | Explanation: One possible longest palindromic subsequence is "bb". 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= s.length <= 1000 24 | s consists only of lowercase English letters. 25 | Accepted 26 | 181.9K 27 | Submissions 28 | 320.7K 29 | */ 30 | //example : s = "abccbe" , (reverse of s ) t = "ebccba" LCS = "bccb" 31 | class Solution { 32 | public: 33 | //finding LCS from given string and its reverse (since palindrome reads same fron both ends , hence its LCS) 34 | int longestPalindromeSubseq(string s) { 35 | int n = s.length(); 36 | string t = s; 37 | reverse(s.begin(),s.end()); 38 | int** dp = new int*[n+1]; 39 | for(int i=0;i<=n;i++){ 40 | dp[i] = new int[n+1]; 41 | } 42 | 43 | for(int i=0;i<=n;i++){ 44 | dp[i][0] = 0; 45 | } 46 | for(int i=0;i<=n;i++){ 47 | dp[0][i] = 0; 48 | } 49 | 50 | for(int i=1;i<=n;i++){ 51 | for(int j=1;j<=n;j++){ 52 | if(s[i-1] == t[j-1]){ 53 | dp[i][j] = 1 + dp[i-1][j-1]; 54 | }else{ 55 | dp[i][j] = max(dp[i-1][j] , dp[i][j-1]); 56 | } 57 | } 58 | } 59 | 60 | return dp[n][n]; 61 | 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Longest repeating subsequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /* 5 | Given a string, find the length of the longest repeating subsequence such that the two subsequences don’t have same 6 | string character at the same position, i.e., any i’th character in the two subsequences shouldn’t have the same index in the 7 | original string. 8 | 9 | example : aabebcdd 10 | longest repeating subsequence is "abd" 11 | 12 | contraint : every character in original string can be used atmost one time in two subsequence 13 | 14 | s1 = aabebcdd 15 | s2 = aabebcdd 16 | 17 | 18 | example 2 : abccab 19 | ans : ab 20 | */ 21 | 22 | #include 23 | using namespace std; 24 | 25 | 26 | string getLRS(string s) 27 | { 28 | int n = s.length(); 29 | string** dp = new string*[n+1]; 30 | for(int i=0;i<=n;i++){ 31 | dp[i] = new string[n+1]; 32 | for(int j=0;j<=n;j++){ 33 | dp[i][j] = ""; 34 | } 35 | } 36 | 37 | for(int i=1;i<=n;i++){ 38 | for(int j=1;j<=n;j++){ 39 | if(s[i-1] == s[j-1] && i != j){ //using same characters in two subsequence is not allowed 40 | dp[i][j] = dp[i-1][j-1] + s[i-1]; 41 | }else{ 42 | dp[i][j] = dp[i-1][j].length() > dp[i][j-1].length() ? dp[i-1][j] : dp[i][j-1]; 43 | } 44 | } 45 | } 46 | 47 | return dp[n][n]; 48 | } 49 | 50 | int main() 51 | { 52 | string s; 53 | cin >> s; 54 | string str = getLRS(s); 55 | cout << str << endl; 56 | } 57 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : MCM.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, 4 | but merely to decide in which order to perform the multiplications. 5 | We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, 6 | the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: 7 | 8 | (ABC)D = (AB)(CD) = A(BCD) = .... 9 | However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. 10 | For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then, 11 | 12 | (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations 13 | A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations./* 14 | */ 15 | #include 16 | using namespace std; 17 | 18 | int dp[100][100]; 19 | 20 | int helper(vector &arr,int start,int end){ 21 | if(start == end){//cost to multiply same matrix is 0 22 | return 0; 23 | } 24 | 25 | if(dp[start][end] != 0){ 26 | return dp[start][end]; 27 | } 28 | 29 | int ans = INT_MAX; 30 | for(int i=start;i> n; 40 | vector arr(n); 41 | for(int i=0;i> arr[i]; 43 | } 44 | 45 | cout << helper(arr,1,n-1); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Maximum subsequence sum such that no three are consecutive.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given a sequence of positive numbers, find the maximum sum that can be formed which has no three consecutive elements present. 4 | Examples : 5 | 6 | Input: arr[] = {1, 2, 3} 7 | Output: 5 8 | We can't take three of them, so answer is 9 | 2 + 3 = 5 10 | 11 | Input: arr[] = {3000, 2000, 1000, 3, 10} 12 | Output: 5013 13 | 3000 + 2000 + 3 + 10 = 5013 14 | */ 15 | 16 | 17 | #include 18 | using namespace std; 19 | 20 | int main(){ 21 | int n; 22 | cin >> n; 23 | vector arr(n); 24 | for(int i=0;i> arr[i]; 26 | } 27 | vector sum(n,0); 28 | sum[0] = arr[0]; 29 | sum[1] = arr[0] + arr[1]; 30 | sum[2] = max({arr[0] + arr[1] , arr[2] + arr[0] , arr[1] + arr[2]}); 31 | for(int i=3;i 8 | using namespace std; 9 | 10 | 11 | int main() 12 | { 13 | int n; 14 | cin >> n; 15 | int* arr = new int[n]; 16 | for(int i=0;i> arr[i]; 18 | } 19 | 20 | int* dp = new int[n]; 21 | for(int i=0;i=0;j--){ 28 | if(arr[j] < arr[i]){ 29 | dp[i] = max(dp[i] , dp[j]+arr[i]); 30 | } 31 | } 32 | } 33 | 34 | int maxi = -1; 35 | for(int i=0;i same(n+1,0); 16 | vector diff(n+1,0); 17 | const int mod = 1e9+7; 18 | same[2] = k; 19 | diff[2] = k*(k-1); 20 | for(int i=3;i<=n;i++){ 21 | same[i] = diff[i-1]%mod;//all prev different colors , we cant add prev n-1 same colors (given : at most 2 of same color) 22 | diff[i] = ( (diff[i-1] % mod + same[i-1] % mod) * (k-1) )%mod;//we can take all prev same and diff ways and add them with diff color ie (k-1) 23 | 24 | } 25 | return (same[n]%mod + diff[n]%mod)%mod; 26 | 27 | } 28 | }; 29 | 30 | /* 31 | n = 3 , k=2 (lets say red , blue) 32 | n = 1 , same = k ways = 2 (r,b) , diff = 0 33 | n = 2 , same = (rr,bb) = 2 , diff = (rb,br) = 2; 34 | n = 3 , same = (rb,br) * (k-1) = (rbr,brb) = 2 , diff = same + diff = (rr,bb)+(rb,br) = (rrb,bbr,rbr,brb) = 4 35 | total = 2 + 4 = 6 36 | */ 37 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Subset Sum Problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array A of size N. 3 | 4 | You are also given an integer B, you need to find whether their exist a subset in A whose sum equal B. 5 | 6 | If there exist a subset then return 1 else return 0. 7 | 8 | 9 | 10 | Problem Constraints 11 | 1 <= N <= 100 12 | 13 | 1 <= A[i] <= 100 14 | 15 | 1 <= B <= 105 16 | 17 | 18 | 19 | Input Format 20 | First argument is an integer array A. 21 | 22 | Second argument is an integer B. 23 | 24 | 25 | 26 | Output Format 27 | Return 1 if there exist a subset with sum B else return 0. 28 | 29 | 30 | 31 | Example Input 32 | Input 1: 33 | 34 | A = [3, 34, 4, 12, 5, 2] 35 | B = 9 36 | Input 2: 37 | 38 | A = [3, 34, 4, 12, 5, 2] 39 | B = 30 40 | 41 | 42 | Example Output 43 | Output 1: 44 | 45 | 1 46 | Output 2: 47 | 48 | 0 49 | 50 | 51 | Example Explanation 52 | Explanation 1: 53 | 54 | There is a subset (4, 5) with sum 9. 55 | Explanation 2: 56 | 57 | There is no subset that add up to 30. 58 | */ 59 | 60 | 61 | int Solution::solve(vector &A, int B) { 62 | int n =A.size(); 63 | bool** dp = new bool*[n+1]; 64 | for(int i=0;i<=n;i++){ 65 | dp[i] = new bool[B+1]; 66 | for(int j=0;j<=B;j++){ 67 | dp[i][j] = false; 68 | } 69 | } 70 | 71 | for(int i=0;i<=n;i++){ 72 | dp[i][0] = true; 73 | } 74 | 75 | for(int i=1;i<=n;i++){ 76 | for(int j=1;j<=B;j++){ 77 | if(j >= A[i-1]){ 78 | dp[i][j] = dp[i-1][j] || dp[i-1][j-A[i-1]];//include 79 | }else{ 80 | dp[i][j] = dp[i-1][j];//exclude 81 | } 82 | 83 | } 84 | } 85 | 86 | return dp[n][B]; 87 | } 88 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 12 | Output: 6 13 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 14 | Example 2: 15 | 16 | Input: height = [4,2,0,3,2,5] 17 | Output: 9 18 | 19 | 20 | Constraints: 21 | 22 | n == height.length 23 | 0 <= n <= 3 * 104 24 | 0 <= height[i] <= 105 25 | Accepted 26 | */ 27 | 28 | 29 | class Solution { 30 | public: 31 | int trap(vector& height) { 32 | int n = height.size(); 33 | if(n<=2){ 34 | return 0; 35 | } 36 | int* left = new int[n]; 37 | int* right = new int[n]; 38 | left[0] = 0; 39 | right[n-1] = 0; 40 | int left_max = height[0]; 41 | for(int i=1;i=0;i--){ 48 | right[i] = right_max; 49 | right_max =max(right_max,height[i]); 50 | } 51 | 52 | int ans = 0; 53 | for(int i=1;i > &A) { 19 | 20 | int m = A.size(); 21 | int n = A[0].size(); 22 | int** arr = new int*[m](); 23 | for(int i=0;i> A = { { 1, 0, 0 }, 68 | { 0, 1, 0 }, 69 | { 0, 0, 0 } }; 70 | 71 | 72 | cout << uniquePathsWithObstacles(A) << " \n"; 73 | } 74 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Dp : count number subsets S1 and S2 with given given difference.cpp: -------------------------------------------------------------------------------- 1 | //count number subsets S1 and S2 with given given difference "d" 2 | //similar as number of subsets with given sum = sum - diff 3 | 4 | /* 5 | approach 6 | 7 | s1 + s1 = sum; 8 | s1 - s2 = diff 9 | 10 | 2*s1 = sum + diff 11 | s1 = (sum + diff)/2; 12 | 13 | find the count of subsets with the the sum s1 14 | */ 15 | #include 16 | using namespace std; 17 | int main() 18 | { 19 | int n; 20 | cin >> n; 21 | int diff; 22 | cin >> diff; 23 | int* arr = new int[n]; 24 | int sum =0; 25 | for(int i=0;i> arr[i]; 27 | sum = sum + arr[i]; 28 | } 29 | 30 | sum = (sum + diff)/2; 31 | 32 | int** dp = new int*[n+1]; 33 | for(int i=0;i<=n;i++){ 34 | dp[i] = new int[sum+1]; 35 | for(int j=0;j<=sum;j++){ 36 | dp[i][j] = 0; 37 | } 38 | } 39 | 40 | for(int i=0;i<=n;i++){ 41 | dp[i][0] = 1; 42 | } 43 | 44 | for(int i=1;i<=n;i++){ 45 | for(int j=1;j<=sum;j++){ 46 | if(j >= arr[i-1]){ 47 | dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]]; 48 | }else{ 49 | dp[i][j] = dp[i-1][j]; 50 | } 51 | } 52 | } 53 | 54 | 55 | cout << dp[n][sum] << endl; 56 | } 57 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Graphs : Cycle detection in undirected graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //union find algorithm 5 | 6 | 7 | int getparent(int v,int* parent) 8 | { 9 | if(v == parent[v]){ 10 | return v; 11 | } 12 | return getparent(parent[v],parent); 13 | } 14 | 15 | int main() 16 | { 17 | int n,e; 18 | cin >> n >> e; 19 | int** arr = new int*[n](); 20 | for(int i=0;i> start >> end; 32 | int startParent = getparent(start,parent); 33 | int endParent = getparent(end,parent); 34 | if(startParent == endParent){ 35 | cout << "cycle detected" << endl; 36 | return 0; 37 | }else{ 38 | parent[endParent] = startParent; //make common parent 39 | } 40 | arr[start][end] = 1; 41 | arr[end][start] = 1; 42 | } 43 | 44 | cout << "No cycle detected" << endl; 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Graphs : Dijkstras single source shortest path.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getMinVertex(int* dist,int n,bool* visited) 5 | { 6 | int minVertex = -1; 7 | for(int i=0;i arr[minVertex][i] + distance[minVertex]){ 39 | distance[i] = distance[minVertex] + arr[minVertex][i]; 40 | parent[i] = minVertex; 41 | } 42 | } 43 | } 44 | } 45 | 46 | 47 | for(int i=0;i> n >> e; 58 | int** arr = new int*[n]; 59 | for(int i=0;i> start >> end >> cost; 69 | arr[start][end] = cost; 70 | arr[end][start] = cost; 71 | } 72 | bool* visited = new bool[n](); 73 | dijkstras(arr,n,0,visited); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Graphs : Prims algorithm for MST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getMinVertex(int* dist,int n,bool* visited) 5 | { 6 | int minVertex = -1; 7 | for(int i=0;i arr[minVertex][i]){ 42 | dist[i] = arr[minVertex][i]; 43 | parent[i] = minVertex; 44 | } 45 | } 46 | } 47 | } 48 | cout << "minimum spanning tree" << endl; 49 | for(int i=0;i> n >> e; 63 | int** arr = new int*[n]; 64 | for(int i=0;i> start >> end >> cost; 74 | arr[start][end] = cost; 75 | arr[end][start] = cost; 76 | } 77 | bool* visited = new bool[n](); 78 | prims(arr,n,e,visited); 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Hashmaps : Largest subarray with 0 sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0. 3 | 4 | Example 1: 5 | 6 | Input: 7 | N = 8 8 | A[] = {15,-2,2,-8,1,7,10,23} 9 | Output: 5 10 | Explanation: The largest subarray with 11 | sum 0 will be -2 2 -8 1 7. 12 | Your Task: 13 | You just have to complete the function maxLen() which takes two arguments an array A and n, 14 | where n is the size of the array A and returns the length of the largest subarray with 0 sum. 15 | 16 | Expected Time Complexity: O(N). 17 | Expected Auxiliary Space: O(N). 18 | 19 | Constraints: 20 | 1 <= N <= 105 21 | -1000 <= A[i] <= 1000, for each valid i 22 | */ 23 | 24 | int maxLen(int arr[], int n) 25 | { 26 | unordered_map m; 27 | int count = 0; 28 | int sum = 0; 29 | for(int i=0;i 23 | using namespace std; 24 | 25 | int main() 26 | { 27 | int n,k; 28 | cin >> n >> k; 29 | int* arr = new int[n]; 30 | for(int i=0;i> arr[i]; 32 | } 33 | int index = 0; 34 | priority_queue,greater> pq; 35 | for(int i=0;i& nums) { 45 | int slow = nums[0]; 46 | int fast = nums[0]; 47 | 48 | //detecting cycle in linked list approach 49 | do{ //using do-while since we intializing slow = fast = nums[0] initially 50 | slow = nums[slow]; 51 | fast = nums[nums[fast]]; 52 | }while(slow != fast); 53 | 54 | 55 | //set fast to nums[0] 56 | fast = nums[0]; 57 | 58 | if(slow == fast){ 59 | return slow; 60 | } 61 | 62 | while(slow != fast){ 63 | slow = nums[slow]; 64 | fast = nums[fast]; 65 | } 66 | return slow; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Merge Without Extra Space.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted arrays arr1[] and arr2[] of sizes n and m in non-decreasing order. Merge them in sorted order without using any extra space. 3 | Modify arr1 so that it contains the first N elements and modify arr2 so that it contains the last M elements. 4 | 5 | 6 | Example 1: 7 | 8 | Input: 9 | n = 4, arr1[] = [1 3 5 7] 10 | m = 5, arr2[] = [0 2 6 8 9] 11 | Output: 12 | arr1[] = [0 1 2 3] 13 | arr2[] = [5 6 7 8 9] 14 | Explanation: 15 | After merging the two 16 | non-decreasing arrays, we get, 17 | 0 1 2 3 5 6 7 8 9. 18 | Example 2: 19 | 20 | Input: 21 | n = 2, arr1[] = [10, 12] 22 | m = 3, arr2[] = [5 18 20] 23 | Output: 24 | arr1[] = [5 10] 25 | arr2[] = [12 18 20] 26 | Explanation: 27 | After merging two sorted arrays 28 | we get 5 10 12 18 20. 29 | 30 | 31 | Your Task: 32 | You don't need to read input or print anything. You only need to complete the function merge() that takes arr1, arr2, 33 | n and m as input parameters and modifies them in-place so that they look like the sorted merged array when concatenated. 34 | 35 | 36 | Expected Time Complexity: O((n+m) log(n+m)) 37 | Expected Auxilliary Space: O(1) 38 | 39 | 40 | Constraints: 41 | 1 <= n, m <= 5*104 42 | 0 <= arr1i, arr2i <= 107 43 | */ 44 | 45 | 46 | void merge(long long arr1[], long long arr2[], int n, int m) 47 | { 48 | int i = 0; 49 | int j = 0; 50 | int k = n-1; 51 | while(i < n && j < m){ 52 | if(arr1[i] <= arr2[j]){ 53 | i++; 54 | }else{//one of the element from first need to come to second array , and second array element has to go to first array 55 | swap(arr2[j],arr1[k]);//swap with last element from first array 56 | k--; 57 | j++; 58 | } 59 | } 60 | sort(arr1,arr1+n); 61 | sort(arr2,arr2+m); 62 | return; 63 | } 64 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Minimum cost to cover the given positions in a N*M grid.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a n*m grid and the position of some poles to be painted in the grid, the task is to find the minimum cost to paint all the poles. 4 | There is no cost involved in moving from the one row to the other, whereas moving to an adjacent column has 1 rupee cost associated with it. 5 | 6 | Examples: 7 | 8 | Input: n = 2, m = 2, noOfPos = 2 9 | pos[0] = 0, 0 10 | pos[1] = 0, 1 11 | 12 | Output: 1 13 | The grid is of 2*2 size and there are two poles at {0, 0} and {0, 1}. 14 | So we will start at {0, 0} and paint the pole and then go to 15 | the next column to paint the pole at {0, 1} position which will 16 | cost 1 rupee to move one column. 17 | 18 | Input: n = 2, m = 2, noOfPos = 2 19 | pos[0] = {0, 0} 20 | pos[1] = {1, 0} 21 | Output: 0 22 | Both poles are in the same column. So, no need to move to another column 23 | 24 | 25 | 26 | 27 | 28 | 29 | Approach: As there is the only cost of moving in columns therefore if we go to any column we will paint all the poles in that column and then move forward. 30 | So basically the answer will be the difference between the two farthest columns 31 | */ 32 | 33 | 34 | 35 | #include 36 | using namespace std; 37 | 38 | void find(int n,int m,int p,int q[][2]) 39 | { 40 | int maxCol = -1; 41 | int minCol = 10000; 42 | for(int i=0;i> dp(M+1,vector(V+1,0)); 46 | 47 | for(int i=1;i<=V;i++){//if no coins exist (make it as infinity) 48 | dp[0][i] = 10000; 49 | } 50 | 51 | for(int i=1;i<=M;i++){ 52 | for(int j=1;j<=V;j++){ 53 | if(j >= coins[i-1]){ 54 | dp[i][j] = min(1 + dp[i][j-coins[i-1]] , dp[i-1][j]); 55 | }else{ 56 | dp[i][j] = dp[i-1][j]; 57 | } 58 | } 59 | } 60 | 61 | return dp[M][V] == 10000 ? -1 : dp[M][V]; 62 | } 63 | 64 | }; 65 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Moores : Majority Element.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given an array nums of size n, return the majority element. 4 | 5 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [3,2,3] 12 | Output: 3 13 | Example 2: 14 | 15 | Input: nums = [2,2,1,1,1,2,2] 16 | Output: 2 17 | 18 | 19 | Constraints: 20 | 21 | n == nums.length 22 | 1 <= n <= 5 * 104 23 | -231 <= nums[i] <= 231 - 1 24 | 25 | 26 | Follow-up: Could you solve the problem in linear time and in O(1) space? 27 | */ 28 | 29 | 30 | //Moore Voting algorithm 31 | 32 | //It works because major element present more than (n/2) times , 33 | //worst case 1 : count never became zero 34 | //worst case 2 : major element present at alternate position , then last element should be major 35 | 36 | class Solution { 37 | public: 38 | int majorityElement(vector& nums) { 39 | int count = 1; 40 | int major = nums[0]; 41 | for(int i=1;i& nums) { 61 | map m; 62 | int n = nums.size(); 63 | for(int i=0;i> pq; 68 | for(auto i : m){ 69 | pq.push({i.second,i.first}); 70 | } 71 | return pq.top().second; 72 | } 73 | }; 74 | */ 75 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Queue : implementation using array.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #include 5 | using namespace std; 6 | #define size 5 7 | int count = 0; 8 | int front; 9 | int rear; 10 | int arr[size]; 11 | 12 | void push(int data){ 13 | if(count == size){ 14 | cout << "overflow" << endl; 15 | return; 16 | } 17 | arr[rear++] = data; 18 | rear = rear % size; 19 | count++; 20 | cout << "pushed " << count << endl; 21 | return; 22 | } 23 | 24 | void pop() 25 | { 26 | if(count == 0){ 27 | cout << "underflow" << endl; 28 | return; 29 | } 30 | front++; 31 | front = front % size; 32 | count--; 33 | cout << "popped " << count << endl; 34 | return; 35 | } 36 | 37 | void display() 38 | { 39 | if(count == 0){ 40 | cout << "underflow" << endl; 41 | return; 42 | } 43 | cout << "display" << endl; 44 | int idx = front; 45 | 46 | for(int i=0;i 2 | using namespace std; 3 | 4 | //SUBSETS IS SAME AS SUBSEQUENCES EXCEPT SUBSET HAS EMPTY STRING 5 | 6 | 7 | void helper(string str,vector &arr) 8 | { 9 | if(str.length() == 0){ 10 | arr.push_back(""); 11 | return; 12 | } 13 | 14 | helper(str.substr(1),arr); // "abc" : call for "bc" then add "a" to all subsequences keeping original values 15 | 16 | int temp = arr.size(); 17 | for(int i=0;i> str; 28 | int n = str.length(); 29 | vector arr; 30 | helper(str,arr); 31 | for(int i=0;i bc -> c -> "" 43 | 44 | ["","c","b","bc","a","ac","ab","abc"] <-- ["","c","b","bc"] <-- ["","c"] <-- "" 45 | 46 | */ 47 | 48 | 49 | 50 | 51 | //finding subsequences using bit manipulation 52 | 53 | // int main() 54 | // { 55 | // string str; 56 | // cin >> str; 57 | // int n = str.length(); 58 | // int size = (1< v; 60 | // for(int i=0;i m; 38 | int start = 0; 39 | int end = 0; 40 | int n = s.length(); 41 | int max_len = -1; 42 | while(end < n){ 43 | m[s[end]]++; 44 | 45 | if(m.size() == k){ 46 | max_len = max(max_len , end-start+1); 47 | }else if(m.size() > k){ //if number of unique chars are more , start removing elmeents from start 48 | while(m.size() > k){ 49 | m[s[start]]--; 50 | if(m[s[start]] == 0){ 51 | m.erase(s[start]); 52 | } 53 | start++; 54 | } 55 | } 56 | 57 | end++; 58 | } 59 | 60 | return max_len; 61 | 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Sliding window : Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, find the length of the longest substring without repeating characters. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: s = "abcabcbb" 9 | Output: 3 10 | Explanation: The answer is "abc", with the length of 3. 11 | Example 2: 12 | 13 | Input: s = "bbbbb" 14 | Output: 1 15 | Explanation: The answer is "b", with the length of 1. 16 | Example 3: 17 | 18 | Input: s = "pwwkew" 19 | Output: 3 20 | Explanation: The answer is "wke", with the length of 3. 21 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 22 | Example 4: 23 | 24 | Input: s = "" 25 | Output: 0 26 | 27 | 28 | Constraints: 29 | 30 | 0 <= s.length <= 5 * 104 31 | s consists of English letters, digits, symbols and spaces. 32 | */ 33 | 34 | class Solution { 35 | public: 36 | int lengthOfLongestSubstring(string s) { 37 | int n = s.length(); 38 | int start = 0; 39 | int end = 0; 40 | unordered_map m; 41 | int max_len = 0; 42 | while(end < n){ 43 | if(m.count(s[end]) == 0){ //char not present , add and update length 44 | m[s[end]]++; 45 | max_len = max(max_len , end-start+1); 46 | end++; 47 | }else{ //curr char is present already ,start poppping all chars from begining unitl previously occured current char is removed 48 | while(m.count(s[end]) != 0){ 49 | m.erase(s[start]); 50 | start++; 51 | } 52 | } 53 | } 54 | 55 | return max_len; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Sliding window : Max Sum Subarray of size K .cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: 9 | N = 4, K = 2 10 | Arr = [100, 200, 300, 400] 11 | Output: 12 | 700 13 | Explanation: 14 | Arr3 + Arr4 =700, 15 | which is maximum. 16 | 17 | 18 | Example 2: 19 | 20 | Input: 21 | N = 4, K = 4 22 | Arr = [100, 200, 300, 400] 23 | Output: 24 | 1000 25 | Explanation: 26 | Arr1 + Arr2 + Arr3 27 | + Arr4 =1000, 28 | which is maximum. 29 | 30 | 31 | Your Task: 32 | 33 | You don't need to read input or print anything. Your task is to complete the function maximumSumSubarray() which takes the integer k, vector Arr with size N, 34 | containing the elements of the array and returns the maximum sum of a subarray of size K. 35 | 36 | 37 | 38 | Expected Time Complexity: O(N) 39 | Expected Auxiliary Space: O(1) 40 | 41 | 42 | 43 | Constraints: 44 | 1<=N<=105 45 | 1<=K<=N 46 | */ 47 | 48 | 49 | class Solution{ 50 | public: 51 | int maximumSumSubarray(int K, vector &Arr , int N){ 52 | // code here 53 | int start = 0; 54 | int end = 0; 55 | int sum = 0; 56 | int max_sum = INT_MIN; 57 | while(end < N){ 58 | sum += Arr[end]; 59 | 60 | if(end-start+1 == K){ 61 | max_sum = max(max_sum , sum); 62 | sum -= Arr[start]; 63 | start++; 64 | } 65 | 66 | end++; 67 | } 68 | 69 | return max_sum; 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Sorting : Merge sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | void merge(int arr[],int start,int mid,int end) 3 | { 4 | int* temp = new int[end-start+1]; //to sort in range (start,end) 5 | int i=start,j=mid+1,k=0; 6 | while(i<=mid && j<=end){ 7 | if(arr[i] <= arr[j]){ 8 | temp[k++] = arr[i++]; 9 | }else{ 10 | temp[k++] = arr[j++]; 11 | } 12 | } 13 | 14 | while(i <= mid){ 15 | temp[k++] = arr[i++]; 16 | } 17 | while(j <= end){ 18 | temp[k++] = arr[j++]; 19 | } 20 | 21 | for(int p=0;p 10 | int partition(int input[],int start,int end) 11 | { 12 | int pivot = input[start]; 13 | int i = start; 14 | int j = end; 15 | int countSmaller = 0; 16 | 17 | //count number of smaller elements that current pivot and place pivot to correct position 18 | for(int k=start+1;k<=end;k++){ 19 | if(input[k] <= pivot){ 20 | countSmaller++; 21 | } 22 | } 23 | int pivotIndex = start + countSmaller; 24 | int temp = input[pivotIndex]; 25 | input[pivotIndex] = pivot; 26 | input[start] = temp; 27 | 28 | 29 | //put all elements <= pivot in left and elements >= pivot in right side 30 | //(Note : elements in left and right after placing need not to be in sorted order) 31 | while(i < pivotIndex && j > pivotIndex){ 32 | if(input[i] <= pivot){ 33 | i++; 34 | }else if(input[j] > pivot){ 35 | j--; 36 | }else{ //swap since they are not in correct side 37 | int temp = input[i]; 38 | input[i] = input[j]; 39 | input[j] = temp; 40 | i++; 41 | j--; 42 | } 43 | } 44 | 45 | return pivotIndex; 46 | } 47 | 48 | void helper(int input[],int start,int end) 49 | { 50 | if(start >= end){ 51 | return; 52 | } 53 | int loc = partition(input,start,end); 54 | helper(input,start,loc-1); 55 | helper(input,loc+1,end); 56 | 57 | } 58 | 59 | void quickSort(int input[], int size) { 60 | helper(input,0,size-1); 61 | return; 62 | } 63 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Stack : Merge Intervals leetcode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover 3 | all the intervals in the input. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 10 | Output: [[1,6],[8,10],[15,18]] 11 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 12 | Example 2: 13 | 14 | Input: intervals = [[1,4],[4,5]] 15 | Output: [[1,5]] 16 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= intervals.length <= 104 22 | intervals[i].length == 2 23 | 0 <= starti <= endi <= 104 24 | 25 | 26 | */ 27 | 28 | 29 | 30 | bool compare(vector v1,vector v2) 31 | { 32 | return v1[0] < v2[0]; 33 | } 34 | 35 | class Solution { 36 | public: 37 | vector> merge(vector>& intervals) { 38 | vector> ans; 39 | sort(intervals.begin(),intervals.end(),compare); 40 | stack> s; 41 | s.push(intervals[0]); 42 | for(int i=1;i temp = s.top(); 44 | if(temp[1] >= intervals[i][0]){ 45 | temp[1] = max(temp[1],intervals[i][1]); //update end time 46 | s.pop(); 47 | s.push(temp); 48 | }else{ 49 | s.push(intervals[i]); 50 | } 51 | } 52 | 53 | while(!s.empty()){ 54 | ans.push_back(s.top()); 55 | s.pop(); 56 | } 57 | return ans; 58 | } 59 | 60 | 61 | 62 | 63 | }; 64 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Stack : Stack using single queue.cpp: -------------------------------------------------------------------------------- 1 | //stack implementation using single queue 2 | 3 | #include 4 | using namespace std; 5 | queue q; 6 | 7 | void size() 8 | { 9 | cout << "size " << q.size() << endl; 10 | return; 11 | } 12 | 13 | void peek() 14 | { 15 | cout << "top " << q.front() << endl; 16 | return; 17 | } 18 | 19 | void push(int key) //making push operation costly 20 | { 21 | cout << "pushed" << endl; 22 | if(q.empty()){ 23 | q.push(key); 24 | return; 25 | } 26 | int n = q.size(); 27 | q.push(key); 28 | while(n--){ //prev queue elements are pushed back again , so that current element is always at front 29 | q.push(q.front()); 30 | q.pop(); 31 | } 32 | 33 | size(); 34 | } 35 | 36 | void pop() 37 | { 38 | if(q.empty()){ 39 | cout << "empty stack" << endl; 40 | return; 41 | } 42 | 43 | q.pop(); 44 | cout << "popped" << endl; 45 | return; 46 | 47 | } 48 | 49 | void display() 50 | { 51 | if(q.empty()){ 52 | cout << "stack empty" << endl; 53 | return; 54 | } 55 | cout << "display " << endl; 56 | int n = q.size(); 57 | while(n--){ 58 | cout << q.front() << endl; 59 | q.push(q.front()); 60 | q.pop(); 61 | } 62 | } 63 | 64 | 65 | 66 | int main() 67 | { 68 | push(1); 69 | peek(); 70 | push(2); 71 | peek(); 72 | pop(); 73 | pop(); 74 | push(5); 75 | display(); 76 | size(); 77 | return 0; 78 | 79 | } 80 | 81 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/String : Partition Labels.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. 4 | 5 | Return a list of integers representing the size of these parts. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "ababcbacadefegdehijhklij" 12 | Output: [9,7,8] 13 | Explanation: 14 | The partition is "ababcbaca", "defegde", "hijhklij". 15 | This is a partition so that each letter appears in at most one part. 16 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. 17 | Example 2: 18 | 19 | Input: s = "eccbbbbdec" 20 | Output: [10] 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= s.length <= 500 26 | s consists of lowercase English letters. 27 | 28 | */ 29 | 30 | 31 | 32 | 33 | class Solution { 34 | public: 35 | vector partitionLabels(string s) { 36 | unordered_map m; 37 | int n = s.length(); 38 | 39 | //store last occurance of each character 40 | for(int i=n-1;i>=0;i--){ 41 | if(m.count(s[i]) == 0){ 42 | m[s[i]] = i; 43 | } 44 | } 45 | 46 | vector ans; 47 | int curr_max = INT_MIN; 48 | int start = 0; 49 | 50 | //for each character check max last position we encountered so far . if 'i' exceeds curr_max we found on part 51 | for(int i=0;i 7 | using namespace std; 8 | int mod = 13; 9 | 10 | bool isMatch(string str,string pattern,int start,int end){ 11 | for(int i=0;i> str >> pattern; 24 | 25 | int p_len = pattern.length()-1; 26 | int pattern_hash = 0; 27 | for(int i=0;i> subsets(vector& nums) { 4 | 5 | vector> res; 6 | 7 | int n = pow(2,nums.size());//total range till 2^n 8 | 9 | for(int mask=0;mask temp; 11 | for(int j=0;j<=10;j++){ //max bit required 10 , given is question num<=10 12 | if(mask & (1< 29 | using namespace std; 30 | 31 | void helper(string str,int start,string temp,vector &ans){ 32 | 33 | ans.push_back(temp); 34 | 35 | for(int i=start;i> str; 48 | vector ans; 49 | string temp = ""; 50 | helper(str,0,temp,ans); 51 | for(int i=0;ileft); 57 | int right = helper(root->right); 58 | int temp = root->data; 59 | root->data = left+right; 60 | return left+right+temp; 61 | } 62 | void toSumTree(Node *node) 63 | { 64 | // Your code here 65 | helper(node); 66 | return; 67 | } 68 | }; 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Trees : Left view of binary tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Node{ 6 | public: 7 | Node* left; 8 | Node* right; 9 | int data; 10 | Node(int data){ 11 | this->data = data; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | }; 16 | 17 | void leftView(Node* root) 18 | { 19 | if(root == NULL){ 20 | return; 21 | } 22 | queue q; 23 | q.push(root); 24 | while(!q.empty()){ 25 | int n = q.size(); 26 | bool flag = true; 27 | for(int i=0;idata << endl; //print first element in a particular level 32 | flag = false; 33 | } 34 | 35 | if(temp->left){ 36 | q.push(temp->left); 37 | } 38 | if(temp->right){ 39 | q.push(temp->right); 40 | } 41 | 42 | } 43 | } 44 | return; 45 | } 46 | 47 | int main() 48 | { 49 | Node* root = new Node(4); 50 | root->left = new Node(2); 51 | root->left->left = new Node(5); 52 | root->right = new Node(3); 53 | leftView(root); 54 | // cout << root->left->data << endl; 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Commonly Asked Problems Practice/Trees : sum of all elements in leaf nodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int data; 8 | node* left; 9 | node* right; 10 | node(int val){ 11 | this->data = val; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | 16 | }; 17 | 18 | int leafSumIterative(node* root) 19 | { 20 | if(root == NULL){ 21 | return 0; 22 | } 23 | int sum = 0; 24 | queue q; 25 | q.push(root); 26 | while(!q.empty()){ 27 | node* temp = q.front(); 28 | q.pop(); 29 | if(temp->left == NULL && temp->right == NULL){ 30 | sum += temp->data; 31 | }else{ 32 | if(temp->left){ 33 | q.push(temp->left); 34 | } 35 | if(temp->right){ 36 | q.push(temp->right); 37 | } 38 | } 39 | } 40 | 41 | return sum; 42 | } 43 | 44 | int leafSumRecursive(node* root) 45 | { 46 | static int sum = 0; 47 | if(root == NULL){ 48 | return 0; 49 | } 50 | 51 | if(!root->left && !root->right){ 52 | sum += root->data; 53 | } 54 | 55 | leafSumRecursive(root->left); 56 | leafSumRecursive(root->right); 57 | return sum; 58 | } 59 | 60 | int main() 61 | { 62 | node* root = new node(3); 63 | root->left = new node(4); 64 | root->right = new node(5); 65 | root->left->left = new node(6); 66 | root->left->right = new node(7); 67 | root->right->right = new node(9); 68 | int leafIterative = leafSumIterative(root); 69 | int leafRecursive = leafSumRecursive(root); 70 | cout << "sum of all leaf nodes is : (iterative) " << leafIterative << endl; 71 | cout << "sum of all leaf nodes is : (recursive) " << leafRecursive << endl; 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /DP & Bitmasking/Candy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Candy 3 | Send Feedback 4 | Gary is a teacher at XYZ school. To reward his N students he bought a packet of N candies all with different flavours. But the problem is some students 5 | like certain flavour while some doesn't. Now Gary wants to know the number of ways he can distribute these N candies to his N students such that every student gets 6 | exactly one candy he likes. 7 | Input Format : 8 | Line 1 : An integer N (1<= N <= 16) denoting number of students and candies. 9 | Next N lines : N integers describing the preferences of one student. 1 at i'th (0 <= i < N) position denotes that this student likes i'th candy , 0 means he doesn't. 10 | Assume input to be 0-indexed based. 11 | Output Format : 12 | Return the number of ways Gary can distribute these N candies to his N students such that every student gets exactly one candy he likes.`` 13 | Sample Input: 14 | 3 15 | 1 1 1 16 | 1 1 1 17 | 1 1 1 18 | Sample Output: 19 | 6 20 | 21 | */ 22 | 23 | 24 | 25 | #include 26 | using namespace std; 27 | #define MAXN 16 28 | 29 | long long solve(int like[][MAXN],int n) 30 | { 31 | // Write your code here. 32 | int* dp = new int[1< 0){ 41 | count += (temp&1); 42 | temp = (temp >> 1); 43 | } 44 | 45 | for(int j=0;j>n; 61 | for(int i = 0; i < n ; i++){ 62 | for(int j = 0; j < n; j++){ 63 | cin>>like[i][j]; 64 | } 65 | } 66 | cout< String 't' is lexicographical larger than string 's'. 6 | -> When you write both 's' and 't' in the reverse order, 't' is still lexicographical larger than 's'. 7 | Find out number of such strings 't'. As the answer could be very large, take modulo 10^9 + 7. 8 | */ 9 | 10 | #define mod 1000000007 11 | #define ll long long int 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | int countStrings(char *s) 17 | { 18 | int i, n; 19 | n = strlen(s); 20 | ll req = 0, dp[100005], arr[100005], ans = 0; 21 | for (i = 0; i < n; i++) 22 | { 23 | arr[i] = (ll)(90 - s[i]); 24 | } 25 | dp[n - 1] = arr[n - 1]; 26 | for (i = n - 2; i >= 0; i--) 27 | { 28 | req = (arr[i + 1] + (26 * req) % mod) % mod; 29 | dp[i] = (arr[i] + (arr[i] * req) % mod) % mod; 30 | } 31 | for (i = 0; i < n; i++) 32 | { 33 | ans = (ans + dp[i]) % mod; 34 | } 35 | ans = ans % mod; 36 | return ans; 37 | } 38 | -------------------------------------------------------------------------------- /DP & Bitmasking/Number of APs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Number of APs 3 | Send Feedback 4 | Given an array of n positive integers. The task is to count the number of Arithmetic Progression subsequences in the array. As the answer could be very large, output it modulo 100001. 5 | Note: Empty sequence or single element sequence is Arithmetic Progression. 6 | Input Format: 7 | First Line: N (the size of the array) 8 | Second Line: Elements of the array separated by spaces. 9 | Output: 10 | Print total number of subsequences 11 | Input Constraints: 12 | 1 <= arr[i] <= 1000 13 | 1 <= sizeof(arr) <= 1000 14 | Sample Input 1 : 15 | 3 16 | 1 2 3 17 | Sample output: 18 | 8 19 | Sample Output Explanation: 20 | Total subsequence are: {}, { 1 }, { 2 }, { 3 }, { 1, 2 }, { 2, 3 }, { 1, 3 }, { 1, 2, 3 } 21 | Sample Input 2: 22 | 7 23 | 1 2 3 4 5 9 10 24 | Sample Output: 25 | 37 26 | */ 27 | 28 | 29 | #define mod 100001 30 | #include 31 | #include 32 | using namespace std; 33 | int numofAP(int *arr, int n){ 34 | /* 35 | Return all possible AP subsequences formed from the given integer array. You donot need to take input or print anything. 36 | Just return the ans. 37 | */ 38 | unordered_map* m = new unordered_map[n];//for each index calculating count of distict values 39 | int ans = 0; 40 | ans = n+1; //single numbers and empty string 41 | for(int i=0;i=0;i--){ 50 | for(int j=i+1;j 23 | #include 24 | using namespace std; 25 | int n; 26 | vectorA; 27 | 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | int solve(int n,vectorv){ 33 | /* Don't write main(). 34 | Don't read input, it is passed as function argument. 35 | Return output and don't print it. 36 | Taking input and printing output is handled automatically. 37 | */ 38 | map m; 39 | for(int i=0;i<=1000;i++){ 40 | m[i]= 0; 41 | } 42 | for(int i=0;i>n; 57 | for(int i=0;i>x; 61 | A.push_back(x); 62 | } 63 | cout< 25 | #include 26 | #include 27 | #include 28 | using namespace std; 29 | #include "solution.h" 30 | 31 | int countBST(int n,int* temp = new int[1001]()) 32 | { 33 | /* Don't write main(). 34 | * Don't read input, it is passed as function argument. 35 | * Return output and don't print it. 36 | * Taking input and printing output is handled automatically. 37 | */ 38 | if(n == 0){ 39 | return 1; 40 | } 41 | if(n == 1){ 42 | return 1; 43 | } 44 | 45 | if(temp[n] > 0){ 46 | return temp[n]; 47 | } 48 | int mod = 1000000000+7; 49 | long long ans = 0; 50 | for(int i=1;i<=n;i++){ 51 | long long left = countBST(i-1,temp)%mod; 52 | temp[i-1] = left; 53 | long long right = countBST(n-i,temp)%mod; 54 | temp[n-i] = right; 55 | ans += (left*right)%mod; 56 | } 57 | ans = ans%mod; 58 | temp[n] = ans; 59 | return ans; 60 | 61 | } 62 | 63 | 64 | 65 | 66 | 67 | int main() 68 | { 69 | int n ; 70 | cin>>n; 71 | cout< 2 | using namespace std; 3 | 4 | int LIS(int* arr,int n){ 5 | int* output = new int[n]; 6 | for(int i=0;i= 0 ;j--){ 9 | if(arr[j] > arr[i]){ 10 | continue; 11 | } 12 | int possibleAns = output[j] + 1; 13 | if(possibleAns > output[i]){ 14 | output[i] = possibleAns; 15 | } 16 | } 17 | } 18 | int best = 0; 19 | for(int i=0;i> n; 30 | int* arr = new int[n]; 31 | for(int i=0;i> arr[i]; 33 | } 34 | int ans = LIS(arr,n);; 35 | cout << ans << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/Loot Houses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A thief wants to loot houses. He knows the amount of money in each house. He cannot loot two consecutive houses. Find the maximum amount of money he can loot. 3 | Input Format 4 | 5 | Line 1 : An integer N 6 | Line 2 : N spaced integers denoting money in each house 7 | Output Format 8 | Line 1 : Maximum amount of money looted 9 | Input Constraints 10 | 1 <= n <= 10^4 11 | 1 <= A[i] < 10^4 12 | Sample Input : 13 | 6 14 | 5 5 10 100 10 5 15 | Sample Output 1 : 16 | 110 17 | */ 18 | 19 | 20 | #include 21 | using namespace std; 22 | 23 | #include 24 | 25 | // int getMaxMoney(int arr[], int n){ 26 | 27 | // /*Write your code here. 28 | // *Don’t write main(). 29 | // *Don’t take input, it is passed as function argument. 30 | // *Don’t print output. 31 | // *Taking input and printing output is handled automatically. 32 | // */ 33 | // long* output = new long[n]; 34 | // output[0] = arr[0]; 35 | // output[1] = (max((long)arr[0],output[1])); 36 | // for(int i=2;i= n){ 47 | return 0; 48 | } 49 | if(temp[i] > 0){ 50 | return temp[i]; 51 | } 52 | int include = arr[i]+getMaxMoney(arr,n,i+2,temp); 53 | int not_include = getMaxMoney(arr,n,i+1,temp); 54 | int maximum = max(include,not_include); 55 | temp[i] = maximum; 56 | return maximum; 57 | } 58 | 59 | 60 | int main(){ 61 | int n; 62 | cin >> n; 63 | int arr[10000]; 64 | for(int i=0; i> arr[i]; 66 | } 67 | cout << getMaxMoney(arr, n); 68 | } 69 | 70 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/Maximum Square Matrix With All Zeros.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a n*m matrix which contains only 0s and 1s, find out the size of maximum square sub-matrix with all 0s. You need to return the size of square with all 0s. 3 | Input format : 4 | Line 1 : n and m (space separated positive integers) 5 | Next n lines : m elements of each row (separated by space). 6 | Output Format: 7 | Line 1 : Size of maximum square sub-matrix 8 | Sample Input : 9 | 3 3 10 | 1 1 0 11 | 1 1 1 12 | 1 1 1 13 | Sample Output : 14 | 1 15 | */ 16 | 17 | 18 | #include 19 | using namespace std; 20 | #include 21 | 22 | int findMaxSquareWithAllZeros(int** arr,int row,int col){ 23 | int maximum = 0; 24 | int** temp = new int*[row]; 25 | for(int i=0;i= 1 && temp[i][j-1] >= 1 && temp[i-1][j-1] >= 1){ 60 | temp[i][j] = 1+min(temp[i-1][j-1],min(temp[i-1][j],temp[i][j-1])); 61 | }else{ 62 | temp[i][j] = 1; 63 | } 64 | } 65 | maximum = max(maximum,temp[i][j]); 66 | } 67 | } 68 | return maximum; 69 | } 70 | 71 | 72 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/Maximum Sum Rectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix. 3 | Input 4 | First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm. 5 | Output 6 | Output a single integer, maximum sum rectangle. 7 | Constraints 8 | 1<=n,m<=100 9 | Sample Input 10 | 4 5 11 | 1 2 -1 -4 -20 12 | -8 -3 4 2 1 13 | 3 8 10 1 3 14 | -4 -1 1 7 -6 15 | Sample Output 16 | 29 17 | */ 18 | 19 | 20 | 21 | #include 22 | using namespace std; 23 | 24 | //to get max subarray sum 25 | int kadane(int* arr,int n){ 26 | int best_sum = INT_MIN; 27 | int cur_sum = 0; 28 | for(int i=0;i best_sum){ 31 | best_sum = cur_sum; 32 | } 33 | if(cur_sum < 0){ 34 | cur_sum = 0; 35 | } 36 | } 37 | return best_sum; 38 | } 39 | 40 | int getSum(int** arr,int m ,int n){ 41 | 42 | int maxsum = INT_MIN; 43 | for(int left = 0;left> m >> n; 59 | int** arr = new int*[m]; 60 | for(int i=0;i> arr[i][j]; 67 | } 68 | } 69 | 70 | cout << getSum(arr,m,n) << endl; 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/StairCase Problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up 3 | to the stairs. You need to return all possible number of ways. 4 | Time complexity of your code should be O(n). 5 | Input format : 6 | Integer n (No. of steps) 7 | Constraints : 8 | n <= 70 9 | Sample Input 1: 10 | 4 11 | Sample Output 1: 12 | 7 13 | */ 14 | 15 | 16 | #include 17 | using namespace std; 18 | 19 | 20 | long getCount(int n,long* arr){ 21 | if(n == 0 || n == 1){ 22 | return 1; 23 | } 24 | if(n == 2){ 25 | return 2; 26 | } 27 | if(arr[n] > 0){ 28 | return arr[n]; 29 | } 30 | 31 | 32 | long ans1 = getCount(n-1,arr); 33 | long ans2 = getCount(n-2,arr); 34 | long ans3 = getCount(n-3,arr); 35 | arr[n-1] = ans1; 36 | arr[n-2] = ans2; 37 | arr[n-3] = ans3; 38 | long ans = ans1 + ans2 + ans3; 39 | arr[n] = ans; 40 | return ans; 41 | } 42 | 43 | long staircase(int n) 44 | { 45 | //Write your code here 46 | long* arr = new long[n+1](); 47 | 48 | return getCount(n,arr); 49 | 50 | } 51 | 52 | int main() 53 | { 54 | int n; 55 | cin >> n; 56 | cout << staircase(n); 57 | } 58 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/Vanya and GCD.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Vanya and GCD 3 | Send Feedback 4 | Vanya has been studying all day long about sequences and other Complex Mathematical Terms. She thinks she has now become really good at it. So, her friend Vasya decides to test her knowledge and keeps the following challenge it front of her: 5 | Vanya has been given an integer array A of size N. Now, she needs to find the number of increasing sub-sequences of this array with length ≥1 and GCD=1. A sub-sequence of an array is obtained by deleting some (or none) elements and maintaining the relative order of the rest of the elements. As the answer may be large, print it Modulo 109+7 6 | She finds this task really easy, and thinks that you can do it too. Can you? 7 | Input Format: 8 | The first line contains a single integer N denoting size of array A. The next line contains N space separated integers denoting the elements of array A 9 | Output Format: 10 | Print the required answer Modulo 10^9+7 on a single line. 11 | Constraints: 12 | 1≤N≤500 13 | 14 | 1≤A[i]≤100 15 | Sample Input 16 | 3 17 | 1 2 3 18 | Sample Output 19 | 5 20 | */ 21 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/sam ans substring.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | amantha and Sam are playing a numbers game. Given a number as a string, no leading zeros, determine the sum of all integer values of substrings of the string. For example, if the string is , the substrings are and . Their sum is . 4 | 5 | Given an integer as a string, sum all of its substrings cast as integers. As the number may become large, return the value modulo 10^9+7 . 6 | 7 | Function Description 8 | 9 | Complete the substrings function in the editor below. It should return the sum of the integer values of all substrings in a string representation of a number, modulo . 10 | 11 | substrings has the following parameter(s): 12 | 13 | n: the string representation of an integer 14 | Input Format 15 | 16 | A single line containing an integer as a string without leading zeros. 17 | 18 | Output Format 19 | 20 | A single line which is sum of the substrings, 21 | 22 | Sample Input 0 23 | 24 | 16 25 | Sample Output 0 26 | 27 | 23 28 | Explanation 0 29 | 30 | The substring of number 16 are 16, 1 and 6 which sums to 23. 31 | 32 | Sample Input 1 33 | 34 | 123 35 | Sample Output 1 36 | 37 | 164 38 | Explanation 1 39 | 40 | The sub-strings of 123 are 1, 2, 3, 12, 23, 123 which sums to 164. 41 | */ 42 | 43 | #include 44 | using namespace std; 45 | #define MOD 1000000007 46 | 47 | 48 | int main(){ 49 | string s; 50 | cin >> s; 51 | long long currentSum = s[0] - '0'; 52 | long long totalSum = currentSum; 53 | for(int i=1;i 21 | using namespace std; 22 | 23 | int getans(char* s1,char* s2,int len1,int len2,int** dp){ 24 | if(len1 <= 0){ 25 | return 1001; 26 | } 27 | if(len2 <= 0){ 28 | return 1; 29 | } 30 | if(dp[len1][len2] > -1){ 31 | return dp[len1][len2]; 32 | } 33 | int ans = 0; 34 | int option1 = getans(s1+1,s2,len1-1,len2,dp); 35 | int i=0; 36 | for(;i>S>>V; 75 | cout< 3 | #include 4 | #include 5 | #include 6 | #define endl '\n' 7 | #define int long long 8 | #define fast \ 9 | ios_base::sync_with_stdio(false); \ 10 | cin.tie(0) 11 | #define base complex 12 | using namespace std; 13 | 14 | vector init_omega(int n) 15 | { 16 | vector omega(n); 17 | double PI = acos(-1); 18 | double angle = 2 * (PI / n); 19 | for (int i = 0; i < n; i++) 20 | { 21 | omega[i] = base(cos(angle * i), sin(angle * i)); 22 | } 23 | return omega; 24 | } 25 | vector fft(vector &a, vector omega) 26 | { 27 | int n = (int)a.size(); 28 | if (n == 1) 29 | { 30 | return a; 31 | } 32 | int half = n >> 1; //it is n/2 33 | vector aeven(half); 34 | vector aodd(half); 35 | for (int i = 0, j = 0; i < n; i += 2, j++) 36 | { 37 | aeven[j] = a[i]; 38 | aodd[j] = a[i + 1]; 39 | } 40 | auto yeven = fft(aeven, omega); 41 | auto yodd = fft(aodd, omega); 42 | vector y(n); 43 | for (int i = 0; i < half; i++) 44 | { 45 | y[i] = yeven[i] + omega[i] * yodd[i]; 46 | y[i + half] = yeven[i] - omega[i] * yodd[i]; 47 | } 48 | return y; 49 | } 50 | int32_t main() 51 | { 52 | fast; 53 | vector a; 54 | a.push_back(1); 55 | a.push_back(2); 56 | a.push_back(3); 57 | a.push_back(4); 58 | vector omega = init_omega(a.size()); 59 | vector y = fft(a, omega); 60 | for (int i = 0; i < y.size(); i++) 61 | { 62 | cout << y[i] << endl; 63 | } 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /Fenwick Tree/Fenwick Tree Demo Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | //to store sum of array elements in given range 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | void update(int index,int val,int* BIT,int n){ 9 | while(index <= n){ 10 | BIT[index] += val; 11 | index += index&(-index); 12 | } 13 | return; 14 | } 15 | 16 | int query(int index,int* BIT){ 17 | int sum = 0; 18 | while(index > 0){ 19 | sum += BIT[index]; 20 | index -= (index)&(-index); 21 | } 22 | return sum; 23 | } 24 | 25 | int main(){ 26 | int n; 27 | cout << "Enter number of array elements " << endl; 28 | cin >> n; 29 | int* arr = new int[n+1](); 30 | int* BIT = new int[n+1](); 31 | cout << "Enter array elements " << endl; 32 | for(int i=1;i<=n;i++){ 33 | cin >> arr[i]; 34 | update(i,arr[i],BIT,n); 35 | } 36 | 37 | cout << "Enter Range for which sum is required " << endl; //indexing start from 1 38 | int left,right; 39 | cin >> left >> right; 40 | int ans = (query(right,BIT) - query(left-1,BIT)); 41 | cout << "Sum from " << left << " to " << right << " is : " << ans << endl; 42 | return 0; 43 | } 44 | */ 45 | -------------------------------------------------------------------------------- /Game Theory/Calculate Grundy Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Calculate Grundy Number 3 | Send Feedback 4 | Calculate the Grundy Number for the given 'n' in the game. 5 | The game starts with a number- ‘n’ and the player to move divides the number- ‘n’ with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. Which player wins the game? 6 | Input Format 7 | An Integer 'n' 8 | Output Format 9 | Grundy Number(n) 10 | Sample Input 1 - 11 | 10 12 | Sample Output 1- 13 | 0 14 | */ 15 | 16 | 17 | #include 18 | using namespace std; 19 | 20 | /* 21 | MEX : minimum excludant set 22 | set s = {1,2,3} -> mex(s) = 0 23 | set s1 = {0,2,3} -> mex(s1) = 1 24 | set s2 = {0,1,2,3} -> mex(s2) = 4 25 | set s3 = {0,1,2,3,5} -> mex(s3) = 4 26 | */ 27 | 28 | int mex(int n1,int n2,int n3){ 29 | set temp; 30 | temp.insert(n1); 31 | temp.insert(n2); 32 | temp.insert(n3); 33 | 34 | int maximum = max(n1,max(n2,n3)); 35 | for(int i=0;i<=maximum;i++){ 36 | if(temp.count(i) == 0){ //checking for minimum element which is not present 37 | return i; //return minimum non-negative element in set 38 | } 39 | } 40 | 41 | return maximum+1; //else return next maximum element which is mex in given set 42 | } 43 | 44 | int grundy(int n){ 45 | if(n == 0){ 46 | return 0; //grundy(0) = 0 from zero'th state we cant move further 47 | } 48 | 49 | return mex(grundy(n/2),grundy(n/3),grundy(n/6)); 50 | } 51 | 52 | int main() { 53 | int n; 54 | cin >> n; 55 | cout << grundy(n) << endl; 56 | } 57 | -------------------------------------------------------------------------------- /Graphs 1/3 Cycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 Cycle 3 | 4 | Send Feedback 5 | Given a graph with N vertices (numbered from 1 to N) and Two Lists (U,V) of size M where (U[i],V[i]) and (V[i],U[i]) are connected by an edge , 6 | then count the distinct 3-cycles in the graph. A 3-cycle PQR is a cycle in which (P,Q), (Q,R) and (R,P) are connected an edge. 7 | Input Format : 8 | Line 1 : Two integers N and M 9 | Line 2 : List u of size of M 10 | Line 3 : List v of size of M 11 | Return Format : 12 | The count the number of 3-cycles in the given Graph 13 | Constraints : 14 | 1<=N<=100 15 | 1<=M<=(N*(N-1))/2 16 | 1<=u[i],v[i]<=N 17 | Sample Input: 18 | 3 3 19 | 1 2 3 20 | 2 3 1 21 | Sample Output: 22 | 1 23 | */ 24 | 25 | 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | 31 | int solve(int n,int m,vector u,vector v) 32 | { 33 | int** edges = new int*[n]; 34 | for(int i=0;iu,v; 72 | cin>>n>>m; 73 | for(int i=0;i>x; 77 | u.push_back(x); 78 | } 79 | for(int i=0;i>x; 83 | v.push_back(x); 84 | } 85 | cout< 3 | #include 4 | using namespace std; 5 | 6 | //All pairs shortest path 7 | //works for all types of graph directed,undirected 8 | //idea is consider all passobility of edges between (i,j) and try to to add vertex " k" between them 9 | //if adding "k" reduces the shortest path update it 10 | //relaxing every edge "k" times 11 | 12 | //Put some large values if no edge is present between two vertices in adjacency matrix (i , i ) put infinity 13 | 14 | 15 | //with k as intermediate vertex update the matrix 16 | void warshall(int** arr,int n) 17 | { 18 | for(int k=0;k> n; 35 | int** arr = new int*[n]; 36 | for(int i=0;i> arr[i][j]; 43 | } 44 | } 45 | 46 | warshall(arr,n); 47 | 48 | for(int i=0;i 3 | #include 4 | using namespace std; 5 | class Edge { 6 | public: 7 | int src; 8 | int dest; 9 | }; 10 | 11 | int findParent(int* parent,int v){ 12 | if(parent[v] == v){ //if parent = vertex (thats the original parent of all ) 13 | return v; 14 | } 15 | return findParent(parent,parent[v]); 16 | } 17 | 18 | void findCycle(Edge* arr,int e,int n,int* parent){ 19 | int count = 0; 20 | while(e--){ 21 | int s = arr[count].src; 22 | int d = arr[count].dest; 23 | int srcParent = findParent(parent,s); 24 | int destParent = findParent(parent,d); 25 | if(srcParent == destParent){ 26 | cout << "graph contain cycle"<< endl; 27 | return; 28 | } 29 | parent[d] = srcParent; 30 | count++; 31 | } 32 | cout << "graph doen't contain cycle" << endl; 33 | return; 34 | } 35 | 36 | 37 | int main() 38 | { 39 | printf("Hello World"); 40 | int n; 41 | int e; 42 | cin >> n >> e; 43 | Edge* arr = new Edge[n](); 44 | for(int i=0;i> s >> d; 47 | arr[i].src = s; 48 | arr[i].dest = d; 49 | } 50 | 51 | int* parent = new int[n]; 52 | for(int i=0;i 28 | using namespace std; 29 | 30 | struct Interval{ 31 | int start; 32 | int end; 33 | }; 34 | 35 | bool compare(Interval i1,Interval i2){ 36 | return i1.end < i2.end; //sort array of structures based on second element in array in increasing order 37 | } 38 | 39 | int main() 40 | { 41 | int n; 42 | cin >> n; 43 | Interval* arr = new Interval[n]; 44 | for(int i=0;i> arr[i].start; 46 | cin >> arr[i].end; 47 | } 48 | sort(arr,arr+n,compare); 49 | int count = 1; 50 | int cur_end = arr[0].end; 51 | for(int i=1;i= cur_end){ 53 | count += 1; 54 | cur_end = arr[i].end; 55 | } 56 | } 57 | cout << count; 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Greedy Problems/Fractional Knapsack ( original ).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Item 5 | { 6 | int weight; 7 | int value; 8 | }; 9 | 10 | //sorting on value/weight 11 | bool compare(Item a, Item b) 12 | { 13 | double ans1 = ((double)a.value / a.weight); 14 | double ans2 = ((double)b.value / b.weight); 15 | return ans1 > ans2; 16 | } 17 | 18 | double knapsack(Item *arr, int n, int w) 19 | { 20 | int curr_w = 0; 21 | double val = 0; 22 | for (int i = 0; i < n; i++) 23 | { 24 | if (curr_w + arr[i].weight <= w) 25 | { 26 | curr_w += arr[i].weight; 27 | val += arr[i].value; 28 | } 29 | else 30 | { 31 | int rem = w - curr_w; 32 | val += ((double)rem / arr[i].weight) * arr[i].value; // ( rem weight/current item weight ) * current value 33 | curr_w = w; 34 | break; 35 | } 36 | } 37 | return val; 38 | } 39 | 40 | int main() 41 | { 42 | int n, w; 43 | cin >> n; 44 | cin >> w; 45 | 46 | Item *arr = new Item[n]; 47 | for (int i = 0; i < n; i++) 48 | { 49 | cin >> arr[i].value >> arr[i].weight; 50 | } 51 | cout << knapsack(arr, n, w) << endl; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Greedy Problems/Min. Absolute Difference In Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Min. Absolute Difference In Array 3 | Send Feedback 4 | Given an integer array A of size N, find and return the minimum absolute difference between any two elements in the array. 5 | We define the absolute difference between two elements ai, and aj (where i != j ) is |ai - aj|. 6 | Input format : 7 | Line 1 : Integer N, Array Size 8 | Line 2 : Array elements (separated by space) 9 | Output Format : 10 | Minimum difference 11 | Constraints : 12 | 1 <= N <= 10^6 13 | Sample Input : 14 | 5 15 | 2 9 0 4 5 16 | Sample Input : 17 | 1 18 | */ 19 | 20 | 21 | #include 22 | using namespace std; 23 | 24 | #include 25 | #include 26 | using namespace std; 27 | 28 | int minAbsoluteDiff(int arr[], int n) { 29 | 30 | sort(arr,arr+n); 31 | int minimum = INT_MAX; 32 | for(int i=1;i> size; 44 | int *input = new int[1 + size]; 45 | 46 | for(int i = 0; i < size; i++) 47 | cin >> input[i]; 48 | 49 | cout<< minAbsoluteDiff(input,size) << endl; 50 | 51 | return 0; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Greedy Problems/Nikunj and Donuts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Nikunj and Donuts 3 | Send Feedback 4 | Nikunj loves donuts, but he also likes to stay fit. He eats n donuts in one sitting, and each donut has a calorie count, ci. After eating a donut with k calories, he must walk at 5 | least 2^j x k(where j is the number donuts he has already eaten) miles to maintain his weight. 6 | Given the individual calorie counts for each of the n donuts, find and print a long integer denoting the minimum number of miles Nikunj must walk to maintain his weight. Note 7 | that he can eat the donuts in any order. 8 | Input 9 | The first line contains an integer, n, denoting the number of donuts. 10 | The second line contains n space-separated integers describing the respective calorie counts of each donut I, i.e ci. 11 | Output 12 | Print a long integer denoting the minimum number of miles Nikunj must walk to maintain his weight. 13 | Constraints 14 | 1 ≤ n ≤ 40 15 | 1 ≤ ci ≤ 1000 16 | Sample Input 17 | 3 18 | 1 3 2 19 | Sample Output 20 | 11 21 | */ 22 | 23 | #include 24 | using namespace std; 25 | int main() 26 | { 27 | int n; 28 | cin >> n; 29 | int* arr = new int[n]; 30 | for(int i=0;i> arr[i]; 32 | } 33 | sort(arr,arr+n,greater()); 34 | long long ans = 0; 35 | for(int i=0;i i with an 7 | energy cost of (j-i)*A[i] + (j2 - i2)*A[i]2, where A[i] for all i are given in input. 8 | 9 | Find the minimum total energy cost to reach town N - 1 from town 0. 10 | 11 | Input 12 | 13 | The first line contains a single integer, N. 14 | The next line contains N space separated integers, ith integer denoting the value of A[i] , 0 ≤ i ≤ N - 1. 15 | Output 16 | Output the minimum cost to reach town N. 17 | 18 | Constraints 19 | 1 ≤ N ≤ 105 20 | -103 ≤ A[i] ≤ 103 21 | Example 1 22 | 23 | Input: 24 | 5 25 | 1 -1 2 2 2 26 | 27 | Output: 28 | 14 29 | Example 2 30 | 31 | Input: 32 | 4 33 | 2 2 3 4 34 | 35 | Output: 36 | 42 37 | */ 38 | 39 | 40 | #include 41 | using namespace std; 42 | 43 | int main() { 44 | // your code goes here 45 | long n; 46 | cin >> n; 47 | 48 | long arr[n]; 49 | for(int i=0;i> arr[i]; 51 | } 52 | long ans = 0; 53 | long cur = 0; 54 | while(cur < (n-1)){ 55 | long next = cur+1; 56 | while(next < (n-1)){ 57 | if((abs(arr[cur]) > (abs(arr[next]))) || ((abs(arr[cur])) == (abs(arr[next])) && arr[cur] > 0)){ 58 | break; 59 | }else{ 60 | next++; 61 | } 62 | } 63 | ans += ((next - cur)*arr[cur]) + ((next*next - cur*cur)*(arr[cur]*arr[cur])); 64 | cur = next; 65 | } 66 | cout << ans << endl; 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Greedy Problems/Winning Lottery.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Winning Lottery 3 | Send Feedback 4 | Harshit knows by his resources that this time the winning lottery number is the smallest number whose sum of the digits is S and the number of digits is D. You have to help Harshit and print the winning lottery number. 5 | Input Format 6 | The Input line contains two space-separated integers: S,D 7 | Output Format 8 | The output contains a single integer denoting the winning lottery number 9 | Constraints 10 | 1 <= D <= 1000 11 | 1 <= S <= 9*D 12 | Time Limit: 1 second 13 | Sample Input1: 14 | 9 2 15 | Sample Output1: 16 | 18 17 | Explanation 18 | There are many other possible numbers like 45, 54, 90, etc with the sum of digits as 9 and number of digits as 2. The smallest of them is 18. 19 | */ 20 | 21 | 22 | #include 23 | using namespace std; 24 | int main() { 25 | 26 | int n; 27 | cin >> n; 28 | int d; 29 | cin >> d; 30 | int num = n-1; 31 | int* arr = new int[d]; 32 | int index = d; 33 | d--; 34 | arr[0] = 1; 35 | int rem = num % 9; 36 | int div = num / 9; 37 | 38 | if(div > 0){ 39 | while(div != 0){ 40 | arr[d] = 9; 41 | div--; 42 | d--; 43 | } 44 | arr[d--] = rem; 45 | while(d != 0){ 46 | arr[d--] = 0; 47 | } 48 | }else{ 49 | arr[d--] = rem; 50 | while(d != 0){ 51 | arr[d--] = 0; 52 | } 53 | } 54 | 55 | for(int i=0;i=1;i--){ 68 | if(sum>9){ 69 | arr[i]=9; 70 | sum=sum-9; 71 | } 72 | else{ 73 | arr[i]=sum; 74 | sum=0; 75 | } 76 | 77 | } 78 | for(int i=0;i 2 | using namespace std; 3 | 4 | struct Item{ 5 | int weight; 6 | int value; 7 | }; 8 | 9 | bool compare(Item a , Item b){ 10 | double ans1 = ((double)(a.value)/a.weight); 11 | double ans2 = ((double)(b.value)/b.weight); 12 | return ans1 > ans2; 13 | } 14 | 15 | double fknapsack(Item* arr,int n,int W){ 16 | double cur_weight = 0; 17 | double cur_value = 0; 18 | for(int i=0;i> n >> W; 36 | Item* arr = new Item[n]; 37 | for(int i=0;i> arr[i].value; 39 | cin >> arr[i].weight; 40 | } 41 | cout << fknapsack(arr,n,W) << endl; 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Langauage tools/Exercise - Different names.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | In Little Flowers Public School, there are many students with same first names. You are given a task to find the students with same names. 3 | You will be given a string comprising of all the names of students and you have to tell the name and count of those students having same. 4 | If all the names are unique, print -1 instead. 5 | Note: We don't have to mention names whose frequency is 1. 6 | Input Format: 7 | The only line of input will have a string ‘str’ with space separated first names of students. 8 | Output Format: 9 | Print the names of students along with their count if they are repeating. If no name is repeating, print -1 10 | Constraints: 11 | 1 <= |str| <= 10^5 12 | Time Limit: 1 second 13 | Sample Input 1: 14 | Abhishek harshit Ayush harshit Ayush Iti Deepak Ayush Iti 15 | Sample Output 1: 16 | harshit 2 17 | Ayush 3 18 | Iti 2 19 | Sample Input 2: 20 | Abhishek Harshit Ayush Iti 21 | Sample Output: 22 | -1 23 | */ 24 | 25 | 26 | 27 | 28 | #include 29 | using namespace std; 30 | 31 | vector splitString(string s){ 32 | vector result; 33 | long start = 0; 34 | long end = 0; 35 | while(end < s.length()){ 36 | while(s[end] != ' '){ 37 | end++; 38 | } 39 | string str = s.substr(start,end-start); 40 | result.push_back(str); 41 | end++; 42 | start = end; 43 | 44 | } 45 | return result; 46 | } 47 | 48 | int main(){ 49 | string s; 50 | getline(cin,s); 51 | map m; 52 | vector v = splitString(s); 53 | map::iterator it; 54 | for(int i=0;i first; 60 | int freq = it -> second; 61 | if(freq >= 2){ 62 | cout << name << " " << freq << endl; 63 | count ++; 64 | } 65 | } 66 | if(count == 0){ 67 | cout << "-1" ; 68 | } 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Langauage tools/Exercise - Extract unique characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, you need to remove all the duplicates. That means, the output string should contain each character only once. The respective order of characters should 3 | remain same. 4 | Input format : 5 | String S 6 | Output format : 7 | Output String 8 | Constraints : 9 | 0 <= Length of S <= 10^8 10 | Sample Input 1 : 11 | ababacd 12 | Sample Output 1 : 13 | abcd 14 | Sample Input 2 : 15 | abcde 16 | Sample Output 2 : 17 | abcde 18 | 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | #include "solution.h" 24 | 25 | #include 26 | 27 | char* uniqueChar(char *str){ 28 | // Write your code here 29 | 30 | map m; 31 | char *arr = new char[1000];//give size anything as it is dynamic 32 | int index = 0; 33 | int i=0; 34 | while(str[i] != '\0'){ 35 | if(m[str[i]] == 0){ 36 | arr[index] = str[i]; 37 | m[str[i]] += 1; 38 | index++; 39 | } 40 | i++; 41 | } 42 | arr[index] = '\0'; 43 | return arr; 44 | 45 | 46 | 47 | } 48 | 49 | int main() { 50 | 51 | char input[1000000]; 52 | cin >> input; 53 | cout << uniqueChar(input) << endl; 54 | } 55 | -------------------------------------------------------------------------------- /Langauage tools/Exercise - Love for characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Ayush loves the characters ‘a’, ‘s’, and ‘p’. He got a string of lowercase letters and he wants to find out how many times characters ‘a’, ‘s’, and ‘p’ occurs in the 3 | string respectively. Help him find it out. 4 | Input: 5 | First line contains an integer denoting length of the string. 6 | Next line contains the string. 7 | Constraints: 8 | 1<=n<=10^5 9 | ‘a’<= each character of string <= ‘z’ 10 | Output: 11 | Three space separated integers denoting the occurrence of letters ‘a’, ‘s’ and ‘p’ respectively. 12 | Sample Input: 13 | 6 14 | aabsas 15 | Sample output: 16 | 3 2 0 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | int main() 22 | { 23 | int n; 24 | cin >> n; 25 | string s; 26 | cin >> s; 27 | map m; 28 | for(int i=0;i 2 | //#include 3 | #include //this includes all the libraries 4 | 5 | using namespace std; 6 | 7 | int main(){ 8 | int arr[] = {1,4,3,56,78,94,34,2}; 9 | sort(arr,arr+8); 10 | // sort(arr,arr+8,greater()); //sorts them in decreasing order 11 | for(int i=0;i<8;i++){ 12 | cout << arr[i] << " "; 13 | } 14 | cout << endl; 15 | 16 | cout << binary_search(arr,arr+8,4) << endl; //returns 1 for found 17 | 18 | cout << "lower bound index is " << lower_bound(arr,arr+8,3) - arr << endl; 19 | 20 | cout << "upper bound idex is " << upper_bound(arr,arr+8,34) - arr << endl; //this returns next index doing -1 gives answer 21 | 22 | cout< 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | void first_char(string str){ 14 | map frequency; 15 | for(int i=0;i> str; 32 | first_char(str); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Langauage tools/remove duplicates.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | void removeDuplicates(vector v){ 10 | 11 | cout << "SOLUTION 1 : "<< endl; 12 | //making use of set 13 | set s; 14 | vector result; 15 | for(int i=0;i result1; 30 | result1.push_back(v[0]); 31 | for(int i=1;i v; 44 | vector::iterator it; 45 | cout << "enter number of elements " << endl; 46 | int n; 47 | cin >> n; 48 | 49 | for(int i=0;i> num; 52 | v.push_back(num); 53 | } 54 | removeDuplicates(v); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/Duplicate in array.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers of size n which contains numbers from 0 to n - 2. Each number is present at least once. That is, if n = 5, 5 | numbers from 0 to 3 is present in the given array at least once and one number is present twice. You need to find and return that duplicate number present in the array. 6 | Assume, duplicate number is always present in the array. 7 | Input format : 8 | Line 1 : Size of input array 9 | Line 2 : Array elements (separated by space) 10 | Output Format : 11 | Duplicate element 12 | Constraints : 13 | 1 <= n <= 10^6 14 | Sample Input: 15 | 9 16 | 0 7 2 5 4 7 1 3 6 17 | Sample Output: 18 | 7 19 | */ 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | // arr - input array 28 | // size - size of array 29 | #include 30 | #include 31 | int DuplicateNumber(int arr[], int size){ 32 | 33 | //USING MAP 34 | // map m; 35 | // map::iterator it; 36 | // for(int i=0;i 1){ 39 | // return arr[i]; 40 | // } 41 | // } 42 | 43 | 44 | // USING SET 45 | set s; 46 | for(int i=0;i 22 | #include 23 | #include "solution.h" 24 | using namespace std; 25 | 26 | 27 | // arr - input array 28 | // size - size of array 29 | 30 | 31 | 32 | #include 33 | using namespace std; 34 | int FindUnique(int arr[], int n){ 35 | /* Don't write main(). 36 | * Don't read input, it is passed as function argument. 37 | * Return output and don't print it. 38 | * Taking input and printing output is handled automatically. 39 | */ 40 | map m; 41 | for(int i=0; i::iterator it; 46 | for(it=m.begin(); it!=m.end(); it++) 47 | { 48 | if(it->second==1) 49 | { 50 | return it->first; 51 | } 52 | } 53 | } 54 | 55 | int main() { 56 | 57 | int size; 58 | 59 | cin>>size; 60 | int *input=new int[1+size]; 61 | 62 | for(int i=0;i>input[i]; 64 | 65 | cout< 35 | using namespace std; 36 | #include "solution.h" 37 | 38 | #include 39 | 40 | void FindTriplet(int arr[], int size, int x) { 41 | sort(arr,arr+size); 42 | for(int i=0;i>size; 60 | 61 | int *input=new int[1+size]; 62 | 63 | for(int i=0;i>input[i]; 65 | cin>>x; 66 | 67 | FindTriplet(input,size,x); 68 | 69 | return 0; 70 | } 71 | 72 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/sum me up.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There will be ‘t’ test cases having an integer. You have to sum up all the digits of this integer. For e.g. For 6754, the answer will be 6 + 7 + 5 + 4 = 22. 3 | Input Format: 4 | First line will have an integer ‘t’ denoting the number of test cases. 5 | Next ‘t’ lines will have an integer ‘val’ each. 6 | Output format: 7 | Print ‘t’ lines of output denoting the sum of all the digits of the number in each test case. 8 | Constraints: 9 | 1 <= t <= 10^5 10 | 0 <= val <= 10^18 11 | Sample Input: 12 | 2 13 | 1547 14 | 45876 15 | Sample Output: 16 | 17 17 | 30 18 | Explanation: 19 | 1 + 5 + 4 + 7 = 17 20 | 4 + 5 + 8 + 7 + 6 = 30 21 | */ 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | #include 31 | using namespace std; 32 | typedef long long ll; 33 | int main() { 34 | 35 | // Write your code here 36 | int t; 37 | cin >> t; 38 | while(t--){ 39 | ll num; 40 | cin >> num; 41 | ll sum = 0; 42 | while(num!=0){ 43 | int rem = num % 10; 44 | sum += rem; 45 | num = num /10; 46 | } 47 | cout < 2 | using namespace std; 3 | struct node 4 | { 5 | int data; 6 | node *next; 7 | }; 8 | 9 | struct node *addnode(node *head, int num) 10 | { 11 | if (head == NULL) 12 | { 13 | node *temp = new node(); 14 | temp->data = num; 15 | temp->next = NULL; 16 | return temp; 17 | } 18 | 19 | node *newnode = new node(); 20 | newnode->data = num; 21 | newnode->next = head; 22 | return newnode; 23 | } 24 | 25 | void print(node *head) 26 | { 27 | node *temp = head; 28 | while (temp != NULL) 29 | { 30 | cout << temp->data << endl; 31 | temp = temp->next; 32 | } 33 | return; 34 | } 35 | int printMiddle(node *head) 36 | { 37 | node *fast = head; 38 | node *slow = head; 39 | while (fast != NULL && fast->next != NULL) 40 | { 41 | fast = fast->next->next; 42 | slow = slow->next; 43 | } 44 | return slow->data; 45 | } 46 | 47 | int main() 48 | { 49 | node *head = NULL; 50 | for (int i = 5; i >= 0; i--) 51 | { 52 | head = addnode(head, i); 53 | } 54 | print(head); 55 | cout << "middle node is " << endl; 56 | cout << printMiddle(head) << endl; 57 | return 0; 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Modulo arithmetic/Number Of Balanced BTs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer h, find the possible number of balanced binary trees of height h. You just need to return the count of possible binary trees which are balanced. 3 | This number can be huge, so return output modulus 10^9 + 7. 4 | Write a simple recursive solution. 5 | Input Format : 6 | Integer h 7 | Output Format : 8 | Count % 10^9 + 7 9 | Input Constraints : 10 | 1 <= h <= 40 11 | Sample Input 1: 12 | 3 13 | Sample Output 1: 14 | 15 15 | Sample Input 2: 16 | 4 17 | Sample Output 2: 18 | 315 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | #include 24 | 25 | #include 26 | // #define mod 1000000007 27 | int balancedBTs(int h) { 28 | /* Don't write main(). 29 | Don't read input, it is passed as function argument. 30 | Return the output and don’t print it. 31 | */ 32 | if( h == 0 || h == 1){ 33 | return 1; 34 | } 35 | int mod = pow(10,9) + 7; 36 | long x = balancedBTs(h-1); 37 | long y = balancedBTs(h-2); 38 | long long ans1 = (long long)(x*x); 39 | long long ans2 = (long long)(2*x*y); 40 | int res1 = (int)(ans1%mod); 41 | int res2 = (int)(ans2%mod); 42 | int res = (res1+res2)%mod; 43 | return res; 44 | } 45 | 46 | 47 | int main() { 48 | int h; 49 | cin >> h; 50 | int ans = balancedBTs(h); 51 | cout << ans << endl; 52 | } 53 | -------------------------------------------------------------------------------- /Number Theory - 1/Extended Euclid algorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given: 3 | Intution: 4 | There exist integral roots x,y for equation ax+by = c if c = gcd(a,b) 5 | ie 6 | gcd(a,b) devides a and b 7 | gcd(a,b) also devides a+b 8 | then gcd(a,b) devides ax+by for some integers x and y 9 | 10 | Extended Euclid algorithm 11 | ax+by = gcd(a,b) then find x,y 12 | ax+by = gcd(a,b) = gcd(b,a%b) 13 | then 14 | bx1 + (a%b)y1 = gcd(b,a%b) = gcd(a,b) rewriting 15 | bx1 + (a - b*floor(a/b))y1 = ax+by 16 | comparing coeff of a and b 17 | b(x1 - floor(a/b)) + ay1 = ax+by 18 | 19 | x = y1 20 | y = (x1 - y1*floor(a/b)) 21 | */ 22 | 23 | 24 | #include 25 | using namespace std; 26 | 27 | 28 | class Triplet{ 29 | public: 30 | int x; 31 | int y; 32 | int gcd; 33 | }; 34 | 35 | Triplet extendedEuclid(int a,int b){ 36 | 37 | if(b == 0){ //ax+by = gcd(a,b) if b=0 then ax = gcd(a,0) = a hence x = 1, y = 0 , gcd = a; 38 | Triplet ans; 39 | ans.gcd = a; 40 | ans.x = 1; 41 | ans.y = 0; 42 | return ans; 43 | } 44 | Triplet smallOutput = extendedEuclid(b,a%b); 45 | Triplet ans; 46 | ans.gcd = smallOutput.gcd; 47 | ans.x = smallOutput.y; 48 | ans.y = smallOutput.x - smallOutput.y*(a/b); 49 | return ans; 50 | } 51 | 52 | int main(){ 53 | int a,b; 54 | cout << "enter two numbers" << endl; 55 | cin >> a >> b; 56 | Triplet ans = extendedEuclid(a,b); 57 | cout << "x = " << ans.x << " y = " << ans.y << " Gcd is " << ans.gcd << endl; 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Number Theory - 1/Find Prime Numbers From 1 to N(sieve of eratosthenes).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find Prime Numbers From 1 to N 3 | Send Feedback 4 | Given a number N, find number of primes in the range [1,N]. 5 | Input: 6 | The only line of input consists of a number N 7 | Output: 8 | Print the number of primes in the range [1,N].` 9 | Constraints: 10 | 1≤N≤1000000 11 | Sample Input : 12 | 3 13 | Sample Output - 14 | 2 15 | */ 16 | 17 | // #include 18 | // using namespace std; 19 | 20 | // bool isPrime(int n){ 21 | // int countFactors = 0; 22 | // for(int j=1;j*j<=n;j++){ 23 | // if((n%j) == 0){ 24 | // if(j*j == n){ 25 | // countFactors += 1; 26 | // }else{ 27 | // countFactors +=2; 28 | // } 29 | // } 30 | // } 31 | // if(countFactors == 2){ 32 | // return true; 33 | // } 34 | // return false; 35 | // } 36 | 37 | // int main(){ 38 | // // Write your code here 39 | // int n; 40 | // cin >> n; 41 | // int count = 0; 42 | // for(int i=1;i<=n;i++){ 43 | // if(isPrime(i)){ 44 | // count++; 45 | // } 46 | // } 47 | // cout << count << endl; 48 | // return 0; 49 | // } 50 | 51 | 52 | 53 | //sieve of erathostenes 54 | //time complexity O(nloglogn) 55 | #include 56 | using namespace std; 57 | #include 58 | int main(){ 59 | int n; 60 | cin >> n; 61 | bool* arr = new bool[n+1]; 62 | for(int i=0;i<=n;i++){ 63 | arr[i] = true; 64 | } 65 | arr[0] = false; 66 | arr[1] = false; 67 | 68 | for(int i=2;i<=sqrt(n);i++){ 69 | if(arr[i]){ 70 | // for(int j=i;j*i<=n;j++){ 71 | // arr[j*i] = false; 72 | // // j = (j+i); 73 | // } 74 | for(int j=i*i;j<=n;j+=i){ 75 | arr[j] = false; 76 | } 77 | } 78 | } 79 | 80 | 81 | 82 | int count = 0; 83 | for(int i=0;i<=n;i++){ 84 | if(arr[i] == true){ 85 | count++; 86 | } 87 | } 88 | cout << count ; 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /Number Theory - 1/GCD(euclid).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | GCD 3 | Send Feedback 4 | Calculate and return GCD of two given numbers x and y. Numbers are within range of Integer. 5 | Input format : 6 | x and y (separated by space) 7 | Output format : 8 | GCD of x and y 9 | Sample Input 1: 10 | 20 11 | 5 12 | Sample Output 1: 13 | 5 14 | Sample Input 2: 15 | 96 16 | 14 17 | Sample Output 2: 18 | 2 19 | */ 20 | // void swap(int &a,int &b){ 21 | // int temp = a; 22 | // a = b; 23 | // b = temp; 24 | // return; 25 | // } 26 | 27 | 28 | 29 | //time complexity of algorithm is O(log2(max(a,b))) 30 | int gcd(int a,int b) 31 | { 32 | 33 | // if(b>a){ 34 | // swap(a,b); 35 | // } 36 | 37 | //no need to handle b>a case algorithm handle itself (dry run to confirm) 38 | if(b == 0){ 39 | return a; 40 | } 41 | 42 | return gcd(b,a%b); 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Number Theory - 1/return count of prime numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | //Time complexity O(n^2) 6 | bool isPrime1(int n){ 7 | int countFactors = 0; 8 | for(int j=1;j<=n;j++){ 9 | if((n%j) == 0){ 10 | countFactors++; 11 | } 12 | } 13 | if(countFactors == 2){ //prime number has only 2 factors 14 | return true; 15 | } 16 | return false; 17 | } 18 | 19 | 20 | 21 | //Time complexity O(n^3/2) 22 | /* 23 | example : 9 24 | 1*9 25 | 3*3 26 | 9*1 27 | 28 | if one factor is less than sqrt(n) then other is greater than sqrt(n) so instead of checking for greater factor increase count by 2 at a time 29 | increase count by 1 only if number i*i = n example : 3*3 increase count by 1 30 | */ 31 | bool isPrime(int n){ 32 | int countFactors = 0; 33 | for(int j=1;j*j<=n;j++){ 34 | if((n%j) == 0){ 35 | if(j*j == n){ 36 | countFactors += 1; 37 | }else{ 38 | countFactors += 2; 39 | } 40 | } 41 | } 42 | if(countFactors == 2){ 43 | return true; 44 | } 45 | 46 | return false; 47 | } 48 | 49 | 50 | int main(){ 51 | int n; 52 | cout << "enter number " << endl; 53 | cin >> n; 54 | int count = 0; 55 | int count1 = 0; 56 | for(int i=1;i<=n;i++){ 57 | if(isPrime(i)){ 58 | count++; 59 | } 60 | 61 | if(isPrime1(i)){ 62 | count1++; 63 | } 64 | } 65 | cout << "number of prime numbers between 1 to n is : " << count << endl; 66 | cout << "number of prime numbers between 1 to n is : " << count1 << endl; 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Number Theory - 2/LCM SUM.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | LCM SUM 3 | 4 | Given n, calculate and print the sum : 5 | LCM(1,n) + LCM(2,n) + .. + LCM(n,n) 6 | where LCM(i,n) denotes the Least Common Multiple of the integers i and n. 7 | Input Format : 8 | Line 1 : Integer n 9 | Output Format : 10 | Required sum 11 | Constraints : 12 | 1 <= T <= 300000 13 | 1 <= n <= 1000000 14 | Sample Input 1 : 15 | 5 16 | Sample Output 1 : 17 | 55 18 | Sample Input 2 : 19 | 2 20 | Sample Output 2 : 21 | 4 22 | */ 23 | -------------------------------------------------------------------------------- /Number Theory - 3/Cubic Square.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Cubic Square 3 | Send Feedback 4 | Varun is learning method of successive squaring so that he can calculate a^b mod m quickly. To give himself practice he wrote many tuples of a, b and m and went to school thinking that he will do it after school. 5 | After school he found that tuples he wrote are modified by his little sister. His sister converted each b into base 3. Varun wrote everything in base 10. 6 | Help Varun to do his excercise. 7 | Input 8 | First line of input contains a number T, number of test cases. Then T test cases follows each containing three numbers a (<=10^9), b and m (<=10^5) (a in base 10, b in base 3 and m in base 10). Number of digits in b will be less than 250. 9 | Output 10 | Output a number for each test case a^b mod m in base 10. 11 | Sample Input: 12 | 2 13 | 2 10 10 14 | 3 21101 19 15 | Sample Output: 16 | 8 17 | 3 18 | */ 19 | -------------------------------------------------------------------------------- /Number Theory - 3/Fibonacci Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Fibonacci Sum 3 | Send Feedback 4 | The fibonacci sequence is defined by the following relation: 5 | F(0) = 0 6 | F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), N >= 2 8 | Your task is very simple. Given two non-negative integers N and M (N <= M), you have to calculate and return the sum (F(N) + F(N + 1) + ... + F(M)) mod 1000000007. 9 | Input Format : 10 | Two non-negative integers N and M. (N <= M) 11 | Output Format : 12 | A single line containing the answer for the task. 13 | Sample Input : 14 | 10 15 | 19 16 | Sample Output : 17 | 10857 18 | */ 19 | -------------------------------------------------------------------------------- /Number Theory - 3/Income On Nth Day.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Income On Nth Day 3 | Send Feedback 4 | Daulat Ram is an affluent business man. After demonetization, IT raid was held at his accommodation in which all his money was seized. He is very eager to gain his money back, he started investing in certain ventures and earned out of them. On the first day, his income was Rs. X, followed by Rs. Y on the second day. Daulat Ram observed his growth as a function and wanted to calculate his income on the Nth day. 5 | The function he found out was FN = FN-1 + FN-2 + FN-1×FN-2 6 | Given his income on day 0 and day 1, calculate his income on the Nth day (yeah Its that simple). 7 | Input: 8 | The first line of input consists of a single integer T denoting number of test cases. 9 | 10 | Each of the next T lines consists of three integers F0, F1 and N respectively. 11 | Output: 12 | For each test case, print a single integer FN, as the output can be large, calculate the answer modulo 10^9+7. 13 | CONSTRAINTS: 14 | 1 ≤ T ≤ 10^5 15 | 16 | 0 ≤ F0, F1, N ≤ 10^9 17 | Sample Input : 18 | 2 19 | 0 1 2 20 | 1 2 4 21 | Sample Output: 22 | 1 23 | 107 24 | Explanation 25 | In the second test case his income on day 0 is 1 and the income on day 1 is 2. We need to calculate his income on day 4. 26 | 27 | F0=1 28 | 29 | F1=2 30 | 31 | F2=1 + 2 + 1×2 = 5 32 | 33 | F3=2 + 5 + 2×5 = 17 34 | 35 | F4=5 + 17 + 5×17 = 107 36 | */ 37 | -------------------------------------------------------------------------------- /Number Theory - 3/Sanchit And Nuclear Reactor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sanchit And Nuclear Reactor 3 | Send Feedback 4 | We all know Sanchit Lee Cooper who is a Caltech theoretical physicist. He has eccentric and arrogant behavior. Due to his belief that he's intellectually superior, he's not ashamed to insult his own friends, like Howard, who is an engineer and not a real scientist. But nobody messes with an engineer. So Howard accepted an challenge from Sanchit. Sanchit was involved in numerous experiments as a wunderkind, such as his plan for building his own nuclear reactor - a plan stopped by government. So Sanchit presented Howard with a problem about his own nuclear reactor. It contains a large tank and at each second an atom is introduced in the tank which reacts with already existing atoms and produces some energy. Also he defined a special threshold number for his reactor called Cooper number m which is always a prime number. Energy output is defined as previous energy output of the tank multiplied by number of atoms present in it. But due to some special condition of the tank, all atoms attains stable state when number of atoms are multiple of Cooper number and no new reaction occurs. Energy output in this case is same as previous case. Also initial energy of the reactor is 1 and initially there is no atom in the tank. Now Sanchit ask Howard to tell the energy output after time T. But sadly Howard is not able to solve it and ask for your help. 5 | Input Format 6 | The first line of the input will contain a single integer N (N <= 100) indicating the number of test cases. Then N lines follow. Each line contains two integers, time T(0<=T<=10^18) and Cooper number m(m<=10,000). 7 | Output Format 8 | You have to determine the energy output after time T. As the number can be quite large so output it modulo Cooper number m. 9 | Sample Input 10 | 2 11 | 1 5 12 | 2 5 13 | Sample Output 14 | 1 15 | 2 16 | Explanation 17 | After 1 seconds, there is only 1 atom in the tank. Hence energy output is 1. After 2 seconds, there are 2 atoms which reacts to give energy output of 2. 18 | */ 19 | -------------------------------------------------------------------------------- /Number Theory - 3/modular-exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | /* 6 | Recursive solution: 7 | 8 | to find power of a^b 9 | Given a,b,c find a^b and take %c to ans to get integer answer 10 | if: b is even we find a^(b/2)*a^(b/2) example: 2^6 = 2^3*2^3 11 | if: b is odd we find a^(b/2) * a^(b/2) * a example: 2^7 = 2^3 * 2^3 * 2 12 | 13 | Iterative solution: 14 | 15 | represent 'b' in binary form 16 | to find (3^45) -> b=45 -> 101101 -> 3^(2^5) * 3^(2^3) * 3^(2^2) * 3^(2^0) -> 3^32 * 3^8 * 3^4 * 3^1 = 3^40 17 | 18 | time complexity by modular exponentiation : O(log(n)) 19 | 20 | note: 21 | 22 | int*int = int 23 | int*long = long 24 | (a*b)%c = ((a%c)*(b%c))%c 25 | (a+c)%c to make ans positive 26 | 27 | 28 | */ 29 | 30 | 31 | //recursive solution 32 | int modularExpo(int a,int b,int c){ 33 | if(a == 0){ 34 | return 0; 35 | } 36 | 37 | if(b == 0){ 38 | return 1; 39 | } 40 | long ans; //since int*int may cross int range so we store it in long 41 | if((b%2)==0){ 42 | long smallAns = modularExpo(a,b/2,c); //though ans is in int we store it in long 43 | ans = (smallAns * smallAns)%c; 44 | }else{ 45 | long smallAns = modularExpo(a,b-1,c); 46 | ans = (a%c); //since 'a' may larger than c 47 | ans = (ans * smallAns)%c; 48 | } 49 | 50 | return int((ans + c)%c); //avoid negative values by adding 'c' since we got ans in range of 'c' by adding 'c' to and makes ans positive 51 | } 52 | 53 | int modularExpo1(int a,int b,int c){ 54 | long ans = 1; 55 | long temp = a; 56 | while(b != 0){ 57 | if((1&b) == 1){ 58 | ans = (ans*temp); 59 | } 60 | temp = (temp*temp)%c;//wether we multiply it to ans or not keep temp multiplying at each step 61 | b = (b>>1);//right shift 62 | } 63 | return (int)((ans+c)%c); 64 | } 65 | 66 | int main(){ 67 | int a,b,c; 68 | cout << "Enter a,b,c " << endl; 69 | cin >> a >> b >> c; 70 | cout << " recursive : " << modularExpo(a,b,c) << endl; 71 | cout << "iterative : " << modularExpo1(a,b,c) << endl; 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Pre-requisites/Even and Odd Indexes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, print two integer values: 3 | First, the sum of all numbers which are even as well as whose index are even. 4 | Second, the sum of all numbers which are odd as well as whose index are odd. 5 | Print the two integers space separated. (Arrays is 0-indexed) 6 | 7 | Input: 8 | Given an integer denoting the size of array. 9 | Next line will have a line containing ‘n’ space separated integers. 10 | 11 | Constraints: 12 | 1<=n<=10^5 13 | 1 <= Ai <= 10^6 14 | 15 | Output: 16 | Two space separated integers denoting even and odd sums respectively. 17 | 18 | Sample Input: 19 | 5 20 | 2 3 5 1 4 21 | 22 | Sample Output: 23 | 6 4 24 | */ 25 | 26 | 27 | 28 | #include 29 | using namespace std; 30 | int main() 31 | { 32 | 33 | int n; 34 | cin >> n; 35 | // int arr[n]; 36 | int* arr = new int[n]; 37 | for(int i=0;i> arr[i]; 39 | } 40 | long esum=0; 41 | long osum=0; 42 | for(int i=0;i 35 | using namespace std; 36 | int main() 37 | { 38 | int n; 39 | cin >> n; 40 | int* arr =new int[n]; 41 | for(int i=0;i> arr[i]; 43 | } 44 | for(int i=0;i<(n/2);i++){ 45 | int nGroups; 46 | int rem; 47 | int sum; 48 | sum = arr[i]+arr[n-i-1]; 49 | nGroups = sum /10; 50 | rem = sum % 10; 51 | cout << nGroups << " " << rem << endl; 52 | 53 | } 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Searching & Sorting Applications/Binary Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int *arr, int key, int start, int end) 5 | { 6 | while (start <= end) 7 | { 8 | int mid = (start + end) / 2; 9 | if (arr[mid] == key) 10 | { 11 | return mid; 12 | } 13 | else 14 | { 15 | if (key < arr[mid]) 16 | { 17 | return binarySearch(arr, key, 0, mid - 1); 18 | } 19 | else 20 | { 21 | return binarySearch(arr, key, mid + 1, end); 22 | } 23 | } 24 | } 25 | return -1; 26 | } 27 | 28 | int main() 29 | { 30 | int n; 31 | cin >> n; 32 | int *arr = new int[n]; 33 | for (int i = 0; i < n; i++) 34 | { 35 | cin >> arr[i]; 36 | } 37 | int key; 38 | cout << "enter key" << endl; 39 | cin >> key; 40 | int ans = binarySearch(arr, key, 0, n - 1); 41 | if (ans == -1) 42 | { 43 | cout << "element not found" << endl; 44 | } 45 | else 46 | { 47 | cout << "element found at : " << ans << endl; 48 | } 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Segment Tree/Lazy propogation demo.cpp: -------------------------------------------------------------------------------- 1 | //min element in array 2 | 3 | #include 4 | using namespace std; 5 | 6 | void buildTree(int* arr,int* tree,int start,int end,int treeNode){ 7 | 8 | if(start == end){ 9 | tree[treeNode] = arr[start]; 10 | return; 11 | } 12 | int mid = (start+end)/2; 13 | 14 | buildTree(arr,tree,start,mid,2*treeNode); 15 | buildTree(arr,tree,mid+1,end,2*treeNode+1); 16 | tree[treeNode] = min(tree[2*treeNode],tree[2*treeNode+1]); 17 | } 18 | 19 | void updateSegmentTreeLazy(int* tree,int* lazy,int low,int high,int startR,int endR,int currPos,int inc){ 20 | 21 | if(low > high){ 22 | return; 23 | } 24 | 25 | if(lazy[currPos] !=0){ 26 | tree[currPos] += lazy[currPos]; 27 | 28 | if(low!=high){ 29 | lazy[2*currPos] += lazy[currPos]; 30 | lazy[2*currPos+1] += lazy[currPos]; 31 | } 32 | lazy[currPos] = 0; 33 | } 34 | 35 | // No overlap 36 | if(startR > high || endR < low){ 37 | return; 38 | } 39 | 40 | // Complete Overlap 41 | 42 | if(startR<= low && high <= endR){ 43 | tree[currPos] += inc; 44 | if(low!=high){ 45 | lazy[2*currPos] += inc; 46 | lazy[2*currPos+1] += inc; 47 | } 48 | return; 49 | } 50 | 51 | // Partial Overlap 52 | 53 | int mid = (low+high)/2; 54 | updateSegmentTreeLazy(tree,lazy,low,mid,startR,endR,2*currPos,inc); 55 | updateSegmentTreeLazy(tree,lazy,mid+1,high,startR,endR,2*currPos+1,inc); 56 | tree[currPos] = min(tree[2*currPos],tree[2*currPos+1]); 57 | } 58 | 59 | int main(){ 60 | 61 | int arr[] = {1,3,-2,4}; 62 | int* tree = new int[12](); 63 | buildTree(arr,tree,0,3,1); 64 | int* lazy = new int[12](); 65 | updateSegmentTreeLazy(tree,lazy,0,3,0,3,1,3); 66 | updateSegmentTreeLazy(tree,lazy,0,3,0,1,1,2); 67 | 68 | cout<< "Segment Tree" < 3 | using namespace std; 4 | 5 | bool isFound(string s,string p,int &index){ 6 | int n = s.length(); 7 | int m = p.length(); 8 | 9 | for(int i=0;i<=(n-m);i++){ 10 | bool flag = true; 11 | index = i; 12 | for(int j=0;j> s ; 30 | cout << "enter pattern" << endl; 31 | cin >> p; 32 | 33 | int index = 0; 34 | if(isFound(s,p,index)){ 35 | cout << "string is found at index" << " " << index << endl; 36 | }else{ 37 | cout << "pattern not found" << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /String Algorithms/KMP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool searchPattern(string text,string pattern,int* arr){ 5 | int textLen = text.length(); 6 | int patternLen = pattern.length(); 7 | int i = 0; 8 | int j = 0; 9 | while(i < textLen && j < patternLen){ 10 | if(text[i] == pattern[j]){ 11 | i++; 12 | j++; 13 | }else{ 14 | if(j != 0){ 15 | j = arr[j-1]; 16 | }else{ 17 | i++; 18 | } 19 | } 20 | } 21 | 22 | if(j >= patternLen){ 23 | return true; 24 | }else{ 25 | return false; 26 | } 27 | } 28 | 29 | void getLPS(string str,int* arr){ 30 | int i = 1; 31 | int j = 0; 32 | int len = str.length(); 33 | arr[0] = 0; 34 | while(i < len){ 35 | if(str[i] == str[j]){ 36 | arr[i] = j+1; 37 | i++; 38 | j++; 39 | }else{ 40 | if(j != 0){ 41 | j = arr[j-1]; 42 | }else{ 43 | arr[i] = 0; 44 | i++; 45 | } 46 | } 47 | } 48 | } 49 | 50 | 51 | int main(){ 52 | string pattern,text; 53 | cout << "Enter Text" << endl; 54 | cin >> text; 55 | 56 | cout << "Enter pattern " << endl; 57 | cin >> pattern; 58 | 59 | int* arr = new int[pattern.length()]; 60 | getLPS(pattern,arr); 61 | 62 | cout << "Longest prefix which is also suffix array for pattern is : " << endl; 63 | for(int i=0;i 2 | using namespace std; 3 | 4 | 5 | int longest_palindrome_substring(string str){ 6 | int n = str.length(); 7 | int maximum = 0; 8 | 9 | for(int i=0;i=0 && right < n) && str[left] == str[right]){ 14 | int len = right-left+1; 15 | maximum = max(maximum,len); 16 | left--; 17 | right++; 18 | } 19 | 20 | //Even 21 | left = i; 22 | right = i+1; 23 | while((left >= 0 && right < n) && str[left] == str[right]){ 24 | int len = right - left + 1; 25 | maximum = max(maximum,len); 26 | left--; 27 | right++; 28 | } 29 | } 30 | 31 | return maximum; 32 | } 33 | 34 | int main(){ 35 | 36 | string s; 37 | cout << " enter string " << endl; 38 | cin >> s; 39 | int ans = longest_palindrome_substring(s); 40 | cout << "longest palindromic substring length is : " << ans << endl; 41 | return 0; 42 | } 43 | 44 | 45 | //aabbccabcddcbapqrs 46 | -------------------------------------------------------------------------------- /String Algorithms/Longest prefix suffix code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void getLPS(string str,int* arr){ 5 | int i = 1; 6 | int j = 0; 7 | int len = str.length(); 8 | arr[0] = 0; 9 | while(i < len){ 10 | if(str[i] == str[j]){ 11 | arr[i] = j+1; 12 | i++; 13 | j++; 14 | }else{ 15 | if(j != 0){ 16 | j = arr[j-1]; 17 | }else{ 18 | arr[i] = 0; 19 | i++; 20 | } 21 | } 22 | } 23 | } 24 | 25 | int main(){ 26 | string pattern; 27 | cout << "Enter pattern " << endl; 28 | cin >> pattern; 29 | int* arr = new int[pattern.length()]; 30 | getLPS(pattern,arr); 31 | for(int i=0;i 20 | using namespace std; 21 | 22 | int countPalindromeSubstrings(char s[]) { 23 | // Write your code here 24 | // int n = sizeof(s)/sizeof(char); 25 | int n = 0; 26 | while(s[n] != '\0'){ 27 | n++; 28 | } 29 | 30 | int count = 0; 31 | for(int i=0;i= 0 && right < n) && s[left] == s[right]){ 35 | count++; 36 | left--; 37 | right++; 38 | } 39 | 40 | left = i; 41 | right = i+1; 42 | while((left >= 0 && right < n) && s[left] == s[right]){ 43 | count++; 44 | left--; 45 | right++; 46 | } 47 | 48 | } 49 | 50 | return count; 51 | } 52 | 53 | 54 | int main() { 55 | char input[10000]; 56 | cin >> input; 57 | cout << countPalindromeSubstrings(input) << endl; 58 | } 59 | -------------------------------------------------------------------------------- /String Algorithms/Z-algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void buildArray(string str,int* arr){ 6 | int left = 0; 7 | int right = 0; 8 | int n = str.length(); 9 | for(int i=1;i right){ 11 | left = i; 12 | right = i; 13 | while(right < n && str[right-left] == str[right]){ 14 | right++; 15 | } 16 | arr[i] = right - left; 17 | right -- ; 18 | }else{ 19 | int k = i - left; 20 | if(arr[k] <= (right-i)){ 21 | arr[i] = arr[k]; 22 | }else{ 23 | left = i; 24 | while(right < n && str[right-left] == str[right]){ 25 | right++; 26 | } 27 | arr[i] = right - left; 28 | right--; 29 | } 30 | } 31 | } 32 | return ; 33 | } 34 | 35 | void searchString(string text,string pattern){ 36 | string str = pattern+"$"+text; 37 | int n = str.length(); 38 | int* arr = new int[n](); 39 | buildArray(str,arr); 40 | for(int i=0;i> text; 52 | cout << "Enter pattern" << endl; 53 | cin >> pattern; 54 | searchString(text,pattern); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Time and Space complexity/kadane.cpp: -------------------------------------------------------------------------------- 1 | //MAX SUBARRAY PROBLEM 2 | 3 | #include 4 | using namespace std; 5 | #define MIN -9999; 6 | 7 | 8 | int kadane(int arr[],int n){ 9 | int current_sum = 0; 10 | int best_sum = MIN; 11 | for(int i=0;i> n; 27 | int* arr =new int[n]; 28 | for(int i=0;i> arr[i]; 30 | } 31 | int ans = kadane(arr,n); 32 | cout << ans; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Time and Space complexity/max product subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | 5 | 6 | ll maxproduct(int arr[],int n){ 7 | ll max_ending_here = 1; 8 | ll min_ending_here = 1; 9 | ll max_so_far = 0; 10 | for(int i=0;i 0){ 12 | max_ending_here = max_ending_here*arr[i]; 13 | min_ending_here = min(1,min_ending_here*arr[i]);//if no prev entries in array are -ve then min_end_here = 1 so to avoid arr[i]*min_ending_here becoming more +ve we take max with 1 14 | }else if(arr[i] == 0){ 15 | max_ending_here = 1; 16 | min_ending_here = 1; 17 | }else{ 18 | int temp = max_ending_here; 19 | max_ending_here = max(1,min_ending_here*arr[i]); 20 | min_ending_here = temp*arr[i]; 21 | } 22 | 23 | max_so_far = max(max_ending_here,max_so_far); 24 | } 25 | return max_so_far; 26 | 27 | } 28 | 29 | int main(){ 30 | int n; 31 | cin >> n; 32 | int* arr = new int[n]; 33 | for(int i=0;i> arr[i]; 35 | } 36 | ll ans = maxproduct(arr,n); 37 | cout << ans << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Time and Space complexity/mind bending.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | finding product of given array except at A[i] 3 | contraints : dont use division by A[i] to product 4 | constant space requirement(no additional creation of array) 5 | 6 | */ 7 | 8 | 9 | 10 | #include 11 | using namespace std; 12 | 13 | 14 | int main(){ 15 | 16 | int n; 17 | cin >> n; 18 | long arr[n]; 19 | long product[n]; 20 | for(int i=0;i> arr[i]; 22 | } 23 | 24 | //SOLUTION 1 : IN ONE ARRAY WE ARE MAINTAINING BOTH LEFT AND RIGHT PRODUCT ARRAY 25 | 26 | long rp = 1; 27 | long lp = 1; 28 | for(int i=0;i=0;i--){ 33 | product[i] = product[i] * rp; 34 | rp = rp * arr[i]; 35 | } 36 | for(int i=0;i=0;i--){ 66 | // right[i] = rp; 67 | // rp = rp*arr[i]; 68 | // } 69 | // int i=0; 70 | // int j=0; 71 | // while(i 2 | using namespace std; 3 | 4 | void increment(int& i) { 5 | i++; 6 | } 7 | 8 | // bad practice 9 | int& f(int n) { 10 | int a = n; 11 | return a; 12 | } 13 | 14 | // bad practice 15 | int* f2() { 16 | int i = 10; 17 | return &i; 18 | } 19 | 20 | int main() { 21 | int* p = f2(); 22 | 23 | int i; 24 | i = 10; 25 | 26 | int& k1 = f(i); 27 | 28 | 29 | increment(i); 30 | cout << i << endl; 31 | 32 | int& j = i; 33 | 34 | i++; 35 | cout << j << endl; 36 | j++; 37 | cout << i << endl; 38 | 39 | int k = 100; 40 | j = k; 41 | cout << i << endl; 42 | } 43 | -------------------------------------------------------------------------------- /pointers/pointers.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nagaraj-U/Coding-Ninjas-Competitive-Programming/4353a4c2ab9f5fa02a4e8234655eb0b72453cd65/pointers/pointers.pdf --------------------------------------------------------------------------------