├── Notes ├── ADT.pdf ├── OOPS.pdf ├── OOPS 2.pdf ├── Queues.pdf ├── Stacks.pdf ├── Trees.pdf ├── Pointers.pdf ├── Recursion.pdf ├── Templates.pdf ├── Vectors.pdf ├── Recursion 1.pdf ├── Recursion 2.pdf ├── Linked List 1.pdf ├── Linked List 2.pdf ├── Priority Queues.pdf ├── Time Complexity.pdf ├── Binary Tree Nodes.pdf └── Dynamic Memory Allocation.pdf ├── README.md ├── Recursion 1 ├── Sum of Digit.cpp ├── Number of Digits.cpp ├── Power.cpp ├── Print Numbers.cpp ├── Sum of Array.cpp ├── Geometric Sum.cpp ├── Multiplication.cpp ├── Check Pallindrome.cpp ├── Check Number.cpp ├── Count Zeroes.cpp ├── First Index of a Number.cpp ├── Last Index of a Number.cpp └── All indices of Number.cpp ├── Binary Tree ├── Pre order.cpp ├── Post Order.cpp ├── Sum of Nodes.cpp ├── Height of a Binary Tree.cpp ├── Min and Max of a Binary tree.cpp ├── Nodes without Sibling.cpp ├── Zig Zag Tree.cpp ├── Mirror.cpp ├── Level order Transversal.cpp ├── Remove leaf Node.cpp └── Check Balanced.cpp ├── Recursion 2 ├── StairCase.cpp ├── Replace Character.cpp ├── Remove Duplicates.cpp ├── Print Keypad Combinations Code.cpp ├── Print Permutations.cpp ├── Print Subset of an Array.cpp ├── Return Permutations - Strings.cpp ├── Print Subset sum to K.cpp ├── Return all code - String.cpp ├── Print all codes.cpp ├── Check AB.cpp ├── Return Subset of an Array.cpp ├── Quick Sort.cpp ├── Return Keypad Code.cpp ├── Return Subsets sum to K.cpp └── Merge Sort.cpp ├── LICENSE ├── Recursion 1b ├── Replace pi.cpp ├── String to Integer.cpp ├── Pair Star.cpp ├── Remove X.cpp └── Tower of Hanoi.cpp ├── Test 1 ├── Does S contain T.cpp ├── Maximum profit on app.cpp └── Split Array.cpp ├── Stacks ├── Reverse a Stack.cpp ├── Balanced Parenthesis.cpp ├── Check Redundant Brackets.cpp ├── Minimum bracket Reversal.cpp └── Stock Span.cpp ├── Linked List 1 ├── Length of LL (Recursive).cpp ├── Print Reverse LL.cpp ├── Print ith node.cpp ├── Palindrome LL.cpp ├── Eliminate duplicates from LL.cpp ├── Length of LL.cpp ├── Delete Node (Recursive).cpp ├── Find a node in Linked List.cpp ├── Insert Node (Recursively).cpp ├── Delete Node.cpp └── Append last to first.cpp ├── Tress ├── Find Sum of Node.cpp ├── Count Leaf node.cpp ├── PostOrder Traversal.cpp ├── Find height.cpp ├── Count Nodes.cpp ├── Max Data Node.cpp ├── Contains X.cpp ├── Node with maximum child sum.cpp ├── Print Level Wise.cpp ├── Next larger.cpp ├── Replace with depth.cpp ├── Second Largest element in tree.cpp └── Structurally identical.cpp ├── Queue └── Reverse Queue.cpp ├── Linked List 2 ├── Find a Node (Recursive).cpp ├── Midpoint of LL.cpp ├── Bubble Sort (Itetative) LL.cpp ├── Reverse LL (Recursive).cpp ├── Reverse LL (Iterative).cpp ├── Swap two Nodes of LL.cpp └── Even after Odd LinkedList.cpp ├── Test 2 ├── Delete Alternate Node.cpp └── Next Number.cpp ├── OOPS └── Complex Number Class.cpp └── BST └── Search in BST.cpp /Notes/ADT.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/ADT.pdf -------------------------------------------------------------------------------- /Notes/OOPS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/OOPS.pdf -------------------------------------------------------------------------------- /Notes/OOPS 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/OOPS 2.pdf -------------------------------------------------------------------------------- /Notes/Queues.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Queues.pdf -------------------------------------------------------------------------------- /Notes/Stacks.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Stacks.pdf -------------------------------------------------------------------------------- /Notes/Trees.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Trees.pdf -------------------------------------------------------------------------------- /Notes/Pointers.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Pointers.pdf -------------------------------------------------------------------------------- /Notes/Recursion.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Recursion.pdf -------------------------------------------------------------------------------- /Notes/Templates.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Templates.pdf -------------------------------------------------------------------------------- /Notes/Vectors.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Vectors.pdf -------------------------------------------------------------------------------- /Notes/Recursion 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Recursion 1.pdf -------------------------------------------------------------------------------- /Notes/Recursion 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Recursion 2.pdf -------------------------------------------------------------------------------- /Notes/Linked List 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Linked List 1.pdf -------------------------------------------------------------------------------- /Notes/Linked List 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Linked List 2.pdf -------------------------------------------------------------------------------- /Notes/Priority Queues.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Priority Queues.pdf -------------------------------------------------------------------------------- /Notes/Time Complexity.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Time Complexity.pdf -------------------------------------------------------------------------------- /Notes/Binary Tree Nodes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Binary Tree Nodes.pdf -------------------------------------------------------------------------------- /Notes/Dynamic Memory Allocation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Its-Aman-Yadav/Data-Structures-and-Algos-Coding-Ninjas/HEAD/Notes/Dynamic Memory Allocation.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding_Ninjas_Introduction_part 2 | I created this for myself and for other people out there to get help by refering these file but it is an humble request you to first try it by yourself then you can refer them otherwise it is just copy pasting work and your certificate will have no value. 3 | 4 | # Contact 5 | For any queries, guidance and help you can ask me at itsamanyadav18@gmail.com
6 | Insta - its_aman_yadav
7 | Twitter - its_aman_yadav
8 | Linkedin - itsamanyadav
9 | Thank you, happy coding :) 10 | -------------------------------------------------------------------------------- /Recursion 1/Sum of Digit.cpp: -------------------------------------------------------------------------------- 1 | /*Write a recursive function that returns the sum of the digits of a given integer. 2 | 3 | Input format : 4 | Integer N 5 | 6 | Output format : 7 | Sum of digits of N 8 | 9 | Constraints : 10 | 0 <= N <= 10^9 11 | 12 | Sample Input 1 : 13 | 12345 14 | 15 | Sample Output 1 : 16 | 15 17 | 18 | Sample Input 2 : 19 | 9 20 | 21 | Sample Output 2 : 22 | 9*/ 23 | 24 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | int sumOfDigits(int n) 27 | { 28 | if (n == 0) 29 | return 0; 30 | else 31 | return n % 10 + sumOfDigits(n / 10); 32 | } 33 | -------------------------------------------------------------------------------- /Binary Tree/Pre order.cpp: -------------------------------------------------------------------------------- 1 | /*You are given the root node of a binary tree.Print its preorder traversal. 2 | 3 | Input Format: 4 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 5 | 6 | Output Format: 7 | The only line of output prints the preorder traversal of the given binary tree. 8 | 9 | Constraints: 10 | 1 <= N <= 10^6 11 | Where N is the total number of nodes in the binary tree. 12 | 13 | Time Limit: 1 sec 14 | 15 | Sample Input 1: 16 | 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1 17 | 18 | Sample Output 1: 19 | 1 2 4 5 3 6 7 20 | 21 | Sample Input 2: 22 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 23 | 24 | Sample Output 1: 25 | 5 6 2 3 9 10*/ 26 | -------------------------------------------------------------------------------- /Recursion 1/Number of Digits.cpp: -------------------------------------------------------------------------------- 1 | /*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 should pass. 2 | 3 | Input Format : 4 | Integer n 5 | 6 | Output Format : 7 | Count of digits 8 | 9 | Constraints : 10 | 1 <= n <= 10^6 11 | 12 | Sample Input 1 : 13 | 156 14 | 15 | Sample Output 1 : 16 | 3 17 | 18 | Sample Input 2 : 19 | 7 20 | 21 | Sample Output 2 : 22 | 1*/ 23 | 24 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | int count(int n){ 27 | if(n == 0){ 28 | return 0; 29 | } 30 | int smallAns = count(n / 10); 31 | return smallAns + 1; 32 | } 33 | -------------------------------------------------------------------------------- /Recursion 1/Power.cpp: -------------------------------------------------------------------------------- 1 | /*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. 2 | Do this recursively. 3 | Input format : 4 | 5 | Two integers x and n (separated by space) 6 | 7 | Output Format : 8 | x^n (i.e. x raise to the power n) 9 | 10 | Constraints : 11 | 0 <= x <= 30 12 | 0 <= n <= 30 13 | 14 | Sample Input 1 : 15 | 3 4 16 | 17 | Sample Output 1 : 18 | 81 19 | 20 | Sample Input 2 : 21 | 2 5 22 | 23 | Sample Output 2 : 24 | 32*/ 25 | 26 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 27 | 28 | int power(int x, int n) 29 | { 30 | if (n == 1) 31 | return x; 32 | if (n == 0) 33 | return 1; 34 | return x * power(x, n - 1); 35 | } 36 | -------------------------------------------------------------------------------- /Recursion 1/Print Numbers.cpp: -------------------------------------------------------------------------------- 1 | /*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. 2 | 3 | Input Format : 4 | Integer 5 | 6 | Output Format : 7 | Numbers from 1 to n (separated by space) 8 | 9 | Constraints : 10 | 1 <= n <= 10000 11 | 12 | Sample Input 1 : 13 | 6 14 | 15 | Sample Output 1 : 16 | 1 2 3 4 5 6 17 | 18 | Sample Input 2 : 19 | 4 20 | 21 | Sample Output 2 : 22 | 1 2 3 4*/ 23 | 24 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | void print(int n) 27 | { 28 | if (n == 1) 29 | cout << n; 30 | else 31 | { 32 | print(n - 1); 33 | cout << " " << n; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Recursion 1/Sum of Array.cpp: -------------------------------------------------------------------------------- 1 | /*Given an array of length N, you need to find and return the sum of all elements of the array. 2 | Do this recursively. 3 | 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 | 8 | Output Format : 9 | Sum 10 | 11 | Constraints : 12 | 1 <= N <= 10^3 13 | 14 | Sample Input 1 : 15 | 3 16 | 9 8 9 17 | 18 | Sample Output 1 : 19 | 26 20 | 21 | Sample Input 2 : 22 | 3 23 | 4 2 1 24 | 25 | Sample Output 2 : 26 | 7 */ 27 | 28 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | int sum(int input[], int n) 31 | { 32 | if (n == 0) 33 | return 0; 34 | return input[0] + sum(input + 1, n - 1); 35 | } 36 | -------------------------------------------------------------------------------- /Recursion 1/Geometric Sum.cpp: -------------------------------------------------------------------------------- 1 | /*Given k, find the geometric sum i.e. 2 | 1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k) 3 | using recursion. 4 | 5 | Input format : 6 | Integer k 7 | 8 | Output format : 9 | Geometric sum (upto 5 decimal places) 10 | 11 | Constraints : 12 | 0 <= k <= 1000 13 | 14 | Sample Input 1 : 15 | 3 16 | 17 | Sample Output 1 : 18 | 1.87500 19 | 20 | Sample Input 2 : 21 | 4 22 | 23 | Sample Output 2 : 24 | 1.93750 25 | 26 | Explanation for Sample Input 1: 27 | 1+ 1/(2^1) + 1/(2^2) + 1/(2^3) = 1.87500*/ 28 | 29 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 30 | 31 | double geometricSum(int k) 32 | { 33 | if (k == 0) 34 | return 1; 35 | else 36 | return 1 / pow(2, k) + geometricSum(k - 1); 37 | } 38 | -------------------------------------------------------------------------------- /Recursion 1/Multiplication.cpp: -------------------------------------------------------------------------------- 1 | /*Given two integers M & N, calculate and return their multiplication using recursion. You can only use subtraction and addition for your calculation. No other operators are allowed. 2 | 3 | Input format : 4 | Line 1 : Integer M 5 | Line 2 : Integer N 6 | 7 | Output format : 8 | M x N 9 | 10 | Constraints : 11 | 0 <= M <= 1000 12 | 0 <= N <= 1000 13 | 14 | Sample Input 1 : 15 | 3 16 | 5 17 | 18 | Sample Output 1 : 19 | 15 20 | 21 | Sample Input 2 : 22 | 4 23 | 0 24 | 25 | Sample Output 2 : 26 | 0*/ 27 | 28 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | int multiplyNumbers(int m, int n) 31 | { 32 | if (n == 0) 33 | return 0; 34 | else 35 | return m + multiplyNumbers(m, n - 1); 36 | } 37 | -------------------------------------------------------------------------------- /Recursion 1/Check Pallindrome.cpp: -------------------------------------------------------------------------------- 1 | /*Check whether a given String S is a palindrome using recursion. Return true or false. 2 | 3 | Input Format : 4 | String S 5 | 6 | Output Format : 7 | 'true' or 'false' 8 | 9 | Constraints : 10 | 0 <= |S| <= 1000 11 | 12 | where |S| represents length of string S. 13 | 14 | Sample Input 1 : 15 | racecar 16 | 17 | Sample Output 1: 18 | true 19 | 20 | Sample Input 2 : 21 | ninja 22 | 23 | Sample Output 2: 24 | false*/ 25 | 26 | ----------------------------------------------------------------------------------------------------------------------------------------------------------- 27 | 28 | #include 29 | bool checkPalindrome(char input[]) 30 | { 31 | static int i = 0; 32 | int l = strlen(input); 33 | if (i == l) 34 | return true; 35 | if (input[i] == input[l - i - 1]) 36 | { 37 | i++; 38 | checkPalindrome(input); 39 | } 40 | else 41 | return false; 42 | } 43 | -------------------------------------------------------------------------------- /Recursion 1/Check Number.cpp: -------------------------------------------------------------------------------- 1 | /*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. 2 | Do this recursively. 3 | Input Format : 4 | Line 1 : An Integer N i.e. size of array 5 | Line 2 : N integers which are elements of the array, separated by spaces 6 | Line 3 : Integer x 7 | 8 | Output Format : 9 | 'true' or 'false' 10 | 11 | Constraints : 12 | 1 <= N <= 10^3 13 | 14 | Sample Input 1 : 15 | 3 16 | 9 8 10 17 | 8 18 | 19 | Sample Output 1 : 20 | true 21 | 22 | Sample Input 2 : 23 | 3 24 | 9 8 10 25 | 2 26 | 27 | Sample Output 2 : 28 | false*/ 29 | 30 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | bool checkNumber(int input[], int size, int x) 33 | { 34 | if (size == 0) 35 | return false; 36 | if (input[0] == x) 37 | return true; 38 | else 39 | return checkNumber(input + 1, size - 1, x); 40 | } 41 | -------------------------------------------------------------------------------- /Recursion 2/StairCase.cpp: -------------------------------------------------------------------------------- 1 | /*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 to the stairs. You need to return number of possible ways W. 2 | 3 | Input format : 4 | Integer N 5 | 6 | Output Format : 7 | Integer W 8 | 9 | Constraints : 10 | 1 <= N <= 30 11 | 12 | Sample Input 1 : 13 | 4 14 | 15 | Sample Output 1 : 16 | 7 17 | 18 | Sample Input 2 : 19 | 5 20 | 21 | Sample Output 2 : 22 | 13*/ 23 | 24 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | #include 27 | using namespace std; 28 | 29 | int staircase(int n){ 30 | 31 | if(n < 0) return 0; 32 | else if(n == 1 || n == 0) return 1; 33 | return staircase(n-1) + staircase(n-2) + staircase(n-3); 34 | } 35 | 36 | int main() { 37 | int n, output; 38 | cin >> n; 39 | output=staircase(n); 40 | cout<< output < 24 | using namespace std; 25 | 26 | void replaceCharacter(char input[], char c1, char c2) { 27 | 28 | if(*input == '\0') { 29 | return; 30 | } 31 | 32 | if(*input == c1) { 33 | *input = c2; 34 | } 35 | 36 | replaceCharacter(input + 1, c1, c2); 37 | 38 | } 39 | 40 | int main() { 41 | char input[1000000]; 42 | char c1, c2; 43 | cin >> input; 44 | cin >> c1 >> c2; 45 | replaceCharacter(input, c1, c2); 46 | cout << input << endl; 47 | } 48 | -------------------------------------------------------------------------------- /Recursion 2/Remove Duplicates.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string S, remove consecutive duplicates from it recursively. 2 | 3 | Input Format : 4 | String S 5 | 6 | Output Format : 7 | Output string 8 | 9 | Constraints : 10 | 1 <= |S| <= 10^3 11 | 12 | where |S| represents the length of string 13 | 14 | Sample Input 1 : 15 | aabccba 16 | 17 | Sample Output 1 : 18 | abcba 19 | 20 | Sample Input 2 : 21 | xxxyyyzwwzzz 22 | 23 | Sample Output 2 : 24 | xyzwz*/ 25 | 26 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 27 | 28 | #include 29 | using namespace std; 30 | 31 | void removeConsecutiveDuplicates(char *input) { 32 | 33 | if(*input == '\0') { 34 | return; 35 | } 36 | 37 | if(*input == *(input + 1)) { 38 | int i = 1; 39 | for(; input[i] != '\0'; i++) { 40 | input[i - 1] = input[i]; 41 | } 42 | input[i - 1] = input[i]; 43 | removeConsecutiveDuplicates(input); 44 | } else { 45 | removeConsecutiveDuplicates(input + 1); 46 | } 47 | 48 | } 49 | 50 | int main() { 51 | char s[100000]; 52 | cin >> s; 53 | removeConsecutiveDuplicates(s); 54 | cout << s << endl; 55 | } 56 | -------------------------------------------------------------------------------- /Recursion 1/Last Index of a Number.cpp: -------------------------------------------------------------------------------- 1 | /*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. 2 | 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 | 5 | You should start traversing your array from 0, not from (N - 1). 6 | Do this recursively. Indexing in the array starts from 0. 7 | 8 | Input Format : 9 | Line 1 : An Integer N i.e. size of array 10 | Line 2 : N integers which are elements of the array, separated by spaces 11 | Line 3 : Integer x 12 | 13 | Output Format : 14 | last index or -1 15 | 16 | Constraints : 17 | 1 <= N <= 10^3 18 | 19 | Sample Input : 20 | 4 21 | 9 8 10 8 22 | 8 23 | 24 | Sample Output : 25 | 3*/ 26 | 27 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 28 | 29 | int lastIndex(int input[], int size, int x) 30 | { 31 | if (size == 0) 32 | return -1; 33 | if (input[size - 1] == x) 34 | return size - 1; 35 | int index = lastIndex(input, size - 1, x); 36 | if (index == -1) 37 | return -1; 38 | else 39 | return index; 40 | } 41 | -------------------------------------------------------------------------------- /Recursion 1/All indices of Number.cpp: -------------------------------------------------------------------------------- 1 | /*Given an array of length N and an integer x, you need to find all the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). 2 | 3 | Do this recursively. Indexing in the array starts from 0. 4 | 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 | 10 | Output Format : 11 | indexes where x is present in the array (separated by space) 12 | 13 | Constraints : 14 | 1 <= N <= 10^3 15 | 16 | Sample Input : 17 | 5 18 | 9 8 10 8 8 19 | 8 20 | 21 | Sample Output : 22 | 1 3 4*/ 23 | 24 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | int allIndexes(int input[], int size, int x, int output[]) 27 | { 28 | if (size == 0) 29 | return 0; 30 | int s = allIndexes(input + 1, size - 1, x, output); 31 | if (input[0] == x) 32 | { 33 | for (int i = s - 1; i >= 0; i--) 34 | output[i + 1] = output[i] + 1; 35 | output[0] = 0; 36 | s++; 37 | } 38 | else 39 | for (int i = s - 1; i >= 0; i--) 40 | output[i] = output[i] + 1; 41 | return s; 42 | } 43 | -------------------------------------------------------------------------------- /Recursion 1b/Replace pi.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string, compute recursively a new string where all appearances of "pi" have been replaced by "3.14". 2 | 3 | Constraints : 4 | 1 <= |S| <= 50 5 | where |S| represents the length of string S. 6 | 7 | Sample Input 1 : 8 | xpix 9 | 10 | Sample Output : 11 | x3.14x 12 | 13 | Sample Input 2 : 14 | pipi 15 | 16 | Sample Output : 17 | 3.143.14 18 | 19 | Sample Input 3 : 20 | pip 21 | 22 | Sample Output : 23 | 3.14p 24 | 25 | Constraints:- 26 | 1<=|S|<=50*/ 27 | 28 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | 31 | #include 32 | #include 33 | #include "solution.h" 34 | using namespace std; 35 | 36 | void replacePi(char input[]) { 37 | if(input[0]=='\0') 38 | return; 39 | if(input[0]=='p' && input[1]=='i'){ 40 | input[0]='3'; 41 | input[1]='.'; 42 | 43 | int size=strlen(input); 44 | for(int i=size+2;i>1;i--){ 45 | input[i]=input[i-2]; 46 | } 47 | input[2]='1'; 48 | input[3]='4'; 49 | } 50 | 51 | replacePi(input+1); 52 | 53 | } 54 | 55 | int main() { 56 | char input[10000]; 57 | cin.getline(input, 10000); 58 | replacePi(input); 59 | cout << input << endl; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /Recursion 1b/String to Integer.cpp: -------------------------------------------------------------------------------- 1 | /*Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer. 2 | 3 | Input format : 4 | Numeric string S (string, Eg. "1234") 5 | 6 | Output format : 7 | Corresponding integer N (int, Eg. 1234) 8 | 9 | Constraints : 10 | 0 <= |S| <= 9 11 | where |S| represents length of string S. 12 | 13 | Sample Input 1 : 14 | 00001231 15 | 16 | Sample Output 1 : 17 | 1231 18 | 19 | Sample Input 2 : 20 | 12567 21 | 22 | Sample Output 2 : 23 | 12567*/ 24 | 25 | ------------------------------------------------------------------------------------------------------------------------------------------------------------- 26 | 27 | #include 28 | #include "solution.h" 29 | using namespace std; 30 | 31 | void stringToNumber_Actual(char temp[], int &n) { 32 | if(*temp == '\0') { 33 | return; 34 | } 35 | 36 | n = (n * 10) + (*temp - '0') ; 37 | 38 | //hyothesis step 39 | stringToNumber_Actual(temp + 1, n); 40 | 41 | } 42 | 43 | int stringToNumber(char temp[]) { 44 | int answer = 0; 45 | 46 | stringToNumber_Actual(temp, answer); 47 | return answer; 48 | } 49 | 50 | int main() { 51 | char input[50]; 52 | cin >> input; 53 | cout << stringToNumber(input) << endl; 54 | } 55 | -------------------------------------------------------------------------------- /Recursion 2/Print Keypad Combinations Code.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n. 2 | Note : The order of strings are not important. Just print different strings in new lines. 3 | 4 | Input Format : 5 | Integer n 6 | 7 | Output Format : 8 | All possible strings in different lines 9 | 10 | Constraints : 11 | 1 <= n <= 10^6 12 | 13 | Sample Input: 14 | 23 15 | 16 | Sample Output: 17 | ad 18 | ae 19 | af 20 | bd 21 | be 22 | bf 23 | cd 24 | ce 25 | cf*/ 26 | 27 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | #define line endl; 34 | 35 | string reference[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 36 | 37 | 38 | void printKeypad(int num, string output = " "){ 39 | if(num == 0) { 40 | cout << output << line; 41 | return; 42 | } 43 | 44 | 45 | int curr = num % 10; 46 | int len = reference[curr].size(); 47 | 48 | 49 | for(int i = 0; i < len; i++) { 50 | printKeypad(num / 10, reference[curr][i] + output); 51 | } 52 | 53 | } 54 | 55 | int main(){ 56 | int num; 57 | cin >> num; 58 | 59 | printKeypad(num); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Recursion 2/Print Permutations.cpp: -------------------------------------------------------------------------------- 1 | /*Given an input string (STR), print all possible permutations of the input string. 2 | Note: 3 | The input string may contain the same characters, so there will also be the same permutations. 4 | The order of permutations doesn’t matter. 5 | 6 | Input Format: 7 | The only input line contains a string (STR) of alphabets in lower case 8 | 9 | Output Format: 10 | Print each permutations in a new line 11 | 12 | Note: 13 | You do not need to print anything, it has already been taken care of. Just implement the function. 14 | 15 | Constraint: 16 | 1<=length of STR<=8 17 | Time Limit: 1sec 18 | 19 | Sample Input 1: 20 | cba 21 | 22 | Sample Output 1: 23 | abc 24 | acb 25 | bac 26 | bca 27 | cab 28 | cba */ 29 | 30 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | #include 33 | #include 34 | #include 35 | using namespace std; 36 | 37 | void printPermutations_Helper(string input, string ans){ 38 | if(input.size() == 0) { 39 | cout << ans << endl; 40 | return; 41 | } 42 | 43 | for(int i = 0; i <= ans.size(); i++){ 44 | printPermutations_Helper(input.substr(1), ans.substr(0,i) + input[0] + ans.substr(i)); 45 | } 46 | 47 | } 48 | void printPermutations(string input){ 49 | string ans; 50 | printPermutations_Helper(input, ans); 51 | } 52 | 53 | int main() { 54 | string input; 55 | cin >> input; 56 | printPermutations(input); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Recursion 1b/Pair Star.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string S, compute recursively a new string where identical chars that are adjacent in the original string are separated from each other by a "*". 2 | 3 | Input format : 4 | String S 5 | 6 | Output format : 7 | Modified string 8 | 9 | Constraints : 10 | 0 <= |S| <= 1000 11 | where |S| represents length of string S. 12 | 13 | Sample Input 1 : 14 | hello 15 | 16 | Sample Output 1: 17 | hel*lo 18 | 19 | Sample Input 2 : 20 | aaaa 21 | 22 | Sample Output 2 : 23 | a*a*a*a*/ 24 | 25 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 26 | 27 | #include 28 | #include "solution.h" 29 | using namespace std; 30 | 31 | void pairStar_Actual(char *temp, char *output, int count = 0) { 32 | //base case 33 | if(*temp == '\0'){ 34 | return; 35 | } 36 | 37 | //nth step 38 | if(*temp == *(temp + 1)) { 39 | output[count++] = *temp; 40 | output[count++] = '*'; 41 | } else { 42 | output[count++] = *temp; 43 | } 44 | 45 | //hypothesis step 46 | pairStar_Actual(temp + 1, output, count); 47 | } 48 | 49 | void pairStar(char input[]) { 50 | // Write your code here 51 | char output[1000] = " "; 52 | 53 | pairStar_Actual(input, output); 54 | 55 | char *ptr = output; 56 | 57 | while(*ptr) { 58 | *input++ = *ptr++; 59 | } 60 | *input = '\0'; 61 | } 62 | 63 | int main() { 64 | char input[100]; 65 | cin.getline(input, 100); 66 | pairStar(input); 67 | cout << input << endl; 68 | } 69 | -------------------------------------------------------------------------------- /Recursion 1b/Remove X.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string, compute recursively a new string where all 'x' chars have been removed. 2 | 3 | Input format : 4 | String S 5 | 6 | Output format : 7 | Modified String 8 | 9 | Constraints : 10 | 1 <= |S| <= 10^3 11 | where |S| represents the length of string S. 12 | 13 | Sample Input 1 : 14 | xaxb 15 | 16 | Sample Output 1: 17 | ab 18 | 19 | Sample Input 2 : 20 | abc 21 | 22 | Sample Output 2: 23 | abc 24 | 25 | Sample Input 3 : 26 | xx 27 | 28 | Sample Output 3: 29 | 30 | */ 31 | 32 | --------------------------------------------------------------------------------------------------------------------------------------------------------------- 33 | 34 | #include 35 | #include "solution.h" 36 | using namespace std; 37 | 38 | void removeX_Actual(char temp[], char output[],int size,int count = 0) { 39 | if(!size) { 40 | return; 41 | } 42 | 43 | if(*temp != 'x'){ 44 | output[count++] = *temp; 45 | } 46 | 47 | removeX_Actual(temp + 1, output, size - 1, count); 48 | 49 | } 50 | 51 | void removeX(char input[]) { 52 | char output[1000] = " "; 53 | 54 | char *ptr = input; 55 | int size = 0; 56 | while(*ptr){ 57 | size++; 58 | ptr++; 59 | } 60 | 61 | removeX_Actual(input, output, size); 62 | 63 | for(int i = 0; input[i] != '\0'; i++) { 64 | input[i] = '\0'; 65 | } 66 | 67 | for(int i = 0; output[i] != '\0'; i++){ 68 | input[i] = output[i]; 69 | } 70 | } 71 | 72 | int main() { 73 | char input[100]; 74 | cin.getline(input, 100); 75 | removeX(input); 76 | cout << input << endl; 77 | } 78 | -------------------------------------------------------------------------------- /Recursion 2/Print Subset of an Array.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer array (of length n), find and print all the subsets of input array. 2 | Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. 3 | Note : The order of subsets are not important. Just print the subsets in different lines. 4 | 5 | Input format : 6 | Line 1 : Integer n, Size of array 7 | Line 2 : Array elements (separated by space) 8 | 9 | Constraints : 10 | 1 <= n <= 15 11 | 12 | Sample Input: 13 | 3 14 | 15 20 12 15 | 16 | Sample Output: 17 | [] (this just represents an empty array, don't worry about the square brackets) 18 | 12 19 | 20 20 | 20 12 21 | 15 22 | 15 12 23 | 15 20 24 | 15 20 12 */ 25 | 26 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 27 | 28 | #include 29 | using namespace std; 30 | 31 | void helper(int input[], int size, int output[], int x){ 32 | if(size == 0){ 33 | for(int i=0; i> length; 53 | for(int i=0; i < length; i++) 54 | cin >> input[i]; 55 | printSubsetsOfArray(input, length); 56 | } 57 | -------------------------------------------------------------------------------- /Test 1/Does S contain T.cpp: -------------------------------------------------------------------------------- 1 | /*Given two string s and t, write a function to check if s contains all characters of t (in the same order as they are in string t). 2 | Return true or false. 3 | Do it recursively. 4 | 5 | E.g. : s = “abchjsgsuohhdhyrikkknddg” contains all characters of t=”coding” in the same order. So function will return true. 6 | 7 | Input Format : 8 | Line 1 : String s 9 | Line 2 : String t 10 | 11 | Output Format : 12 | true or false 13 | 14 | Sample Input 1 : 15 | abchjsgsuohhdhyrikkknddg 16 | coding 17 | 18 | Sample Output 1 : 19 | true 20 | 21 | Sample Input 2 : 22 | abcde 23 | aeb 24 | 25 | Sample Output 2 : 26 | false*/ 27 | 28 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | #include 31 | using namespace std; 32 | 33 | bool checksequenece(char large[], char *small) 34 | { 35 | bool val; 36 | if (large[1] == '\0' && small[1] != '\0') 37 | return false; 38 | if (large[0] == small[0] && small[1] == '\0') 39 | return true; 40 | if (large[0] != small[0] && small[1] == '\0' && large[1] == '\0') 41 | return false; 42 | if (large[0] == small[0]) 43 | val = checksequenece(large + 1, small + 1); 44 | else 45 | val = checksequenece(large + 1, small); 46 | if (val == true) 47 | return true; 48 | else 49 | return false; 50 | } 51 | 52 | int main() 53 | { 54 | char large[10000]; 55 | char small[10000]; 56 | cin>>large; 57 | cin>>small; 58 | bool x=checksequenece(large , small); 59 | 60 | if(x) 61 | cout<<"true"; 62 | else 63 | cout<<"false"; 64 | 65 | } 66 | -------------------------------------------------------------------------------- /Recursion 2/Return Permutations - Strings.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string S, find and return all the possible permutations of the input string. 2 | 3 | Note 1 : The order of permutations is not important. 4 | Note 2 : If original string contains duplicate characters, permutations will also be duplicates. 5 | 6 | Input Format : 7 | String S 8 | 9 | Output Format : 10 | All permutations (in different lines) 11 | 12 | Sample Input : 13 | abc 14 | 15 | Sample Output : 16 | abc 17 | acb 18 | bac 19 | bca 20 | cab 21 | cba*/ 22 | 23 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 24 | 25 | #include 26 | #include 27 | using namespace std; 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | int returnPermutations(string input, string output[]){ 34 | if(input.size() == 0){ 35 | output[0] =""; 36 | return 1; 37 | } 38 | 39 | string smallString[10000]; 40 | int smallsize = returnPermutations(input.substr(1), smallString); 41 | 42 | int idx = 0; 43 | for(int i = 0; i < smallsize; i++) { 44 | for(int j = 0; j <= smallString[i].size(); j++){ 45 | output[idx++] = smallString[i].substr(0,j) + input[0] + smallString[i].substr(j); 46 | } 47 | } 48 | 49 | return idx; 50 | 51 | } 52 | 53 | int main(){ 54 | string input; 55 | cin >> input; 56 | string output[10000]; 57 | int count = returnPermutations(input, output); 58 | for(int i = 0; i < count && i < 10000; i++){ 59 | cout << output[i] << endl; 60 | } 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Recursion 2/Print Subset sum to K.cpp: -------------------------------------------------------------------------------- 1 | /*Given an array A and an integer K, print all subsets of A which sum to K. 2 | Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. 3 | Note : The order of subsets are not important. Just print them in different lines. 4 | 5 | Input format : 6 | Line 1 : Size of input array 7 | Line 2 : Array elements separated by space 8 | Line 3 : K 9 | 10 | Sample Input: 11 | 9 12 | 5 12 3 17 1 18 15 3 17 13 | 6 14 | 15 | Sample Output: 16 | 3 3 17 | 5 1*/ 18 | 19 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 20 | 21 | #include 22 | using namespace std; 23 | 24 | void helper(int input[], int n, int output[], int s, int k){ 25 | if(n == 0){ 26 | int sum = 0; 27 | for(int i=0; i> length; 54 | for(int i=0; i < length; i++) 55 | cin >> input[i]; 56 | cin>>k; 57 | printSubsetSumToK(input, length,k); 58 | } 59 | -------------------------------------------------------------------------------- /Recursion 2/Return all code - String.cpp: -------------------------------------------------------------------------------- 1 | /*Given an array A and an integer K, print all subsets of A which sum to K. 2 | Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. 3 | Note : The order of subsets are not important. Just print them in different lines. 4 | 5 | Input format : 6 | Line 1 : Size of input array 7 | Line 2 : Array elements separated by space 8 | Line 3 : K 9 | 10 | Sample Input: 11 | 9 12 | 5 12 3 17 1 18 15 3 17 13 | 6 14 | 15 | Sample Output: 16 | 3 3 17 | 5 1 18 | */ 19 | 20 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 21 | 22 | #include 23 | using namespace std; 24 | 25 | void helper(int input[], int n, int output[], int s, int k){ 26 | if(n == 0){ 27 | int sum = 0; 28 | for(int i=0; i> length; 55 | for(int i=0; i < length; i++) 56 | cin >> input[i]; 57 | cin>>k; 58 | printSubsetSumToK(input, length,k); 59 | } 60 | -------------------------------------------------------------------------------- /Recursion 2/Print all codes.cpp: -------------------------------------------------------------------------------- 1 | /*Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. You are given a numeric string S. Write a program to print the list of all possible codes that can be generated from the given string. 2 | Note : The order of codes are not important. Just print them in different lines. 3 | 4 | Input format : 5 | A numeric string S 6 | 7 | Output Format : 8 | All possible codes in different lines 9 | 10 | Constraints : 11 | 1 <= Length of String S <= 10 12 | 13 | Sample Input: 14 | 1123 15 | 16 | Sample Output: 17 | aabc 18 | kbc 19 | alc 20 | aaw 21 | kw*/ 22 | 23 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 24 | 25 | #include 26 | using namespace std; 27 | 28 | #include 29 | #include 30 | using namespace std; 31 | 32 | char ctchar(int i) { 33 | char c = 'a' + i - 1; 34 | return c; 35 | } 36 | int ctin(char a) { 37 | int n = a - '0'; 38 | return n; 39 | } 40 | 41 | void printAllPossibleCodes_Helper(string input, string ans) { 42 | if(input.empty()) { 43 | cout << ans << endl; 44 | return; 45 | } 46 | 47 | char add = ctchar(ctin(input[0])); 48 | printAllPossibleCodes_Helper(input.substr(1), ans + add); 49 | 50 | if(input.size() > 1){ 51 | int curr = ctin(input[0]) * 10 + ctin(input[1]); 52 | if(curr >= 10 & curr <= 26) { 53 | printAllPossibleCodes_Helper(input.substr(2), ans + ctchar(curr)); 54 | } 55 | } 56 | } 57 | 58 | void printAllPossibleCodes(string input) { 59 | string res; 60 | printAllPossibleCodes_Helper(input, res); 61 | } 62 | 63 | 64 | int main(){ 65 | string input; 66 | cin >> input; 67 | 68 | printAllPossibleCodes(input); 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Recursion 2/Check AB.cpp: -------------------------------------------------------------------------------- 1 | /*Suppose you have a string, S, made up of only 'a's and 'b's. Write a recursive function that checks if the string was generated using the following rules: 2 | a. The string begins with an 'a' 3 | b. Each 'a' is followed by nothing or an 'a' or "bb" 4 | c. Each "bb" is followed by nothing or an 'a' 5 | If all the rules are followed by the given string, return true otherwise return false. 6 | 7 | Input format : 8 | String S 9 | 10 | Output format : 11 | 'true' or 'false' 12 | 13 | Constraints : 14 | 1 <= |S| <= 1000 15 | where |S| represents length of string S. 16 | 17 | Sample Input 1 : 18 | abb 19 | 20 | Sample Output 1 : 21 | true 22 | 23 | Sample Input 2 : 24 | abababa 25 | 26 | Sample Output 2 : 27 | false 28 | 29 | Explanation for Sample Input 2 30 | In the above example, a is not followed by either "a" or "bb", instead it's followed by "b" which results in false to be returned.*/ 31 | 32 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 33 | 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | bool checkAB(char input[]) { 39 | if(strlen(input) == 0) return true; 40 | 41 | if(input[0] == 'a'){ 42 | if(input[1] == 'a'){ 43 | checkAB(input+1); 44 | } 45 | else if(input[1] == 'b' && input[2] == 'b'){ 46 | checkAB(input + 3); 47 | } 48 | else if(input[1] == '\0'){ 49 | return true; 50 | } 51 | else{ 52 | return false; 53 | } 54 | } 55 | else{ 56 | return false; 57 | } 58 | } 59 | 60 | int main() { 61 | char input[100]; 62 | bool ans; 63 | cin >> input; 64 | ans=checkAB(input); 65 | if(ans) 66 | cout<< "true" << endl; 67 | else 68 | cout<< "false" << endl; 69 | } 70 | -------------------------------------------------------------------------------- /Recursion 1b/Tower of Hanoi.cpp: -------------------------------------------------------------------------------- 1 | /*Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move all disks from source rod to destination rod using third rod (say auxiliary). The rules are : 2 | 1) Only one disk can be moved at a time. 3 | 2) A disk can be moved only if it is on the top of a rod. 4 | 3) No disk can be placed on the top of a smaller disk. 5 | 6 | Print the steps required to move n disks from source rod to destination rod. 7 | Source Rod is named as 'a', auxiliary rod as 'b' and destination rod as 'c'. 8 | 9 | Input Format : 10 | Integer n 11 | 12 | Output Format : 13 | Steps in different lines (in one line print source and destination rod name separated by space) 14 | 15 | Constraints : 16 | 0 <= n <= 20 17 | 18 | Sample Input 1 : 19 | 2 20 | 21 | Sample Output 1 : 22 | a b 23 | a c 24 | b c 25 | 26 | Sample Input 2 : 27 | 3 28 | 29 | Sample Output 2 : 30 | a c 31 | a b 32 | c b 33 | a c 34 | b a 35 | b c 36 | a c*/ 37 | 38 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ 39 | 40 | #include 41 | using namespace std; 42 | 43 | void towerOfHanoi(int n, char source, char auxiliary, char destination) { 44 | // Write your code here 45 | // base case 46 | if(n == 1) { 47 | cout << source << " " << destination << endl; 48 | return; 49 | } 50 | // corner case 51 | if(n == 0) { 52 | return; 53 | } 54 | 55 | // hypothesis step to move n-1 disk from a to b using c 56 | towerOfHanoi(n - 1, source, destination, auxiliary); 57 | 58 | // nth step 59 | cout << source << " " << destination << endl; 60 | 61 | // completing the nth step by moving the n-1 disk from b to c using a 62 | towerOfHanoi(n - 1, auxiliary, source, destination); 63 | } 64 | 65 | int main() { 66 | int n; 67 | cin >> n; 68 | towerOfHanoi(n, 'a', 'b', 'c'); 69 | } 70 | -------------------------------------------------------------------------------- /Recursion 2/Return Subset of an Array.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer array (of length n), find and return all the subsets of input array. 2 | Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. 3 | Note : The order of subsets are not important. 4 | 5 | Input format : 6 | 7 | Line 1 : Size of array 8 | 9 | Line 2 : Array elements (separated by space) 10 | 11 | Sample Input: 12 | 3 13 | 15 20 12 14 | 15 | Sample Output: 16 | [] (this just represents an empty array, don't worry about the square brackets) 17 | 12 18 | 20 19 | 20 12 20 | 15 21 | 15 12 22 | 15 20 23 | 15 20 12 */ 24 | 25 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 26 | 27 | #include 28 | using namespace std; 29 | 30 | int subset(int input[], int n, int output[][20]) { 31 | if(n <= 0){ 32 | output[0][0] = 0; 33 | return 1; 34 | } 35 | else{ 36 | int r = subset(input + 1, n-1, output); 37 | for(int i=0; i> length; 59 | for(int i=0; i < length; i++) 60 | cin >> input[i]; 61 | 62 | int size = subset(input, length, output); 63 | 64 | for( int i = 0; i < size; i++) { 65 | for( int j = 1; j <= output[i][0]; j++) { 66 | cout << output[i][j] << " "; 67 | } 68 | cout << endl; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Recursion 2/Quick Sort.cpp: -------------------------------------------------------------------------------- 1 | /*Sort an array A using Quick Sort. 2 | Change in the input array itself. So no need to return or print anything. 3 | 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 | 1 5 2 7 3 25 | 26 | Sample Output 2 : 27 | 1 2 3 5 7 */ 28 | 29 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 30 | 31 | #include 32 | using namespace std; 33 | 34 | void swap(int *a, int *b) { 35 | int temp; 36 | temp = *a; 37 | *a = *b; 38 | *b = temp; 39 | } 40 | 41 | int partition(int *arr, int start, int end) { 42 | int pivot = arr[end]; 43 | int j = start; 44 | int i = start - 1; 45 | 46 | while(j < end) { 47 | if(arr[j] < pivot) { 48 | i++; 49 | swap(&arr[j],&arr[i]); 50 | 51 | } 52 | j++; 53 | } 54 | swap(&arr[i + 1], &arr[j]); 55 | 56 | return i + 1; 57 | 58 | } 59 | 60 | void quickSort(int input[], int start, int end) { 61 | // base case 62 | if(start >= end) { 63 | return; 64 | } 65 | int pivot = partition(input, start, end); 66 | 67 | quickSort(input, start, pivot - 1); 68 | quickSort(input, pivot + 1, end); 69 | } 70 | 71 | void quickSort(int input[], int size) { 72 | 73 | quickSort(input, 0, size - 1); 74 | 75 | } 76 | 77 | 78 | int main(){ 79 | int n; 80 | cin >> n; 81 | 82 | int *input = new int[n]; 83 | 84 | for(int i = 0; i < n; i++) { 85 | cin >> input[i]; 86 | } 87 | 88 | quickSort(input, n); 89 | for(int i = 0; i < n; i++) { 90 | cout << input[i] << " "; 91 | } 92 | 93 | delete [] input; 94 | 95 | } 96 | 97 | 98 | -------------------------------------------------------------------------------- /Test 1/Maximum profit on app.cpp: -------------------------------------------------------------------------------- 1 | /*You have made a smartphone app and want to set its subscription price such that the profit earned is maximised. There are certain users who will subscribe to your app only if their budget is greater than or equal to your price. 2 | 3 | You will be provided with a list of size N having budgets of subscribers and you need to return the maximum profit that you can earn. 4 | Lets say you decide that price of your app is Rs. x and there are N number of subscribers. So maximum profit you can earn is : 5 | m * x 6 | 7 | where m is total number of subscribers whose budget is greater than or equal to x. 8 | 9 | Input format : 10 | Line 1 : N (No. of subscribers) 11 | Line 2 : Budget of subscribers (separated by space) 12 | 13 | Output Format : 14 | Maximum profit 15 | 16 | Constraints : 17 | 1 <= N <= 10^6 18 | 1 <=budget[i]<=9999 19 | 20 | Sample Input 1 : 21 | 4 22 | 30 20 53 14 23 | 24 | Sample Output 1 : 25 | 60 26 | 27 | Sample Output 1 Explanation : 28 | Price of your app should be Rs. 20 or Rs. 30. For both prices, you can get the profit Rs. 60. 29 | 30 | Sample Input 2 : 31 | 5 32 | 34 78 90 15 67 33 | 34 | Sample Output 2 : 35 | 201 36 | 37 | Sample Output 2 Explanation : 38 | Price of your app should be Rs. 67. You can get the profit Rs. 201 (i.e. 3 * 67).*/ 39 | 40 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41 | 42 | #include 43 | #include 44 | using namespace std; 45 | 46 | 47 | int maximumProfit(int budget[], int n) 48 | { 49 | sort(budget, budget + n); 50 | int max_profit = budget[0] * n; 51 | for (int i = 1; i < n; i++) 52 | { 53 | if (budget[i] * (n - i) > max_profit) 54 | max_profit = budget[i] * (n - i); 55 | } 56 | return max_profit; 57 | } 58 | 59 | int main() { 60 | int n ,*input,i,*cost; 61 | cin>>n; 62 | input = new int[n]; 63 | for(i = 0;i < n;i++) 64 | cin>>input[i]; 65 | 66 | cout << maximumProfit(input, n) << endl; 67 | 68 | } 69 | -------------------------------------------------------------------------------- /Stacks/Reverse a Stack.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given two stacks that can store integers as the data. Out of the two given stacks, one is populated and the other one is empty. You are required to write a function that reverses the populated stack using the one which is empty. 2 | For Example: 3 | Alt txt 4 | 5 | Input Format : 6 | The first line of input contains an integer N, denoting the total number of elements in the stack. 7 | 8 | The second line of input contains N integers separated by a single space, representing the order in which the elements are pushed into the stack. 9 | Output Format: 10 | The only line of output prints the order in which the stack elements are popped, all of them separated by a single space. 11 | Note: 12 | You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input stack itself. 13 | 14 | Constraints: 15 | 1 <= N <= 10^3 16 | -2^31 <= data <= 2^31 - 1 17 | 18 | Time Limit: 1sec 19 | Sample Input 1: 20 | 6 21 | 1 2 3 4 5 10 22 | 23 | Note: 24 | Here, 10 is at the top of the stack. 25 | 26 | Sample Output 1: 27 | 1 2 3 4 5 10 28 | 29 | Note: 30 | Here, 1 is at the top of the stack. 31 | 32 | Sample Input 2: 33 | 5 34 | 2 8 15 1 10 35 | 36 | Sample Output 2: 37 | 2 8 15 1 10*/ 38 | 39 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 40 | 41 | #include 42 | #include 43 | using namespace std; 44 | 45 | void reverseStack(stack &input, stack &extra) 46 | { 47 | while (!input.empty()) 48 | { 49 | int n = input.top(); 50 | extra.push(n); 51 | input.pop(); 52 | } 53 | input = extra; 54 | } 55 | 56 | int main() { 57 | stack input, extra; 58 | int size; 59 | cin >> size; 60 | 61 | for (int i = 0, val; i < size; i++) { 62 | cin >> val; 63 | input.push(val); 64 | } 65 | 66 | reverseStack(input, extra); 67 | 68 | while (!input.empty()) { 69 | cout << input.top() << " "; 70 | input.pop(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Recursion 2/Return Keypad Code.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer n, using phone keypad find out all the possible strings that can be made using digits of input n. 2 | Return empty string for numbers 0 and 1. 3 | Note : 1. The order of strings are not important. 4 | 5 | 2. Input and output has already been managed for you. You just have to populate the output array and return the count of elements populated in the output array. 6 | 7 | Input Format : 8 | Integer n 9 | 10 | Output Format : 11 | All possible strings in different lines 12 | 13 | Constraints : 14 | 1 <= n <= 10^6 15 | 16 | Sample Input: 17 | 23 18 | 19 | Sample Output: 20 | ad 21 | ae 22 | af 23 | bd 24 | be 25 | bf 26 | cd 27 | ce 28 | cf*/ 29 | 30 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 31 | 32 | #include 33 | #include 34 | using namespace std; 35 | 36 | 37 | using namespace std; 38 | string reference[10] = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 39 | 40 | int keypad(int num, string output[]){ 41 | 42 | if(num == 0) { 43 | output[0] = ""; 44 | return 1; 45 | } 46 | 47 | int smallOutput = keypad(num / 10, output); 48 | 49 | int curr = num % 10; 50 | int len = reference[curr].size(); 51 | 52 | 53 | for(int i = 0; i < len - 1; i++) { 54 | for(int j = 0; j < smallOutput; j++) { 55 | output[j + (i + 1) * smallOutput] = output[j]; 56 | } 57 | } 58 | 59 | string corr = reference[curr]; 60 | 61 | 62 | int index = 0; 63 | 64 | for(int i = 0; i < len; i++) { 65 | for(int j = 0; j < smallOutput; j++){ 66 | output[index++] += corr[i]; 67 | } 68 | } 69 | 70 | return smallOutput * len; 71 | 72 | } 73 | 74 | int main(){ 75 | int num; 76 | cin >> num; 77 | 78 | string output[10000]; 79 | int count = keypad(num, output); 80 | for(int i = 0; i < count && i < 10000; i++){ 81 | cout << output[i] << endl; 82 | } 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /Test 1/Split Array.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer array A of size N, check if the input array can be splitted in two parts such that - 2 | - Sum of both parts is equal 3 | - All elements in the input, which are divisible by 5 should be in same group. 4 | - All elements in the input, which are divisible by 3 (but not divisible by 5) should be in other group. 5 | - Elements which are neither divisible by 5 nor by 3, can be put in any group. 6 | 7 | Groups can be made with any set of elements, i.e. elements need not to be continuous. And you need to consider each and every element of input array in some group. 8 | Return true, if array can be split according to the above rules, else return false. 9 | 10 | Note : You will get marks only if all the test cases are passed. 11 | Input Format : 12 | Line 1 : Integer N (size of array) 13 | Line 2 : Array A elements (separated by space) 14 | 15 | Output Format : 16 | true or false 17 | 18 | Constraints : 19 | 1 <= N <= 50 20 | 21 | Sample Input 1 : 22 | 2 23 | 1 2 24 | 25 | Sample Output 1 : 26 | false 27 | 28 | Sample Input 2 : 29 | 3 30 | 1 4 3 31 | 32 | Sample Output 2 : 33 | true*/ 34 | 35 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 36 | 37 | #include 38 | using namespace std; 39 | 40 | bool spliter(int arr[], int n, int start, int ls, int rs) 41 | { 42 | 43 | if (start == n) 44 | return ls == rs; 45 | if (arr[start] % 5 == 0) 46 | ls += arr[start]; 47 | else if (arr[start] % 3 == 0) 48 | rs += arr[start]; 49 | else 50 | return spliter(arr, n, start + 1, ls + arr[start], rs) + spliter(arr, n, start + 1, ls, rs + arr[start]); 51 | return spliter(arr, n, start + 1, ls, rs); 52 | } 53 | bool splitArray(int *input, int size) 54 | { 55 | return spliter(input, size, 0, 0, 0); 56 | } 57 | 58 | int main() { 59 | 60 | int size; 61 | cin>>size; 62 | int *input=new int[1+size]; 63 | 64 | for(int i=0;i>input[i]; 66 | 67 | if(splitArray(input, size)) { 68 | cout << "true" << endl; 69 | } 70 | else { 71 | cout << "false" << endl; 72 | } 73 | 74 | 75 | return 0; 76 | 77 | } 78 | -------------------------------------------------------------------------------- /Linked List 1/Length of LL (Recursive).cpp: -------------------------------------------------------------------------------- 1 | /*Given a linked list, find and return the length of the given linked list recursively. 2 | 3 | Input format : 4 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 5 | 6 | First and the only line of each test case or query contains elements of the singly linked list separated by a single space. 7 | 8 | Remember/Consider : 9 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. 10 | 11 | Output format : 12 | For each test case, print the length of the linked list. 13 | 14 | Output for every test case will be printed in a separate line. 15 | 16 | Constraints : 17 | 1 <= t <= 20 18 | 0 <= N <= 10^4 19 | 20 | Time Limit: 1 sec 21 | 22 | Sample Input 1: 23 | 1 24 | 3 4 5 2 6 1 9 -1 25 | 26 | Sample Output 1: 27 | 7*/ 28 | 29 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 30 | 31 | #include 32 | class Node { 33 | public: 34 | int data; 35 | Node *next; 36 | Node(int data) { 37 | this->data = data; 38 | this->next = NULL; 39 | } 40 | }; 41 | 42 | int length(Node *head) 43 | { 44 | if (head == NULL) 45 | return 0; 46 | else 47 | return 1 + length(head->next); 48 | } 49 | 50 | using namespace std; 51 | 52 | 53 | Node *takeinput() { 54 | int data; 55 | cin >> data; 56 | Node *head = NULL, *tail = NULL; 57 | while (data != -1) { 58 | Node *newNode = new Node(data); 59 | if (head == NULL) { 60 | head = newNode; 61 | tail = newNode; 62 | } else { 63 | tail->next = newNode; 64 | tail = newNode; 65 | } 66 | cin >> data; 67 | } 68 | return head; 69 | } 70 | 71 | void print(Node *head) { 72 | Node *temp = head; 73 | 74 | while (temp != NULL) { 75 | cout << temp->data << " "; 76 | temp = temp->next; 77 | } 78 | 79 | cout << endl; 80 | } 81 | 82 | int main() { 83 | int t; 84 | cin >> t; 85 | 86 | while (t--) { 87 | Node *head = takeinput(); 88 | cout << length(head) << "\n"; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Recursion 2/Return Subsets sum to K.cpp: -------------------------------------------------------------------------------- 1 | /*Given an array A of size n and an integer K, return all subsets of A which sum to K. 2 | Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. 3 | Note : The order of subsets are not important. 4 | 5 | Input format : 6 | Line 1 : Integer n, Size of input array 7 | Line 2 : Array elements separated by space 8 | Line 3 : K 9 | 10 | Constraints : 11 | 1 <= n <= 20 12 | 13 | Sample Input : 14 | 9 15 | 5 12 3 17 1 18 15 3 17 16 | 6 17 | 18 | Sample Output : 19 | 3 3 20 | 5 1*/ 21 | 22 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 23 | 24 | #include 25 | using namespace std; 26 | 27 | int subsetSumToK(int input[], int n, int output[][50], int k) { 28 | if(n == 0){ 29 | if(k == 0){ 30 | output[0][0] = 0; 31 | return 1; 32 | } 33 | else{ 34 | return 0; 35 | } 36 | } 37 | else{ 38 | int arr1[1000][50], arr2[1000][50]; 39 | int s1 = subsetSumToK(input+1, n-1, arr1, k-input[0]); 40 | int s2 = subsetSumToK(input+1, n-1, arr2, k); 41 | 42 | for(int i=0; i> length; 68 | for(int i=0; i < length; i++) 69 | cin >> input[i]; 70 | 71 | cin >> k; 72 | 73 | int size = subsetSumToK(input, length, output, k); 74 | 75 | for( int i = 0; i < size; i++) { 76 | for( int j = 1; j <= output[i][0]; j++) { 77 | cout << output[i][j] << " "; 78 | } 79 | cout << endl; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Tress/Find Sum of Node.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, find and return the sum of all nodes present in the given tree. 2 | 3 | Input format : 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | Output Format : 7 | The first and only line of output prints the sum of all nodes of the given generic tree. 8 | 9 | Constraints: 10 | Time Limit: 1 sec 11 | 12 | Sample Input 1: 13 | 10 3 20 30 40 2 40 50 0 0 0 0 14 | 15 | Sample Output 1: 16 | 190*/ 17 | 18 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 19 | 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | template 26 | class TreeNode { 27 | public: 28 | T data; 29 | vector*> children; 30 | 31 | TreeNode(T data) { this->data = data; } 32 | 33 | ~TreeNode() { 34 | for (int i = 0; i < children.size(); i++) { 35 | delete children[i]; 36 | } 37 | } 38 | }; 39 | 40 | TreeNode* takeInputLevelWise() { 41 | int rootData; 42 | cin >> rootData; 43 | TreeNode* root = new TreeNode(rootData); 44 | 45 | queue*> pendingNodes; 46 | 47 | pendingNodes.push(root); 48 | while (pendingNodes.size() != 0) { 49 | TreeNode* front = pendingNodes.front(); 50 | pendingNodes.pop(); 51 | int numChild; 52 | cin >> numChild; 53 | for (int i = 0; i < numChild; i++) { 54 | int childData; 55 | cin >> childData; 56 | TreeNode* child = new TreeNode(childData); 57 | front->children.push_back(child); 58 | pendingNodes.push(child); 59 | } 60 | } 61 | 62 | return root; 63 | } 64 | 65 | int sumOfNodes(TreeNode *root) 66 | { 67 | if (root == NULL) 68 | return 0; 69 | int sum = root->data; 70 | for (int i = 0; i < root->children.size(); i++) 71 | sum = sum + sumOfNodes(root->children[i]); 72 | return sum; 73 | } 74 | 75 | int main() { 76 | TreeNode* root = takeInputLevelWise(); 77 | cout << sumOfNodes(root); 78 | } 79 | -------------------------------------------------------------------------------- /Recursion 2/Merge Sort.cpp: -------------------------------------------------------------------------------- 1 | /*Sort an array A using Merge Sort. 2 | Change in the input array itself. So no need to return or print anything. 3 | 4 | Input format : 5 | Line 1 : Integer n i.e. Array size 6 | Line 2 : Array elements (separated by space) 7 | 8 | Output format : 9 | Array elements in increasing order (separated by space) 10 | 11 | Constraints : 12 | 1 <= n <= 10^3 13 | 14 | Sample Input 1 : 15 | 6 16 | 2 6 8 5 4 3 17 | 18 | Sample Output 1 : 19 | 2 3 4 5 6 8 20 | 21 | Sample Input 2 : 22 | 5 23 | 2 1 5 2 3 24 | 25 | Sample Output 2 : 26 | 1 2 2 3 5 */ 27 | 28 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | #include 31 | using namespace std; 32 | 33 | void mergeHalves(int *input, int s, int mid, int e) { 34 | int l1 = mid - s + 1; 35 | int l2 = e - mid; 36 | 37 | int arr1[1000], arr2[1000]; 38 | 39 | for(int i = 0; i < l1 ; i++) { 40 | arr1[i] = input[s + i]; 41 | } 42 | 43 | for(int i = 0 ; i < l2; i++) { 44 | arr2[i] = input[mid + i + 1]; 45 | } 46 | 47 | int i = 0; 48 | int j = 0; 49 | int k = s; 50 | 51 | while(i < l1 and j < l2) { 52 | if(arr1[i] < arr2[j]) { 53 | input[k++] = arr1[i++]; 54 | } 55 | else { 56 | input[k++] = arr2[j++]; 57 | } 58 | } 59 | 60 | while(i < l1) { 61 | input[k++] = arr1[i++]; 62 | } 63 | 64 | while( j < l2) { 65 | input[k++] = arr2[j++]; 66 | 67 | } 68 | } 69 | 70 | void mergeSort_Actual(int *arr,int s, int e) { 71 | // base case 72 | if(s >= e) { 73 | return; 74 | } 75 | int mid = (s + e) / 2; 76 | 77 | mergeSort_Actual(arr, s, mid); 78 | mergeSort_Actual(arr, mid + 1, e); 79 | 80 | mergeHalves(arr, s, mid, e); 81 | } 82 | 83 | 84 | void mergeSort(int input[], int size){ 85 | mergeSort_Actual(input,0,size - 1); 86 | } 87 | 88 | 89 | int main() { 90 | int length; 91 | cin >> length; 92 | int* input = new int[length]; 93 | for(int i=0; i < length; i++) 94 | cin >> input[i]; 95 | mergeSort(input, length); 96 | for(int i = 0; i < length; i++) { 97 | cout << input[i] << " "; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Queue/Reverse Queue.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a queue that can store integers as the data. You are required to write a function that reverses the populated queue itself without using any other data structures. 2 | Example: 3 | Alt txt 4 | 5 | Alt txt 6 | 7 | Input Format: 8 | The first list of input contains an integer 't' denoting the number of test cases/queries to be run. 9 | Then the test cases follow. 10 | 11 | The first line input for each test case/query contains an integer N, denoting the total number of elements in the queue. 12 | 13 | The second line of input contains N integers separated by a single space, representing the order in which the elements are enqueued into the queue. 14 | Output Format: 15 | For each test case/query, the only line of output prints the order in which the queue elements are dequeued, all of them separated by a single space. 16 | 17 | Output for every test case/query will be printed on a new line. 18 | Note: 19 | You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input queue itself. 20 | Constraints: 21 | 1 <= t <= 100 22 | 1 <= N <= 10^4 23 | -2^31 <= data <= 2^31 - 1 24 | 25 | Time Limit: 1sec 26 | Sample Input 1: 27 | 1 28 | 6 29 | 1 2 3 4 5 10 30 | 31 | Note: 32 | Here, 1 is at the front and 10 is at the rear of the queue. 33 | 34 | Sample Output 1: 35 | 10 5 4 3 2 1 36 | 37 | Sample Input 2: 38 | 2 39 | 5 40 | 2 8 15 1 10 41 | 3 42 | 10 20 30 43 | 44 | Sample Output 2: 45 | 10 1 15 8 2 46 | 30 20 10 */ 47 | 48 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 49 | 50 | #include 51 | using namespace std; 52 | #include 53 | 54 | void reverseQueue(queue &input) 55 | { 56 | if (input.empty()) 57 | return; 58 | int x = input.front(); 59 | input.pop(); 60 | reverseQueue(input); 61 | input.push(x); 62 | } 63 | 64 | int main() { 65 | int t; 66 | cin >> t; 67 | 68 | while (t--) { 69 | queue q; 70 | int size; 71 | cin >> size; 72 | 73 | for (int i = 0, val; i < size; i++) { 74 | cin >> val; 75 | q.push(val); 76 | } 77 | 78 | reverseQueue(q); 79 | while (!q.empty()) { 80 | cout << q.front() << " "; 81 | q.pop(); 82 | } 83 | 84 | cout << "\n"; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Tress/Count Leaf node.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, count and return the number of leaf nodes present in the given tree. 2 | 3 | Input format : 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | Output Format : 7 | The first and only line of output prints the count of leaf nodes present in the given tree. 8 | 9 | Constraints: 10 | Time Limit: 1 sec 11 | 12 | Sample Input 1 : 13 | 10 3 20 30 40 2 40 50 0 0 0 0 14 | 15 | Sample Output 1 : 16 | 4*/ 17 | 18 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 19 | 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | template 26 | class TreeNode { 27 | public: 28 | T data; 29 | vector*> children; 30 | 31 | TreeNode(T data) { this->data = data; } 32 | 33 | ~TreeNode() { 34 | for (int i = 0; i < children.size(); i++) { 35 | delete children[i]; 36 | } 37 | } 38 | }; 39 | 40 | TreeNode* takeInputLevelWise() { 41 | int rootData; 42 | cin >> rootData; 43 | TreeNode* root = new TreeNode(rootData); 44 | 45 | queue*> pendingNodes; 46 | 47 | pendingNodes.push(root); 48 | while (pendingNodes.size() != 0) { 49 | TreeNode* front = pendingNodes.front(); 50 | pendingNodes.pop(); 51 | int numChild; 52 | cin >> numChild; 53 | for (int i = 0; i < numChild; i++) { 54 | int childData; 55 | cin >> childData; 56 | TreeNode* child = new TreeNode(childData); 57 | front->children.push_back(child); 58 | pendingNodes.push(child); 59 | } 60 | } 61 | 62 | return root; 63 | } 64 | 65 | int getLeafNodeCount(TreeNode *root) 66 | { 67 | if (root == NULL) 68 | return 0; 69 | int count = 0; 70 | if (root->children.size() == 0) 71 | return 1; 72 | for (int i = 0; i < root->children.size(); i++) 73 | count = count + getLeafNodeCount(root->children[i]); 74 | return count; 75 | } 76 | 77 | int main() { 78 | TreeNode* root = takeInputLevelWise(); 79 | cout << getLeafNodeCount(root); 80 | } 81 | -------------------------------------------------------------------------------- /Tress/PostOrder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, print the post-order traversal of given tree. 2 | 3 | The post-order traversal is: visit child nodes first and then root node. 4 | Input format: 5 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 6 | 7 | Output Format : 8 | The first and only line of output contains the elements printed in post-order traversal. The elements in the output must be separated by a single space. 9 | 10 | Constraints: 11 | Time Limit: 1 sec 12 | 13 | Sample Input 1: 14 | 10 3 20 30 40 2 400 50 0 0 0 0 15 | 16 | Sample Output 1: 17 | 400 50 20 30 40 10*/ 18 | 19 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 20 | 21 | #include 22 | #include 23 | #include 24 | using namespace std; 25 | 26 | template 27 | class TreeNode { 28 | public: 29 | T data; 30 | vector*> children; 31 | 32 | TreeNode(T data) { this->data = data; } 33 | 34 | ~TreeNode() { 35 | for (int i = 0; i < children.size(); i++) { 36 | delete children[i]; 37 | } 38 | } 39 | }; 40 | 41 | TreeNode* takeInputLevelWise() { 42 | int rootData; 43 | cin >> rootData; 44 | TreeNode* root = new TreeNode(rootData); 45 | 46 | queue*> pendingNodes; 47 | 48 | pendingNodes.push(root); 49 | while (pendingNodes.size() != 0) { 50 | TreeNode* front = pendingNodes.front(); 51 | pendingNodes.pop(); 52 | int numChild; 53 | cin >> numChild; 54 | for (int i = 0; i < numChild; i++) { 55 | int childData; 56 | cin >> childData; 57 | TreeNode* child = new TreeNode(childData); 58 | front->children.push_back(child); 59 | pendingNodes.push(child); 60 | } 61 | } 62 | 63 | return root; 64 | } 65 | 66 | void printPostOrder(TreeNode *root) 67 | { 68 | if (root == NULL) 69 | return; 70 | for (int i = 0; i < root->children.size(); i++) 71 | printPostOrder(root->children[i]); 72 | cout << root->data << " "; 73 | } 74 | 75 | int main() { 76 | TreeNode* root = takeInputLevelWise(); 77 | printPostOrder(root); 78 | } 79 | -------------------------------------------------------------------------------- /Tress/Find height.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, find and return the height of given tree. 2 | 3 | Input Format: 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | Output Format : 7 | The first and only line of output prints the height of the given generic tree. 8 | 9 | Constraints: 10 | Time Limit: 1 sec 11 | 12 | Sample Input 1: 13 | 10 3 20 30 40 2 40 50 0 0 0 0 14 | 15 | Sample Output 1: 16 | 3*/ 17 | 18 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 19 | 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | template 26 | class TreeNode { 27 | public: 28 | T data; 29 | vector*> children; 30 | 31 | TreeNode(T data) { this->data = data; } 32 | 33 | ~TreeNode() { 34 | for (int i = 0; i < children.size(); i++) { 35 | delete children[i]; 36 | } 37 | } 38 | }; 39 | 40 | TreeNode* takeInputLevelWise() { 41 | int rootData; 42 | cin >> rootData; 43 | TreeNode* root = new TreeNode(rootData); 44 | 45 | queue*> pendingNodes; 46 | 47 | pendingNodes.push(root); 48 | while (pendingNodes.size() != 0) { 49 | TreeNode* front = pendingNodes.front(); 50 | pendingNodes.pop(); 51 | int numChild; 52 | cin >> numChild; 53 | for (int i = 0; i < numChild; i++) { 54 | int childData; 55 | cin >> childData; 56 | TreeNode* child = new TreeNode(childData); 57 | front->children.push_back(child); 58 | pendingNodes.push(child); 59 | } 60 | } 61 | 62 | return root; 63 | } 64 | 65 | void getHeight(TreeNode *root, int height, int *max) 66 | { 67 | if ((*max) < height) 68 | *max = height; 69 | for (int i = 0; i < root->children.size(); i++) 70 | getHeight(root->children[i], 1 + height, max); 71 | } 72 | int getHeight(TreeNode *root) 73 | { 74 | if (root == NULL) 75 | return 0; 76 | int max = 1, height = 1; 77 | getHeight(root, height, &max); 78 | return max; 79 | } 80 | 81 | int main() { 82 | TreeNode* root = takeInputLevelWise(); 83 | cout << getHeight(root); 84 | } 85 | -------------------------------------------------------------------------------- /Stacks/Balanced Parenthesis.cpp: -------------------------------------------------------------------------------- 1 | /*For a given a string expression containing only round brackets or parentheses, check if they are balanced or not. Brackets are said to be balanced if the bracket which opens last, closes first. 2 | Example: 3 | 4 | Expression: (()()) 5 | Since all the opening brackets have their corresponding closing brackets, we say it is balanced and hence the output will be, 'true'. 6 | You need to return a boolean value indicating whether the expression is balanced or not. 7 | 8 | Note: 9 | The input expression will not contain spaces in between. 10 | 11 | Input Format: 12 | The first and the only line of input contains a string expression without any spaces in between. 13 | 14 | Output Format: 15 | The only line of output prints 'true' or 'false'. 16 | 17 | Note: 18 | You don't have to print anything explicitly. It has been taken care of. Just implement the function. 19 | 20 | Constraints: 21 | 1 <= N <= 10^7 22 | Where N is the length of the expression. 23 | 24 | Time Limit: 1sec 25 | Sample Input 1 : 26 | (()()()) 27 | 28 | Sample Output 1 : 29 | true 30 | 31 | Sample Input 2 : 32 | ()()(() 33 | 34 | Sample Output 2 : 35 | false 36 | 37 | Explanation to Sample Input 2: 38 | The initial two pairs of brackets are balanced. But when you see, the opening bracket at the fourth index doesn't have its corresponding closing bracket which makes it imbalanced and in turn, making the whole expression imbalanced. Hence the output prints 'false'.*/ 39 | 40 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41 | 42 | #include 43 | #include 44 | using namespace std; 45 | 46 | #include 47 | bool isBalanced(string expression) 48 | { 49 | stack s; 50 | for (int i = 0; i < expression.length(); i++) 51 | { 52 | if (s.empty() && expression[i] == ')') 53 | return false; 54 | else if (s.empty()) 55 | s.push(expression[i]); 56 | else if (expression[i] == '(') 57 | s.push(expression[i]); 58 | else if (expression[i] == ')' && s.top() == '(') 59 | s.pop(); 60 | else 61 | s.push(expression[i]); 62 | } 63 | if (s.empty()) 64 | return true; 65 | else 66 | return false; 67 | } 68 | 69 | int main() 70 | { 71 | string input; 72 | cin >> input; 73 | cout << ((isBalanced(input)) ? "true" : "false"); 74 | } 75 | -------------------------------------------------------------------------------- /Binary Tree/Post Order.cpp: -------------------------------------------------------------------------------- 1 | /*For a given Binary Tree of integers, print the post-order traversal. 2 | 3 | Input Format: 4 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 5 | 6 | Output Format: 7 | The only line of output prints the post-order traversal of the given binary tree. 8 | 9 | Constraints: 10 | 1 <= N <= 10^6 11 | Where N is the total number of nodes in the binary tree. 12 | 13 | Time Limit: 1 sec 14 | Sample Input 1: 15 | 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1 16 | 17 | Sample Output 1: 18 | 4 5 2 6 7 3 1 19 | 20 | Sample Input 2: 21 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 22 | 23 | Sample Output 1: 24 | 2 9 3 6 10 5 */ 25 | 26 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 27 | 28 | #include 29 | #include 30 | 31 | template 32 | class BinaryTreeNode { 33 | public: 34 | T data; 35 | BinaryTreeNode* left; 36 | BinaryTreeNode* right; 37 | 38 | BinaryTreeNode(T data) { 39 | this->data = data; 40 | left = NULL; 41 | right = NULL; 42 | } 43 | }; 44 | 45 | using namespace std; 46 | 47 | BinaryTreeNode* takeInput() { 48 | int rootData; 49 | cin >> rootData; 50 | if (rootData == -1) { 51 | return NULL; 52 | } 53 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 54 | queue*> q; 55 | q.push(root); 56 | while (!q.empty()) { 57 | BinaryTreeNode* currentNode = q.front(); 58 | q.pop(); 59 | int leftChild, rightChild; 60 | 61 | cin >> leftChild; 62 | if (leftChild != -1) { 63 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 64 | currentNode->left = leftNode; 65 | q.push(leftNode); 66 | } 67 | 68 | cin >> rightChild; 69 | if (rightChild != -1) { 70 | BinaryTreeNode* rightNode = 71 | new BinaryTreeNode(rightChild); 72 | currentNode->right = rightNode; 73 | q.push(rightNode); 74 | } 75 | } 76 | return root; 77 | } 78 | 79 | void postOrder(BinaryTreeNode *root) { 80 | if(root==NULL){ 81 | return; 82 | } 83 | 84 | postOrder(root->left); 85 | postOrder(root->right); 86 | cout<data<<" "; 87 | } 88 | 89 | int main() { 90 | BinaryTreeNode* root = takeInput(); 91 | postOrder(root); 92 | } 93 | -------------------------------------------------------------------------------- /Linked List 1/Print Reverse LL.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a singly linked list of integers. Write a function to print the list in a reverse order. 2 | To explain it further, you need to start printing the data from the tail and move towards the head of the list, printing the head data at the end. 3 | Note : 4 | You can’t change any of the pointers in the linked list, just print it in the reverse order. 5 | Input format : 6 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 7 | 8 | The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. 9 | Remember/Constraints : 10 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. 11 | 12 | Output format : 13 | For each test case, print the singly linked list of integers in a reverse fashion, in a row, separated by a single space. 14 | 15 | Output for every test case will be printed in a seperate line. 16 | 17 | Constraints : 18 | 1 <= t <= 10^2 19 | 0 <= M <= 10^3 20 | Time Limit: 1sec 21 | 22 | Where 'M' is the size of the singly linked list. 23 | Sample Input 1 : 24 | 1 25 | 1 2 3 4 5 -1 26 | 27 | Sample Output 1 : 28 | 5 4 3 2 1 29 | 30 | Sample Input 2 : 31 | 2 32 | 1 2 3 -1 33 | 10 20 30 40 50 -1 34 | 35 | Sample Output 2 : 36 | 3 2 1 37 | 50 40 30 20 10*/ 38 | 39 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 40 | 41 | #include 42 | 43 | class Node 44 | { 45 | public: 46 | int data; 47 | Node *next; 48 | Node(int data) 49 | { 50 | this->data = data; 51 | this->next = NULL; 52 | } 53 | }; 54 | 55 | using namespace std; 56 | 57 | Node *takeinput() 58 | { 59 | int data; 60 | cin >> data; 61 | Node *head = NULL, *tail = NULL; 62 | while (data != -1) 63 | { 64 | Node *newnode = new Node(data); 65 | if (head == NULL) 66 | { 67 | head = newnode; 68 | tail = newnode; 69 | } 70 | else 71 | { 72 | tail->next = newnode; 73 | tail = newnode; 74 | } 75 | cin >> data; 76 | } 77 | return head; 78 | } 79 | 80 | void printReverse(Node *head) 81 | { 82 | if (head == NULL) 83 | return; 84 | printReverse(head->next); 85 | cout << head->data << " "; 86 | } 87 | 88 | int main() 89 | { 90 | int t; 91 | cin >> t; 92 | while (t--) 93 | { 94 | Node *head = takeinput(); 95 | printReverse(head); 96 | cout << endl; 97 | } 98 | return 0; 99 | } 100 | -------------------------------------------------------------------------------- /Tress/Count Nodes.cpp: -------------------------------------------------------------------------------- 1 | /*Given a tree and an integer x, find and return the number of nodes which contains data greater than x. 2 | 3 | Input format: 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | The following line contains an integer, that denotes the value of x. 7 | 8 | Output Format : 9 | The first and only line of output prints the count of nodes greater than x. 10 | 11 | Constraints: 12 | Time Limit: 1 sec 13 | 14 | Sample Input 1 : 15 | 10 3 20 30 40 2 40 50 0 0 0 0 16 | 35 17 | 18 | Sample Output 1 : 19 | 3 20 | 21 | Sample Input 2 : 22 | 10 3 20 30 40 2 40 50 0 0 0 0 23 | 10 24 | 25 | Sample Output 2: 26 | 5*/ 27 | 28 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | #include 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | template 36 | class TreeNode { 37 | public: 38 | T data; 39 | vector*> children; 40 | 41 | TreeNode(T data) { this->data = data; } 42 | 43 | ~TreeNode() { 44 | for (int i = 0; i < children.size(); i++) { 45 | delete children[i]; 46 | } 47 | } 48 | }; 49 | 50 | int getLargeNodeCount(TreeNode* root, int x) { 51 | if(root==NULL){ 52 | return 0; 53 | } 54 | int count=0; 55 | for(int i=0;ichildren.size(); i++){ 56 | count = count + getLargeNodeCount(root->children[i],x); 57 | 58 | } 59 | if(((*root).data)>x){ 60 | return 1+count; 61 | } 62 | return count; 63 | } 64 | 65 | TreeNode* takeInputLevelWise() { 66 | int rootData; 67 | cin >> rootData; 68 | TreeNode* root = new TreeNode(rootData); 69 | 70 | queue*> pendingNodes; 71 | 72 | pendingNodes.push(root); 73 | while (pendingNodes.size() != 0) { 74 | TreeNode* front = pendingNodes.front(); 75 | pendingNodes.pop(); 76 | int numChild; 77 | cin >> numChild; 78 | for (int i = 0; i < numChild; i++) { 79 | int childData; 80 | cin >> childData; 81 | TreeNode* child = new TreeNode(childData); 82 | front->children.push_back(child); 83 | pendingNodes.push(child); 84 | } 85 | } 86 | 87 | return root; 88 | } 89 | 90 | int main() { 91 | TreeNode* root = takeInputLevelWise(); 92 | int x; 93 | cin >> x; 94 | cout << getLargeNodeCount(root, x); 95 | } 96 | -------------------------------------------------------------------------------- /Tress/Max Data Node.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, find and return the node with maximum data. You need to return the node which is having maximum data. 2 | 3 | Return null if tree is empty. 4 | Input format : 5 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 6 | 7 | Output Format : 8 | The first and only line of output contains the data of the node with largest data in the given tree. 9 | 10 | Constraints: 11 | Time Limit: 1 sec 12 | 13 | Sample Input 1: 14 | 10 3 20 30 40 2 40 50 0 0 0 0 15 | 16 | Sample Output 1: 17 | 50*/ 18 | 19 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 20 | 21 | #include 22 | #include 23 | #include 24 | using namespace std; 25 | 26 | template 27 | class TreeNode { 28 | public: 29 | T data; 30 | vector*> children; 31 | 32 | TreeNode(T data) { this->data = data; } 33 | 34 | ~TreeNode() { 35 | for (int i = 0; i < children.size(); i++) { 36 | delete children[i]; 37 | } 38 | } 39 | }; 40 | 41 | TreeNode *maxDataNode(TreeNode *root) 42 | { 43 | if (root == NULL) 44 | return NULL; 45 | int max = root->data; 46 | TreeNode *Node = root; 47 | for (int i = 0; i < root->children.size(); i++) 48 | { 49 | TreeNode *temp = maxDataNode(root->children[i]); 50 | if (temp->data > max) 51 | { 52 | max = temp->data; 53 | Node = temp; 54 | } 55 | } 56 | return Node; 57 | } 58 | 59 | TreeNode* takeInputLevelWise() { 60 | int rootData; 61 | cin >> rootData; 62 | TreeNode* root = new TreeNode(rootData); 63 | 64 | queue*> pendingNodes; 65 | 66 | pendingNodes.push(root); 67 | while (pendingNodes.size() != 0) { 68 | TreeNode* front = pendingNodes.front(); 69 | pendingNodes.pop(); 70 | int numChild; 71 | cin >> numChild; 72 | for (int i = 0; i < numChild; i++) { 73 | int childData; 74 | cin >> childData; 75 | TreeNode* child = new TreeNode(childData); 76 | front->children.push_back(child); 77 | pendingNodes.push(child); 78 | } 79 | } 80 | 81 | return root; 82 | } 83 | 84 | int main() { 85 | TreeNode* root = takeInputLevelWise(); 86 | TreeNode* ans = maxDataNode(root); 87 | 88 | if (root != NULL) { 89 | cout << ans->data; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Linked List 2/Find a Node (Recursive).cpp: -------------------------------------------------------------------------------- 1 | /*Given a singly linked list of integers and an integer n, find and return the index for the first occurrence of 'n' in the linked list. -1 otherwise. 2 | Follow a recursive approach to solve this. 3 | Note : 4 | Assume that the Indexing for the linked list always starts from 0. 5 | Input format : 6 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 7 | 8 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 9 | 10 | The second line of input contains a single integer depicting the value of 'n'. 11 | Remember/Consider : 12 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 13 | Output format : 14 | For each test case/query, print the elements of the updated singly linked list. 15 | 16 | Output for every test case will be printed in a seperate line. 17 | 18 | Constraints : 19 | 1 <= t <= 10^2 20 | 0 <= M <= 10^5 21 | Where M is the size of the singly linked list. 22 | 23 | Time Limit: 1sec 24 | 25 | Sample Input 1 : 26 | 1 27 | 3 4 5 2 6 1 9 -1 28 | 100 29 | 30 | Sample Output 1 : 31 | -1 32 | 33 | Sample Input 2 : 34 | 2 35 | 10 20010 30 400 600 -1 36 | 20010 37 | 100 200 300 400 9000 -34 -1 38 | -34 39 | 40 | Sample Output 2 : 41 | 1 42 | 5*/ 43 | 44 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 45 | 46 | #include 47 | 48 | class Node 49 | { 50 | public: 51 | int data; 52 | Node *next; 53 | Node(int data) 54 | { 55 | this->data = data; 56 | this->next = NULL; 57 | } 58 | }; 59 | 60 | using namespace std; 61 | 62 | Node *takeinput() 63 | { 64 | int data; 65 | cin >> data; 66 | Node *head = NULL, *tail = NULL; 67 | while (data != -1) 68 | { 69 | Node *newNode = new Node(data); 70 | if (head == NULL) 71 | { 72 | head = newNode; 73 | tail = newNode; 74 | } 75 | else 76 | { 77 | tail->next = newNode; 78 | tail = newNode; 79 | } 80 | cin >> data; 81 | } 82 | return head; 83 | } 84 | 85 | int findNodeRec(Node *head, int n) 86 | { 87 | if (head == NULL) 88 | return -1; 89 | if (n == head->data) 90 | return 0; 91 | else 92 | { 93 | int pos = findNodeRec(head->next, n); 94 | if (pos != -1) 95 | return 1 + pos; 96 | else 97 | return -1; 98 | } 99 | } 100 | 101 | int main() 102 | { 103 | int t; 104 | cin >> t; 105 | while (t--) 106 | { 107 | Node *head = takeinput(); 108 | int val; 109 | cin >> val; 110 | cout << findNodeRec(head, val) << endl; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Linked List 2/Midpoint of LL.cpp: -------------------------------------------------------------------------------- 1 | /*For a given singly linked list of integers, find and return the node present at the middle of the list. 2 | Note : 3 | If the length of the singly linked list is even, then return the first middle node. 4 | 5 | Example: Consider, 10 -> 20 -> 30 -> 40 is the given list, then the nodes present at the middle with respective data values are, 20 and 30. We return the first node with data 20. 6 | Input format : 7 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 8 | 9 | The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. 10 | Remember/Consider : 11 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 12 | 13 | Output Format : 14 | For each test case/query, print the data value of the node at the middle of the given list. 15 | 16 | Output for every test case will be printed in a seperate line. 17 | 18 | Constraints : 19 | 1 <= t <= 10^2 20 | 0 <= M <= 10^5 21 | Where M is the size of the singly linked list. 22 | 23 | Time Limit: 1sec 24 | 25 | Sample Input 1 : 26 | 1 27 | 1 2 3 4 5 -1 28 | 29 | Sample Output 1 : 30 | 3 31 | 32 | Sample Input 2 : 33 | 2 34 | -1 35 | 1 2 3 4 -1 36 | 37 | Sample Output 2 : 38 | 2*/ 39 | 40 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41 | 42 | #include 43 | 44 | class Node 45 | { 46 | public: 47 | int data; 48 | Node *next; 49 | Node(int data) 50 | { 51 | this->data = data; 52 | this->next = NULL; 53 | } 54 | }; 55 | 56 | using namespace std; 57 | 58 | Node *takeinput() 59 | { 60 | int data; 61 | cin >> data; 62 | Node *head = NULL, *tail = NULL; 63 | while (data != -1) 64 | { 65 | Node *newnode = new Node(data); 66 | if (head == NULL) 67 | { 68 | head = newnode; 69 | tail = newnode; 70 | } 71 | else 72 | { 73 | tail->next = newnode; 74 | tail = newnode; 75 | } 76 | cin >> data; 77 | } 78 | return head; 79 | } 80 | 81 | Node *midPoint(Node *head) 82 | { 83 | if (head == NULL || head->next == NULL) 84 | return head; 85 | Node *slow = head; 86 | Node *fast = head->next; 87 | while (fast != NULL && fast->next != NULL) 88 | { 89 | slow = slow->next; 90 | fast = fast->next->next; 91 | } 92 | return slow; 93 | } 94 | 95 | int main() 96 | { 97 | int t; 98 | cin >> t; 99 | while (t--) 100 | { 101 | Node *head = takeinput(); 102 | Node *mid = midPoint(head); 103 | if (mid != NULL) 104 | { 105 | cout << mid->data; 106 | } 107 | cout << endl; 108 | } 109 | return 0; 110 | } 111 | -------------------------------------------------------------------------------- /Linked List 1/Print ith node.cpp: -------------------------------------------------------------------------------- 1 | /*For a given a singly linked list of integers and a position 'i', print the node data at the 'i-th' position. 2 | 3 | Note : 4 | Assume that the Indexing for the singly linked list always starts from 0. 5 | 6 | If the given position 'i', is greater than the length of the given singly linked list, then don't print anything. 7 | 8 | Input format : 9 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 10 | 11 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 12 | 13 | The second line contains the value of 'i'. It denotes the position in the given singly linked list. 14 | 15 | Remember/Consider : 16 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. 17 | 18 | Output format : 19 | For each test case, print the node data at the 'i-th' position of the linked list(if exists). 20 | 21 | Output for every test case will be printed in a seperate line. 22 | 23 | Constraints : 24 | 1 <= t <= 10^2 25 | 0 <= N <= 10^5 26 | i >= 0 27 | 28 | Time Limit: 1sec 29 | 30 | Sample Input 1 : 31 | 1 32 | 3 4 5 2 6 1 9 -1 33 | 3 34 | 35 | Sample Output 1 : 36 | 2 37 | 38 | Sample Input 2 : 39 | 2 40 | 3 4 5 2 6 1 9 -1 41 | 0 42 | 9 8 4 0 7 8 -1 43 | 3 44 | 45 | Sample Output 2 : 46 | 3 47 | 0*/ 48 | 49 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 50 | 51 | #include 52 | using namespace std; 53 | 54 | class Node 55 | { 56 | public: 57 | int data; 58 | Node *next; 59 | Node(int data) 60 | { 61 | this->data = data; 62 | this->next = NULL; 63 | } 64 | }; 65 | 66 | void printIthNode(Node *head, int i) 67 | { 68 | int j = 0; 69 | Node *current = head; 70 | while (current != NULL) 71 | { 72 | if (j == i) 73 | { 74 | cout << current->data; 75 | break; 76 | } 77 | current = current->next; 78 | j++; 79 | } 80 | } 81 | 82 | Node *takeinput() 83 | { 84 | int data; 85 | cin >> data; 86 | Node *head = NULL, *tail = NULL; 87 | while (data != -1) 88 | { 89 | Node *newNode = new Node(data); 90 | if (head == NULL) 91 | { 92 | head = newNode; 93 | tail = newNode; 94 | } 95 | else 96 | { 97 | tail->next = newNode; 98 | tail = newNode; 99 | } 100 | cin >> data; 101 | } 102 | return head; 103 | } 104 | 105 | int main() 106 | { 107 | int t; 108 | cin >> t; 109 | while (t--) 110 | { 111 | Node *head = takeinput(); 112 | int pos; 113 | cin >> pos; 114 | printIthNode(head, pos); 115 | cout << endl; 116 | } 117 | return 0; 118 | } 119 | -------------------------------------------------------------------------------- /Test 2/Delete Alternate Node.cpp: -------------------------------------------------------------------------------- 1 | /*Given a Singly Linked List of integers, delete all the alternate nodes in the list. 2 | 3 | Example: 4 | List: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> null 5 | Alternate nodes will be: 20, 40, and 60. 6 | 7 | Hence after deleting, the list will be: 8 | 9 | Output: 10 -> 30 -> 50 -> null 10 | Note : 11 | 12 | The head of the list will remain the same. Don't need to print or return anything. 13 | Input format : 14 | The first and the only line of input will contain the elements of the Singly Linked List separated by a single space and terminated by -1. 15 | 16 | Output Format : 17 | The only line of output will contain the updated list elements. 18 | 19 | Input Constraints: 20 | 1 <= N <= 10 ^ 6. 21 | Where N is the size of the Singly Linked List 22 | 23 | Time Limit: 1 sec 24 | Sample Input 1: 25 | 1 2 3 4 5 -1 26 | 27 | Sample Output 1: 28 | 1 3 5 29 | Explanation of Sample Input 1: 30 | 2, 4 are alternate nodes so we need to delete them 31 | 32 | Sample Input 2: 33 | 10 20 30 40 50 60 70 -1 34 | 35 | Sample Output 2: 36 | 10 30 50 70 */ 37 | 38 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 39 | 40 | #include 41 | 42 | class Node { 43 | public: 44 | int data; 45 | Node * next; 46 | Node(int data){ 47 | this -> data = data; 48 | this -> next = NULL; 49 | } 50 | 51 | ~Node() { 52 | if(next) { 53 | delete next; 54 | } 55 | } 56 | }; 57 | 58 | using namespace std; 59 | 60 | Node* takeinput() { 61 | int data; 62 | cin >> data; 63 | Node *head = NULL, *tail = NULL; 64 | while(data != -1){ 65 | Node *newNode = new Node(data); 66 | if(head == NULL) { 67 | head = newNode; 68 | tail = newNode; 69 | } 70 | else{ 71 | tail -> next = newNode; 72 | tail = newNode; 73 | } 74 | cin >> data; 75 | } 76 | return head; 77 | } 78 | 79 | void deleteAlternateNodes(Node *head) 80 | { 81 | if (head == NULL) 82 | return; 83 | 84 | Node *prev = head; 85 | Node *node = head->next; 86 | 87 | while (prev != NULL && node != NULL) 88 | { 89 | prev->next = node->next; 90 | prev = prev->next; 91 | if (prev != NULL) 92 | node = prev->next; 93 | } 94 | } 95 | 96 | void print(Node *head) { 97 | Node *temp = head; 98 | while(temp != NULL) { 99 | cout << temp -> data << " "; 100 | temp = temp -> next; 101 | } 102 | cout << endl; 103 | } 104 | 105 | int main() { 106 | Node *head = takeinput(); 107 | deleteAlternateNodes(head); 108 | print(head); 109 | delete head; 110 | return 0; 111 | } 112 | -------------------------------------------------------------------------------- /Stacks/Check Redundant Brackets.cpp: -------------------------------------------------------------------------------- 1 | /*For a given expression in the form of a string, find if there exist any redundant brackets or not. It is given that the expression contains only rounded brackets or parenthesis and the input expression will always be balanced. 2 | A pair of the bracket is said to be redundant when a sub-expression is surrounded by unnecessary or needless brackets. 3 | 4 | Example: 5 | Expression: (a+b)+c 6 | Since there are no needless brackets, hence, the output must be 'false'. 7 | 8 | Expression: ((a+b)) 9 | The expression can be reduced to (a+b). Hence the expression has redundant brackets and the output will be 'true'. 10 | Note: 11 | You will not get a partial score for this problem. You will get marks only if all the test cases are passed. 12 | 13 | Input Format : 14 | The first and the only line of input contains a string expression, without any spaces in between. 15 | 16 | Output Format : 17 | The first and the only line of output will print either 'true' or 'false'(without the quotes) denoting whether the input expression contains redundant brackets or not. 18 | Note: 19 | You are not required to print the expected result. It has already been taken care of. 20 | 21 | Constraints: 22 | 0 <= N <= 10^6 23 | Where N is the length of the expression. 24 | 25 | Time Limit: 1 second 26 | Sample Input 1: 27 | a+(b)+c 28 | 29 | Sample Output 1: 30 | true 31 | Explanation: 32 | The expression can be reduced to a+b+c. Hence, the brackets are redundant. 33 | 34 | Sample Input 2: 35 | (a+b) 36 | 37 | Sample Output 2: 38 | false*/ 39 | 40 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41 | 42 | #include 43 | #include 44 | using namespace std; 45 | 46 | #include 47 | bool checkRedundantBrackets(string input) 48 | { 49 | stack s; 50 | int i = 0, j = 0; 51 | int count = 0; 52 | while (input[i] != '\0') 53 | { 54 | while (input[i] != ')') 55 | { 56 | if (input[i] == '\0') 57 | { 58 | return false; 59 | } 60 | s.push(input[i]); 61 | i++; 62 | } 63 | if (input[i] == ')') 64 | { 65 | if (s.empty()) 66 | return false; 67 | while (s.top() != '(') 68 | { 69 | s.pop(); 70 | count++; 71 | } 72 | if (count == 0 || count == 1) 73 | { 74 | return true; 75 | } 76 | else 77 | { 78 | s.pop(); 79 | count = 0; 80 | } 81 | } 82 | i++; 83 | } 84 | return false; 85 | } 86 | 87 | int main() { 88 | string input; 89 | cin >> input; 90 | cout << ((checkRedundantBrackets(input)) ? "true" : "false"); 91 | } 92 | -------------------------------------------------------------------------------- /Stacks/Minimum bracket Reversal.cpp: -------------------------------------------------------------------------------- 1 | /*For a given expression in the form of a string, find the minimum number of brackets that can be reversed in order to make the expression balanced. The expression will only contain curly brackets. 2 | If the expression can't be balanced, return -1. 3 | Example: 4 | Expression: {{{{ 5 | If we reverse the second and the fourth opening brackets, the whole expression will get balanced. Since we have to reverse two brackets to make the expression balanced, the expected output will be 2. 6 | 7 | Expression: {{{ 8 | In this example, even if we reverse the last opening bracket, we would be left with the first opening bracket and hence will not be able to make the expression balanced and the output will be -1. 9 | Input Format : 10 | The first and the only line of input contains a string expression, without any spaces in between. 11 | Output Format : 12 | The only line of output will print the number of reversals required to balance the whole expression. Prints -1, otherwise. 13 | Note: 14 | You don't have to print anything. It has already been taken care of. 15 | 16 | Constraints: 17 | 0 <= N <= 10^6 18 | Where N is the length of the expression. 19 | 20 | Time Limit: 1sec 21 | Sample Input 1: 22 | {{{ 23 | 24 | Sample Output 1: 25 | -1 26 | 27 | Sample Input 2: 28 | {{{{}} 29 | 30 | Sample Output 2: 31 | 1*/ 32 | 33 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 34 | 35 | #include 36 | #include 37 | using namespace std; 38 | 39 | #include 40 | int countBracketReversals(string input) 41 | { 42 | int l = 0; 43 | for (int i = 0; input[i] != '\0'; i++) 44 | { 45 | l++; 46 | } 47 | if (l % 2 != 0) 48 | return -1; 49 | else 50 | { 51 | stack s; 52 | int i = 0; 53 | while (input[i] != '\0') 54 | { 55 | if (input[i] == '{') 56 | 57 | s.push('{'); 58 | 59 | else if (input[i] == '}' && s.empty()) 60 | s.push('}'); 61 | else if (input[i] == '}' && !(s.empty())) 62 | { 63 | if (s.top() == '{') 64 | s.pop(); 65 | else 66 | s.push('}'); 67 | } 68 | i++; 69 | } 70 | int count = 0; 71 | char c1, c2; 72 | while (!(s.empty())) 73 | { 74 | 75 | c1 = s.top(); 76 | s.pop(); 77 | c2 = s.top(); 78 | if (c1 == c2) 79 | { 80 | count++; 81 | } 82 | else 83 | count += 2; 84 | s.pop(); 85 | } 86 | return count; 87 | } 88 | } 89 | 90 | 91 | int main() { 92 | string input; 93 | cin >> input; 94 | cout << countBracketReversals(input); 95 | } 96 | -------------------------------------------------------------------------------- /Stacks/Stock Span.cpp: -------------------------------------------------------------------------------- 1 | /*Afzal has been working with an organization called 'Money Traders' for the past few years. The organization is into the money trading business. His manager assigned him a task. For a given array/list of stock's prices for N days, find the stock's span for each day. 2 | The span of the stock's price today is defined as the maximum number of consecutive days(starting from today and going backwards) for which the price of the stock was less than today's price. 3 | For example, if the price of a stock over a period of 7 days are [100, 80, 60, 70, 60, 75, 85], then the stock spans will be [1, 1, 1, 2, 1, 4, 6]. 4 | Explanation: 5 | On the sixth day when the price of the stock was 75, the span came out to be 4, because the last 4 prices(including the current price of 75) were less than the current or the sixth day's price. 6 | 7 | Similarly, we can deduce the remaining results. 8 | Afzal has to return an array/list of spans corresponding to each day's stock's price. Help him to achieve the task. 9 | Input Format: 10 | The first line of input contains an integer N, denoting the total number of days. 11 | 12 | The second line of input contains the stock prices of each day. A single space will separate them 13 | 14 | Output Format: 15 | The only line of output will print the span for each day's stock price. A single space will separate them. 16 | 17 | Note: 18 | You are not required to print the expected output explicitly. It has already been taken care of. 19 | 20 | Constraints: 21 | 0 <= N <= 10^7 22 | 1 <= X <= 10^9 23 | Where X denotes the stock's price for a day. 24 | 25 | Time Limit: 1 second 26 | Sample Input 1: 27 | 4 28 | 10 10 10 10 29 | 30 | Sample Output 1: 31 | 1 1 1 1 32 | 33 | Sample Input 2: 34 | 8 35 | 60 70 80 100 90 75 80 120 36 | 37 | Sample Output 2: 38 | 1 2 3 4 1 1 2 8*/ 39 | 40 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41 | 42 | #include 43 | using namespace std; 44 | 45 | #include 46 | int *stockSpan(int *price, int size) 47 | { 48 | ios_base::sync_with_stdio(false); 49 | cin.tie(0); 50 | int *S = new int[size]; 51 | stack st; 52 | st.push(0); 53 | 54 | S[0] = 1; 55 | 56 | for (int i = 1; i < size; i++) 57 | { 58 | while (!st.empty() && price[st.top()] < price[i]) 59 | st.pop(); 60 | S[i] = (st.empty()) ? (i + 1) : (i - st.top()); 61 | st.push(i); 62 | } 63 | return S; 64 | } 65 | 66 | int main() { 67 | int size; 68 | cin >> size; 69 | 70 | int *input = new int[size]; 71 | for (int i = 0; i < size; i++) { 72 | cin >> input[i]; 73 | } 74 | 75 | int *output = stockSpan(input, size); 76 | for (int i = 0; i < size; i++) { 77 | cout << output[i] << " "; 78 | } 79 | 80 | cout << "\n"; 81 | 82 | delete[] input; 83 | delete[] output; 84 | } 85 | -------------------------------------------------------------------------------- /Linked List 2/Bubble Sort (Itetative) LL.cpp: -------------------------------------------------------------------------------- 1 | /*Given a singly linked list of integers, sort it using 'Bubble Sort.' 2 | 3 | Note : 4 | No need to print the list, it has already been taken care. Only return the new head to the list. 5 | Input format : 6 | The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. 7 | Remember/Consider : 8 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 9 | Output format : 10 | For each test case/query, print the elements of the sorted singly linked list. 11 | 12 | Output for every test case will be printed in a seperate line. 13 | 14 | Constraints : 15 | 0 <= M <= 10^3 16 | Where M is the size of the singly linked list. 17 | 18 | Time Limit: 1sec 19 | Sample Input 1 : 20 | 10 9 8 7 6 5 4 3 -1 21 | 22 | Sample Output 1 : 23 | 3 4 5 6 7 8 9 10 24 | 25 | Sample Input 2 : 26 | 10 -5 9 90 5 67 1 89 -1 27 | 28 | Sample Output 2 : 29 | -5 1 5 9 10 67 89 90 */ 30 | 31 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 32 | 33 | //bubble sort iterative 34 | #include 35 | class Node 36 | { 37 | public: 38 | int data; 39 | Node *next; 40 | Node(int data) 41 | { 42 | this->data = data; 43 | this->next = NULL; 44 | } 45 | }; 46 | 47 | using namespace std; 48 | Node *takeinput() 49 | { 50 | int data; 51 | cin >> data; 52 | Node *head = NULL, *tail = NULL; 53 | while (data != -1) 54 | { 55 | Node *newnode = new Node(data); 56 | if (head == NULL) 57 | { 58 | head = newnode; 59 | tail = newnode; 60 | } 61 | else 62 | { 63 | tail->next = newnode; 64 | tail = newnode; 65 | } 66 | cin >> data; 67 | } 68 | return head; 69 | } 70 | 71 | Node *bubbleSort(Node *head) 72 | { 73 | if (head == NULL) 74 | return head; 75 | Node *current = head; 76 | Node *tail = head; 77 | while (tail->next != NULL) 78 | tail = tail->next; 79 | while (current != tail) 80 | { 81 | if (current->data > current->next->data) 82 | { 83 | int temp = current->next->data; 84 | current->next->data = current->data; 85 | current->data = temp; 86 | } 87 | if (current->next == tail) 88 | { 89 | tail = current; 90 | current = head; 91 | } 92 | else 93 | current = current->next; 94 | } 95 | return head; 96 | } 97 | 98 | 99 | void print(Node *head) 100 | { 101 | Node *temp = head; 102 | while (temp != NULL) 103 | { 104 | cout << temp->data << " "; 105 | temp = temp->next; 106 | } 107 | cout << endl; 108 | } 109 | int main() 110 | { 111 | Node *head = takeinput(); 112 | head = bubbleSort(head); 113 | print(head); 114 | } 115 | -------------------------------------------------------------------------------- /Tress/Contains X.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree and an integer x, check if x is present in the given tree or not. Return true if x is present, return false otherwise. 2 | 3 | Input format : 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | The following line contains an integer, that denotes the value of x. 7 | 8 | Output format : 9 | The first and only line of output contains true, if x is present and false, otherwise. 10 | 11 | Constraints: 12 | Time Limit: 1 sec 13 | 14 | Sample Input 1 : 15 | 10 3 20 30 40 2 40 50 0 0 0 0 16 | 40 17 | 18 | Sample Output 1 : 19 | true 20 | 21 | Sample Input 2 : 22 | 10 3 20 30 40 2 40 50 0 0 0 0 23 | 4 24 | 25 | Sample Output 2: 26 | false*/ 27 | 28 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | #include 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | template 36 | class TreeNode { 37 | public: 38 | T data; 39 | vector*> children; 40 | 41 | TreeNode(T data) { this->data = data; } 42 | 43 | ~TreeNode() { 44 | for (int i = 0; i < children.size(); i++) { 45 | delete children[i]; 46 | } 47 | } 48 | }; 49 | 50 | bool isPresent(TreeNode* root, int x) { 51 | if (root==NULL){ 52 | return false; 53 | } 54 | for(int i=0; ichildren.size(); i++){ 55 | bool value = isPresent(root->children[i],x); 56 | if(value==true){ 57 | return true; 58 | } 59 | 60 | } 61 | if(root->data==x){ 62 | return true; 63 | } 64 | else{ 65 | return false; 66 | } 67 | } 68 | 69 | TreeNode* takeInputLevelWise() { 70 | int rootData; 71 | cin >> rootData; 72 | TreeNode* root = new TreeNode(rootData); 73 | 74 | queue*> pendingNodes; 75 | 76 | pendingNodes.push(root); 77 | while (pendingNodes.size() != 0) { 78 | TreeNode* front = pendingNodes.front(); 79 | pendingNodes.pop(); 80 | int numChild; 81 | cin >> numChild; 82 | for (int i = 0; i < numChild; i++) { 83 | int childData; 84 | cin >> childData; 85 | TreeNode* child = new TreeNode(childData); 86 | front->children.push_back(child); 87 | pendingNodes.push(child); 88 | } 89 | } 90 | 91 | return root; 92 | } 93 | 94 | int main() { 95 | TreeNode* root = takeInputLevelWise(); 96 | int x; 97 | cin >> x; 98 | cout << (isPresent(root, x) ? "true" : "false"); 99 | } 100 | -------------------------------------------------------------------------------- /Test 2/Next Number.cpp: -------------------------------------------------------------------------------- 1 | /*Given a large number represented in the form of a linked list. Write code to increment the number by 1 in-place(i.e. without using extra space). 2 | Note: You don't need to print the elements, just update the elements and return the head of updated LL. 3 | Input Constraints: 4 | 1 <= Length of Linked List <=10^6. 5 | 6 | Input format : 7 | Line 1 : Linked list elements (separated by space and terminated by -1) 8 | 9 | Output Format : 10 | Line 1: Updated linked list elements 11 | 12 | Sample Input 1 : 13 | 3 9 2 5 -1 14 | 15 | Sample Output 1 : 16 | 3 9 2 6 17 | 18 | Sample Input 2 : 19 | 9 9 9 -1 20 | 21 | Sample Output 1 : 22 | 1 0 0 0 */ 23 | 24 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 25 | 26 | #include 27 | class Node{ 28 | public: 29 | int data; 30 | Node *next; 31 | Node(int data){ 32 | this -> data = data; 33 | this -> next = NULL; 34 | } 35 | }; 36 | 37 | using namespace std; 38 | 39 | Node* takeinput() { 40 | int data; 41 | cin >> data; 42 | Node* head = NULL, *tail = NULL; 43 | while(data != -1){ 44 | Node *newNode = new Node(data); 45 | if(head == NULL) { 46 | head = newNode; 47 | tail = newNode; 48 | } 49 | else{ 50 | tail -> next = newNode; 51 | tail = newNode; 52 | } 53 | cin >> data; 54 | } 55 | return head; 56 | } 57 | 58 | void print(Node *head) { 59 | Node *temp = head; 60 | while(temp != NULL) { 61 | cout << temp -> data << " "; 62 | temp = temp -> next; 63 | } 64 | cout<next; 75 | current->next = prev; 76 | prev = current; 77 | current = next; 78 | } 79 | return prev; 80 | } 81 | 82 | Node *addOneUtil(Node *head) 83 | { 84 | Node *res = head; 85 | Node *temp, *prev = NULL; 86 | 87 | int carry = 1, sum; 88 | 89 | while (head != NULL) 90 | { 91 | sum = carry + head->data; 92 | carry = (sum >= 10) ? 1 : 0; 93 | sum = sum % 10; 94 | head->data = sum; 95 | 96 | temp = head; 97 | head = head->next; 98 | } 99 | 100 | if (carry > 0) 101 | temp->next = new Node(carry); 102 | return res; 103 | } 104 | 105 | 106 | Node *NextLargeNumber(Node *head) 107 | { 108 | 109 | head = reverse(head); 110 | head = addOneUtil(head); 111 | 112 | return reverse(head); 113 | } 114 | 115 | int main() { 116 | Node *head = takeinput(); 117 | 118 | head = NextLargeNumber(head); 119 | print(head); 120 | return 0; 121 | } 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /Tress/Node with maximum child sum.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, find and return the node for which sum of its data and data of all its child nodes is maximum. In the sum, data of the node and data of its immediate child nodes has to be taken. 2 | 3 | Input format : 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | Output format : 7 | The first and only line of output contains the data of the node with maximum sum, as described in the task. 8 | 9 | Constraints: 10 | Time Limit: 1 sec 11 | 12 | Sample Input 1 : 13 | 5 3 1 2 3 1 15 2 4 5 1 6 0 0 0 0 14 | 15 | Sample Output 1 : 16 | 1*/ 17 | 18 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 19 | 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | template 26 | class TreeNode { 27 | public: 28 | T data; 29 | vector*> children; 30 | 31 | TreeNode(T data) { this->data = data; } 32 | 33 | ~TreeNode() { 34 | for (int i = 0; i < children.size(); i++) { 35 | delete children[i]; 36 | } 37 | } 38 | }; 39 | 40 | void maxSum(TreeNode *root, TreeNode **maxNode, int *max) 41 | { 42 | int sum = root->data; 43 | for (int i = 0; i < root->children.size(); i++) 44 | sum += root->children[i]->data; 45 | if (sum > *max) 46 | { 47 | *max = sum; 48 | *maxNode = root; 49 | } 50 | for (int i = 0; i < root->children.size(); i++) 51 | maxSum(root->children[i], maxNode, max); 52 | } 53 | TreeNode *maxSumNode(TreeNode *root) 54 | { 55 | if (root == NULL) 56 | return NULL; 57 | TreeNode *maxNode; 58 | int max = 0; 59 | maxSum(root, &maxNode, &max); 60 | return maxNode; 61 | } 62 | 63 | TreeNode* takeInputLevelWise() { 64 | int rootData; 65 | cin >> rootData; 66 | TreeNode* root = new TreeNode(rootData); 67 | 68 | queue*> pendingNodes; 69 | 70 | pendingNodes.push(root); 71 | while (pendingNodes.size() != 0) { 72 | TreeNode* front = pendingNodes.front(); 73 | pendingNodes.pop(); 74 | int numChild; 75 | cin >> numChild; 76 | for (int i = 0; i < numChild; i++) { 77 | int childData; 78 | cin >> childData; 79 | TreeNode* child = new TreeNode(childData); 80 | front->children.push_back(child); 81 | pendingNodes.push(child); 82 | } 83 | } 84 | 85 | return root; 86 | } 87 | 88 | int main() { 89 | TreeNode* root = takeInputLevelWise(); 90 | 91 | TreeNode* ans = maxSumNode(root); 92 | 93 | if (ans != NULL) { 94 | cout << ans->data; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Linked List 1/Palindrome LL.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a head to a singly linked list of integers. Write a function check to whether the list given is a 'Palindrome' or not. 2 | Input format : 3 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 4 | 5 | First and the only line of each test case or query contains the the elements of the singly linked list separated by a single space. 6 | Remember/Consider : 7 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. 8 | Output format : 9 | For each test case, the only line of output that print 'true' if the list is Palindrome or 'false' otherwise. 10 | 11 | Constraints : 12 | 1 <= t <= 10^2 13 | 0 <= M <= 10^5 14 | Time Limit: 1sec 15 | 16 | Where 'M' is the size of the singly linked list. 17 | 18 | Sample Input 1 : 19 | 1 20 | 9 2 3 3 2 9 -1 21 | 22 | Sample Output 1 : 23 | true 24 | 25 | Sample Input 2 : 26 | 2 27 | 0 2 3 2 5 -1 28 | -1 29 | 30 | Sample Output 2 : 31 | false 32 | true 33 | Explanation for the Sample Input 2 : 34 | For the first query, it is pretty intuitive that the the given list is not a palindrome, hence the output is 'false'. 35 | 36 | For the second query, the list is empty. An empty list is always a palindrome , hence the output is 'true'.*/ 37 | 38 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 39 | 40 | #include 41 | 42 | class Node 43 | { 44 | public: 45 | int data; 46 | Node *next; 47 | Node(int data) 48 | { 49 | this->data = data; 50 | this->next = NULL; 51 | } 52 | }; 53 | 54 | using namespace std; 55 | 56 | Node *takeinput() 57 | { 58 | int data; 59 | cin >> data; 60 | Node *head = NULL, *tail = NULL; 61 | while (data != -1) 62 | { 63 | Node *newnode = new Node(data); 64 | if (head == NULL) 65 | { 66 | head = newnode; 67 | tail = newnode; 68 | } 69 | else 70 | { 71 | tail->next = newnode; 72 | tail = newnode; 73 | } 74 | cin >> data; 75 | } 76 | return head; 77 | } 78 | 79 | bool isPalindrome(Node *head) 80 | { 81 | if (head == NULL || head->next == NULL) 82 | return true; 83 | Node *current = head; 84 | Node *prev = NULL; 85 | while (current->next != NULL) 86 | { 87 | prev = current; 88 | current = current->next; 89 | } 90 | if (head->data == current->data) 91 | { 92 | prev->next = NULL; 93 | delete current; 94 | return isPalindrome(head->next); 95 | } 96 | else 97 | return false; 98 | } 99 | 100 | int main() 101 | { 102 | int t; 103 | cin >> t; 104 | 105 | while (t--) 106 | { 107 | Node *head = takeinput(); 108 | bool ans = isPalindrome(head); 109 | 110 | if (ans) cout << "true"; 111 | else cout << "false"; 112 | 113 | cout << endl; 114 | } 115 | 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /OOPS/Complex Number Class.cpp: -------------------------------------------------------------------------------- 1 | /*A ComplexNumber class contains two data members : one is the real part (R) and the other is imaginary (I) (both integers). 2 | Implement the Complex numbers class that contains following functions - 3 | 4 | 1. constructor 5 | You need to create the appropriate constructor. 6 | 2. plus - 7 | This function adds two given complex numbers and updates the first complex number. 8 | e.g. 9 | if C1 = 4 + i5 and C2 = 3 +i1 10 | C1.plus(C2) results in: 11 | C1 = 7 + i6 and C2 = 3 + i1 12 | 13 | 3. multiply - 14 | This function multiplies two given complex numbers and updates the first complex number. 15 | e.g. 16 | if C1 = 4 + i5 and C2 = 1 + i2 17 | C1.multiply(C2) results in: 18 | C1 = -6 + i13 and C2 = 1 + i2 19 | 20 | 4. print - 21 | This function prints the given complex number in the following format : 22 | a + ib 23 | Note : There is space before and after '+' (plus sign) and no space between 'i' (iota symbol) and b. 24 | 25 | Input Format : 26 | Line 1 : Two integers - real and imaginary part of 1st complex number 27 | Line 2 : Two integers - real and imaginary part of 2nd complex number 28 | Line 3 : An integer representing choice (1 or 2) (1 represents plus function will be called and 2 represents multiply function will be called) 29 | 30 | Output format : 31 | Check details of 'print' function given above. 32 | Sample Input 1 : 33 | 4 5 34 | 6 7 35 | 1 36 | 37 | Sample Output 1 : 38 | 10 + i12 39 | 40 | Sample Input 2 : 41 | 4 5 42 | 6 7 43 | 2 44 | 45 | Sample Output 2 : 46 | -11 + i58*/ 47 | 48 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 49 | 50 | #include 51 | using namespace std; 52 | 53 | class ComplexNumbers 54 | { 55 | int real, imaginary; 56 | 57 | public: 58 | ComplexNumbers(int re, int img) 59 | { 60 | real = re; 61 | imaginary = img; 62 | } 63 | void plus(ComplexNumbers c) 64 | { 65 | this->real = this->real + c.real; 66 | this->imaginary = this->imaginary + c.imaginary; 67 | } 68 | void multiply(ComplexNumbers c) 69 | { 70 | int re = this->real * c.real - this->imaginary * c.imaginary; 71 | int img = this->real * c.imaginary + this->imaginary * c.real; 72 | this->real = re; 73 | this->imaginary = img; 74 | } 75 | void print() 76 | { 77 | cout << real << " + i" << imaginary; 78 | } 79 | }; 80 | 81 | int main() { 82 | int real1, imaginary1, real2, imaginary2; 83 | 84 | cin >> real1 >> imaginary1; 85 | cin >> real2 >> imaginary2; 86 | 87 | ComplexNumbers c1(real1, imaginary1); 88 | ComplexNumbers c2(real2, imaginary2); 89 | 90 | int choice; 91 | cin >> choice; 92 | 93 | if(choice == 1) { 94 | c1.plus(c2); 95 | c1.print(); 96 | } 97 | else if(choice == 2) { 98 | c1.multiply(c2); 99 | c1.print(); 100 | } 101 | else { 102 | return 0; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Linked List 1/Eliminate duplicates from LL.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a singly linked list of integers where the elements are sorted in ascending order. Write a function that removes the consecutive duplicate values such that the given list only contains unique elements and returns the head to the updated list. 2 | Input format : 3 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 4 | 5 | The first and the only line of each test case or query contains the elements(in ascending order) of the singly linked list separated by a single space. 6 | Remember/Consider : 7 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. 8 | 9 | Output format : 10 | For each test case/query, print the resulting singly linked list of integers in a row, separated by a single space. 11 | 12 | Output for every test case will be printed in a seperate line. 13 | Constraints : 14 | 1 <= t <= 10^2 15 | 0 <= M <= 10^5 16 | Time Limit: 1sec 17 | 18 | Where 'M' is the size of the singly linked list. 19 | 20 | Sample Input 1 : 21 | 1 22 | 1 2 3 3 3 3 4 4 4 5 5 7 -1 23 | 24 | Sample Output 1 : 25 | 1 2 3 4 5 7 26 | 27 | Sample Input 2 : 28 | 2 29 | 10 20 30 40 50 -1 30 | 10 10 10 10 -1 31 | 32 | Sample Output 2 : 33 | 10 20 30 40 50 34 | 10*/ 35 | 36 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 37 | 38 | #include 39 | 40 | class Node 41 | { 42 | public: 43 | int data; 44 | Node *next; 45 | Node(int data) 46 | { 47 | this->data = data; 48 | this->next = NULL; 49 | } 50 | }; 51 | 52 | using namespace std; 53 | 54 | Node *takeinput() 55 | { 56 | int data; 57 | cin >> data; 58 | Node *head = NULL, *tail = NULL; 59 | while (data != -1) 60 | { 61 | Node *newnode = new Node(data); 62 | if (head == NULL) 63 | { 64 | head = newnode; 65 | tail = newnode; 66 | } 67 | else 68 | { 69 | tail->next = newnode; 70 | tail = newnode; 71 | } 72 | cin >> data; 73 | } 74 | return head; 75 | } 76 | 77 | Node *removeDuplicates(Node *head) 78 | { 79 | if (head == NULL || head->next == NULL) 80 | return head; 81 | Node *current = head; 82 | while (current->next != NULL) 83 | { 84 | if (current->data == (current->next->data)) 85 | { 86 | Node *temp = current->next->next; 87 | delete current->next; 88 | current->next = temp; 89 | } 90 | else 91 | current = current->next; 92 | } 93 | return head; 94 | } 95 | 96 | void print(Node *head) 97 | { 98 | Node *temp = head; 99 | while (temp != NULL) 100 | { 101 | cout << temp->data << " "; 102 | temp = temp->next; 103 | } 104 | cout << endl; 105 | } 106 | 107 | int main() 108 | { 109 | int t; 110 | cin >> t; 111 | while (t--) 112 | { 113 | Node *head = takeinput(); 114 | head = removeDuplicates(head); 115 | print(head); 116 | } 117 | return 0; 118 | } 119 | -------------------------------------------------------------------------------- /Tress/Print Level Wise.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, print the input tree in level wise order. 2 | 3 | For printing a node with data N, you need to follow the exact format - 4 | N:x1,x2,x3,...,xn 5 | where, N is data of any node present in the generic tree. x1, x2, x3, ...., xn are the children of node N. Note that there is no space in between. 6 | You need to print all nodes in the level order form in different lines. 7 | 8 | Input format : 9 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 10 | 11 | Output Format : 12 | The first and only line of output contains the elements of the tree in level wise order, as described in the task. 13 | 14 | Constraints: 15 | Time Limit: 1 sec 16 | 17 | Sample Input 1: 18 | 10 3 20 30 40 2 40 50 0 0 0 0 19 | 20 | Sample Output 1: 21 | 10:20,30,40 22 | 20:40,50 23 | 30: 24 | 40: 25 | 40: 26 | 50:*/ 27 | 28 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 29 | 30 | #include 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | template 36 | class TreeNode { 37 | public: 38 | T data; 39 | vector*> children; 40 | 41 | TreeNode(T data) { this->data = data; } 42 | 43 | ~TreeNode() { 44 | for (int i = 0; i < children.size(); i++) { 45 | delete children[i]; 46 | } 47 | } 48 | }; 49 | 50 | TreeNode* takeInputLevelWise() { 51 | int rootData; 52 | cin >> rootData; 53 | TreeNode* root = new TreeNode(rootData); 54 | 55 | queue*> pendingNodes; 56 | 57 | pendingNodes.push(root); 58 | while (pendingNodes.size() != 0) { 59 | TreeNode* front = pendingNodes.front(); 60 | pendingNodes.pop(); 61 | int numChild; 62 | cin >> numChild; 63 | for (int i = 0; i < numChild; i++) { 64 | int childData; 65 | cin >> childData; 66 | TreeNode* child = new TreeNode(childData); 67 | front->children.push_back(child); 68 | pendingNodes.push(child); 69 | } 70 | } 71 | 72 | return root; 73 | } 74 | 75 | void printLevelWise(TreeNode *root) 76 | { 77 | if (root == NULL) 78 | return; 79 | queue *> q; 80 | q.push(root); 81 | while (q.size() != 0) 82 | { 83 | TreeNode *front = q.front(); 84 | q.pop(); 85 | cout << front->data << ":"; 86 | for (int i = 0; i < front->children.size(); i++) 87 | { 88 | if (i == 0) 89 | cout << front->children[i]->data; 90 | else 91 | cout << "," << front->children[i]->data; 92 | q.push(front->children[i]); 93 | } 94 | cout << "\n"; 95 | } 96 | } 97 | 98 | 99 | int main() { 100 | TreeNode* root = takeInputLevelWise(); 101 | printLevelWise(root); 102 | } 103 | -------------------------------------------------------------------------------- /Linked List 1/Length of LL.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a linked list of integers. Your task is to write a function that inserts a node at a given position, 'pos'. 2 | 3 | Note: 4 | Assume that the Indexing for the linked list always starts from 0. 5 | 6 | If the given position 'pos' is greater than length of linked list, then you should return the same linked list without any change. And if position 'pos' is equal to length of input linked list, then insert the node at the last position. 7 | Input format: 8 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 9 | 10 | The first line of each test case or query contains the elements of the linked list separated by a single space. 11 | 12 | The second line of each test case contains two space separated integers, that denote the value of 'pos' and the data to be inserted respectively. 13 | Remember/Consider : 14 | 15 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 16 | 17 | Output format: 18 | For each test case/query, print the resulting linked list of integers in a row, separated by a single space. 19 | 20 | Output for every test case will be printed in a separate line. 21 | You don't need to print explicitly, it has been taken care of. 22 | 23 | Constraints: 24 | 1 <= t <= 20 25 | 0 <= length of linked list <= 10^4 26 | 0 <= pos, data to be inserted <= 2^31 - 1 27 | 28 | Time Limit: 1 second 29 | 30 | Sample Input 1: 31 | 1 32 | 3 4 5 2 6 1 9 -1 33 | 3 100 34 | 35 | Sample Output 1: 36 | 3 4 5 100 2 6 1 9 37 | 38 | Sample Input 2: 39 | 1 40 | 3 4 5 2 6 1 9 -1 41 | 0 20 42 | 43 | Sample Output 2: 44 | 20 3 4 5 2 6 1 9*/ 45 | 46 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 47 | 48 | #include 49 | using namespace std; 50 | 51 | class Node { 52 | public: 53 | int data; 54 | Node *next; 55 | Node(int data) { 56 | this->data = data; 57 | this->next = NULL; 58 | } 59 | }; 60 | 61 | Node *insertNode(Node *head, int i, int data) 62 | { 63 | // Write your code here 64 | if (head == NULL) 65 | return head; 66 | if (i == 0) 67 | { 68 | Node *newNode = new Node(data); 69 | newNode->next = head; 70 | head = newNode; 71 | } 72 | else if (i == 1) 73 | { 74 | Node *newNode = new Node(data); 75 | Node *temp = head->next; 76 | head->next = newNode; 77 | newNode->next = temp; 78 | return head; 79 | } 80 | else 81 | insertNode(head->next, i - 1, data); 82 | return head; 83 | } 84 | 85 | Node *takeinput() { 86 | int data; 87 | cin >> data; 88 | Node *head = NULL, *tail = NULL; 89 | while (data != -1) { 90 | Node *newNode = new Node(data); 91 | if (head == NULL) { 92 | head = newNode; 93 | tail = newNode; 94 | } else { 95 | tail->next = newNode; 96 | tail = newNode; 97 | } 98 | cin >> data; 99 | } 100 | return head; 101 | } 102 | -------------------------------------------------------------------------------- /Binary Tree/Sum of Nodes.cpp: -------------------------------------------------------------------------------- 1 | /*For a given Binary Tree of integers, find and return the sum of all the nodes data. 2 | Example: 3 | 10 4 | / \ 5 | 20 30 6 | / \ 7 | 40 50 8 | 9 | When we sum up all the nodes data together, [10, 20, 30, 40 50] we get 150. Hence, the output will be 150. 10 | Input Format: 11 | The first and the only line of input will contain the nodes data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 12 | Output Format: 13 | The first and the only line of output prints the sum of all the nodes data present in the binary tree. 14 | Note: 15 | You are not required to print anything explicitly. It has already been taken care of. 16 | Constraints: 17 | 1 <= N <= 10^6 18 | Where N is the total number of nodes in the binary tree. 19 | 20 | Time Limit: 1 sec 21 | Sample Input 1: 22 | 2 3 4 6 -1 -1 -1 -1 -1 23 | Sample Output 1: 24 | 15 25 | Sample Input 2: 26 | 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1 27 | Sample Output 2: 28 | 28*/ 29 | 30 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | #include 33 | #include 34 | 35 | template 36 | class BinaryTreeNode { 37 | public: 38 | T data; 39 | BinaryTreeNode* left; 40 | BinaryTreeNode* right; 41 | 42 | BinaryTreeNode(T data) { 43 | this->data = data; 44 | left = NULL; 45 | right = NULL; 46 | } 47 | }; 48 | 49 | using namespace std; 50 | 51 | BinaryTreeNode* takeInput() { 52 | int rootData; 53 | cin >> rootData; 54 | if (rootData == -1) { 55 | return NULL; 56 | } 57 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 58 | queue*> q; 59 | q.push(root); 60 | while (!q.empty()) { 61 | BinaryTreeNode* currentNode = q.front(); 62 | q.pop(); 63 | int leftChild, rightChild; 64 | 65 | cin >> leftChild; 66 | if (leftChild != -1) { 67 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 68 | currentNode->left = leftNode; 69 | q.push(leftNode); 70 | } 71 | 72 | cin >> rightChild; 73 | if (rightChild != -1) { 74 | BinaryTreeNode* rightNode = 75 | new BinaryTreeNode(rightChild); 76 | currentNode->right = rightNode; 77 | q.push(rightNode); 78 | } 79 | } 80 | return root; 81 | } 82 | 83 | int getSum(BinaryTreeNode* root) { 84 | if(root == NULL){ 85 | return 0; 86 | } 87 | 88 | int sum = 0; 89 | 90 | if(root->left != NULL){ 91 | sum = sum + getSum(root->left); 92 | } 93 | 94 | if(root->right != NULL){ 95 | sum = sum = getSum(root->right); 96 | } 97 | 98 | sum = sum + root->data; 99 | return sum; 100 | 101 | } 102 | 103 | int main() { 104 | BinaryTreeNode* root = takeInput(); 105 | cout << getSum(root); 106 | } 107 | -------------------------------------------------------------------------------- /Linked List 1/Delete Node (Recursive).cpp: -------------------------------------------------------------------------------- 1 | /*Given a singly linked list of integers and position 'i', delete the node present at the 'i-th' position in the linked list recursively. 2 | 3 | Note : 4 | Assume that the Indexing for the linked list always starts from 0. 5 | No need to print the list, it has already been taken care. Only return the new head to the list. 6 | 7 | input format : 8 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 9 | 10 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 11 | 12 | The second line of input contains a single integer depicting the value of 'i'. 13 | 14 | Remember/Consider : 15 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 16 | Output format : 17 | For each test case/query, print the elements of the updated singly linked list. 18 | 19 | Output for every test case will be printed in a seperate line. 20 | Constraints : 21 | 1 <= t <= 10^2 22 | 0 <= M <= 10^5 23 | Where M is the size of the singly linked list. 24 | 0 <= i < M 25 | 26 | Time Limit: 1sec 27 | 28 | Sample Input 1 : 29 | 1 30 | 3 4 5 2 6 1 9 -1 31 | 3 32 | 33 | Sample Output 1 : 34 | 3 4 5 6 1 9 35 | 36 | Sample Input 2 : 37 | 2 38 | 30 -1 39 | 0 40 | 10 20 30 50 60 -1 41 | 4 42 | 43 | Sample Output 2 : 44 | 10 20 30 50 */ 45 | 46 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 47 | 48 | #include 49 | 50 | class Node 51 | { 52 | public: 53 | int data; 54 | Node *next; 55 | Node(int data) 56 | { 57 | this->data = data; 58 | this->next = NULL; 59 | } 60 | }; 61 | 62 | using namespace std; 63 | 64 | Node *takeinput() 65 | { 66 | int data; 67 | cin >> data; 68 | Node *head = NULL, *tail = NULL; 69 | while (data != -1) 70 | { 71 | Node *newNode = new Node(data); 72 | if (head == NULL) 73 | { 74 | head = newNode; 75 | tail = newNode; 76 | } 77 | else 78 | { 79 | tail->next = newNode; 80 | tail = newNode; 81 | } 82 | cin >> data; 83 | } 84 | return head; 85 | } 86 | 87 | Node *deleteNodeRec(Node *head, int pos) 88 | { 89 | if (head == NULL || head->next == NULL) 90 | return head; 91 | if (pos == 0) 92 | { 93 | Node *current = head; 94 | head = current->next; 95 | delete current; 96 | return head; 97 | } 98 | else if (pos == 1) 99 | { 100 | Node *temp = head->next->next; 101 | delete head->next; 102 | head->next = temp; 103 | return head; 104 | } 105 | else 106 | deleteNodeRec(head->next, pos - 1); 107 | return head; 108 | } 109 | 110 | void print(Node *head) 111 | { 112 | Node *temp = head; 113 | while (temp != NULL) 114 | { 115 | cout << temp->data << " "; 116 | temp = temp->next; 117 | } 118 | cout << endl; 119 | } 120 | 121 | int main() 122 | { 123 | int t; 124 | cin >> t; 125 | 126 | while (t--) 127 | { 128 | Node *head = takeinput(); 129 | int pos; 130 | cin >> pos; 131 | head = deleteNodeRec(head, pos); 132 | print(head); 133 | } 134 | 135 | return 0; 136 | } 137 | -------------------------------------------------------------------------------- /Linked List 1/Find a node in Linked List.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a singly linked list of integers. Write a function that returns the index/position of integer data denoted by 'N' (if it exists). Return -1 otherwise. 2 | Note : 3 | Assume that the Indexing for the singly linked list always starts from 0. 4 | Input format : 5 | The first line contains an Integer 'T' which denotes the number of test cases. 6 | 7 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 8 | 9 | The second line contains the integer value 'N'. It denotes the data to be searched in the given singly linked list. 10 | Remember/Consider : 11 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence -1 would never be a list element. 12 | Output format : 13 | For each test case, return the index/position of 'N' in the singly linked list. Return -1, otherwise. 14 | 15 | Output for every test case will be printed in a separate line. 16 | Note: 17 | You do not need to print anything; it has already been taken care of. Just implement the given function. 18 | Constraints : 19 | 1 <= T <= 10^2 20 | 0 <= M <= 10^5 21 | 22 | Where 'M' is the size of the singly linked list. 23 | 24 | Time Limit: 1 sec 25 | 26 | Sample Input 1 : 27 | 2 28 | 3 4 5 2 6 1 9 -1 29 | 5 30 | 10 20 30 40 50 60 70 -1 31 | 6 32 | 33 | Sample Output 1 : 34 | 2 35 | -1 36 | Explanation for Sample Output 1: 37 | In test case 1, 'N' = 5 appears at position 2 (0-based indexing) in the given linked list. 38 | 39 | In test case 2, we can see that 'N' = 6 is not present in the given linked list. 40 | 41 | Sample Input 2 : 42 | 2 43 | 1 -1 44 | 2 45 | 3 4 5 2 6 1 9 -1 46 | 6 47 | 48 | Sample Output 2 : 49 | -1 50 | 4 51 | Explanation for Sample Output 2: 52 | In test case 1, we can see that 'N' = 2 is not present in the given linked list. 53 | 54 | In test case 2, 'N' = 6 appears at position 4 (0-based indexing) in the given linked list.*/ 55 | 56 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 57 | 58 | #include 59 | 60 | class Node 61 | { 62 | public: 63 | int data; 64 | Node *next; 65 | Node(int data) 66 | { 67 | this->data = data; 68 | this->next = NULL; 69 | } 70 | }; 71 | 72 | using namespace std; 73 | 74 | Node *takeinput() 75 | { 76 | int data; 77 | cin >> data; 78 | Node *head = NULL, *tail = NULL; 79 | while (data != -1) 80 | { 81 | Node *newNode = new Node(data); 82 | if (head == NULL) 83 | { 84 | head = newNode; 85 | tail = newNode; 86 | } 87 | else 88 | { 89 | tail->next = newNode; 90 | tail = newNode; 91 | } 92 | cin >> data; 93 | } 94 | return head; 95 | } 96 | 97 | int findNode(Node *head, int n) 98 | { 99 | int i = 0; 100 | while (head != NULL) 101 | { 102 | if (head->data == n) 103 | return i; 104 | else 105 | { 106 | head = head->next; 107 | i++; 108 | } 109 | } 110 | return -1; 111 | } 112 | 113 | int main() 114 | { 115 | int t; 116 | cin >> t; 117 | while (t--) 118 | { 119 | Node *head = takeinput(); 120 | int val; 121 | cin >> val; 122 | cout << findNode(head, val) << endl; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /BST/Search in BST.cpp: -------------------------------------------------------------------------------- 1 | /*Given a BST and an integer k. Find if the integer k is present in given BST or not. You have to return true, if node with data k is present, return false otherwise. 2 | 3 | Note: Assume that BST contains all unique elements. 4 | Input Format: 5 | The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node. 6 | The following line of input contains an integer, that denotes the value of k. 7 | 8 | Output Format: 9 | The first and only line of output contains a boolean value. Print true, if node with data k is present, print false otherwise. 10 | 11 | Constraints: 12 | Time Limit: 1 second 13 | 14 | Sample Input 1 : 15 | 8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1 16 | 2 17 | 18 | Sample Output 1 : 19 | true 20 | 21 | Sample Input 2 : 22 | 8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1 23 | 12 24 | 25 | Sample Output 2 : 26 | false*/ 27 | 28 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 29 | 30 | #include 31 | #include 32 | 33 | template 34 | class BinaryTreeNode { 35 | public: 36 | T data; 37 | BinaryTreeNode *left; 38 | BinaryTreeNode *right; 39 | 40 | BinaryTreeNode(T data) { 41 | this->data = data; 42 | left = NULL; 43 | right = NULL; 44 | } 45 | ~BinaryTreeNode() { 46 | if (left) delete left; 47 | if (right) delete right; 48 | } 49 | }; 50 | 51 | using namespace std; 52 | 53 | BinaryTreeNode *takeInput() { 54 | int rootData; 55 | cin >> rootData; 56 | if (rootData == -1) { 57 | return NULL; 58 | } 59 | BinaryTreeNode *root = new BinaryTreeNode(rootData); 60 | queue *> q; 61 | q.push(root); 62 | while (!q.empty()) { 63 | BinaryTreeNode *currentNode = q.front(); 64 | q.pop(); 65 | int leftChild, rightChild; 66 | cin >> leftChild; 67 | if (leftChild != -1) { 68 | BinaryTreeNode *leftNode = new BinaryTreeNode(leftChild); 69 | currentNode->left = leftNode; 70 | q.push(leftNode); 71 | } 72 | cin >> rightChild; 73 | if (rightChild != -1) { 74 | BinaryTreeNode *rightNode = 75 | new BinaryTreeNode(rightChild); 76 | currentNode->right = rightNode; 77 | q.push(rightNode); 78 | } 79 | } 80 | return root; 81 | } 82 | 83 | bool searchInBST(BinaryTreeNode *root, int k) 84 | {n 85 | if (root == NULL) 86 | return false; 87 | 88 | if (root->data < k) 89 | searchInBST(root->right, k); 90 | 91 | else if (root->data > k) 92 | searchInBST(root->left, k); 93 | 94 | else if (root->data == k) 95 | return true; 96 | } 97 | 98 | int main() { 99 | BinaryTreeNode *root = takeInput(); 100 | int k; 101 | cin >> k; 102 | cout << ((searchInBST(root, k)) ? "true" : "false"); 103 | delete root; 104 | } 105 | -------------------------------------------------------------------------------- /Tress/Next larger.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree and an integer n. Find and return the node with next larger element in the tree i.e. find a node with value just greater than n. 2 | 3 | Note: Return NULL if no node is present with the value greater than n. 4 | 5 | Input format : 6 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 7 | 8 | The following line contains an integer, that denotes the value of n. 9 | 10 | Output format : 11 | The first and only line of output contains data of the node, whose data is just greater than n. 12 | 13 | Constraints: 14 | Time Limit: 1 sec 15 | 16 | Sample Input 1 : 17 | 10 3 20 30 40 2 40 50 0 0 0 0 18 | 18 19 | 20 | Sample Output 1 : 21 | 20 22 | 23 | Sample Input 2 : 24 | 10 3 20 30 40 2 40 50 0 0 0 0 25 | 21 26 | 27 | Sample Output 2: 28 | 30*/ 29 | 30 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | #include 33 | #include 34 | #include 35 | using namespace std; 36 | 37 | template 38 | class TreeNode { 39 | public: 40 | T data; 41 | vector*> children; 42 | 43 | TreeNode(T data) { this->data = data; } 44 | 45 | ~TreeNode() { 46 | for (int i = 0; i < children.size(); i++) { 47 | delete children[i]; 48 | } 49 | } 50 | }; 51 | 52 | #include 53 | void getNextLarger(TreeNode *root, TreeNode **nextLarger, int *num, int x) 54 | { 55 | if (root->data > x && root->data <= *num) 56 | { 57 | *num = root->data; 58 | *nextLarger = root; 59 | } 60 | for (int i = 0; i < root->children.size(); i++) 61 | getNextLarger(root->children[i], nextLarger, num, x); 62 | } 63 | TreeNode *getNextLargerElement(TreeNode *root, int x) 64 | { 65 | // Write your code here 66 | if (root == NULL) 67 | return NULL; 68 | TreeNode *nextLarger; 69 | int num = INT_MAX; 70 | getNextLarger(root, &nextLarger, &num, x); 71 | return nextLarger; 72 | } 73 | 74 | TreeNode* takeInputLevelWise() { 75 | int rootData; 76 | cin >> rootData; 77 | TreeNode* root = new TreeNode(rootData); 78 | 79 | queue*> pendingNodes; 80 | 81 | pendingNodes.push(root); 82 | while (pendingNodes.size() != 0) { 83 | TreeNode* front = pendingNodes.front(); 84 | pendingNodes.pop(); 85 | int numChild; 86 | cin >> numChild; 87 | for (int i = 0; i < numChild; i++) { 88 | int childData; 89 | cin >> childData; 90 | TreeNode* child = new TreeNode(childData); 91 | front->children.push_back(child); 92 | pendingNodes.push(child); 93 | } 94 | } 95 | 96 | return root; 97 | } 98 | 99 | int main() { 100 | TreeNode* root = takeInputLevelWise(); 101 | int x; 102 | cin >> x; 103 | TreeNode* ans = getNextLargerElement(root, x); 104 | 105 | if (ans != NULL) { 106 | cout << ans->data; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Linked List 2/Reverse LL (Recursive).cpp: -------------------------------------------------------------------------------- 1 | /*Given a singly linked list of integers, reverse it using recursion and return the head to the modified list. You have to do this in O(N) time complexity where N is the size of the linked list. 2 | Note : 3 | No need to print the list, it has already been taken care. Only return the new head to the list. 4 | Input format : 5 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 6 | The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. 7 | Remember/Consider : 8 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 9 | Output format : 10 | For each test case/query, print the elements of the updated singly linked list. 11 | Output for every test case will be printed in a seperate line. 12 | Constraints : 13 | 1 <= t <= 10^2 14 | 0 <= M <= 10^4 15 | Where M is the size of the singly linked list. 16 | Time Limit: 1sec 17 | Sample Input 1 : 18 | 1 19 | 1 2 3 4 5 6 7 8 -1 20 | Sample Output 1 : 21 | 8 7 6 5 4 3 2 1 22 | Sample Input 2 : 23 | 2 24 | 10 -1 25 | 10 20 30 40 50 -1 26 | Sample Output 2 : 27 | 10 28 | 50 40 30 20 10 */ 29 | 30 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | #include 33 | 34 | class Node 35 | { 36 | public: 37 | int data; 38 | Node *next; 39 | Node(int data) 40 | { 41 | this->data = data; 42 | this->next = NULL; 43 | } 44 | }; 45 | 46 | using namespace std; 47 | #include "solution.h" 48 | 49 | Node *takeinput() 50 | { 51 | int data; 52 | cin >> data; 53 | Node *head = NULL, *tail = NULL; 54 | while (data != -1) 55 | { 56 | Node *newnode = new Node(data); 57 | if (head == NULL) 58 | { 59 | head = newnode; 60 | tail = newnode; 61 | } 62 | else 63 | { 64 | tail->next = newnode; 65 | tail = newnode; 66 | } 67 | cin >> data; 68 | } 69 | return head; 70 | } 71 | 72 | void reverseLinkedList(Node *head, Node *tail) 73 | { 74 | Node *current = head; 75 | if (current != tail) 76 | { 77 | int temp = current->data; 78 | current->data = tail->data; 79 | tail->data = temp; 80 | while (current->next != tail) 81 | current = current->next; 82 | if (head->next == tail) 83 | return; 84 | reverseLinkedList(head->next, current); 85 | } 86 | else 87 | return; 88 | } 89 | Node *reverseLinkedListRec(Node *head) 90 | { 91 | // Write your code here 92 | if (head == NULL) 93 | return head; 94 | Node *tail = head; 95 | while (tail->next != NULL) 96 | tail = tail->next; 97 | reverseLinkedList(head, tail); 98 | return head; 99 | } 100 | 101 | void print(Node *head) 102 | { 103 | Node *temp = head; 104 | while (temp != NULL) 105 | { 106 | cout << temp->data << " "; 107 | temp = temp->next; 108 | } 109 | cout << endl; 110 | } 111 | 112 | int main() 113 | { 114 | int t; 115 | cin >> t; 116 | 117 | while(t--) 118 | { 119 | Node *head = takeinput(); 120 | head = reverseLinkedListRec(head); 121 | print(head); 122 | } 123 | 124 | return 0; 125 | } 126 | -------------------------------------------------------------------------------- /Linked List 2/Reverse LL (Iterative).cpp: -------------------------------------------------------------------------------- 1 | /*Given a singly linked list of integers, reverse it iteratively and return the head to the modified list. 2 | Note : 3 | No need to print the list, it has already been taken care. Only return the new head to the list. 4 | Input format : 5 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 6 | 7 | The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. 8 | Remember/Consider : 9 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 10 | Output format : 11 | For each test case/query, print the elements of the updated singly linked list. 12 | 13 | Output for every test case will be printed in a separate line. 14 | Constraints : 15 | 1 <= t <= 10^2 16 | 0 <= N <= 10^4 17 | 18 | Where N is the size of the singly linked list. 19 | 20 | Time Limit: 1 sec 21 | 22 | Sample Input 1 : 23 | 1 24 | 1 2 3 4 5 6 7 8 -1 25 | 26 | Sample Output 1 : 27 | 8 7 6 5 4 3 2 1 28 | 29 | Sample Input 2 : 30 | 2 31 | 10 -1 32 | 10 20 30 40 50 -1 33 | 34 | Sample Output 2 : 35 | 10 36 | 50 40 30 20 10 */ 37 | 38 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 39 | 40 | #include 41 | 42 | class Node { 43 | public: 44 | int data; 45 | Node *next; 46 | Node(int data) { 47 | this->data = data; 48 | this->next = NULL; 49 | } 50 | }; 51 | 52 | using namespace std; 53 | #include "solution.h" 54 | 55 | Node *takeinput() { 56 | int data; 57 | cin >> data; 58 | Node *head = NULL, *tail = NULL; 59 | while (data != -1) { 60 | Node *newnode = new Node(data); 61 | if (head == NULL) { 62 | head = newnode; 63 | tail = newnode; 64 | } else { 65 | tail->next = newnode; 66 | tail = newnode; 67 | } 68 | cin >> data; 69 | } 70 | return head; 71 | } 72 | 73 | Node *reverseLinkedList(Node *head) 74 | { 75 | if (head == NULL) 76 | return head; 77 | Node *current = head; 78 | Node *tail = head; 79 | while (tail->next != NULL) 80 | tail = tail->next; 81 | while (current != tail) 82 | { 83 | int temp = current->data; 84 | current->data = tail->data; 85 | tail->data = temp; 86 | if (current->next != tail) 87 | { 88 | Node *prev = current; 89 | while (prev->next != tail) 90 | prev = prev->next; 91 | tail = prev; 92 | current = current->next; 93 | } 94 | else 95 | current = current->next; 96 | } 97 | return head; 98 | } 99 | 100 | void print(Node *head) { 101 | Node *temp = head; 102 | 103 | while (temp != NULL) { 104 | cout << temp->data << " "; 105 | temp = temp->next; 106 | } 107 | 108 | cout << "\n"; 109 | } 110 | 111 | int main() { 112 | int t; 113 | cin >> t; 114 | 115 | while (t--) { 116 | Node *head = takeinput(); 117 | head = reverseLinkedList(head); 118 | print(head); 119 | } 120 | 121 | return 0; 122 | } 123 | -------------------------------------------------------------------------------- /Tress/Replace with depth.cpp: -------------------------------------------------------------------------------- 1 | /*You are given a generic tree. You have to replace each node with its depth value. You just have to update the data of each node, there is no need to return or print anything. 2 | 3 | Input format : 4 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 5 | 6 | Output format: 7 | The updated tree is printed level wise. Each level is printed in a new line. Please refer to sample output 1 for more details. 8 | 9 | Constraints: 10 | Time Limit: 1 sec 11 | 12 | Sample Input 1: 13 | 10 3 20 30 40 2 40 50 0 0 0 0 14 | 15 | Sample Output 1: 16 | 0 17 | 1 1 1 18 | 2 2*/ 19 | 20 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | using namespace std; 27 | 28 | template 29 | class TreeNode { 30 | public: 31 | T data; 32 | vector*> children; 33 | 34 | TreeNode(T data) { this->data = data; } 35 | 36 | ~TreeNode() { 37 | for (int i = 0; i < children.size(); i++) { 38 | delete children[i]; 39 | } 40 | } 41 | }; 42 | 43 | void replaceWithDepth(TreeNode *root, int count) 44 | { 45 | root->data = count; 46 | for (int i = 0; i < root->children.size(); i++) 47 | replaceWithDepth(root->children[i], count + 1); 48 | } 49 | void replaceWithDepthValue(TreeNode *root) 50 | { 51 | if (root == NULL) 52 | return; 53 | int count = 0; 54 | replaceWithDepth(root, count); 55 | } 56 | 57 | TreeNode* takeInputLevelWise() { 58 | int rootData; 59 | cin >> rootData; 60 | TreeNode* root = new TreeNode(rootData); 61 | 62 | queue*> pendingNodes; 63 | 64 | pendingNodes.push(root); 65 | while (pendingNodes.size() != 0) { 66 | TreeNode* front = pendingNodes.front(); 67 | pendingNodes.pop(); 68 | int numChild; 69 | cin >> numChild; 70 | for (int i = 0; i < numChild; i++) { 71 | int childData; 72 | cin >> childData; 73 | TreeNode* child = new TreeNode(childData); 74 | front->children.push_back(child); 75 | pendingNodes.push(child); 76 | } 77 | } 78 | 79 | return root; 80 | } 81 | 82 | void printLevelATNewLine(TreeNode* root) { 83 | queue*> q; 84 | q.push(root); 85 | q.push(NULL); 86 | while (!q.empty()) { 87 | TreeNode* first = q.front(); 88 | q.pop(); 89 | if (first == NULL) { 90 | if (q.empty()) { 91 | break; 92 | } 93 | cout << endl; 94 | q.push(NULL); 95 | continue; 96 | } 97 | cout << first->data << " "; 98 | for (int i = 0; i < first->children.size(); i++) { 99 | q.push(first->children[i]); 100 | } 101 | } 102 | } 103 | 104 | int main() { 105 | TreeNode* root = takeInputLevelWise(); 106 | replaceWithDepthValue(root); 107 | printLevelATNewLine(root); 108 | } 109 | -------------------------------------------------------------------------------- /Linked List 2/Swap two Nodes of LL.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a singly linked list of integers along with two integers, 'i,' and 'j.' Swap the nodes that are present at the 'i-th' and 'j-th' positions. 2 | Note : 3 | Remember, the nodes themselves must be swapped and not the datas. 4 | 5 | No need to print the list, it has already been taken care. Only return the new head to the list. 6 | 7 | Input format : 8 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 9 | 10 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 11 | 12 | The second line of input contains two integer values 'i,' and 'j,' respectively. A single space will separate them. 13 | Remember/consider : 14 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 15 | 16 | Output format : 17 | For each test case/query, print the elements of the updated singly linked list. 18 | 19 | Output for every test case will be printed in a seperate line. 20 | 21 | Constraints : 22 | 1 <= t <= 10^2 23 | 0 <= M <= 10^5 24 | Where M is the size of the singly linked list. 25 | 0 <= i < M 26 | 0 <= j < M 27 | 28 | Time Limit: 1sec 29 | Sample Input 1 : 30 | 1 31 | 3 4 5 2 6 1 9 -1 32 | 3 4 33 | 34 | Sample Output 1 : 35 | 3 4 5 6 2 1 9 36 | 37 | Sample Input 2 : 38 | 2 39 | 10 20 30 40 -1 40 | 1 2 41 | 70 80 90 25 65 85 90 -1 42 | 0 6 43 | 44 | Sample Output 2 : 45 | 10 30 20 40 46 | 90 80 90 25 65 85 70 */ 47 | 48 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 49 | 50 | #include 51 | 52 | class Node 53 | { 54 | public: 55 | int data; 56 | Node *next; 57 | Node(int data) 58 | { 59 | this->data = data; 60 | this->next = NULL; 61 | } 62 | }; 63 | 64 | using namespace std; 65 | 66 | Node *takeinput() 67 | { 68 | int data; 69 | cin >> data; 70 | Node *head = NULL, *tail = NULL; 71 | while (data != -1) 72 | { 73 | Node *newnode = new Node(data); 74 | if (head == NULL) 75 | { 76 | head = newnode; 77 | tail = newnode; 78 | } 79 | else 80 | { 81 | tail->next = newnode; 82 | tail = newnode; 83 | } 84 | cin >> data; 85 | } 86 | return head; 87 | } 88 | 89 | Node *swapNodes(Node *head, int i, int j) 90 | { 91 | if (head == NULL) 92 | return head; 93 | int k = 0; 94 | Node *current = head; 95 | Node *val1 = NULL; 96 | Node *val2 = NULL; 97 | while (k <= i || k <= j) 98 | { 99 | if (k == i) 100 | val1 = current; 101 | if (k == j) 102 | val2 = current; 103 | current = current->next; 104 | k++; 105 | } 106 | int temp = val1->data; 107 | val1->data = val2->data; 108 | val2->data = temp; 109 | return head; 110 | } 111 | 112 | void print(Node *head) 113 | { 114 | Node *temp = head; 115 | while (temp != NULL) 116 | { 117 | cout << temp->data << " "; 118 | temp = temp->next; 119 | } 120 | cout << endl; 121 | } 122 | 123 | int main() 124 | { 125 | int t; 126 | cin >> t; 127 | while (t--) 128 | { 129 | int i, j; 130 | Node *head = takeinput(); 131 | cin >> i; 132 | cin >> j; 133 | head = swapNodes(head, i, j); 134 | print(head); 135 | } 136 | return 0; 137 | } 138 | -------------------------------------------------------------------------------- /Binary Tree/Height of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /*For a given Binary Tree of integers, find and return the height of the tree. 2 | 3 | Example: 4 | 10 5 | / \ 6 | 20 30 7 | / \ 8 | 40 50 9 | 10 | Height of the given tree is 3. 11 | 12 | Height is defined as the total number of nodes along the longest path from the root to any of the leaf node. 13 | 14 | Input Format: 15 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 16 | 17 | Output Format: 18 | The first and the only line of output prints the height of the given binary tree. 19 | 20 | Note: 21 | You are not required to print anything explicitly. It has already been taken care of. 22 | 23 | Constraints: 24 | 0 <= N <= 10^5 25 | Where N is the total number of nodes in the binary tree. 26 | 27 | Time Limit: 1 sec 28 | 29 | Sample Input 1: 30 | 10 20 30 40 50 -1 -1 -1 -1 -1 -1 31 | 32 | Sample Output 1: 33 | 3 34 | 35 | Sample Input 2: 36 | 3 -1 -1 37 | 38 | Sample Output 2: 39 | 1*/ 40 | 41 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 42 | 43 | #include 44 | #include 45 | 46 | template 47 | class BinaryTreeNode { 48 | public: 49 | T data; 50 | BinaryTreeNode* left; 51 | BinaryTreeNode* right; 52 | 53 | BinaryTreeNode(T data) { 54 | this->data = data; 55 | left = NULL; 56 | right = NULL; 57 | } 58 | }; 59 | 60 | using namespace std; 61 | 62 | BinaryTreeNode* takeInput() { 63 | int rootData; 64 | cin >> rootData; 65 | if (rootData == -1) { 66 | return NULL; 67 | } 68 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 69 | queue*> q; 70 | q.push(root); 71 | while (!q.empty()) { 72 | BinaryTreeNode* currentNode = q.front(); 73 | q.pop(); 74 | int leftChild, rightChild; 75 | 76 | cin >> leftChild; 77 | if (leftChild != -1) { 78 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 79 | currentNode->left = leftNode; 80 | q.push(leftNode); 81 | } 82 | 83 | cin >> rightChild; 84 | if (rightChild != -1) { 85 | BinaryTreeNode* rightNode = 86 | new BinaryTreeNode(rightChild); 87 | currentNode->right = rightNode; 88 | q.push(rightNode); 89 | } 90 | } 91 | return root; 92 | } 93 | 94 | void heightMax(BinaryTreeNode *root, int height, int *max) 95 | { 96 | if (root == NULL) 97 | return; 98 | if ((*max) < height) 99 | *max = height; 100 | if (root->left != NULL) 101 | heightMax(root->left, 1 + height, max); 102 | if (root->right != NULL) 103 | heightMax(root->right, 1 + height, max); 104 | } 105 | int height(BinaryTreeNode *root) 106 | { 107 | if (root == NULL) 108 | return 0; 109 | int height = 1, max = 1; 110 | heightMax(root, height, &max); 111 | return max; 112 | } 113 | 114 | 115 | int main() { 116 | BinaryTreeNode* root = takeInput(); 117 | cout << height(root); 118 | } 119 | -------------------------------------------------------------------------------- /Tress/Second Largest element in tree.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, find and return the node with second largest value in given tree. 2 | Note: Return NULL if no node with required value is present. 3 | 4 | Input format : 5 | The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 6 | 7 | Output Format : 8 | The first and only line of output contains data of the node with second largest data. 9 | 10 | Constraints: 11 | Time Limit: 1 sec 12 | 13 | Sample Input 1 : 14 | 10 3 20 30 40 2 40 50 0 0 0 0 15 | 16 | Sample Output 1 : 17 | 40*/ 18 | 19 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | using namespace std; 26 | 27 | template 28 | class TreeNode { 29 | public: 30 | T data; 31 | vector*> children; 32 | 33 | TreeNode(T data) { this->data = data; } 34 | 35 | ~TreeNode() { 36 | for (int i = 0; i < children.size(); i++) { 37 | delete children[i]; 38 | } 39 | } 40 | }; 41 | 42 | void getSecondLargest(TreeNode *root, TreeNode **secondLargestNode, TreeNode **largestNode) 43 | { 44 | if (*largestNode == NULL) 45 | *largestNode = root; 46 | else if (*secondLargestNode == NULL && (root->data) < ((*largestNode)->data)) 47 | *secondLargestNode = root; 48 | else if ((root->data) > ((*largestNode)->data)) 49 | { 50 | *secondLargestNode = *largestNode; 51 | *largestNode = root; 52 | } 53 | else if ((root->data) < ((*largestNode)->data) && (root->data) > ((*secondLargestNode)->data)) 54 | *secondLargestNode = root; 55 | for (int i = 0; i < root->children.size(); i++) 56 | getSecondLargest(root->children[i], secondLargestNode, largestNode); 57 | } 58 | TreeNode *getSecondLargestNode(TreeNode *root) 59 | { 60 | // Write your code here 61 | if (root == NULL || root->children.size() == 0) 62 | return NULL; 63 | TreeNode *secondLargestNode = NULL; 64 | TreeNode *largestNode = NULL; 65 | getSecondLargest(root, &secondLargestNode, &largestNode); 66 | return secondLargestNode; 67 | } 68 | 69 | TreeNode* takeInputLevelWise() { 70 | int rootData; 71 | cin >> rootData; 72 | TreeNode* root = new TreeNode(rootData); 73 | 74 | queue*> pendingNodes; 75 | 76 | pendingNodes.push(root); 77 | while (pendingNodes.size() != 0) { 78 | TreeNode* front = pendingNodes.front(); 79 | pendingNodes.pop(); 80 | int numChild; 81 | cin >> numChild; 82 | for (int i = 0; i < numChild; i++) { 83 | int childData; 84 | cin >> childData; 85 | TreeNode* child = new TreeNode(childData); 86 | front->children.push_back(child); 87 | pendingNodes.push(child); 88 | } 89 | } 90 | 91 | return root; 92 | } 93 | 94 | int main() { 95 | TreeNode* root = takeInputLevelWise(); 96 | 97 | TreeNode* ans = getSecondLargestNode(root); 98 | 99 | if (ans != NULL) { 100 | cout << ans->data; 101 | } else { 102 | cout << INT_MIN; 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /Tress/Structurally identical.cpp: -------------------------------------------------------------------------------- 1 | /*Given two generic trees, return true if they are structurally identical. Otherwise return false. 2 | 3 | Structural Identical 4 | If the two given trees are made of nodes with the same values and the nodes are arranged in the same way, then the trees are called identical. 5 | Input format : 6 | The first line of input contains data of the nodes of the first tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 7 | The following line of input contains data of the nodes of the second tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. 8 | 9 | Output format : 10 | The first and only line of output contains true, if the given trees are structurally identical and false, otherwise. 11 | 12 | Constraints: 13 | Time Limit: 1 sec 14 | 15 | Sample Input 1 : 16 | 10 3 20 30 40 2 40 50 0 0 0 0 17 | 10 3 20 30 40 2 40 50 0 0 0 0 18 | 19 | Sample Output 1 : 20 | true 21 | 22 | Sample Input 2 : 23 | 10 3 20 30 40 2 40 50 0 0 0 0 24 | 10 3 2 30 40 2 40 50 0 0 0 0 25 | 26 | Sample Output 2: 27 | false*/ 28 | 29 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 30 | 31 | #include 32 | #include 33 | #include 34 | using namespace std; 35 | 36 | template 37 | class TreeNode { 38 | public: 39 | T data; 40 | vector*> children; 41 | 42 | TreeNode(T data) { this->data = data; } 43 | 44 | ~TreeNode() { 45 | for (int i = 0; i < children.size(); i++) { 46 | delete children[i]; 47 | } 48 | } 49 | }; 50 | 51 | bool areIdentical(TreeNode *root1, TreeNode * root2) { 52 | if (root1==NULL && root2==NULL){ 53 | return false; 54 | } 55 | 56 | if(root1->children.size()!=root2->children.size()){ 57 | return false; 58 | } 59 | 60 | for(int i=0; ichildren.size(); i++){ 61 | bool value = areIdentical(root1->children[i], root2->children[i]); 62 | if (!value){ 63 | return false; 64 | } 65 | } 66 | if(root1->data != root2->data){ 67 | return false; 68 | } 69 | 70 | else{ 71 | return true; 72 | } 73 | 74 | } 75 | 76 | TreeNode* takeInputLevelWise() { 77 | int rootData; 78 | cin >> rootData; 79 | TreeNode* root = new TreeNode(rootData); 80 | 81 | queue*> pendingNodes; 82 | 83 | pendingNodes.push(root); 84 | while (pendingNodes.size() != 0) { 85 | TreeNode* front = pendingNodes.front(); 86 | pendingNodes.pop(); 87 | int numChild; 88 | cin >> numChild; 89 | for (int i = 0; i < numChild; i++) { 90 | int childData; 91 | cin >> childData; 92 | TreeNode* child = new TreeNode(childData); 93 | front->children.push_back(child); 94 | pendingNodes.push(child); 95 | } 96 | } 97 | 98 | return root; 99 | } 100 | 101 | int main() { 102 | TreeNode* root1 = takeInputLevelWise(); 103 | TreeNode* root2 = takeInputLevelWise(); 104 | cout << (areIdentical(root1, root2) ? "true" : "false"); 105 | } 106 | -------------------------------------------------------------------------------- /Binary Tree/Min and Max of a Binary tree.cpp: -------------------------------------------------------------------------------- 1 | /*For a given a Binary Tree of type integer, find and return the minimum and the maximum data values. 2 | 3 | Return the output as an object of Pair class, which is already created. 4 | 5 | Note: 6 | All the node data will be unique and hence there will always exist a minimum and maximum node data. 7 | 8 | Input Format: 9 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 10 | 11 | Output Format: 12 | The only line of output prints two integers denoting the minimum and the maximum data values respectively. A single line will separate them both. 13 | 14 | Constraints: 15 | 2 <= N <= 10^5 16 | Where N is the total number of nodes in the binary tree. 17 | 18 | Time Limit: 1 sec 19 | 20 | Sample Input 1: 21 | 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 22 | 23 | Sample Output 1: 24 | 1 14 25 | 26 | Sample Input 2: 27 | 10 20 60 -1 -1 3 50 -1 -1 -1 -1 28 | 29 | Sample Output 2: 30 | 3 60*/ 31 | 32 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 33 | 34 | #include 35 | #include 36 | 37 | template 38 | class BinaryTreeNode { 39 | public: 40 | T data; 41 | BinaryTreeNode* left; 42 | BinaryTreeNode* right; 43 | 44 | BinaryTreeNode(T data) { 45 | this->data = data; 46 | left = NULL; 47 | right = NULL; 48 | } 49 | }; 50 | 51 | using namespace std; 52 | 53 | BinaryTreeNode* takeInput() { 54 | int rootData; 55 | cin >> rootData; 56 | if (rootData == -1) { 57 | return NULL; 58 | } 59 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 60 | queue*> q; 61 | q.push(root); 62 | while (!q.empty()) { 63 | BinaryTreeNode* currentNode = q.front(); 64 | q.pop(); 65 | int leftChild, rightChild; 66 | 67 | cin >> leftChild; 68 | if (leftChild != -1) { 69 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 70 | currentNode->left = leftNode; 71 | q.push(leftNode); 72 | } 73 | 74 | cin >> rightChild; 75 | if (rightChild != -1) { 76 | BinaryTreeNode* rightNode = new BinaryTreeNode(rightChild); 77 | currentNode->right = rightNode; 78 | q.push(rightNode); 79 | } 80 | } 81 | return root; 82 | } 83 | 84 | #include 85 | void Min(BinaryTreeNode *root, int *min) 86 | { 87 | if (root == NULL) 88 | return; 89 | if ((*min) > root->data) 90 | *min = root->data; 91 | Min(root->left, min); 92 | Min(root->right, min); 93 | } 94 | void Max(BinaryTreeNode *root, int *max) 95 | { 96 | if (root == NULL) 97 | return; 98 | if ((*max) < root->data) 99 | *max = root->data; 100 | Max(root->left, max); 101 | Max(root->right, max); 102 | } 103 | pair getMinAndMax(BinaryTreeNode *root) 104 | { 105 | pair p = {0, 0}; 106 | if (root == NULL) 107 | return p; 108 | int min = INT_MAX, max = INT_MIN; 109 | Min(root, &min); 110 | Max(root, &max); 111 | p = {min, max}; 112 | return p; 113 | } 114 | 115 | int main() { 116 | BinaryTreeNode* root = takeInput(); 117 | pair ans = getMinAndMax(root); 118 | cout << ans.first << " " << ans.second; 119 | } 120 | -------------------------------------------------------------------------------- /Binary Tree/Nodes without Sibling.cpp: -------------------------------------------------------------------------------- 1 | /*For a given Binary Tree of type integer, print all the nodes without any siblings. 2 | 3 | Input Format: 4 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 5 | 6 | Output Format: 7 | The only line of output prints the node data in a top to down fashion with reference to the root. 8 | Node data in the left subtree will be printed first and then the right subtree. 9 | A single space will separate them all. 10 | 11 | Constraints: 12 | 1 <= N <= 10^5 13 | Where N is the total number of nodes in the binary tree. 14 | 15 | Time Limit: 1 second 16 | 17 | Sample Input 1: 18 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 19 | 20 | Sample Output 1: 21 | 9 22 | 23 | Sample Input 2: 24 | 2 4 5 6 -1 -1 7 20 30 80 90 -1 -1 -1 -1 -1 -1 -1 -1 25 | 26 | Sample Output 2: 27 | 6 7 28 | 29 | Explanation of Sample Input 2: 30 | The input tree when represented in a two-dimensional plane, it would look like this: 31 | alt txt 32 | 33 | In respect to the root, node data in the left subtree that satisfy the condition of not having a sibling would be 6, taken in a top-down sequence. Similarly, for the right subtree, 7 is the node data without any sibling. 34 | 35 | Since we print the siblings in the left-subtree first and then the siblings from the right subtree, taken in a top-down fashion, we print 6 7.*/ 36 | 37 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 38 | 39 | #include 40 | #include 41 | 42 | template 43 | class BinaryTreeNode { 44 | public: 45 | T data; 46 | BinaryTreeNode* left; 47 | BinaryTreeNode* right; 48 | 49 | BinaryTreeNode(T data) { 50 | this->data = data; 51 | left = NULL; 52 | right = NULL; 53 | } 54 | }; 55 | 56 | using namespace std; 57 | 58 | BinaryTreeNode* takeInput() { 59 | int rootData; 60 | cin >> rootData; 61 | if (rootData == -1) { 62 | return NULL; 63 | } 64 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 65 | queue*> q; 66 | q.push(root); 67 | while (!q.empty()) { 68 | BinaryTreeNode* currentNode = q.front(); 69 | q.pop(); 70 | int leftChild, rightChild; 71 | cin >> leftChild; 72 | if (leftChild != -1) { 73 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 74 | currentNode->left = leftNode; 75 | q.push(leftNode); 76 | } 77 | cin >> rightChild; 78 | if (rightChild != -1) { 79 | BinaryTreeNode* rightNode = 80 | new BinaryTreeNode(rightChild); 81 | currentNode->right = rightNode; 82 | q.push(rightNode); 83 | } 84 | } 85 | return root; 86 | } 87 | 88 | void printNodesWithoutSibling(BinaryTreeNode *root) { 89 | if(root==NULL){ 90 | return ; 91 | } 92 | 93 | if(root->left!=NULL&&root->right==NULL){ 94 | cout<left->data<<" "; 95 | 96 | } 97 | if(root->left==NULL&&root->right!=NULL){ 98 | cout<right->data<<" "; 99 | 100 | } 101 | 102 | 103 | printNodesWithoutSibling(root->right); 104 | printNodesWithoutSibling(root->left); 105 | 106 | return ; 107 | } 108 | 109 | int main() { 110 | BinaryTreeNode* root = takeInput(); 111 | printNodesWithoutSibling(root); 112 | } 113 | -------------------------------------------------------------------------------- /Binary Tree/Zig Zag Tree.cpp: -------------------------------------------------------------------------------- 1 | /*Given a binary tree, print the zig zag order. In zigzag order, level 1 is printed from left to right, level 2 from right to left and so on. This means odd levels should get printed from left to right and even level right to left. 2 | 3 | Input format: 4 | The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have a left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node. 5 | 6 | Output Format: 7 | The binary tree is printed level wise, as described in the task. Each level is printed in new line. 8 | 9 | Constraints 10 | Time Limit: 1 second 11 | 12 | Sample Input : 13 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 14 | 15 | Sample Output : 16 | 5 17 | 10 6 18 | 2 3 19 | 9*/ 20 | 21 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 22 | 23 | #include 24 | #include 25 | 26 | template 27 | class BinaryTreeNode { 28 | public: 29 | T data; 30 | BinaryTreeNode* left; 31 | BinaryTreeNode* right; 32 | 33 | BinaryTreeNode(T data) { 34 | this->data = data; 35 | left = NULL; 36 | right = NULL; 37 | } 38 | }; 39 | 40 | using namespace std; 41 | 42 | BinaryTreeNode* takeInput() { 43 | int rootData; 44 | cin >> rootData; 45 | if (rootData == -1) { 46 | return NULL; 47 | } 48 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 49 | queue*> q; 50 | q.push(root); 51 | while (!q.empty()) { 52 | BinaryTreeNode* currentNode = q.front(); 53 | q.pop(); 54 | int leftChild, rightChild; 55 | 56 | cin >> leftChild; 57 | if (leftChild != -1) { 58 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 59 | currentNode->left = leftNode; 60 | q.push(leftNode); 61 | } 62 | 63 | cin >> rightChild; 64 | if (rightChild != -1) { 65 | BinaryTreeNode* rightNode = 66 | new BinaryTreeNode(rightChild); 67 | currentNode->right = rightNode; 68 | q.push(rightNode); 69 | } 70 | } 71 | return root; 72 | } 73 | 74 | #include 75 | void zigZagOrder(BinaryTreeNode *root) 76 | { 77 | if (root == NULL) 78 | return; 79 | vector *> pendingNodes; 80 | pendingNodes.push_back(root); 81 | int level = 1; 82 | while (pendingNodes.size() != 0) 83 | { 84 | int n = pendingNodes.size(); 85 | if (level % 2 == 0) 86 | { 87 | for (int i = n - 1; i >= 0; i--) 88 | cout << pendingNodes[i]->data << " "; 89 | } 90 | else 91 | { 92 | for (auto i : pendingNodes) 93 | cout << i->data << " "; 94 | } 95 | for (int i = 0; i < n; i++) 96 | { 97 | BinaryTreeNode *front = pendingNodes[i]; 98 | if (front->left != NULL) 99 | pendingNodes.push_back(front->left); 100 | if (front->right != NULL) 101 | pendingNodes.push_back(front->right); 102 | } 103 | pendingNodes.erase(pendingNodes.begin(), pendingNodes.begin() + n); 104 | cout << "\n"; 105 | level++; 106 | } 107 | } 108 | 109 | int main() { 110 | BinaryTreeNode* root = takeInput(); 111 | zigZagOrder(root); 112 | } 113 | -------------------------------------------------------------------------------- /Linked List 2/Even after Odd LinkedList.cpp: -------------------------------------------------------------------------------- 1 | /*For a given singly linked list of integers, arrange the elements such that all the even numbers are placed after the odd numbers. The relative order of the odd and even terms should remain unchanged. 2 | Note : 3 | No need to print the list, it has already been taken care. Only return the new head to the list. 4 | Input format: 5 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 6 | 7 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 8 | Remember/Consider : 9 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 10 | 11 | Output format: 12 | For each test case/query, print the elements of the updated singly linked list. 13 | 14 | Output for every test case will be printed in a seperate line. 15 | Constraints : 16 | 1 <= t <= 10^2 17 | 0 <= M <= 10^5 18 | Where M is the size of the singly linked list. 19 | 20 | Time Limit: 1sec 21 | Sample Input 1 : 22 | 1 23 | 1 4 5 2 -1 24 | 25 | Sample Output 1 : 26 | 1 5 4 2 27 | 28 | Sample Input 2 : 29 | 2 30 | 1 11 3 6 8 0 9 -1 31 | 10 20 30 40 -1 32 | 33 | Sample Output 2 : 34 | 1 11 3 9 6 8 0 35 | 10 20 30 40*/ 36 | 37 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 38 | 39 | #include 40 | 41 | class Node 42 | { 43 | public: 44 | int data; 45 | Node *next; 46 | Node(int data) 47 | { 48 | this->data = data; 49 | this->next = NULL; 50 | } 51 | }; 52 | 53 | using namespace std; 54 | 55 | Node *takeinput() 56 | { 57 | int data; 58 | cin >> data; 59 | Node *head = NULL, *tail = NULL; 60 | while (data != -1) 61 | { 62 | Node *newnode = new Node(data); 63 | if (head == NULL) 64 | { 65 | head = newnode; 66 | tail = newnode; 67 | } 68 | else 69 | { 70 | tail->next = newnode; 71 | tail = newnode; 72 | } 73 | cin >> data; 74 | } 75 | return head; 76 | } 77 | 78 | void print(Node *head) 79 | { 80 | Node *temp = head; 81 | while (temp != NULL) 82 | { 83 | cout << temp->data << " "; 84 | temp = temp->next; 85 | } 86 | cout << endl; 87 | } 88 | 89 | Node *evenAfterOdd(Node *head) 90 | { 91 | if (head == NULL) 92 | return head; 93 | Node *head1 = NULL, *tail1 = NULL, *head2 = NULL, *tail2 = NULL; 94 | while (head != NULL) 95 | { 96 | if (head->data % 2 == 0) 97 | { 98 | if (head1 == NULL) 99 | { 100 | head1 = head; 101 | tail1 = head; 102 | } 103 | else 104 | { 105 | tail1->next = head; 106 | tail1 = head; 107 | } 108 | } 109 | else 110 | { 111 | if (head2 == NULL) 112 | { 113 | head2 = head; 114 | tail2 = head; 115 | } 116 | else 117 | { 118 | tail2->next = head; 119 | tail2 = head; 120 | } 121 | } 122 | head = head->next; 123 | } 124 | if (tail2 != NULL) 125 | tail2->next = head1; 126 | if (tail1 != NULL) 127 | tail1->next = NULL; 128 | if (head2 == NULL) 129 | return head1; 130 | else 131 | return head2; 132 | } 133 | 134 | int main() 135 | { 136 | int t; 137 | cin >> t; 138 | while (t--) 139 | { 140 | Node *head = takeinput(); 141 | head = evenAfterOdd(head); 142 | print(head); 143 | } 144 | return 0; 145 | } 146 | -------------------------------------------------------------------------------- /Linked List 1/Insert Node (Recursively).cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a linked list of integers. Your task is to write a function that inserts a node at a given position, 'pos'. 2 | Note: 3 | Assume that the Indexing for the linked list always starts from 0. 4 | 5 | If the given position 'pos' is greater than length of linked list, then you should return the same linked list without any change. And if position 'pos' is equal to length of input linked list, then insert the node at the last position. 6 | Input format: 7 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 8 | 9 | The first line of each test case or query contains the elements of the linked list separated by a single space. 10 | 11 | The second line of each test case contains two space separated integers, that denote the value of 'pos' and the data to be inserted respectively. 12 | Remember/Consider : 13 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 14 | 15 | Output format: 16 | For each test case/query, print the resulting linked list of integers in a row, separated by a single space. 17 | 18 | Output for every test case will be printed in a separate line. 19 | You don't need to print explicitly, it has been taken care of. 20 | 21 | Constraints: 22 | 1 <= t <= 20 23 | 0 <= length of linked list <= 10^4 24 | 0 <= pos, data to be inserted <= 2^31 - 1 25 | 26 | Time Limit: 1 second 27 | 28 | Sample Input 1: 29 | 1 30 | 3 4 5 2 6 1 9 -1 31 | 3 100 32 | 33 | Sample Output 1: 34 | 3 4 5 100 2 6 1 9 35 | 36 | Sample Input 2: 37 | 1 38 | 3 4 5 2 6 1 9 -1 39 | 0 20 40 | 41 | Sample Output 2: 42 | 20 3 4 5 2 6 1 9*/ 43 | 44 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- 45 | 46 | #include 47 | 48 | class Node { 49 | public: 50 | int data; 51 | Node *next; 52 | Node(int data) { 53 | this->data = data; 54 | this->next = NULL; 55 | } 56 | }; 57 | 58 | using namespace std; 59 | 60 | Node *takeinput() { 61 | int data; 62 | cin >> data; 63 | Node *head = NULL, *tail = NULL; 64 | while (data != -1) { 65 | Node *newNode = new Node(data); 66 | if (head == NULL) { 67 | head = newNode; 68 | tail = newNode; 69 | } else { 70 | tail->next = newNode; 71 | tail = newNode; 72 | } 73 | cin >> data; 74 | } 75 | return head; 76 | } 77 | 78 | Node *insertNode(Node *head, int i, int data) 79 | { 80 | // Write your code here 81 | if (head == NULL) 82 | return head; 83 | if (i == 0) 84 | { 85 | Node *newNode = new Node(data); 86 | newNode->next = head; 87 | head = newNode; 88 | } 89 | else if (i == 1) 90 | { 91 | Node *newNode = new Node(data); 92 | Node *temp = head->next; 93 | head->next = newNode; 94 | newNode->next = temp; 95 | return head; 96 | } 97 | else 98 | insertNode(head->next, i - 1, data); 99 | return head; 100 | } 101 | 102 | void print(Node *head) { 103 | Node *temp = head; 104 | 105 | while (temp != NULL) { 106 | cout << temp->data << " "; 107 | temp = temp->next; 108 | } 109 | 110 | cout << "\n"; 111 | } 112 | 113 | int main() { 114 | int t; 115 | cin >> t; 116 | 117 | while (t--) { 118 | Node *head = takeinput(); 119 | int pos, data; 120 | cin >> pos >> data; 121 | head = insertNode(head, pos, data); 122 | print(head); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Linked List 1/Delete Node.cpp: -------------------------------------------------------------------------------- 1 | /*You have been given a linked list of integers. Your task is to write a function that deletes a node from a given position, 'POS'. 2 | 3 | Note : 4 | Assume that the Indexing for the linked list always starts from 0. 5 | 6 | If the position is greater than or equal to the length of the linked list, you should return the same linked list without any change. 7 | Illustration : 8 | The following images depict how the deletion has been performed. 9 | Image-I : 10 | Alt txt 11 | 12 | Image-II : 13 | Alt txt 14 | 15 | Input format : 16 | The first line contains an Integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow. 17 | 18 | The first line of each test case or query contains the elements of the linked list separated by a single space. 19 | 20 | The second line of each test case contains the integer value of 'POS'. It denotes the position in the linked list from where the node has to be deleted. 21 | 22 | Remember/Consider : 23 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element 24 | 25 | Output format : 26 | For each test case/query, print the resulting linked list of integers in a row, separated by a single space. 27 | 28 | Output for every test case will be printed in a separate line. 29 | 30 | Note: 31 | You are not required to print the output, it has already been taken care of. Just implement the function. 32 | 33 | Constraints : 34 | 1 <= T <= 10^2 35 | 0 <= N <= 10^5 36 | POS >= 0 37 | 38 | Time Limit: 1sec 39 | 40 | Sample Input 1 : 41 | 1 42 | 3 4 5 2 6 1 9 -1 43 | 3 44 | 45 | Sample Output 1 : 46 | 3 4 5 6 1 9 47 | 48 | Sample Input 2 : 49 | 2 50 | 3 4 5 2 6 1 9 -1 51 | 0 52 | 10 20 30 40 50 60 -1 53 | 7 54 | 55 | Sample Output 2 : 56 | 4 5 2 6 1 9 57 | 10 20 30 40 50 60*/ 58 | 59 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 60 | 61 | #include 62 | 63 | class Node{ 64 | public: 65 | int data; 66 | Node *next; 67 | Node(int data) 68 | { 69 | this->data = data; 70 | this->next = NULL; 71 | } 72 | }; 73 | 74 | Node *takeinput() 75 | { 76 | int data; 77 | cin >> data; 78 | Node *head = NULL, *tail = NULL; 79 | while (data != -1) 80 | { 81 | Node *newNode = new Node(data); 82 | if (head == NULL) 83 | { 84 | head = newNode; 85 | tail = newNode; 86 | } 87 | else 88 | { 89 | tail->next = newNode; 90 | tail = newNode; 91 | } 92 | cin >> data; 93 | } 94 | return head; 95 | } 96 | 97 | Node *deleteNode(Node *head, int pos) 98 | { 99 | 100 | int i = 0; 101 | Node *current = head; 102 | if (head == NULL) 103 | return head; 104 | if (pos == 0) 105 | { 106 | head = current->next; 107 | delete current; 108 | return head; 109 | } 110 | while (i < pos - 1 && current->next != NULL) 111 | { 112 | current = current->next; 113 | i++; 114 | } 115 | if (current->next != NULL) 116 | { 117 | Node *temp = current->next->next; 118 | delete current->next; 119 | current->next = temp; 120 | } 121 | return head; 122 | } 123 | 124 | 125 | void print(Node *head) 126 | { 127 | Node *temp = head; 128 | while (temp != NULL) 129 | { 130 | cout << temp->data << " "; 131 | temp = temp->next; 132 | } 133 | cout << endl; 134 | } 135 | 136 | using namespace std; 137 | 138 | int main() 139 | { 140 | int t; 141 | cin >> t; 142 | 143 | while (t--) 144 | { 145 | Node *head = takeinput(); 146 | int pos; 147 | cin >> pos; 148 | head = deleteNode(head, pos); 149 | print(head); 150 | } 151 | 152 | return 0; 153 | } 154 | -------------------------------------------------------------------------------- /Binary Tree/Mirror.cpp: -------------------------------------------------------------------------------- 1 | /*For a given Binary Tree of type integer, update it with its corresponding mirror image. 2 | 3 | Input Format: 4 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 5 | 6 | Output Format: 7 | The only line of output prints the mirrored tree in a level-wise order. 8 | Each level will be printed on a new line. Elements printed at each level will be separated by a single line. 9 | 10 | Note: 11 | You are not required to print anything explicitly. It has already been taken care of. 12 | 13 | Constraints: 14 | 1 <= N <= 10^5 15 | Where N is the total number of nodes in the binary tree. 16 | 17 | Time Limit: 1 sec 18 | 19 | Sample Input 1: 20 | 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1 21 | 22 | Sample Output 1: 23 | 1 24 | 3 2 25 | 7 6 5 4 26 | 27 | Sample Input 2: 28 | 5 10 6 2 3 -1 -1 -1 -1 -1 9 -1 -1 29 | 30 | Sample Output 2: 31 | 5 32 | 6 10 33 | 3 2 34 | 9*/ 35 | 36 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 37 | 38 | #include 39 | #include 40 | 41 | template 42 | class BinaryTreeNode { 43 | public: 44 | T data; 45 | BinaryTreeNode *left; 46 | BinaryTreeNode *right; 47 | 48 | BinaryTreeNode(T data) { 49 | this->data = data; 50 | left = NULL; 51 | right = NULL; 52 | } 53 | }; 54 | 55 | using namespace std; 56 | 57 | BinaryTreeNode *takeInput() { 58 | int rootData; 59 | 60 | cin >> rootData; 61 | if (rootData == -1) { 62 | return NULL; 63 | } 64 | BinaryTreeNode *root = new BinaryTreeNode(rootData); 65 | queue *> q; 66 | q.push(root); 67 | while (!q.empty()) { 68 | BinaryTreeNode *currentNode = q.front(); 69 | q.pop(); 70 | int leftChild, rightChild; 71 | cin >> leftChild; 72 | if (leftChild != -1) { 73 | BinaryTreeNode *leftNode = new BinaryTreeNode(leftChild); 74 | currentNode->left = leftNode; 75 | q.push(leftNode); 76 | } 77 | 78 | cin >> rightChild; 79 | if (rightChild != -1) { 80 | BinaryTreeNode *rightNode = 81 | new BinaryTreeNode(rightChild); 82 | currentNode->right = rightNode; 83 | q.push(rightNode); 84 | } 85 | } 86 | return root; 87 | } 88 | 89 | void printLevelATNewLine(BinaryTreeNode *root) { 90 | queue *> q; 91 | q.push(root); 92 | q.push(NULL); 93 | while (!q.empty()) { 94 | BinaryTreeNode *first = q.front(); 95 | q.pop(); 96 | if (first == NULL) { 97 | if (q.empty()) { 98 | break; 99 | } 100 | cout << endl; 101 | q.push(NULL); 102 | continue; 103 | } 104 | cout << first->data << " "; 105 | if (first->left != NULL) { 106 | q.push(first->left); 107 | } 108 | if (first->right != NULL) { 109 | q.push(first->right); 110 | } 111 | } 112 | } 113 | 114 | void mirrorBinaryTree(BinaryTreeNode* root) { 115 | if(root == NULL){ 116 | return ; 117 | } 118 | 119 | BinaryTreeNode* child = root->left; 120 | root->left = root->right; 121 | root->right = child; 122 | mirrorBinaryTree(root->left); 123 | mirrorBinaryTree(root->right); 124 | } 125 | 126 | int main() { 127 | BinaryTreeNode *root = takeInput(); 128 | mirrorBinaryTree(root); 129 | printLevelATNewLine(root); 130 | } 131 | -------------------------------------------------------------------------------- /Binary Tree/Level order Transversal.cpp: -------------------------------------------------------------------------------- 1 | /*For a given a Binary Tree of type integer, print it in a level order fashion where each level will be printed on a new line. Elements on every level will be printed in a linear fashion and a single space will separate them. 2 | Example: 3 | alt txt 4 | 5 | For the above-depicted tree, when printed in a level order fashion, the output would look like: 6 | 7 | 10 8 | 20 30 9 | 40 50 60 10 | 11 | Where each new line denotes the level in the tree. 12 | 13 | Input Format: 14 | The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. 15 | 16 | Output Format: 17 | The given input tree will be printed in a level order fashion where each level will be printed on a new line. 18 | Elements on every level will be printed in a linear fashion. A single space will separate them. 19 | 20 | Constraints: 21 | 1 <= N <= 10^5 22 | Where N is the total number of nodes in the binary tree. 23 | 24 | Time Limit: 1 sec 25 | 26 | Sample Input 1: 27 | 10 20 30 40 50 -1 60 -1 -1 -1 -1 -1 -1 28 | 29 | Sample Output 1: 30 | 10 31 | 20 30 32 | 40 50 60 33 | 34 | Sample Input 2: 35 | 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 36 | 37 | Sample Output 2: 38 | 8 39 | 3 10 40 | 1 6 14 41 | 4 7 13 */ 42 | 43 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 44 | 45 | #include 46 | #include 47 | 48 | template 49 | class BinaryTreeNode { 50 | public: 51 | T data; 52 | BinaryTreeNode* left; 53 | BinaryTreeNode* right; 54 | 55 | BinaryTreeNode(T data) { 56 | this->data = data; 57 | left = NULL; 58 | right = NULL; 59 | } 60 | }; 61 | 62 | using namespace std; 63 | 64 | BinaryTreeNode* takeInput() { 65 | int rootData; 66 | 67 | cin >> rootData; 68 | if (rootData == -1) { 69 | return NULL; 70 | } 71 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 72 | queue*> q; 73 | q.push(root); 74 | while (!q.empty()) { 75 | BinaryTreeNode* currentNode = q.front(); 76 | q.pop(); 77 | int leftChild, rightChild; 78 | 79 | cin >> leftChild; 80 | if (leftChild != -1) { 81 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 82 | currentNode->left = leftNode; 83 | q.push(leftNode); 84 | } 85 | 86 | cin >> rightChild; 87 | if (rightChild != -1) { 88 | BinaryTreeNode* rightNode = 89 | new BinaryTreeNode(rightChild); 90 | currentNode->right = rightNode; 91 | q.push(rightNode); 92 | } 93 | } 94 | return root; 95 | } 96 | 97 | void printLevelWise(BinaryTreeNode *root) 98 | { 99 | if (root == NULL) 100 | return; 101 | queue *> pendingNodes; 102 | pendingNodes.push(root); 103 | while (pendingNodes.size() != 0) 104 | { 105 | int n = pendingNodes.size(); 106 | while (n != 0) 107 | { 108 | BinaryTreeNode *front = pendingNodes.front(); 109 | pendingNodes.pop(); 110 | cout << front->data << " "; 111 | if (front->left != NULL) 112 | pendingNodes.push(front->left); 113 | if (front->right != NULL) 114 | pendingNodes.push(front->right); 115 | n--; 116 | } 117 | cout << "\n"; 118 | } 119 | } 120 | 121 | int main() { 122 | BinaryTreeNode* root = takeInput(); 123 | printLevelWise(root); 124 | } 125 | -------------------------------------------------------------------------------- /Binary Tree/Remove leaf Node.cpp: -------------------------------------------------------------------------------- 1 | /*Given a binary tree, remove all leaf nodes from it. Leaf nodes are those nodes, which don't have any children. 2 | 3 | Note: 4 | 1. Root will also be a leaf node if it doesn't have left and right child. 5 | 2. You don't need to print the tree, just remove all leaf nodes and return the updated root. 6 | 7 | Input format: 8 | The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have a left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node. 9 | 10 | Output Format: 11 | The updated binary tree, after removing leaf nodes, is printed level wise. Each level is printed in new line. 12 | 13 | Constraints 14 | Time Limit: 1 second 15 | 16 | Sample Input 1: 17 | 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 18 | 19 | Sample Output 1: 20 | 8 21 | 3 10 22 | 6 14 */ 23 | 24 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 25 | 26 | #include 27 | #include 28 | 29 | template 30 | class BinaryTreeNode { 31 | public: 32 | T data; 33 | BinaryTreeNode* left; 34 | BinaryTreeNode* right; 35 | 36 | BinaryTreeNode(T data) { 37 | this->data = data; 38 | left = NULL; 39 | right = NULL; 40 | } 41 | }; 42 | 43 | using namespace std; 44 | 45 | BinaryTreeNode* takeInput() { 46 | int rootData; 47 | cin >> rootData; 48 | if (rootData == -1) { 49 | return NULL; 50 | } 51 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 52 | queue*> q; 53 | q.push(root); 54 | while (!q.empty()) { 55 | BinaryTreeNode* currentNode = q.front(); 56 | q.pop(); 57 | int leftChild, rightChild; 58 | 59 | cin >> leftChild; 60 | if (leftChild != -1) { 61 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 62 | currentNode->left = leftNode; 63 | q.push(leftNode); 64 | } 65 | 66 | cin >> rightChild; 67 | if (rightChild != -1) { 68 | BinaryTreeNode* rightNode = 69 | new BinaryTreeNode(rightChild); 70 | currentNode->right = rightNode; 71 | q.push(rightNode); 72 | } 73 | } 74 | return root; 75 | } 76 | 77 | void printLevelATNewLine(BinaryTreeNode* root) { 78 | queue*> q; 79 | q.push(root); 80 | q.push(NULL); 81 | while (!q.empty()) { 82 | BinaryTreeNode* first = q.front(); 83 | q.pop(); 84 | if (first == NULL) { 85 | if (q.empty()) { 86 | break; 87 | } 88 | cout << endl; 89 | q.push(NULL); 90 | continue; 91 | } 92 | cout << first->data << " "; 93 | if (first->left != NULL) { 94 | q.push(first->left); 95 | } 96 | if (first->right != NULL) { 97 | q.push(first->right); 98 | } 99 | } 100 | } 101 | 102 | BinaryTreeNode *removeLeafNodes(BinaryTreeNode *root) 103 | { 104 | if (root == NULL || (root->left == NULL && root->right == NULL)) 105 | return NULL; 106 | if (root->left != NULL) 107 | root->left = removeLeafNodes(root->left); 108 | if (root->right != NULL) 109 | root->right = removeLeafNodes(root->right); 110 | return root; 111 | } 112 | 113 | int main() { 114 | BinaryTreeNode* root = takeInput(); 115 | root = removeLeafNodes(root); 116 | printLevelATNewLine(root); 117 | } 118 | -------------------------------------------------------------------------------- /Binary Tree/Check Balanced.cpp: -------------------------------------------------------------------------------- 1 | /*Given a binary tree, check if it is balanced. Return true if given binary tree is balanced, false otherwise. 2 | 3 | Balanced Binary Tree: 4 | A empty binary tree or binary tree with zero nodes is always balanced. For a non empty binary tree to be balanced, following conditions must be met: 5 | 1. The left and right subtrees must be balanced. 6 | 2. |hL - hR| <= 1, where hL is the height or depth of left subtree and hR is the height or depth of right subtree. 7 | 8 | Input format: 9 | The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have a left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node. 10 | 11 | Output format 12 | The first and only line of output contains true or false. 13 | 14 | Constraints 15 | Time Limit: 1 second 16 | 17 | Sample Input 1 : 18 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 19 | 20 | Sample Output 1 : 21 | false 22 | 23 | Sample Input 2 : 24 | 1 2 3 -1 -1 -1 -1 25 | 26 | Sample Output 2 : 27 | true*/ 28 | 29 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 30 | 31 | #include 32 | #include 33 | 34 | template 35 | class BinaryTreeNode { 36 | public: 37 | T data; 38 | BinaryTreeNode* left; 39 | BinaryTreeNode* right; 40 | 41 | BinaryTreeNode(T data) { 42 | this->data = data; 43 | left = NULL; 44 | right = NULL; 45 | } 46 | }; 47 | 48 | using namespace std; 49 | 50 | BinaryTreeNode* takeInput() { 51 | int rootData; 52 | cin >> rootData; 53 | if (rootData == -1) { 54 | return NULL; 55 | } 56 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 57 | queue*> q; 58 | q.push(root); 59 | while (!q.empty()) { 60 | BinaryTreeNode* currentNode = q.front(); 61 | q.pop(); 62 | int leftChild, rightChild; 63 | 64 | cin >> leftChild; 65 | if (leftChild != -1) { 66 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 67 | currentNode->left = leftNode; 68 | q.push(leftNode); 69 | } 70 | 71 | cin >> rightChild; 72 | if (rightChild != -1) { 73 | BinaryTreeNode* rightNode = 74 | new BinaryTreeNode(rightChild); 75 | currentNode->right = rightNode; 76 | q.push(rightNode); 77 | } 78 | } 79 | return root; 80 | } 81 | 82 | void heightMax(BinaryTreeNode *root, int height, int *max) 83 | { 84 | if (root == NULL) 85 | return; 86 | if ((*max) < height) 87 | *max = height; 88 | if (root->left != NULL) 89 | heightMax(root->left, 1 + height, max); 90 | if (root->right != NULL) 91 | heightMax(root->right, 1 + height, max); 92 | } 93 | int height(BinaryTreeNode *root) 94 | { 95 | // Write our code here 96 | if (root == NULL) 97 | return 0; 98 | int height = 1, max = 1; 99 | heightMax(root, height, &max); 100 | return max; 101 | } 102 | bool isBalanced(BinaryTreeNode *root) 103 | { 104 | if (root == NULL) 105 | return true; 106 | bool val1 = isBalanced(root->left); 107 | bool val2 = isBalanced(root->right); 108 | if (val1 && val2) 109 | { 110 | if (abs(height(root->left) - height(root->right)) <= 1) 111 | return true; 112 | else 113 | return false; 114 | } 115 | else 116 | return false; 117 | } 118 | 119 | int main() { 120 | BinaryTreeNode* root = takeInput(); 121 | cout << (isBalanced(root) ? "true" : "false"); 122 | } 123 | -------------------------------------------------------------------------------- /Linked List 1/Append last to first.cpp: -------------------------------------------------------------------------------- 1 | /**You have been given a singly linked list of integers along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list. 2 | 3 | Input format : 4 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 5 | The first line of each test case or query contains the elements of the singly linked list separated by a single space. 6 | The second line contains the integer value 'N'. It denotes the number of nodes to be moved from last to the front of the singly linked list. 7 | 8 | Remember/Consider : 9 | While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. 10 | 11 | Output format : 12 | For each test case/query, print the resulting singly linked list of integers in a row, separated by a single space. 13 | 14 | Output for every test case will be printed in a seperate line. 15 | Constraints : 16 | 1 <= t <= 10^2 17 | 0 <= M <= 10^5 18 | 0 <= N < M 19 | Time Limit: 1sec 20 | 21 | Where 'M' is the size of the singly linked list. 22 | 23 | Sample Input 1 : 24 | 2 25 | 1 2 3 4 5 -1 26 | 3 27 | 10 20 30 40 50 60 -1 28 | 5 29 | 30 | Sample Output 1 : 31 | 3 4 5 1 2 32 | 20 30 40 50 60 10 33 | 34 | Sample Input 2 : 35 | 1 36 | 10 6 77 90 61 67 100 -1 37 | 4 38 | 39 | Sample Output 2 : 40 | 90 61 67 100 10 6 77 41 | Explanation to Sample Input 2 : 42 | We have been required to move the last 4 nodes to the front of the list. Here, "90->61->67->100" is the list which represents the last 4 nodes. When we move this list to the front then the remaining part of the initial list which is, "10->6->77" is attached after 100. Hence, the new list formed with an updated head pointing to 90*/ 43 | 44 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 45 | 46 | #include 47 | 48 | class Node 49 | { 50 | public: 51 | int data; 52 | Node *next; 53 | Node(int data) 54 | { 55 | this->data = data; 56 | this->next = NULL; 57 | } 58 | }; 59 | 60 | using namespace std; 61 | 62 | Node *takeinput() 63 | { 64 | int data; 65 | cin >> data; 66 | Node *head = NULL, *tail = NULL; 67 | while (data != -1) 68 | { 69 | Node *newnode = new Node(data); 70 | if (head == NULL) 71 | { 72 | head = newnode; 73 | tail = newnode; 74 | } 75 | else 76 | { 77 | tail->next = newnode; 78 | tail = newnode; 79 | } 80 | cin >> data; 81 | } 82 | return head; 83 | } 84 | 85 | int length(Node *head) 86 | { 87 | if (head == NULL) 88 | return 0; 89 | else 90 | return 1 + length(head->next); 91 | } 92 | Node *appendLastNToFirst(Node *head, int n) 93 | { 94 | 95 | int len = length(head); 96 | if (n < len && n != 0) 97 | { 98 | int skip = len - n; 99 | Node *current = head; 100 | Node *prev = NULL; 101 | while (skip) 102 | { 103 | prev = current; 104 | current = current->next; 105 | skip--; 106 | } 107 | prev->next = NULL; 108 | Node *temp = current; 109 | while (current->next != NULL) 110 | { 111 | current = current->next; 112 | } 113 | current->next = head; 114 | head = temp; 115 | } 116 | return head; 117 | } 118 | 119 | void print(Node *head) 120 | { 121 | Node *temp = head; 122 | while (temp != NULL) 123 | { 124 | cout << temp->data << " "; 125 | temp = temp->next; 126 | } 127 | cout << endl; 128 | } 129 | 130 | int main() 131 | { 132 | int t; 133 | cin >> t; 134 | while (t--) 135 | { 136 | Node *head = takeinput(); 137 | int n; 138 | cin >> n; 139 | head = appendLastNToFirst(head, n); 140 | print(head); 141 | } 142 | return 0; 143 | } 144 | --------------------------------------------------------------------------------