├── Assignment Recursion 1 ├── Pair star ├── Remove X ├── Replace pi ├── String to Integer └── Tower of Hanoi ├── Bubble Sort (Iterative) LinkedList ├── Code : Balanced Parenthesis ├── LECTURE 2:OOPS 2 ├── Car.java ├── Fraction.java ├── FractionUse.java ├── Truck.java ├── Vehicle.java ├── VehicleUse.java └── ZeroDenominatorException.java ├── Lecture 10 : Trees ├── Check if generic tree contain element x ├── Code : Count leaf nodes ├── Code : Print Level Wise ├── Code : Sum of nodes ├── Depth of a node K ├── Find Height ├── Find number of nodes ├── Largest node (Recursive) ├── Next larger element.java ├── Node having sum of children and node is max.java ├── Number of Nodes greater than x ├── Post-order Traversal ├── Replace node with depth.java ├── Second Largest Element In Tree.java ├── checkIdentical.java ├── preOrder.java └── takeInputLevelWise() ├── Lecture 11: Binary Trees ├── BinaryTreeNode ├── BinaryTreeUse ├── Code: Construct Tree from Preorder and Inorder ├── Construct Tree from Postorder and Inorder ├── Find Node ├── Height Of Binary Tree ├── Level order traversal ├── Level wise linkedlist ├── Mirror a Binary Tree ├── Nodes without sibling ├── Postorder Binary Tree ├── Preorder Binary Tree ├── Remove Leaf nodes ├── Sum of all nodes ├── ZigZag tree └── is Balanced ├── Lecture 12: Binary Search Trees ├── Check if a Binary Tree is BST ├── Code: Search Node in BST └── Print Elements in Range ├── Lecture 1:OOPS 1 ├── Complex number class ├── Fraction.java ├── FractionUse.java └── Polynomial class ├── Lecture 3: Recursion 1 ├── All Indices of Number ├── Calculate Power ├── Check Number in Array ├── Check Palindrome ├── Count Zeros ├── First Index of Number ├── Geometric Sum ├── Last Index of Number ├── Multiplication (Recursive) ├── Number of Digits ├── Print Numbers ├── Sum of Array └── Sum of digits ├── Lecture 4: Recursion 2 ├── Binary Search (Recursive) ├── Check AB ├── Merge Sort Code ├── Print Keypad Combinations Code ├── Print Permutations - String ├── Print Subsequences ├── Print Subset Sum to K ├── Print Subsets of Array ├── Print all Codes - String ├── Quick Sort Code ├── Remove Duplicates Recursively ├── Replace Character Recursively ├── Return Keypad Code ├── Return Permutations - String ├── Return all codes - String ├── Return subset of an array ├── Return subsets sum to K ├── Staircase └── findSubsequences ├── Lecture 5: Time and Space Complexity Analysis ├── Check array rotation ├── Duplicate in array ├── Find the Unique Element ├── Pair sum in array ├── Print Array intersection ├── Rotate array └── Triplet sum ├── Lecture 7: Linked List 1 ├── AppendLastNToFirst ├── Delete Node in LL ├── Eliminate duplicates from LL ├── Find a node in LL ├── Length of LL ├── Palindrome LinkedList ├── Print ith Node └── Print reverse LinkedList ├── Lecture 8 : Linked List 2 ├── Bubble Sort (Iterative) LinkedList ├── Code : Merge Sort ├── Code: Midpoint of the linked list ├── Delete every N nodes ├── Delete node (recursive) ├── Even after Odd LinkedList ├── Find a node in LL (recursive) ├── Merge two sorted LL ├── Reverse LL (Iterative) ├── Reverse LL (Recursive) ├── Swap two Node of LL ├── kReverse └── reverseLLBetter ├── Lecture 9 : Stacks and Queues ├── Check redundant brackets ├── Code : Queue Using LL ├── Code : Stack Using LL ├── Minimum bracket Reversal ├── QueueEmptyException.java ├── QueueFullException.java ├── QueueUse.java ├── QueueUsingArray.java ├── Reverse Queue ├── Reverse Stack ├── StackEmptyException.java ├── StackFullException.java ├── StackUse.java ├── StackUsingArray.java └── Stock Span ├── README.md ├── Test 1 ├── Complexity of a Recurrence Relation ├── Complexity of different operations in a sorted array. ├── Does s contain t ? ├── Maximum Profit on App ├── Recurrence Relation for Tower of Hanoi Problem └── Split Array └── Test 2 ├── Delete alternate nodes ├── Dequeue └── Next Number /Assignment Recursion 1/Pair star: -------------------------------------------------------------------------------- 1 | // Pair star 2 | // Send Feedback 3 | // Given a string, compute recursively a new string where 4 | // identical chars that are adjacent in the original string 5 | // are separated from each other by a "*". 6 | // Sample Input 1 : 7 | // hello 8 | // Sample Output 1: 9 | // hel*lo 10 | // Sample Input 2 : 11 | // xxyy 12 | // Sample Output 2: 13 | // x*xy*y 14 | // Sample Input 3 : 15 | // aaaa 16 | // Sample Output 3: 17 | // a*a*a*a 18 | 19 | 20 | 21 | public class solution { 22 | 23 | // Return the updated string 24 | public static String addStars(String s) { 25 | // Write your code here 26 | 27 | 28 | if (s.length() == 1) { 29 | return s; 30 | } 31 | 32 | 33 | if (s.charAt(0) == s.charAt(1) ) { 34 | return s.charAt(0) +"*"+ addStars(s.substring(1, s.length())); 35 | } 36 | 37 | 38 | 39 | return s.charAt(0) + addStars(s.substring(1, s.length())); 40 | 41 | 42 | 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Assignment Recursion 1/Remove X: -------------------------------------------------------------------------------- 1 | // Remove X 2 | // Send Feedback 3 | // Given a string, compute recursively a new string where all 'x' chars have been removed. 4 | // Sample Input 1 : 5 | // xaxb 6 | // Sample Output 1: 7 | // ab 8 | // Sample Input 2 : 9 | // abc 10 | // Sample Output 2: 11 | // abc 12 | // Sample Input 3 : 13 | // xx 14 | // Sample Output 3: 15 | 16 | 17 | 18 | public class solution { 19 | 20 | // Return the changed string 21 | public static String removeX(String input){ 22 | // Write your code here 23 | 24 | 25 | if (input.length() == 0) { 26 | return input; 27 | } 28 | 29 | 30 | if (input.charAt(0) == 'x' ) { 31 | return removeX(input.substring(1, input.length())); 32 | } 33 | 34 | 35 | 36 | return input.charAt(0) + removeX(input.substring(1, input.length())); 37 | 38 | 39 | 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assignment Recursion 1/Replace pi: -------------------------------------------------------------------------------- 1 | // Replace pi (recursive) 2 | // Send Feedback 3 | // Given a string, compute recursively a new string where all 4 | // appearances of "pi" have been replaced by "3.14". 5 | // Sample Input 1 : 6 | // xpix 7 | // Sample Output : 8 | // x3.14x 9 | // Sample Input 2 : 10 | // pipi 11 | // Sample Output : 12 | // 3.143.14 13 | // Sample Input 3 : 14 | // pip 15 | // Sample Output : 16 | // 3.14p 17 | 18 | public class solution { 19 | 20 | // Return the changed string 21 | public static String replace(String input){ 22 | 23 | 24 | 25 | // base condition 26 | // if the string is empty 27 | // or of length one 28 | if (input.length() <= 1) { 29 | return input; 30 | } 31 | 32 | // if the first character is 'p' 33 | // and the first character of the part 34 | // passed to recursion is 'i' then replace 35 | //"pi" with "3.14" 36 | if (input.charAt(0) == 'p' && input.length() >=2 && input.charAt(1) == 'i') { 37 | return "3.14" + replace(input.substring(2, input.length())); 38 | } 39 | 40 | // if the first character is not 'p' 41 | // then just put that character in 42 | // front of the answer which came 43 | // from recursion 44 | return input.charAt(0) + replace(input.substring(1, input.length())); 45 | 46 | 47 | 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Assignment Recursion 1/String to Integer: -------------------------------------------------------------------------------- 1 | // String to Integer 2 | // Send Feedback 3 | // Write a recursive function to convert a given string into the 4 | // number it represents. That is input will be a numeric string 5 | // that contains only numbers, you need to convert the string into 6 | // corresponding integer and return the answer. 7 | // Input format : 8 | // Numeric string (string, Eg. "1234") 9 | // Output format : 10 | // Corresponding integer (int, Eg. 1234) 11 | // Sample Input 1 : 12 | // 1231 13 | // Sample Output 1: 14 | // 1231 15 | // Sample Input 2 : 16 | // 12567 17 | // Sample Output 2 : 18 | // 12567 19 | 20 | 21 | 22 | public class solution { 23 | 24 | public static int convertStringToInt(String input){ 25 | // Write your code here 26 | if(input.length()==0) 27 | return 0; 28 | 29 | int m=(int)input.charAt(0)-48; 30 | int n=input.length(); 31 | 32 | while(n!=1) 33 | { 34 | m*=10; 35 | n--; 36 | } 37 | 38 | return m+convertStringToInt(input.substring(1,input.length())); 39 | 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Assignment Recursion 1/Tower of Hanoi: -------------------------------------------------------------------------------- 1 | // Tower of Hanoi 2 | // Send Feedback 3 | // Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. 4 | // The objective of the puzzle is to move all disks from source rod to destination rod 5 | // using third rod (say auxiliary). The rules are : 6 | // 1) Only one disk can be moved at a time. 7 | // 2) A disk can be moved only if it is on the top of a rod. 8 | // 3) No disk can be placed on the top of a smaller disk. 9 | // Print the steps required to move n disks from source rod to destination rod. 10 | // Source Rod is named as 'a', auxiliary rod as 'b' and destination rod as 'c'. 11 | // Input Format : 12 | // Integer n 13 | // Output Format : 14 | // Steps in different lines (in one line print source and destination rod name separated by space) 15 | // Sample Input : 16 | // 2 17 | // Sample Output : 18 | // a b 19 | // a c 20 | // b c 21 | 22 | 23 | 24 | public class solution { 25 | 26 | public static void towerOfHanoi(int disks, char source, char auxiliary, char destination) 27 | { 28 | // Write your code here 29 | if(disks==0) 30 | return; 31 | 32 | 33 | if (disks == 1) 34 | { 35 | System.out.println(source + " " + destination); 36 | return; 37 | } 38 | towerOfHanoi(disks-1, source, destination, auxiliary); 39 | System.out.println(source + " " + destination); 40 | towerOfHanoi(disks-1, auxiliary, source, destination); 41 | 42 | 43 | 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Bubble Sort (Iterative) LinkedList: -------------------------------------------------------------------------------- 1 | // Bubble Sort (Iterative) LinkedList 2 | // Send Feedback 3 | // Sort a given linked list using Bubble Sort (iteratively). While sorting, you need to swap just the data. 4 | // You don't need to print the elements, just sort the elements and return the head of updated LL. 5 | // Input format : Linked list elements (separated by space and terminated by -1)` 6 | 7 | // Sample Input 1 : 8 | // 1 4 5 2 -1 9 | // Sample Output 1 : 10 | // 1 2 4 5 11 | 12 | 13 | public class Solution { 14 | 15 | 16 | 17 | public static LinkedListNode bubbleSort(LinkedListNode head ) 18 | { 19 | //Write your code here 20 | 21 | 22 | LinkedListNode current = head, index = null; 23 | int temp; 24 | 25 | if(head == null) { 26 | return head; 27 | } 28 | else 29 | { 30 | while(current != null) 31 | { 32 | //Node index will point to node next to current 33 | index = current.next; 34 | 35 | while(index != null) 36 | { 37 | //If current node's data is greater than index's node data, swap the data between them 38 | if(current.data > index.data) 39 | { 40 | temp = current.data; 41 | current.data = index.data; 42 | index.data = temp; 43 | } 44 | index = index.next; 45 | } 46 | current = current.next; 47 | } 48 | 49 | } return head; 50 | 51 | } 52 | 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Code : Balanced Parenthesis: -------------------------------------------------------------------------------- 1 | // Code : Balanced Parenthesis 2 | // Send Feedback 3 | // Given a string expression, check if brackets present in the expression are balanced or not. Brackets are balanced if the bracket which opens last, closes first. 4 | // You need to return true if it is balanced, false otherwise. 5 | // Note: This problem was asked in initial rounds in Facebook 6 | // Sample Input 1 : 7 | // { a + [ b+ (c + d)] + (e + f) } 8 | // Sample Output 1 : 9 | // true 10 | // Sample Input 2 : 11 | // { a + [ b - c } ] 12 | // Sample Output 2 : 13 | // false 14 | 15 | import java.util.*; 16 | public class Solution { 17 | 18 | public static boolean matchingPeer(char open , char close){ 19 | if ( open == '(' && close == ')'){ 20 | return true; 21 | } 22 | if ( open == '[' && close == ']'){ 23 | return true; 24 | } 25 | if ( open == '{' && close == '}'){ 26 | return true; 27 | } 28 | // you can add more open and close rule 29 | 30 | else{ 31 | return false; 32 | } 33 | } 34 | 35 | public static boolean checkBalanced(String equation) 36 | { 37 | // Write your code here 38 | char[] c = equation.toCharArray(); 39 | Stack myStack= new Stack (); 40 | 41 | for (int i = 0; i < c.length; i++) 42 | { 43 | if(c[i]=='(' || c[i] == '[' || c[i] == '{'){ 44 | myStack.push(c[i]); 45 | continue; 46 | } 47 | else if (c[i]== ')' || c[i]==']' || c[i] == '}'){ 48 | if(myStack.isEmpty()) 49 | return false; 50 | if(matchingPeer(myStack.peek(),c[i]) == true){ 51 | myStack.pop(); 52 | 53 | } else { 54 | return false; 55 | } 56 | } 57 | } 58 | if(myStack.isEmpty()){ 59 | return true; 60 | } 61 | else { 62 | return false; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/Car.java: -------------------------------------------------------------------------------- 1 | package vehicle; 2 | 3 | public class Car extends Vehicle { 4 | int numGears; 5 | boolean isConvertible; 6 | 7 | public void print() { 8 | super.print(); 9 | System.out.println("Car numGears : " + numGears); 10 | System.out.println("Car isConvertible : " + isConvertible); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/Fraction.java: -------------------------------------------------------------------------------- 1 | package Exceptions; 2 | 3 | public class Fraction { 4 | private int numerator; 5 | private int denominator; 6 | 7 | public Fraction(int numerator, int denominator) { 8 | this.numerator = numerator; 9 | if (denominator == 0) { 10 | // TODO error out 11 | } 12 | this.denominator = denominator; 13 | simplify(); 14 | } 15 | 16 | 17 | public int getDenominator() { 18 | return denominator; 19 | } 20 | 21 | public int getNumerator() { 22 | return numerator; 23 | } 24 | 25 | public void setNumerator(int n) { 26 | this.numerator = n; 27 | simplify(); 28 | } 29 | 30 | 31 | public void setDenominator(int d) throws ZeroDenominatorException { 32 | if (d == 0){ 33 | ZeroDenominatorException e = new ZeroDenominatorException(); 34 | throw e; 35 | } 36 | this.denominator = d; 37 | this.simplify(); 38 | } 39 | 40 | public void print() { 41 | if (denominator == 1) { 42 | System.out.println(numerator); 43 | } else { 44 | System.out.println(numerator + "/" + denominator); 45 | } 46 | } 47 | 48 | private void simplify() { 49 | int gcd = 1; 50 | int smaller = Math.min(numerator, denominator); 51 | for (int i = 2; i <= smaller; i++) { 52 | if (numerator % i == 0 && denominator % i == 0) { 53 | gcd = i; 54 | } 55 | } 56 | numerator = numerator/gcd; 57 | denominator = denominator/gcd; 58 | } 59 | 60 | public static Fraction add(Fraction f1, Fraction f2) { 61 | int newNum = f1.numerator * f2.denominator + f2.numerator * f1.denominator; 62 | int newDen = f1.denominator * f2.denominator; 63 | Fraction f = new Fraction(newNum, newDen); 64 | return f; 65 | } 66 | 67 | public void add(Fraction f2) { 68 | this.numerator = this.numerator * f2.denominator + this.denominator*f2.numerator; 69 | this.denominator = this.denominator * f2.denominator; 70 | simplify(); 71 | } 72 | 73 | public void multiply(Fraction f2) { 74 | this.numerator = this.numerator * f2.numerator; 75 | this.denominator = this.denominator * f2.denominator; 76 | simplify(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/FractionUse.java: -------------------------------------------------------------------------------- 1 | package Exceptions; 2 | 3 | public class FractionUse { 4 | 5 | public static void temp() { 6 | Fraction f1 = new Fraction(20,30); 7 | f1.print(); 8 | // 2/3 9 | 10 | f1.setNumerator(12); 11 | // 4/1 12 | int d = f1.getDenominator(); 13 | System.out.println(d); 14 | f1.print(); 15 | // 16 | f1.setNumerator(10); 17 | int i = 47; 18 | try { 19 | i++; 20 | f1.setDenominator(0); 21 | i++; 22 | 23 | } catch(ZeroDenominatorException e) { 24 | System.out.println("Hey dont input 0 as denominator"); 25 | } finally { 26 | 27 | } 28 | 29 | 30 | System.out.println(i); 31 | 32 | 33 | // 1/3 34 | f1.print(); 35 | // 36 | Fraction f2 = new Fraction(3,4); 37 | f1.add(f2); 38 | f1.print(); 39 | // f1 => 13/12 40 | f2.print(); 41 | // f2 => 3/4 42 | // 43 | Fraction f3 = new Fraction(4,5); 44 | f3.multiply(f2); 45 | f3.print(); 46 | // f3 => 3/5 47 | f2.print(); 48 | // f2 => 3/4 49 | // 50 | Fraction f4 = Fraction.add(f1, f3); 51 | f1.print(); 52 | f3.print(); 53 | f4.print(); 54 | } 55 | 56 | public static void main(String[] args) throws ZeroDenominatorException{ 57 | temp(); 58 | // String s = ""; 59 | // File f; 60 | // try { 61 | // f = new File(s); 62 | // // read file 63 | // } catch (FileNotFoundException exception) { 64 | // 65 | // } finally { 66 | // f.close(); 67 | // } 68 | 69 | 70 | 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/Truck.java: -------------------------------------------------------------------------------- 1 | package vehicle_temp; 2 | 3 | import vehicle.Vehicle; 4 | 5 | public class Truck extends Vehicle { 6 | int maxLoadingCapacity; 7 | public void print() { 8 | System.out.println("Truck Capacity : " + maxLoadingCapacity); 9 | System.out.println("Truck color : " + color); 10 | System.out.println("Truck Speed : " + getMaxSpeed()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/Vehicle.java: -------------------------------------------------------------------------------- 1 | package vehicle; 2 | 3 | public class Vehicle { 4 | protected String color; 5 | private int maxSpeed; 6 | 7 | public int getMaxSpeed() { 8 | return maxSpeed; 9 | } 10 | 11 | public void setMaxSpeed(int maxSpeed) { 12 | this.maxSpeed = maxSpeed; 13 | } 14 | 15 | public void print() { 16 | System.out.println("Vehicle color : " + color); 17 | System.out.println("Vehicle Speed : " + maxSpeed); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/VehicleUse.java: -------------------------------------------------------------------------------- 1 | package vehicle; 2 | 3 | public class VehicleUse { 4 | 5 | public static void main(String[] args) { 6 | Vehicle v = new Vehicle(); 7 | v.color = "Black"; 8 | v.setMaxSpeed(10); 9 | v.print(); 10 | 11 | Car c = new Car(); 12 | c.numGears = 10; 13 | c.color = "Black"; 14 | c.setMaxSpeed(100); 15 | c.print(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LECTURE 2:OOPS 2/ZeroDenominatorException.java: -------------------------------------------------------------------------------- 1 | package Exceptions; 2 | 3 | public class ZeroDenominatorException extends Exception { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Check if generic tree contain element x: -------------------------------------------------------------------------------- 1 | // Check if generic tree contain element x 2 | // Send Feedback 3 | // 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. 4 | // Input format : 5 | 6 | // Line 1 : Integer x 7 | 8 | // Line 2 : Elements in level order form separated by space (as per done in class). Order is - 9 | 10 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 11 | 12 | // Output format : true or false 13 | 14 | // Sample Input 1 : 15 | // 40 16 | // 10 3 20 30 40 2 40 50 0 0 0 0 17 | // Sample Output 1 : 18 | // true 19 | // Sample Input 2 : 20 | // 4 21 | // 10 3 20 30 40 2 40 50 0 0 0 0 22 | // Sample Output 2: 23 | // false 24 | 25 | import java.util.*; 26 | public class Solution { 27 | 28 | /* TreeNode class 29 | * 30 | * class TreeNode { 31 | T data; 32 | ArrayList> children; 33 | 34 | TreeNode(T data){ 35 | this.data = data; 36 | children = new ArrayList>(); 37 | } 38 | }*/ 39 | 40 | public static boolean checkIfContainsX(TreeNode root, int x){ 41 | 42 | // Write your code here 43 | 44 | if(root==null) 45 | return false; 46 | // Write your code here 47 | Queue> queue = new LinkedList<>(); 48 | //added 1st level here 49 | queue.add(root); 50 | queue.add(null); 51 | int ans=0; 52 | 53 | // if(x frontNode = queue.remove(); 59 | if(frontNode == null) 60 | { 61 | if(queue.isEmpty()){ 62 | break; 63 | } 64 | 65 | queue.add(null); 66 | } 67 | else{ 68 | if(frontNode.data==x) 69 | return true; 70 | //System.out.print(frontNode.data+" "); 71 | for(int i=0;i { 21 | T data; 22 | ArrayList> children; 23 | 24 | TreeNode(T data){ 25 | this.data = data; 26 | children = new ArrayList>(); 27 | } 28 | }*/ 29 | 30 | public static int countLeafNodes(TreeNode root){ 31 | 32 | // Write your code here 33 | int leaf = 0; 34 | 35 | if (root == null ) 36 | { 37 | return 0; 38 | } 39 | 40 | 41 | if (root.children.size() == 0) 42 | { 43 | return 1; 44 | } 45 | 46 | 47 | 48 | for (TreeNode child : root.children) 49 | { 50 | leaf += countLeafNodes(child); 51 | } 52 | 53 | return leaf ; 54 | 55 | 56 | 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Code : Print Level Wise: -------------------------------------------------------------------------------- 1 | // Code : Print Level Wise 2 | // Send Feedback 3 | // Given a generic tree, print the input tree in level wise order. That is, print the elements at same level in one line (separated by space). Print different levels in differnet lines. 4 | // Input format : 5 | // Elements in level order form separated by space (as per done in class). Order is - 6 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 7 | // Output Format : 8 | // Level wise print 9 | // Sample Input : 10 | // 10 3 20 30 40 2 40 50 0 0 0 0 11 | // Sample Output : 12 | // 10 13 | // 20 30 40 14 | // 40 50 15 | 16 | 17 | 18 | 19 | 20 | import java.util.Queue; 21 | import java.util.LinkedList; 22 | 23 | public class Solution { 24 | 25 | /* TreeNode structure 26 | * 27 | * class TreeNode { 28 | T data; 29 | ArrayList> children; 30 | 31 | TreeNode(T data){ 32 | this.data = data; 33 | children = new ArrayList>(); 34 | } 35 | }*/ 36 | 37 | 38 | 39 | public static void printLevelWise(TreeNode root){ 40 | Queue> queue = new LinkedList<>(); 41 | //added 1st level here 42 | queue.add(root); 43 | queue.add(null); 44 | 45 | while(!queue.isEmpty()) 46 | { 47 | TreeNode frontNode = queue.remove(); 48 | if(frontNode == null){ 49 | if(queue.isEmpty()){ 50 | break; 51 | } 52 | System.out.println(); 53 | queue.add(null); 54 | }else{ 55 | System.out.print(frontNode.data+" "); 56 | for(int i=0;i { 20 | T data; 21 | ArrayList> children; 22 | 23 | TreeNode(T data){ 24 | this.data = data; 25 | children = new ArrayList>(); 26 | } 27 | }*/ 28 | 29 | static int sum=0; 30 | 31 | public static int sumOfAllNode(TreeNode root){ 32 | 33 | Queue> queue = new LinkedList<>(); 34 | queue.add(root); 35 | queue.add(null); 36 | 37 | while(!queue.isEmpty()) 38 | { 39 | TreeNode frontNode = queue.remove(); 40 | if(frontNode == null){ 41 | if(queue.isEmpty()){ 42 | break; 43 | } 44 | 45 | queue.add(null); 46 | } 47 | else{ 48 | sum+=frontNode.data; 49 | for(int i=0;i root, int k) { 2 | if (k < 0) { 3 | return; 4 | } 5 | if (k == 0) { 6 | System.out.println(root.data); 7 | return; 8 | } 9 | for (TreeNode child : root.children) { 10 | printAtK(root.children.get(i), k - 1); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Find Height: -------------------------------------------------------------------------------- 1 | // Code : Find Height 2 | // Send Feedback 3 | // Given a generic tree, find and return the height of given tree. 4 | // Input format : 5 | // Elements in level order form separated by space (as per done in class). Order is - 6 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 7 | // Output Format : 8 | // Height 9 | // Sample Input : 10 | // 10 3 20 30 40 2 40 50 0 0 0 0 11 | // Sample Output : 12 | // 3 13 | 14 | 15 | 16 | import java.util.*; 17 | public class Solution { 18 | 19 | /* TreeNode structure 20 | * 21 | * class TreeNode { 22 | T data; 23 | ArrayList> children; 24 | 25 | TreeNode(T data){ 26 | this.data = data; 27 | children = new ArrayList>(); 28 | } 29 | }*/ 30 | 31 | public static int height(TreeNode root){ 32 | /* Your class should be named Solution 33 | * Don't write main(). 34 | * Don't read input, it is passed as function argument. 35 | * Return output and don't print it. 36 | * Taking input and printing output is handled automatically. 37 | */ 38 | int height = 0; 39 | if (root == null ) 40 | { 41 | return height; 42 | } 43 | 44 | if (root.children == null) 45 | { 46 | return 1; 47 | } 48 | 49 | for (TreeNode child : root.children) 50 | { 51 | height = Math.max(height, height(child)); 52 | } 53 | return height + 1; 54 | 55 | 56 | 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Find number of nodes: -------------------------------------------------------------------------------- 1 | public static int numNodes(TreeNode root) { 2 | if (root == null) { 3 | return 0; 4 | } 5 | int count = 1; 6 | for (int i = 0; i < root.children.size(); i++) { 7 | count += numNodes(root.children.get(i)); 8 | } 9 | return count; 10 | } 11 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Largest node (Recursive): -------------------------------------------------------------------------------- 1 | public static int largest(TreeNode root) { 2 | if (root == null) { 3 | return Integer.MIN_VALUE; 4 | } 5 | 6 | int ans = root.data; 7 | for (int i = 0; i < root.children.size(); i++) { 8 | int childLargest = largest(root.children.get(i)); 9 | if (childLargest > ans) { 10 | ans = childLargest; 11 | } 12 | } 13 | return ans; 14 | } 15 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Next larger element.java: -------------------------------------------------------------------------------- 1 | // Next larger element 2 | // Send Feedback 3 | // 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. 4 | // Return NULL if no node is present with value greater than n. 5 | // Input format : 6 | 7 | // Line 1 : Integer n 8 | 9 | // Line 2 : Elements in level order form separated by space (as per done in class). Order is - 10 | 11 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 12 | 13 | // Output format : Node with value just greater than n. 14 | 15 | // Sample Input 1 : 16 | // 18 17 | // 10 3 20 30 40 2 40 50 0 0 0 0 18 | // Sample Output 1 : 19 | // 20 20 | // Sample Input 2 : 21 | // 21 22 | // 10 3 20 30 40 2 40 50 0 0 0 0 23 | // Sample Output 2: 24 | // 30 25 | 26 | import java.util.Queue; 27 | import java.util.LinkedList; 28 | public class Solution { 29 | 30 | /* TreeNode structure 31 | * 32 | * class TreeNode { 33 | T data; 34 | ArrayList> children; 35 | 36 | TreeNode(T data){ 37 | this.data = data; 38 | children = new ArrayList>(); 39 | } 40 | }*/ 41 | static TreeNode res =null; 42 | static void nextLargerElementUtil(TreeNode root, int x) 43 | { 44 | if (root == null) 45 | { 46 | return; 47 | } 48 | 49 | // if root is less than res but 50 | // greater than x, update res 51 | if (root.data > x) 52 | { 53 | if (res==null || root.data findNextLargerNode(TreeNode root, int n){ 73 | 74 | // resultant node 75 | //TreeNode res = new TreeNode<>(Integer.MIN_VALUE); 76 | // calling helper function 77 | nextLargerElementUtil(root,n); 78 | //System.out.println(res); 79 | 80 | return res; 81 | 82 | 83 | 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Node having sum of children and node is max.java: -------------------------------------------------------------------------------- 1 | // Node having sum of children and node is max 2 | // Send Feedback 3 | // Given a tree, find and return the node for which sum of data of all children and the node itself is maximum. In the sum, data of node itself and data of immediate children is to be taken. 4 | // Input format : 5 | 6 | // Line 1 : Elements in level order form separated by space (as per done in class). Order is - 7 | 8 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 9 | 10 | // Output format : Node with maximum sum. 11 | 12 | // Sample Input 1 : 13 | // 5 3 1 2 3 1 15 2 4 5 1 6 0 0 0 0 14 | // Sample Output 1 : 15 | // 1 16 | 17 | 18 | 19 | public class Solution { 20 | 21 | /* TreeNode structure 22 | * 23 | * class TreeNode { 24 | T data; 25 | ArrayList> children; 26 | 27 | TreeNode(T data){ 28 | this.data = data; 29 | children = new ArrayList>(); 30 | } 31 | }*/ 32 | 33 | 34 | public static TreeNode maxSumNode(TreeNode root){ 35 | // Write your code here 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Number of Nodes greater than x: -------------------------------------------------------------------------------- 1 | // Number of Nodes greater than x 2 | // Send Feedback 3 | // Given a tree and an integer x, find and return number of Nodes which are greater than x. 4 | // Input format : 5 | // Single Line : First Integer denotes x and rest of the elements in level order form separated by space. Order is - 6 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 7 | // Output Format : 8 | // Count of nodes greater than x 9 | // Sample Input 1 : 10 | // 35 10 3 20 30 40 2 40 50 0 0 0 0 11 | // Sample Output 1 : 12 | // 3 13 | // Sample Input 2 : 14 | // 10 10 3 20 30 40 2 40 50 0 0 0 0 15 | // Sample Output 2: 16 | // 5 17 | 18 | import java.util.*; 19 | public class Solution { 20 | 21 | /* TreeNode class 22 | * 23 | * class TreeNode { 24 | T data; 25 | ArrayList> children; 26 | 27 | TreeNode(T data){ 28 | this.data = data; 29 | children = new ArrayList>(); 30 | } 31 | }*/ 32 | 33 | 34 | public static int numNodeGreater(TreeNode root,int x){ 35 | 36 | // Write your code here 37 | if(root==null) 38 | return 0; 39 | // Write your code here 40 | Queue> queue = new LinkedList<>(); 41 | //added 1st level here 42 | queue.add(root); 43 | queue.add(null); 44 | int ans=0; 45 | 46 | // if(x frontNode = queue.remove(); 52 | if(frontNode == null){ 53 | if(queue.isEmpty()){ 54 | break; 55 | } 56 | 57 | queue.add(null); 58 | }else{ 59 | if(x { 22 | T data; 23 | ArrayList> children; 24 | 25 | TreeNode(T data){ 26 | this.data = data; 27 | children = new ArrayList>(); 28 | } 29 | }*/ 30 | 31 | public static void postOrder(TreeNode root){ 32 | /* Your class should be named Solution. 33 | * Don't write main() function. 34 | * Don't read input, it is passed as function argument. 35 | * Print output as specified in the question 36 | */ 37 | if(root.children.size()==0){ 38 | System.out.print(root.data+" "); 39 | return; 40 | } 41 | 42 | for(TreeNode child:root.children) 43 | { 44 | postOrder(child); 45 | } 46 | 47 | 48 | System.out.print(root.data+" "); 49 | 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/Replace node with depth.java: -------------------------------------------------------------------------------- 1 | // Replace node with depth 2 | // Send Feedback 3 | // In a given Generic Tree, replace each node with its depth value. You need to just update the data of each node, no need to return or print anything. 4 | // Input format : 5 | 6 | // Line 1 : Elements in level order form separated by space (as per done in class). Order is - 7 | 8 | // Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 9 | 10 | // Sample Input 1 : 11 | // 10 3 20 30 40 2 40 50 0 0 0 0 12 | // Sample Output 1 : (Level wise, each level in new line) 13 | // 0 14 | // 1 1 1 15 | // 2 2 16 | import java.util.Queue; 17 | import java.util.LinkedList; 18 | 19 | 20 | public class Solution { 21 | 22 | /* TreeNode structure 23 | * 24 | * class TreeNode { 25 | T data; 26 | ArrayList> children; 27 | 28 | TreeNode(T data){ 29 | this.data = data; 30 | children = new ArrayList>(); 31 | } 32 | }*/ 33 | 34 | static int a=0; 35 | 36 | public static void replaceWithDepthValue(TreeNode root){ 37 | 38 | 39 | 40 | 41 | Queue> queue = new LinkedList<>(); 42 | //added 1st level here 43 | queue.add(root); 44 | queue.add(null); 45 | 46 | while(!queue.isEmpty()) 47 | { 48 | TreeNode frontNode = queue.remove(); 49 | 50 | if(frontNode == null) 51 | { 52 | if(queue.isEmpty()) 53 | { 54 | break; 55 | } 56 | 57 | a++; 58 | queue.add(null); 59 | } 60 | else 61 | { 62 | frontNode.data=a; 63 | for(int i=0;i { 22 | T data; 23 | ArrayList> children; 24 | 25 | TreeNode(T data){ 26 | this.data = data; 27 | children = new ArrayList>(); 28 | } 29 | }*/ 30 | 31 | 32 | 33 | public static TreeNode findSecondLargest(TreeNode root){ 34 | 35 | if(root.children.size() == 0){ 36 | return null; 37 | } 38 | Queue> queue = new LinkedList<>(); 39 | TreeNode fl=root,sl=null; 40 | int data = 0; 41 | queue.add(root); 42 | //queue.add(null); 43 | 44 | while(!queue.isEmpty()) 45 | { 46 | TreeNode frontNode = queue.poll(); 47 | // if(frontNode == null){ 48 | // if(queue.isEmpty()){ 49 | // break; 50 | // } 51 | 52 | // queue.add(null); 53 | // } 54 | // else{ 55 | for(int i=0;i data){ 60 | if(frontNode.data > fl.data){ 61 | sl = fl; 62 | data = fl.data; 63 | fl = frontNode; 64 | } 65 | else if (frontNode.data < fl.data){ 66 | sl = frontNode; 67 | data = sl.data; 68 | } 69 | } 70 | // if(fl.data { 34 | T data; 35 | ArrayList> children; 36 | 37 | TreeNode(T data){ 38 | this.data = data; 39 | children = new ArrayList>(); 40 | } 41 | }*/ 42 | public static int countLeafNodes(TreeNode root){ 43 | /* Your class should be named Solution. 44 | * Don't write main() function. 45 | * Don't read input, it is passed as function argument. 46 | * Print output as specified in the question 47 | */ 48 | int leaf = 0; 49 | 50 | if (root == null ) 51 | { 52 | return 0; 53 | } 54 | 55 | 56 | if (root.children.size() == 0) 57 | { 58 | return 1; 59 | } 60 | 61 | 62 | 63 | for (TreeNode child : root.children) 64 | { 65 | leaf += countLeafNodes(child); 66 | } 67 | 68 | return leaf ; 69 | 70 | 71 | } 72 | 73 | 74 | public static boolean checkIdentical(TreeNode root1, TreeNode root2){ 75 | 76 | // Write your code here 77 | 78 | int a=countLeafNodes(root1),b=countLeafNodes(root2); 79 | 80 | return a==b; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/preOrder.java: -------------------------------------------------------------------------------- 1 | public static void preOrder(TreeNode root){ 2 | 3 | if(root==null) 4 | return; 5 | 6 | System.out.print(root.data+" "); 7 | for(TreeNode child:root.children) 8 | { 9 | preOrder(child); 10 | } 11 | 12 | 13 | 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Lecture 10 : Trees/takeInputLevelWise(): -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Scanner; 3 | 4 | class QueueEmptyException extends Exception { 5 | 6 | } 7 | 8 | class QueueUsingLL { 9 | 10 | class Node { 11 | T data; 12 | Node next; 13 | Node(T data){ 14 | this.data = data; 15 | } 16 | } 17 | 18 | private Node head; 19 | private Node tail; 20 | private int size = 0; 21 | 22 | public int size(){ 23 | return size; 24 | } 25 | 26 | public boolean isEmpty(){ 27 | if(size == 0){ 28 | return true; 29 | } 30 | return false; 31 | } 32 | 33 | public T front() throws QueueEmptyException{ 34 | if(size == 0){ 35 | QueueEmptyException e = new QueueEmptyException(); 36 | throw e; 37 | } 38 | 39 | return head.data; 40 | } 41 | 42 | 43 | public void enqueue(T element){ 44 | Node newNode = new Node(element); 45 | 46 | if(head == null){ 47 | head = newNode; 48 | tail = newNode; 49 | } 50 | else{ 51 | tail.next = newNode; 52 | tail = newNode; 53 | } 54 | 55 | size++; 56 | } 57 | 58 | public T dequeue() throws QueueEmptyException{ 59 | if(head == null){ 60 | QueueEmptyException e = new QueueEmptyException(); 61 | throw e; 62 | } 63 | if(head == tail){ 64 | tail = null; 65 | } 66 | T temp = head.data; 67 | head = head.next; 68 | size--; 69 | return temp; 70 | } 71 | } 72 | 73 | class TreeNode { 74 | T data; 75 | ArrayList> children; 76 | 77 | TreeNode(T data){ 78 | this.data = data; 79 | children = new ArrayList>(); 80 | } 81 | } 82 | 83 | public class Main { 84 | 85 | 86 | 87 | static Scanner s = new Scanner(System.in); 88 | 89 | public static TreeNode takeInputLevelWise(){ 90 | QueueUsingLL> pendingNodes = new QueueUsingLL>(); // Queue of node that are entered themselves but their children aren't added yet 91 | int rootData = s.nextInt(); 92 | TreeNode root = new TreeNode(rootData); 93 | pendingNodes.enqueue(root); 94 | while(!pendingNodes.isEmpty()){ 95 | TreeNode currentNode; 96 | try { 97 | currentNode = pendingNodes.dequeue(); 98 | int numChild = s.nextInt(); 99 | for(int i = 0 ; i < numChild; i++){ 100 | int currentChild = s.nextInt(); 101 | TreeNode childNode = new TreeNode(currentChild); 102 | pendingNodes.enqueue(childNode); 103 | currentNode.children.add(childNode); 104 | } 105 | } catch (QueueEmptyException e) { 106 | } 107 | } 108 | return root; 109 | } 110 | 111 | 112 | public static void main(String[] args) { 113 | TreeNode root = takeInputLevelWise(); 114 | 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/BinaryTreeNode: -------------------------------------------------------------------------------- 1 | 2 | public class BinaryTreeNode 3 | { 4 | public T data; 5 | public BinaryTreeNode left; 6 | public BinaryTreeNode right; 7 | 8 | BinaryTreeNode(T data) 9 | { 10 | this.data=data; 11 | } 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/BinaryTreeUse: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class BinaryTreeUse { 4 | 5 | public static BinaryTreeNode takeInput(Scanner s) 6 | { 7 | int rootdata; 8 | System.out.println("Enter root data - "); 9 | rootdata=s.nextInt(); 10 | 11 | if(rootdata==-1) 12 | return null; 13 | 14 | 15 | BinaryTreeNode root= new BinaryTreeNode(rootdata); 16 | root.left=takeInput(s); 17 | root.right=takeInput(s); 18 | return root; 19 | 20 | } 21 | 22 | 23 | public static void printTree(BinaryTreeNode root) 24 | { 25 | if(root==null) 26 | return; 27 | 28 | String s=root.data+" "; 29 | 30 | if(root.left!=null) 31 | s+="L. "+root.left.data+" ,"; 32 | 33 | if(root.right!=null) 34 | s+="R. "+root.right.data; 35 | 36 | System.out.println(s); 37 | printTree(root.left); 38 | printTree(root.right); 39 | 40 | } 41 | 42 | 43 | 44 | public static void main(String[] args) { 45 | // TODO Auto-generated method stub 46 | // BinaryTreeNode root= new BinaryTreeNode(1); 47 | // BinaryTreeNode node1=new BinaryTreeNode(2); 48 | // root.left=node1; 49 | // BinaryTreeNode node2=new BinaryTreeNode(3); 50 | // root.left=node2; 51 | 52 | 53 | Scanner s=new Scanner(System.in); 54 | BinaryTreeNode root=takeInput(s); 55 | printTree(root); 56 | s.close(); 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Code: Construct Tree from Preorder and Inorder: -------------------------------------------------------------------------------- 1 | // Code: Construct Tree from Preorder and Inorder 2 | // Send Feedback 3 | // Given Preorder and Inorder traversal of a binary tree, create the binary tree associated with the traversals.You just need to construct the tree and return the root. 4 | // Note: Assume binary tree contains only unique elements. 5 | // Input format : 6 | 7 | // Line 1 : n (Total number of nodes in binary tree) 8 | 9 | // Line 2 : Pre order traversal 10 | 11 | // Line 3 : Inorder Traversal 12 | 13 | // Output Format : 14 | 15 | // Elements are printed level wise, each level in new line (separated by space). 16 | 17 | // Sample Input : 18 | // 12 19 | // 1 2 3 4 15 5 6 7 8 10 9 12 20 | // 4 15 3 2 5 1 6 10 8 7 9 12 21 | // Sample Output : 22 | // 1 23 | // 2 6 24 | // 3 5 7 25 | // 4 8 9 26 | // 15 10 12 27 | 28 | 29 | 30 | public class Solution { 31 | 32 | /* Binary Tree Node class 33 | * 34 | * class BinaryTreeNode { 35 | T data; 36 | BinaryTreeNode left; 37 | BinaryTreeNode right; 38 | 39 | public BinaryTreeNode(T data) { 40 | this.data = data; 41 | } 42 | } 43 | */ 44 | 45 | 46 | 47 | 48 | public static BinaryTreeNode getTreeFromPreorderAndInorder(int[] pre,int[] in){ 49 | 50 | return helper (0, 0, in.length - 1, pre, in); 51 | } 52 | 53 | private static BinaryTreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) { 54 | 55 | //base condition 56 | if (preStart > preorder.length - 1 || inStart > inEnd) 57 | return null; 58 | 59 | //get the root node with curr preorder element 60 | BinaryTreeNode root = new BinaryTreeNode(preorder[preStart]); 61 | 62 | //get inIndex; finding preorder's element's index in inorder 63 | int inIndex = 0; 64 | 65 | for (int i = inStart; i <= inEnd; i++) { 66 | if(inorder[i] == root.data) { 67 | inIndex = i; 68 | } 69 | } 70 | //(next, left of inIndex is the end for left subtree) 71 | root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder); 72 | //(prestart + length of left subtree + 1) 73 | root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder); 74 | 75 | return root; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Construct Tree from Postorder and Inorder: -------------------------------------------------------------------------------- 1 | // Construct Tree from Postorder and Inorder 2 | // Send Feedback 3 | // Given Postorder and Inorder traversal of a binary tree, create the binary tree associated with the traversals.You just need to construct the tree and return the root. 4 | // Note: Assume binary tree contains only unique elements. 5 | // Input format : 6 | 7 | // Line 1 : n (Total number of nodes in binary tree) 8 | 9 | // Line 2 : Post order traversal 10 | 11 | // Line 3 : Inorder Traversal 12 | 13 | // Output Format : 14 | 15 | // Elements are printed level wise, each level in new line (separated by space). 16 | 17 | // Sample Input : 18 | // 8 19 | // 8 4 5 2 6 7 3 1 20 | // 4 8 2 5 1 6 3 7 21 | // Sample Output : 22 | // 1 23 | // 2 3 24 | // 4 5 6 7 25 | // 8 26 | 27 | 28 | import java.util.*; 29 | public class Solution { 30 | 31 | /* Binary Tree Node class 32 | * 33 | * class BinaryTreeNode { 34 | T data; 35 | BinaryTreeNode left; 36 | BinaryTreeNode right; 37 | 38 | public BinaryTreeNode(T data) { 39 | this.data = data; 40 | } 41 | } 42 | */ 43 | 44 | public static BinaryTreeNode getTreeFromPostorderAndInorder(int[] postorder,int[] inorder){ 45 | 46 | if (inorder.length == 0 || postorder.length == 0) return null; 47 | int ip = inorder.length - 1; 48 | int pp = postorder.length - 1; 49 | 50 | Stack> stack = new Stack>(); 51 | BinaryTreeNode prev = null; 52 | BinaryTreeNode root = new BinaryTreeNode(postorder[pp]); 53 | stack.push(root); 54 | pp--; 55 | 56 | while (pp >= 0) { 57 | while (!stack.isEmpty() && stack.peek().data == inorder[ip]) { 58 | prev = stack.pop(); 59 | ip--; 60 | } 61 | BinaryTreeNode newNode = new BinaryTreeNode(postorder[pp]); 62 | if (prev != null) { 63 | prev.left = newNode; 64 | } else if (!stack.isEmpty()) { 65 | BinaryTreeNode currTop = stack.peek(); 66 | currTop.right = newNode; 67 | } 68 | stack.push(newNode); 69 | prev = null; 70 | pp--; 71 | } 72 | 73 | return root; 74 | 75 | 76 | 77 | } 78 | 79 | 80 | 81 | } 82 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Find Node: -------------------------------------------------------------------------------- 1 | // Find Node 2 | // Send Feedback 3 | // Given a Binary Tree and an integer x, check if node with data x is present in the input binary tree or not. Return true or false. 4 | // Input format : 5 | // Line 1 : Elements in level order form (separated by space) 6 | // (If any node does not have left or right child, take -1 in its place) 7 | // Line 2 : Integer x 8 | // Output Format : 9 | // true or false 10 | // Sample Input : 11 | // 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 12 | // 7 13 | // Sample Output : 14 | // true 15 | 16 | 17 | public class Solution { 18 | 19 | /* Binary Tree Node class 20 | * 21 | * class BinaryTreeNode { 22 | T data; 23 | BinaryTreeNode left; 24 | BinaryTreeNode right; 25 | 26 | public BinaryTreeNode(T data) { 27 | this.data = data; 28 | } 29 | } 30 | */ 31 | 32 | public static boolean isNodePresent(BinaryTreeNode root,int x){ 33 | /* Your class should be named Solution 34 | * Don't write main(). 35 | * Don't read input, it is passed as function argument. 36 | * Return output and don't print it. 37 | * Taking input and printing output is handled automatically. 38 | */ 39 | 40 | if(root==null) 41 | return false; 42 | 43 | boolean ans=false; 44 | 45 | if(root.data==x) 46 | return true; 47 | 48 | ans=isNodePresent(root.left,x); 49 | if(ans) 50 | return ans; 51 | ans=isNodePresent(root.right,x); 52 | return ans; 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Height Of Binary Tree: -------------------------------------------------------------------------------- 1 | // Height Of Binary Tree 2 | // Send Feedback 3 | // Given a binary tree, find and return the height of given tree. 4 | // Input format : 5 | // Nodes in the level order form (separated by space). If any node does not have left or right child, take -1 in its place 6 | // Output format : 7 | // Height 8 | // Constraints : 9 | // 1 <= N <= 10^5 10 | // Sample Input : 11 | // 10 12 | // 9 13 | // 4 14 | // -1 15 | // -1 16 | // 5 17 | // 8 18 | // -1 19 | // 6 20 | // -1 21 | // -1 22 | // 3 23 | // -1 24 | // -1 25 | // -1 26 | // Sample Output : 27 | // 5 28 | public class Solution { 29 | 30 | 31 | 32 | /* Binary Tree Node class 33 | * 34 | * class BinaryTreeNode { 35 | T data; 36 | BinaryTreeNode left; 37 | BinaryTreeNode right; 38 | 39 | public BinaryTreeNode(T data) { 40 | this.data = data; 41 | } 42 | } 43 | */ 44 | public static int height(BinaryTreeNode root) { 45 | /* Your class should be named Solution 46 | * Don't write main(). 47 | * Don't read input, it is passed as function argument. 48 | * Return output and don't print it. 49 | * Taking input and printing output is handled automatically. 50 | */ 51 | if (root==null) 52 | return 0; 53 | 54 | int left=height(root.left),right=height(root.right); 55 | 56 | 57 | if(left>right) 58 | return left+1; 59 | else 60 | return right+1; 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Level order traversal: -------------------------------------------------------------------------------- 1 | // Level order traversal 2 | // Send Feedback 3 | // Given a binary tree, print the level order traversal. Make sure each level start in new line. 4 | // Input format : 5 | 6 | // Elements in level order form (separated by space). If any node does not have left or right child, take -1 in its place. 7 | 8 | // Output Format : 9 | 10 | // Elements are printed level wise, each level in new line (separated by space). 11 | 12 | // Sample Input : 13 | // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 14 | // Sample Output : 15 | // 5 16 | // 6 10 17 | // 2 3 18 | // 9 19 | 20 | import java.util.ArrayList; 21 | 22 | 23 | public class Solution { 24 | 25 | /* Binary Tree Node class 26 | * 27 | * class BinaryTreeNode { 28 | T data; 29 | BinaryTreeNode left; 30 | BinaryTreeNode right; 31 | 32 | public BinaryTreeNode(T data) { 33 | this.data = data; 34 | } 35 | } 36 | */ 37 | 38 | public static void printLevelWise(BinaryTreeNode root){ 39 | 40 | QueueUsingLL> primary = new QueueUsingLL<>(); 41 | QueueUsingLL> secondary = new QueueUsingLL<>(); 42 | 43 | primary.enqueue(root); 44 | 45 | while(!primary.isEmpty()) 46 | { 47 | BinaryTreeNode current=null; 48 | try { 49 | current = primary.dequeue(); 50 | } catch (QueueEmptyException e) { 51 | System.out.println("Not possible"); 52 | } 53 | 54 | System.out.print(current.data + " "); 55 | 56 | if(current.left != null) 57 | { 58 | secondary.enqueue(current.left); 59 | } 60 | 61 | if(current.right != null) 62 | { 63 | secondary.enqueue(current.right); 64 | } 65 | 66 | if(primary.isEmpty()) 67 | { 68 | QueueUsingLL> temp = secondary; 69 | secondary = primary; 70 | primary = temp; 71 | System.out.println(); 72 | } 73 | } 74 | 75 | 76 | } 77 | 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Level wise linkedlist: -------------------------------------------------------------------------------- 1 | Level wise linkedlist 2 | // Send Feedback 3 | // Given a binary tree, write code to create a separate linked list for each level. You need to return the array which contains head of each level linked list. 4 | // Input format : 5 | 6 | // Elements in level order form (separated by space). If any node does not have left or right child, take -1 in its place. 7 | 8 | // Output format : Each level linked list is printed in new line (elements separated by space). 9 | 10 | // Sample Input : 11 | // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 12 | // Sample Output : 13 | // 5 14 | // 6 10 15 | // 2 3 16 | // 9 17 | 18 | import java.util.*; 19 | 20 | 21 | public class Solution { 22 | 23 | /* Binary Tree Node class 24 | * 25 | * class BinaryTreeNode { 26 | T data; 27 | BinaryTreeNode left; 28 | BinaryTreeNode right; 29 | 30 | public BinaryTreeNode(T data) { 31 | this.data = data; 32 | } 33 | } 34 | */ 35 | 36 | /* class Node { 37 | T data; 38 | Node next; 39 | Node(T data){ 40 | this.data = data; 41 | } 42 | } 43 | */ 44 | public static ArrayList>> LLForEachLevel(BinaryTreeNode root) 45 | { 46 | 47 | 48 | ArrayList>> al = new ArrayList>>(); 49 | QueueUsingLL> myQ = new QueueUsingLL>(); 50 | myQ.enqueue(root); 51 | myQ.enqueue(null); 52 | try{ 53 | Node> head = null; 54 | Node> tail = null; 55 | while(!myQ.isEmpty()){ 56 | BinaryTreeNode temp = myQ.dequeue(); 57 | if(temp == null){ 58 | // System.out.println(); 59 | al.add(head); 60 | head = null; 61 | tail = null; 62 | if(!myQ.isEmpty()){ 63 | myQ.enqueue(null); 64 | } 65 | continue; 66 | } 67 | // System.out.print(temp.data+" "); 68 | Node> var = new Node>(temp); 69 | if(head == null){ 70 | head = var; 71 | tail = var; 72 | } 73 | else{ 74 | tail.next = var; 75 | tail = var; 76 | } 77 | if(temp.left != null){ 78 | myQ.enqueue(temp.left); 79 | } 80 | if(temp.right != null){ 81 | myQ.enqueue(temp.right); 82 | } 83 | 84 | } 85 | } 86 | catch(Exception e){ 87 | 88 | } 89 | return al; 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Mirror a Binary Tree: -------------------------------------------------------------------------------- 1 | // Mirror a Binary Tree 2 | // Send Feedback 3 | // Mirror the given binary tree. That is, right child of every nodes should become left and left should become right. 4 | // Alt text 5 | 6 | // Note : You don't need to print or return the tree, just mirror it. 7 | // Input format : 8 | 9 | // Line 1 : Elements in level order form (separated by space) 10 | 11 | // (If any node does not have left or right child, take -1 in its place) 12 | 13 | // Output format : Elements in level order form (Every level in new line) 14 | 15 | // Sample Input 1: 16 | // 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1 17 | // Sample Output 1: 18 | // 1 19 | // 3 2 20 | // 7 6 5 4 21 | // Sample Input 2: 22 | // 5 10 6 2 3 -1 -1 -1 -1 -1 9 -1 -1 23 | // Sample Output 2: 24 | // 5 25 | // 6 10 26 | // 3 2 27 | // 9 28 | 29 | 30 | public class Solution { 31 | 32 | /* Binary Tree Node class 33 | * 34 | * class BinaryTreeNode { 35 | T data; 36 | BinaryTreeNode left; 37 | BinaryTreeNode right; 38 | 39 | public BinaryTreeNode(T data) { 40 | this.data = data; 41 | } 42 | } 43 | */ 44 | 45 | public static void mirror(BinaryTreeNode root){ 46 | /* Your class should be named Solution 47 | * Don't write main(). 48 | * Don't read input, it is passed as function argument. 49 | * No need to print or return the output. 50 | * Taking input and printing output is handled automatically. 51 | */ 52 | 53 | if (root==null) 54 | return; 55 | 56 | 57 | BinaryTreeNode temp=root.right; 58 | root.right=root.left; 59 | root.left=temp; 60 | 61 | mirror(root.left); 62 | mirror(root.right); 63 | 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Nodes without sibling: -------------------------------------------------------------------------------- 1 | // Nodes without sibling 2 | // Send Feedback 3 | // Given a binary tree, print all nodes that don’t have a sibling. 4 | // Edit : Print the elements in different lines. And order of elements doesn't matter. 5 | // Input format : 6 | // Elements in level order form (separated by space). If any node does not have left or right child, take -1 in its place. 7 | // Output format : 8 | // Print nodes separated by new line. 9 | // Sample Input : 10 | // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 11 | // Sample Output : 12 | // 9 13 | 14 | import java.util.ArrayList; 15 | 16 | 17 | public class Solution { 18 | 19 | /* Binary Tree Node class 20 | * 21 | * class BinaryTreeNode { 22 | T data; 23 | BinaryTreeNode left; 24 | BinaryTreeNode right; 25 | 26 | public BinaryTreeNode(T data) { 27 | this.data = data; 28 | } 29 | } 30 | */ 31 | 32 | public static void printNodesWithoutSibling(BinaryTreeNode root) { 33 | 34 | 35 | if(root==null) 36 | return; 37 | 38 | if( root.left!=null && root.right==null ) 39 | System.out.println(root.left.data); 40 | 41 | if( root.left==null && root.right!=null ) 42 | System.out.println(root.right.data); 43 | 44 | 45 | printNodesWithoutSibling(root.left); 46 | 47 | printNodesWithoutSibling(root.right); 48 | 49 | 50 | } 51 | 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Postorder Binary Tree: -------------------------------------------------------------------------------- 1 | // Postorder Binary Tree 2 | // Send Feedback 3 | // Given a binary tree, print the postorder traversal of given tree. 4 | // Post-order traversal is: LeftChild RightChild Root 5 | // Input format : 6 | // Elements in level order form (separated by space) 7 | // (If any node does not have left or right child, take -1 in its place) 8 | // Output Format : 9 | // Post-order traversal, elements separated by space 10 | // Sample Input : 11 | // 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 12 | // Sample Output : 13 | // 1 4 7 6 3 13 14 10 8 14 | 15 | public class Solution { 16 | 17 | /* Binary Tree Node class 18 | * 19 | * class BinaryTreeNode { 20 | T data; 21 | BinaryTreeNode left; 22 | BinaryTreeNode right; 23 | 24 | public BinaryTreeNode(T data) { 25 | this.data = data; 26 | } 27 | } 28 | */ 29 | public static void postOrder(BinaryTreeNode root) { 30 | /* Your class should be named Solution 31 | * Don't write main(). 32 | * Don't read input, it is passed as function argument. 33 | * Print output and don't return it. 34 | * Taking input is handled automatically. 35 | */ 36 | 37 | if(root==null) 38 | return; 39 | 40 | 41 | postOrder(root.left); 42 | postOrder(root.right); 43 | System.out.print(root.data+" "); 44 | 45 | 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Preorder Binary Tree: -------------------------------------------------------------------------------- 1 | 2 | // Preorder Binary Tree 3 | // Send Feedback 4 | // Given a binary tree, print the preorder traversal of given tree. 5 | // Pre-order traversal is: Root LeftChild RightChild 6 | // Input format : 7 | // Elements in level order form (separated by space) 8 | // (If any node does not have left or right child, take -1 in its place) 9 | // Output Format : 10 | // Pre-order traversal, elements separated by space 11 | // Sample Input : 12 | // 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 13 | // Sample Output : 14 | // 8 3 1 6 4 7 10 14 13 15 | 16 | public class Solution { 17 | 18 | /* Binary Tree Node class 19 | * 20 | * class BinaryTreeNode { 21 | T data; 22 | BinaryTreeNode left; 23 | BinaryTreeNode right; 24 | 25 | public BinaryTreeNode(T data) { 26 | this.data = data; 27 | } 28 | } 29 | */ 30 | public static void preOrder(BinaryTreeNode root) { 31 | /* Your class should be named Solution 32 | * Don't write main(). 33 | * Don't read input, it is passed as function argument. 34 | * Print output and don't return it. 35 | * Taking input is handled automatically. 36 | */ 37 | if(root==null) 38 | return; 39 | 40 | System.out.print(root.data+" "); 41 | preOrder(root.left); 42 | preOrder(root.right); 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Remove Leaf nodes: -------------------------------------------------------------------------------- 1 | // Remove Leaf nodes 2 | // Send Feedback 3 | // Remove all leaf nodes from a given Binary Tree. Leaf nodes are those nodes, which don't have any children. 4 | // Note : Root will also be a leaf node if it doesn't have left and right child. You don't need to print the tree, just remove all leaf nodes and return the updated root. 5 | // Input format : 6 | 7 | // Elements in level order form (separated by space) 8 | 9 | // (If any node does not have left or right child, take -1 in its place) 10 | 11 | // Output Format : 12 | 13 | // Elements are printed level wise, each level in new line (separated by space). 14 | 15 | // Sample Input : 16 | // 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1 17 | // Sample Output : 18 | // 8 19 | // 3 10 20 | // 6 14 21 | 22 | import java.util.ArrayList; 23 | 24 | 25 | public class Solution { 26 | 27 | /* Binary Tree Node class 28 | * 29 | * class BinaryTreeNode { 30 | T data; 31 | BinaryTreeNode left; 32 | BinaryTreeNode right; 33 | 34 | public BinaryTreeNode(T data) { 35 | this.data = data; 36 | } 37 | } 38 | */ 39 | 40 | public static BinaryTreeNode removeAllLeaves(BinaryTreeNode root){ 41 | 42 | if(root==null) 43 | return null; 44 | 45 | if(root.right==null && root.left==null) 46 | return null; 47 | 48 | BinaryTreeNode left= removeAllLeaves(root.left); 49 | BinaryTreeNode right = removeAllLeaves(root.right); 50 | 51 | if(left==null) 52 | root.left=null; 53 | 54 | 55 | if(right==null) 56 | root.right=null; 57 | 58 | 59 | return root; 60 | 61 | 62 | } 63 | 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/Sum of all nodes: -------------------------------------------------------------------------------- 1 | // Sum of all nodes 2 | // Send Feedback 3 | // Given a binary tree, find and return the sum of all nodes. 4 | // Input format : 5 | 6 | // Elements in level order form (separated by space). If any node does 7 | // not have left or right child, take -1 in its place. 8 | 9 | // Sample Input : 10 | // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 11 | // Sample Output : 12 | // 35 13 | 14 | 15 | public class Solution { 16 | 17 | /* Binary Tree Node class 18 | * 19 | * class BinaryTreeNode { 20 | T data; 21 | BinaryTreeNode left; 22 | BinaryTreeNode right; 23 | 24 | public BinaryTreeNode(T data) { 25 | this.data = data; 26 | } 27 | } 28 | */ 29 | 30 | public static int sum(BinaryTreeNode root){ 31 | 32 | if(root==null) 33 | return 0; 34 | 35 | int sum=0; 36 | sum+=root.data+sum(root.left)+sum(root.right); 37 | return sum; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/ZigZag tree: -------------------------------------------------------------------------------- 1 | // ZigZag tree 2 | // Send Feedback 3 | // Given a binary tree, print the zig zag order i.e print level 1 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. 4 | // Input format : 5 | 6 | // Elements in level order form (separated by space) 7 | 8 | // (If any node does not have left or right child, take -1 in its place) 9 | 10 | // Output Format : 11 | 12 | // Elements are printed level wise, each level in new line (separated by space). 13 | 14 | // Sample Input : 15 | // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 16 | // Sample Output : 17 | // 5 18 | // 10 6 19 | // 2 3 20 | // 9 21 | 22 | import java.util.ArrayList; 23 | import java.util.*; 24 | 25 | public class Solution { 26 | 27 | /* Binary Tree Node class 28 | * 29 | * class BinaryTreeNode { 30 | T data; 31 | BinaryTreeNode left; 32 | BinaryTreeNode right; 33 | 34 | public BinaryTreeNode(T data) { 35 | this.data = data; 36 | } 37 | } 38 | */ 39 | 40 | public static void printZigZag(BinaryTreeNode root) { 41 | 42 | 43 | Stack> s1 = new Stack>(); 44 | Stack> s2 = new Stack>(); 45 | 46 | s1.push(root); 47 | s2.push(root); 48 | while(!s1.empty() && !s2.empty()){ 49 | BinaryTreeNode pp = s2.pop(); 50 | while(!s1.empty()){ 51 | if(s1.peek().left != null){ 52 | s2.push(s1.peek().left); 53 | } 54 | if(s1.peek().right != null){ 55 | s2.push(s1.peek().right); 56 | } 57 | System.out.print(s1.pop().data+" "); 58 | } 59 | System.out.println(); 60 | 61 | while(!s2.empty()){ 62 | if(s2.peek().right != null){ 63 | s1.push(s2.peek().right); 64 | } 65 | if(s2.peek().left != null){ 66 | s1.push(s2.peek().left); 67 | } 68 | System.out.print(s2.pop().data+" "); 69 | } 70 | System.out.println(); 71 | s2.push(root); 72 | } 73 | 74 | 75 | 76 | 77 | } 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /Lecture 11: Binary Trees/is Balanced: -------------------------------------------------------------------------------- 1 | // is Balanced 2 | // Send Feedback 3 | // Given a binary tree, check if its balanced i.e. depth of left and right subtrees of every node differ by at max 1. Return true if given binary tree is balanced, false otherwise. 4 | // Input format : 5 | 6 | // Elements in level order form (separated by space). If any node does not have left or right child, take -1 in its place. 7 | 8 | // Sample Input 1 : 9 | // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 10 | // Sample Output 1 : 11 | // false 12 | // Sample Input 2 : 13 | // 1 2 3 -1 -1 -1 -1 14 | // Sample Output 2 : 15 | // true 16 | 17 | 18 | import java.util.*; 19 | 20 | public class Solution { 21 | 22 | /* Binary Tree Node class 23 | * 24 | * class BinaryTreeNode { 25 | T data; 26 | BinaryTreeNode left; 27 | BinaryTreeNode right; 28 | 29 | public BinaryTreeNode(T data) { 30 | this.data = data; 31 | } 32 | } 33 | */ 34 | 35 | public static int height(BinaryTreeNode root) 36 | { 37 | /* base case tree is empty */ 38 | if (root == null) 39 | return 0; 40 | 41 | /* If tree is not empty then height = 1 + max of left 42 | height and right heights */ 43 | return 1 + Math.max(height(root.left), height(root.right)); 44 | } 45 | 46 | 47 | 48 | public static boolean checkBalanced(BinaryTreeNode root){ 49 | 50 | 51 | int lh; /* for height of left subtree */ 52 | 53 | int rh; /* for height of right subtree */ 54 | 55 | /* If tree is empty then return true */ 56 | if (root == null) 57 | return true; 58 | 59 | /* Get the height of left and right sub trees */ 60 | lh = height(root.left); 61 | rh = height(root.right); 62 | 63 | if (Math.abs(lh - rh) <= 1 64 | && checkBalanced(root.left) 65 | && checkBalanced(root.right)) 66 | return true; 67 | 68 | /* If we reach here then tree is not height-balanced */ 69 | return false; 70 | 71 | 72 | 73 | 74 | } 75 | 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /Lecture 12: Binary Search Trees/Check if a Binary Tree is BST: -------------------------------------------------------------------------------- 1 | // Check if a Binary Tree is BST 2 | // Send Feedback 3 | // Given a binary tree with N number of nodes, check if that input tree is BST (Binary Search Tree) or not. If yes, return true, return false otherwise. 4 | // Duplicate elements should be in right subtree. 5 | // Input format : 6 | // Line 1 : Nodes in level order form (separated by space). If any node does not have left or right child, take -1 in its place 7 | // Output format : 8 | // true or false 9 | // Constraints : 10 | // 1 <= N <= 10^5 11 | // Sample Input 1 : 12 | // 3 1 5 -1 2 -1 -1 -1 -1 13 | // Sample Output 1 : 14 | // true 15 | // Sample Input 2 : 16 | // 5 2 10 0 1 -1 15 -1 -1 -1 -1 -1 -1 17 | // Sample Output 2 : 18 | // false 19 | 20 | 21 | import java.util.*; 22 | 23 | public class Solution { 24 | 25 | 26 | public static int maximum(BinaryTreeNode root) 27 | { 28 | if(root==null) 29 | return Integer.MIN_VALUE; 30 | 31 | return Math.max(root.data,Math.max(maximum(root.left),maximum(root.right))); 32 | 33 | 34 | } 35 | 36 | 37 | public static int minimum(BinaryTreeNode root) 38 | { 39 | if(root==null) 40 | return Integer.MAX_VALUE; 41 | 42 | return Math.min(root.data,Math.min(minimum(root.left),minimum(root.right))); 43 | } 44 | 45 | 46 | 47 | 48 | 49 | public static boolean isBST(BinaryTreeNode root) { 50 | /* Your class should be named Solution 51 | * Don't write main(). 52 | * Don't read input, it is passed as function argument. 53 | * Return output and don't print it. 54 | * Taking input and printing output is handled automatically. 55 | */ 56 | if(root==null) 57 | return true; 58 | 59 | 60 | int leftmax= maximum(root.left); 61 | int rightmin=minimum(root.right); 62 | 63 | // boolean temp=true; 64 | 65 | 66 | // if(root.left!=null) 67 | // { 68 | if(root.data<=leftmax) 69 | return false; 70 | 71 | 72 | if(root.data>rightmin) 73 | return false; 74 | 75 | 76 | 77 | 78 | 79 | 80 | boolean isLeftBst=isBST(root.left); 81 | 82 | boolean isRightBst=isBST(root.right); 83 | 84 | 85 | 86 | if(isLeftBst && isRightBst) 87 | return true; 88 | else 89 | return false; 90 | 91 | 92 | 93 | 94 | 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Lecture 12: Binary Search Trees/Code: Search Node in BST: -------------------------------------------------------------------------------- 1 | // Code: Search Node in BST 2 | // Send Feedback 3 | // Given a BST and an integer k. Find if the integer k is present in given BST or not. Return the node with data k if it is present, return null otherwise. 4 | // Assume that BST contains all unique elements. 5 | // Input Format : 6 | // Line 1 : Elements in level order form (separated by space) 7 | // (If any node does not have left or right child, take -1 in its place) 8 | // Line 2 : Integer k 9 | // Output Format : 10 | // Node with data k 11 | // Sample Input 1 : 12 | // 8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1 13 | // 2 14 | // Sample Output 1 : 15 | // 2 16 | // Sample Input 2 : 17 | // 8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1 18 | // 12 19 | // Sample Output 2 : 20 | // (empty)public class Solution { 21 | 22 | 23 | 24 | /* Binary Tree Node class 25 | * 26 | * class BinaryTreeNode { 27 | T data; 28 | BinaryTreeNode left; 29 | BinaryTreeNode right; 30 | 31 | public BinaryTreeNode(T data) { 32 | this.data = data; 33 | } 34 | } 35 | */ 36 | 37 | public static BinaryTreeNode searchInBST(BinaryTreeNode root , int k){ 38 | /* Your class should be named Solution 39 | * Don't write main(). 40 | * Don't read input, it is passed as function argument. 41 | * Return output and don't print it. 42 | * Taking input and printing output is handled automatically. 43 | */ 44 | 45 | BinaryTreeNode temp=null; 46 | 47 | if(root==null) 48 | return null; 49 | 50 | if(root.data==k) 51 | return root; 52 | 53 | 54 | if(root.data>k) 55 | temp=searchInBST(root.left,k); 56 | else if(root.data { 23 | T data; 24 | BinaryTreeNode left; 25 | BinaryTreeNode right; 26 | 27 | public BinaryTreeNode(T data) { 28 | this.data = data; 29 | } 30 | } 31 | */ 32 | 33 | public static void printNodeFromK1ToK2(BinaryTreeNode root,int k1,int k2){ 34 | 35 | 36 | BinaryTreeNode temp=null; 37 | 38 | if(root==null) 39 | return ; 40 | 41 | 42 | if(root.data>k1) 43 | printNodeFromK1ToK2(root.left,k1,k2); 44 | 45 | 46 | if(root.data>=k1 && root.data<=k2) 47 | System.out.print(root.data+" "); 48 | 49 | 50 | 51 | 52 | if(root.data=0)?"+ ":"- "; 112 | System.out.print(s+"i"+this.imaginary); 113 | } 114 | 115 | 116 | 117 | 118 | } 119 | 120 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /Lecture 1:OOPS 1/Fraction.java: -------------------------------------------------------------------------------- 1 | package classes_and_objects; 2 | 3 | public class Fraction { 4 | private int numerator; 5 | private int denominator; 6 | 7 | public Fraction(int numerator, int denominator) { 8 | this.numerator = numerator; 9 | if (denominator == 0) { 10 | // TODO error out 11 | } 12 | this.denominator = denominator; 13 | simplify(); 14 | } 15 | 16 | 17 | public int getDenominator() { 18 | return denominator; 19 | } 20 | 21 | public int getNumerator() { 22 | return numerator; 23 | } 24 | 25 | public void setNumerator(int n) { 26 | this.numerator = n; 27 | simplify(); 28 | } 29 | 30 | 31 | public void setDenominator(int d) { 32 | if (d == 0){ 33 | // TODO error out 34 | return; 35 | } 36 | this.denominator = d; 37 | this.simplify(); 38 | } 39 | 40 | public void print() { 41 | if (denominator == 1) { 42 | System.out.println(numerator); 43 | } else { 44 | System.out.println(numerator + "/" + denominator); 45 | } 46 | } 47 | 48 | private void simplify() { 49 | int gcd = 1; 50 | int smaller = Math.min(numerator, denominator); 51 | for (int i = 2; i <= smaller; i++) { 52 | if (numerator % i == 0 && denominator % i == 0) { 53 | gcd = i; 54 | } 55 | } 56 | numerator = numerator/gcd; 57 | denominator = denominator/gcd; 58 | } 59 | 60 | public static Fraction add(Fraction f1, Fraction f2) { 61 | int newNum = f1.numerator * f2.denominator + f2.numerator * f1.denominator; 62 | int newDen = f1.denominator * f2.denominator; 63 | Fraction f = new Fraction(newNum, newDen); 64 | return f; 65 | } 66 | 67 | public void add(Fraction f2) { 68 | this.numerator = this.numerator * f2.denominator + this.denominator*f2.numerator; 69 | this.denominator = this.denominator * f2.denominator; 70 | simplify(); 71 | } 72 | 73 | public void multiply(Fraction f2) { 74 | this.numerator = this.numerator * f2.numerator; 75 | this.denominator = this.denominator * f2.denominator; 76 | simplify(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /Lecture 1:OOPS 1/FractionUse.java: -------------------------------------------------------------------------------- 1 | package classes_and_objects; 2 | 3 | public class FractionUse { 4 | 5 | public static void main(String[] args) { 6 | Fraction f1 = new Fraction(20,30); 7 | f1.print(); 8 | // 2/3 9 | 10 | f1.setNumerator(12); 11 | // 4/1 12 | int d = f1.getDenominator(); 13 | System.out.println(d); 14 | f1.print(); 15 | // 16 | f1.setNumerator(10); 17 | f1.setDenominator(30); 18 | // 1/3 19 | f1.print(); 20 | // 21 | Fraction f2 = new Fraction(3,4); 22 | f1.add(f2); 23 | f1.print(); 24 | // f1 => 13/12 25 | f2.print(); 26 | // f2 => 3/4 27 | // 28 | Fraction f3 = new Fraction(4,5); 29 | f3.multiply(f2); 30 | f3.print(); 31 | // f3 => 3/5 32 | f2.print(); 33 | // f2 => 3/4 34 | // 35 | Fraction f4 = Fraction.add(f1, f3); 36 | f1.print(); 37 | f3.print(); 38 | f4.print(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Lecture 3: Recursion 1/All Indices of Number: -------------------------------------------------------------------------------- 1 | // All Indices of Number 2 | // Send Feedback 3 | // Given an array of length N and an integer x, you need to find all 4 | // the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). 5 | // Do this recursively. Indexing in the array starts from 0. 6 | // Input Format : 7 | // Line 1 : An Integer N i.e. size of array 8 | // Line 2 : N integers which are elements of the array, separated by spaces 9 | // Line 3 : Integer x 10 | // Output Format : 11 | // indexes where x is present in the array (separated by space) 12 | // Constraints : 13 | // 1 <= N <= 10^3 14 | // Sample Input : 15 | // 5 16 | // 9 8 10 8 8 17 | // 8 18 | // Sample Output : 19 | // 1 3 4 20 | 21 | 22 | 23 | public class Solution { 24 | 25 | 26 | 27 | public static int[] AllIndexesRecursive(int input[], 28 | int x, int start) 29 | { 30 | // If the start index reaches the 31 | // length of the array, then 32 | // return empty array 33 | if (start == input.length) { 34 | int[] ans = new int[0]; // empty array 35 | return ans; 36 | } 37 | 38 | // Getting the recursive answer in 39 | // smallIndex array 40 | int[] smallIndex = AllIndexesRecursive(input, x, 41 | start + 1); 42 | 43 | // If the element at start index is equal 44 | // to x then 45 | // (which is the answer of recursion) and then 46 | // (which came through recursion) 47 | if (input[start] == x) { 48 | int[] myAns = new int[smallIndex.length + 1]; 49 | 50 | // Put the start index in front 51 | // of the array 52 | myAns[0] = start; 53 | for (int i = 0; i < smallIndex.length; i++) { 54 | 55 | // Shift the elements of the array 56 | // one step to the right 57 | // and putting them in 58 | // myAns array 59 | myAns[i + 1] = smallIndex[i]; 60 | } 61 | return myAns; 62 | } 63 | else { 64 | 65 | // If the element at start index is not 66 | // equal to x then just simply return the 67 | // answer which came from recursion. 68 | return smallIndex; 69 | } 70 | } 71 | 72 | public static int[] allIndexes(int input[], int x) 73 | { 74 | 75 | return AllIndexesRecursive(input, x, 0); 76 | } 77 | 78 | 79 | 80 | } 81 | 82 | -------------------------------------------------------------------------------- /Lecture 3: Recursion 1/Calculate Power: -------------------------------------------------------------------------------- 1 | // Calculate Power 2 | // Send Feedback 3 | // Write a program to find x to the power n (i.e. x^n). 4 | // Take x and n from the user. You need to return the answer. 5 | // Do this recursively. 6 | // Input format : 7 | // Two integers x and n (separated by space) 8 | // Output Format : 9 | // x^n (i.e. x raise to the power n) 10 | // Constraints : 11 | // 1 <= x <= 30 12 | // 0 <= n <= 30 13 | // Sample Input 1 : 14 | // 3 4 15 | // Sample Output 1 : 16 | // 81 17 | // Sample Input 2 : 18 | // 2 5 19 | // Sample Output 2 : 20 | // 32 21 | 22 | 23 | 24 | public class Solution { 25 | 26 | 27 | public static int power(int x, int n) { 28 | 29 | if(n==0) 30 | return 1; 31 | else 32 | return x*power(x,n-1); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Lecture 3: Recursion 1/Check Number in Array: -------------------------------------------------------------------------------- 1 | // Check Number in Array 2 | // Send Feedback 3 | // Given an array of length N and an integer x, you 4 | // need to find if x is present in the array or not. Return true or false. 5 | // Do this recursively. 6 | // Input Format : 7 | // Line 1 : An Integer N i.e. size of array 8 | // Line 2 : N integers which are elements of the array, separated by spaces 9 | // Line 3 : Integer x 10 | // Output Format : 11 | // true or false 12 | // Constraints : 13 | // 1 <= N <= 10^3 14 | // Sample Input : 15 | // 3 16 | // 9 8 10 17 | // 8 18 | // Sample Output : 19 | // true 20 | 21 | 22 | 23 | public class Solution { 24 | 25 | public static boolean checkNumber(int input[], int x) { 26 | /* Your class should be named Solution 27 | * Don't write main(). 28 | * Don't read input, it is passed as function argument. 29 | * Return output and don't print it. 30 | * Taking input and printing output is handled automatically. 31 | */ 32 | 33 | 34 | 35 | 36 | boolean ans; 37 | 38 | 39 | if(input[0]==x) 40 | return true; 41 | 42 | if(input[0]!=x && input.length==1) 43 | return false; 44 | 45 | int arr[]=new int[input.length-1]; 46 | 47 | for(int i=1;ielement) 43 | { 44 | return indexFind(input,element,start,mid-1); 45 | } 46 | } 47 | return -1; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Check AB: -------------------------------------------------------------------------------- 1 | // Check AB 2 | // Send Feedback 3 | // Suppose you have a string made up of only 'a' and 'b'. Write a recursive 4 | // function that checks if the string was generated using the following rules: 5 | // a. The string begins with an 'a' 6 | // b. Each 'a' is followed by nothing or an 'a' or "bb" 7 | // c. Each "bb" is followed by nothing or an 'a' 8 | // If all the rules are followed by the given string, return true otherwise return false. 9 | // Sample Input: 10 | // abb 11 | // Sample Output: 12 | // true 13 | 14 | public class Solution { 15 | 16 | public static boolean checkAB(String input) { 17 | // Write your code here 18 | boolean smallAnswer = false; 19 | if (input.length() == 0) { 20 | return true; 21 | } 22 | if (input.length() == 1) { 23 | if (input.charAt(0) == 'a') { 24 | smallAnswer = true; 25 | input = input.substring(1); 26 | } 27 | } else if (input.length() == 2) { 28 | if (input.charAt(0) == 'a' && input.charAt(1) == 'a') { 29 | smallAnswer = true; 30 | input = input.substring(2); 31 | } 32 | } else if (input.length() >= 3) { 33 | if (input.charAt(0) == 'a' && input.substring(1, 3).equals("bb")) { 34 | smallAnswer = true; 35 | input = input.substring(3); 36 | } else if (input.charAt(0) == 'a' && input.charAt(1) == 'a') { 37 | smallAnswer = true; 38 | input = input.substring(1); 39 | } 40 | } 41 | return smallAnswer && checkAB(input); 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Merge Sort Code: -------------------------------------------------------------------------------- 1 | // Merge Sort Code 2 | // Send Feedback 3 | // Sort an array A using Merge Sort. 4 | // Change in the input array itself. So no need to return or print anything. 5 | // Input format : 6 | // Line 1 : Integer n i.e. Array size 7 | // Line 2 : Array elements (separated by space) 8 | // Output format : 9 | // Array elements in increasing order (separated by space) 10 | // Constraints : 11 | // 1 <= n <= 1000 12 | // Sample Input: 13 | // 6 14 | // 2 6 8 5 4 3 15 | // Sample Output: 16 | // 2 3 4 5 6 8 17 | 18 | 19 | public class solution { 20 | 21 | 22 | 23 | public static void merge(int arr[], int start, int mid, int end) 24 | { 25 | // Find sizes of two subarrays to be merged 26 | int n1 = mid - start + 1; 27 | int n2 = end - mid; 28 | 29 | /* Create temp arrays */ 30 | int L[] = new int [n1]; 31 | int R[] = new int [n2]; 32 | 33 | /*Copy data to temp arrays*/ 34 | for (int i=0; i=end) 101 | // {return;} 102 | 103 | // int mid=(start+end)/2; 104 | // mergesort(input,start,mid); 105 | 106 | // mergesort(input,mid+1,end); 107 | // merge(input,start,mid,end); 108 | 109 | // } 110 | 111 | 112 | 113 | public static void mergeSort(int[] input){ 114 | // Write your code here 115 | 116 | int p1=input.length-1; 117 | sort(input,0,p1); 118 | 119 | 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Print Keypad Combinations Code: -------------------------------------------------------------------------------- 1 | // Print Keypad Combinations Code 2 | // Send Feedback 3 | // Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n. 4 | // Note : The order of strings are not important. Just print different strings in new lines. 5 | // Input Format : 6 | // Integer n 7 | // Output Format : 8 | // All possible strings in different lines 9 | // Constraints : 10 | // 1 <= n <= 10^6 11 | // Sample Input: 12 | // 23 13 | // Sample Output: 14 | // ad 15 | // ae 16 | // af 17 | // bd 18 | // be 19 | // bf 20 | // cd 21 | // ce 22 | // cf 23 | 24 | 25 | public class solution { 26 | 27 | 28 | public static String dial(int n) 29 | { 30 | switch(n) 31 | { 32 | case 2: return "abc"; 33 | 34 | case 3: return "def"; 35 | 36 | case 4: return "ghi"; 37 | 38 | case 5: return "jkl"; 39 | 40 | case 6: return "mno"; 41 | 42 | case 7: return "pqrs"; 43 | 44 | case 8: return "tuv"; 45 | 46 | case 9: return "wxyz"; 47 | 48 | default:break; 49 | } 50 | return ""; 51 | } 52 | 53 | 54 | 55 | 56 | 57 | public static void pK(int num,String out) 58 | { 59 | 60 | if(num==0) 61 | { 62 | System.out.println(out); 63 | return; 64 | } 65 | 66 | String pd=dial(num%10); 67 | for(int i=0;i res = new ArrayList<>(); 33 | res=decodeToAlphabet(input); 34 | 35 | for(int i=0;i decodeToAlphabet(String num) { 42 | List res = new ArrayList<>(); 43 | if (num == null || num.length() == 0) { 44 | return res; 45 | } 46 | dfs(num, 0, new StringBuilder(), res); 47 | return res; 48 | } 49 | 50 | private static void dfs(String num, int pos, StringBuilder path, List res) { 51 | if (pos == num.length()) { 52 | res.add(path.toString()); 53 | return; 54 | } 55 | int num1= Integer.valueOf(num.substring(pos, pos + 1)); 56 | path.append((char)('a' + num1 - 1)); 57 | dfs(num, pos + 1, path, res); 58 | path.deleteCharAt(path.length() - 1); 59 | if (pos + 1 < num.length()) { 60 | int num2 = Integer.valueOf(num.substring(pos, pos + 2)); 61 | if (10 <= num2 && num2 <= 26) { 62 | path.append((char)('a' + num2 - 1)); 63 | dfs(num, pos + 2, path, res); 64 | path.deleteCharAt(path.length() - 1); 65 | } 66 | } 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Quick Sort Code: -------------------------------------------------------------------------------- 1 | // Quick Sort Code 2 | // Send Feedback 3 | // Sort an array A using Quick Sort. 4 | // Change in the input array itself. So no need to return or print anything. 5 | // Input format : 6 | // Line 1 : Integer n i.e. Array size 7 | // Line 2 : Array elements (separated by space) 8 | // Output format : 9 | // Array elements in increasing order (separated by space) 10 | // Constraints : 11 | // 1 <= n <= 1000 12 | // Sample Input: 13 | // 6 14 | // 2 6 8 5 4 3 15 | // Sample Output: 16 | // 2 3 4 5 6 8 17 | 18 | 19 | public class Solution { 20 | 21 | public static int partition(int arr[], int low, int high) 22 | { 23 | int pivot = arr[high]; 24 | int i = (low-1); // index of smaller element 25 | for (int j=low; j Array to be sorted, 50 | low --> Starting index, 51 | high --> Ending index */ 52 | public static void sort(int arr[], int low, int high) 53 | { 54 | if (low < high) 55 | { 56 | /* pi is partitioning index, arr[pi] is 57 | now at right place */ 58 | int pi = partition(arr, low, high); 59 | 60 | // Recursively sort elements before 61 | // partition and after partition 62 | sort(arr, low, pi-1); 63 | sort(arr, pi+1, high); 64 | } 65 | } 66 | 67 | 68 | 69 | 70 | public static void quickSort(int[] input) { 71 | /* Your class should be named Solution 72 | * Don't write main(). 73 | * Don't read input, it is passed as function argument. 74 | * No need to print or return the output. 75 | * Taking input and printing output is handled automatically. 76 | */ 77 | int si=0; 78 | int ei=input.length-1; 79 | sort(input,si,ei); 80 | 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Remove Duplicates Recursively: -------------------------------------------------------------------------------- 1 | // Remove Duplicates Recursively 2 | // Send Feedback 3 | // Given a string S, remove consecutive duplicates from it recursively. 4 | // Input Format : 5 | // String S 6 | // Output Format : 7 | // Output string 8 | // Constraints : 9 | // 1 <= Length of String S <= 10^3 10 | // Sample Input : 11 | // aabccba 12 | // Sample Output : 13 | // abcba 14 | 15 | public class Solution { 16 | 17 | public static String removeConsecutiveDuplicates(String s) { 18 | 19 | 20 | public static String removeConsecutiveDuplicates(String s) { 21 | // Write your code here 22 | if(s.length()==1){ 23 | return s; 24 | } 25 | 26 | String ans=""; 27 | if(s.charAt(0) != s.charAt(1)){ 28 | ans=ans+s.charAt(0); 29 | } 30 | 31 | String str1=removeConsecutiveDuplicates(s.substring(1)); 32 | return ans+str1; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Replace Character Recursively: -------------------------------------------------------------------------------- 1 | // Replace Character Recursively 2 | // Send Feedback 3 | // Given an input string S and two characters c1 and c2, you need to 4 | // replace every occurrence of character c1 with character c2 in the given string. 5 | // Do this recursively. 6 | // Input Format : 7 | // Line 1 : Input String S 8 | // Line 2 : Character c1 and c2 (separated by space) 9 | // Output Format : 10 | // Updated string 11 | // Constraints : 12 | // 1 <= Length of String S <= 10^6 13 | // Sample Input : 14 | // abacd 15 | // a x 16 | // Sample Output : 17 | // xbxcd 18 | 19 | 20 | 21 | public class Solution { 22 | 23 | public static String replaceCharacter(String input, char c1, char c2) { 24 | 25 | 26 | if(input.length()==0) 27 | return input; 28 | 29 | String ans=""; 30 | if(input.charAt(0)!=c1) 31 | ans=ans + input.charAt(0); 32 | 33 | if(input.charAt(0)==c1) 34 | ans=ans + c2; 35 | 36 | String smallans=replaceCharacter(input.substring(1),c1,c2); 37 | return ans+smallans; 38 | 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Return Keypad Code: -------------------------------------------------------------------------------- 1 | // Return Keypad Code 2 | // Send Feedback 3 | // Given an integer n, using phone keypad find out all 4 | // the possible strings that can be made using digits of input n. 5 | // Return empty string for numbers 0 and 1. 6 | // Note : The order of strings are not important. 7 | // Input Format : 8 | // Integer n 9 | // Output Format : 10 | // All possible strings in different lines 11 | // Constraints : 12 | // 1 <= n <= 10^6 13 | // Sample Input: 14 | // 23 15 | // Sample Output: 16 | // ad 17 | // ae 18 | // af 19 | // bd 20 | // be 21 | // bf 22 | // cd 23 | // ce 24 | // cf 25 | 26 | 27 | public class solution { 28 | /*returns the string corresponding to an integer*/ 29 | 30 | public static String setOfCharacter(int n) 31 | { 32 | switch(n) 33 | { 34 | case 2: return "abc"; 35 | 36 | case 3: return "def"; 37 | 38 | case 4: return "ghi"; 39 | 40 | case 5: return "jkl"; 41 | 42 | case 6: return "mno"; 43 | 44 | case 7: return "pqrs"; 45 | 46 | case 8: return "tuv"; 47 | 48 | case 9: return "wxyz"; 49 | 50 | default:break; 51 | } 52 | return ""; 53 | } 54 | 55 | 56 | // Return a string array that contains all the possible strings 57 | public static String[] keypad(int n) 58 | { 59 | // Write your code here 60 | if(n<=1) 61 | { 62 | String s[]={""}; 63 | return s; 64 | } 65 | 66 | String prev[]=keypad(n/10); 67 | String actual[]=new String[(int)Math.pow(4.00,count(n))]; 68 | 69 | 70 | String helper=setOfCharacter(n%10); 71 | int k=0; 72 | 73 | for(int j=0;j0) 107 | { 108 | count++; 109 | n=n/10; 110 | } 111 | return count; 112 | } 113 | 114 | 115 | 116 | 117 | 118 | } 119 | -------------------------------------------------------------------------------- /Lecture 4: Recursion 2/Return Permutations - String: -------------------------------------------------------------------------------- 1 | // Return Permutations - String 2 | // Send Feedback 3 | // Given a string S, find and return all the possible permutations of the input string. 4 | // Note 1 : The order of permutations is not important. 5 | // Note 2 : If original string contains duplicate characters, permutations will also be duplicates. 6 | // Input Format : 7 | // String S 8 | // Output Format : 9 | // All permutations (in different lines) 10 | // Sample Input : 11 | // abc 12 | // Sample Output : 13 | // abc 14 | // acb 15 | // bac 16 | // bca 17 | // cab 18 | // cba 19 | 20 | public class solution { 21 | 22 | public static String[] permutationOfString(String input){ 23 | if(input.length()==2){ 24 | String a=input.substring(0,1)+input.substring(1); 25 | String b=input.substring(1)+input.substring(0,1); 26 | String[] arr=new String[]{a,b}; 27 | return arr; 28 | } 29 | 30 | int f=1,c=0; 31 | for(int i=1; i<=input.length(); i++) 32 | f*=i; 33 | 34 | String[] ans=new String[f]; 35 | for(int i=0; i=2){ 41 | String[] ssans=getCode(input.substring(2)); 42 | int l=96+(Integer.parseInt(input.substring(0,2))); 43 | if(l>=97 && l<=122){ 44 | char cc=(char)(l); 45 | String ss=String.valueOf(cc); 46 | String[] arr=new String[sans.length+ssans.length]; 47 | int i,k=0; 48 | for(i=0; i arr[i]) 38 | { 39 | min = arr[i]; 40 | min_index = i; 41 | } 42 | } 43 | return min_index; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Lecture 5: Time and Space Complexity Analysis/Duplicate in array: -------------------------------------------------------------------------------- 1 | // Duplicate in array 2 | // Send Feedback 3 | // Given an array of integers of size n which contains numbers from 0 to n - 2. Each number is present at least once. That is, if n = 5, numbers from 0 to 3 is present in the given array at least once and one number is present twice. You need to find and return that duplicate number present in the array. 4 | // Assume, duplicate number is always present in the array. 5 | // Input format : 6 | // Line 1 : Size of input array 7 | // Line 2 : Array elements (separated by space) 8 | // Output Format : 9 | // Duplicate element 10 | // Constraints : 11 | // 1 <= n <= 10^6 12 | // Sample Input: 13 | // 9 14 | // 0 7 2 5 4 7 1 3 6 15 | // Sample Output: 16 | // 7 17 | 18 | public class DuplicateInArray{ 19 | 20 | public static int duplicate(int[] arr){ 21 | /* Your class should be named DuplicateInArray 22 | * Don't write main(). 23 | * Don't read input, it is passed as function argument. 24 | * Return output and don't print it. 25 | * Taking input and printing output is handled automatically. 26 | */ 27 | 28 | int res = 0; 29 | int n=arr.length-1; 30 | for (int i = 0; i < n ; i++) 31 | { res = res ^ i; 32 | res=res ^ arr[i]; 33 | } 34 | res = res ^ arr[n]; 35 | 36 | return res; 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Lecture 5: Time and Space Complexity Analysis/Find the Unique Element: -------------------------------------------------------------------------------- 1 | // Find the Unique Element 2 | // Send Feedback 3 | // Given an integer array of size 2N + 1. In this given array, N numbers are present twice and one number is present only once in the array. 4 | // You need to find and return that number which is unique in the array. 5 | // Note : Given array will always contain odd number of elements. 6 | // Input format : 7 | // Line 1 : Array size i.e. 2N+1 8 | // Line 2 : Array elements (separated by space) 9 | // Output Format : 10 | // Unique element present in the array 11 | // Constraints : 12 | // 1 <= N <= 10^6 13 | // Sample Input : 14 | // 7 15 | // 2 3 1 6 3 6 2 16 | // Sample Output : 17 | // 1 18 | 19 | public class FindUnique{ 20 | 21 | public static int findUnique(int[] arr){ 22 | /* Your class should be named FindUnique 23 | * Don't write main(). 24 | * Don't read input, it is passed as function argument. 25 | * Return output and don't print it. 26 | * Taking input and printing output is handled automatically. 27 | */ 28 | 29 | 30 | int res = 0; 31 | int n=arr.length-1; 32 | for (int i = 0; i <= n ; i++) 33 | { 34 | res=res ^ arr[i]; 35 | } 36 | 37 | 38 | return res; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Lecture 5: Time and Space Complexity Analysis/Pair sum in array: -------------------------------------------------------------------------------- 1 | // Pair sum in array 2 | // Send Feedback 3 | // Given a random integer array A and a number x. Find and print the pair of elements in the array which sum to x. 4 | // Array A can contain duplicate elements. 5 | // While printing a pair, print the smaller element first. 6 | // That is, if a valid pair is (6, 5) print "5 6". There is no constraint that out of 5 pairs which have to be printed in 1st line. You can print pairs in any order, just be careful about the order of elements in a pair. 7 | // Input format : 8 | // Line 1 : Integer N (Array size) 9 | // Line 2 : Array elements (separated by space) 10 | // Line 3 : Integer x 11 | // Output format : 12 | // Line 1 : Pair 1 elements (separated by space) 13 | // Line 2 : Pair 2 elements (separated by space) 14 | // Line 3 : and so on 15 | // Constraints : 16 | // 1 <= N <= 1000 17 | // 1 <= x <= 100 18 | // Sample Input: 19 | // 9 20 | // 1 3 6 2 5 4 3 2 4 21 | // 7 22 | // Sample Output : 23 | // 1 6 24 | // 3 4 25 | // 3 4 26 | // 2 5 27 | // 2 5 28 | // 3 4 29 | // 3 4 30 | 31 | 32 | public class PairSum{ 33 | 34 | public static void pairSum(int[] input, int x){ 35 | /* Your class should be named PairSum 36 | * Don't write main(). 37 | * Don't read input, it is passed as function argument. 38 | * Print output and don't return it. 39 | * Taking input is handled automatically. 40 | */ 41 | 42 | for(int i=0;iarr[j]) 44 | {int temp; 45 | temp=arr[j]; 46 | arr[j]=arr[i]; 47 | arr[i]=temp;} 48 | } 49 | } 50 | 51 | System.out.println(arr[0]+" "+arr[1]+" "+arr[2]); 52 | } 53 | 54 | 55 | public static void FindTriplet(int[] input, int x){ 56 | /* Your class should be named TripletSum. 57 | * Don't write main(). 58 | * Don't read input, it is passed as function argument. 59 | * Print output and don't return it. 60 | * Taking input is handled automatically. 61 | */ 62 | for(int i=0;i { 19 | public T data; 20 | public LinkedListNode next; 21 | 22 | public LinkedListNode(T data) { 23 | this.setData(data); 24 | this.next = null; 25 | } 26 | 27 | public T getData() { 28 | return data; 29 | } 30 | 31 | public void setData(T data) { 32 | this.data = data; 33 | } 34 | 35 | } 36 | * */ 37 | public class Solution { 38 | 39 | public static int LengthIterative(LinkedListNode head){ 40 | int count=0; 41 | while(head!=null) 42 | { 43 | count++; 44 | head=head.next; 45 | } 46 | return count; 47 | } 48 | 49 | 50 | public static LinkedListNode append(LinkedListNode head, int n) { 51 | 52 | LinkedListNode temp1=head; 53 | LinkedListNode temp2=head; 54 | int length=LengthIterative(head); 55 | int i=0; 56 | while(i tempHead=head; 64 | while(tempHead.next!=null) 65 | { 66 | tempHead=tempHead.next; 67 | } 68 | tempHead.next=temp2; 69 | return head; 70 | 71 | 72 | 73 | 74 | 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Lecture 7: Linked List 1/Delete Node in LL: -------------------------------------------------------------------------------- 1 | // Delete Node in LL 2 | // Send Feedback 3 | // Given a linked list and a position i, delete the node of ith position from Linked List iteratively. 4 | // If position i is greater than length of LL, then you should return the same LL without any change. 5 | // Indexing starts from 0. You don't need to print the elements, just delete the node and return the head of updated LL. 6 | // Input format : 7 | // Line 1 : Linked list elements (separated by space and terminated by -1) 8 | // Line 2 : Integer i (position) 9 | // Output format : 10 | // Updated LL elements (separated by space) 11 | // Sample Input 1 : 12 | // 3 4 5 2 6 1 9 -1 13 | // 3 14 | // Sample Output 1 : 15 | // 3 4 5 6 1 9 16 | // Sample Input 2 : 17 | // 3 4 5 2 6 1 9 -1 18 | // 0 19 | // Sample Output 2 : 20 | // 4 5 2 6 1 9 21 | 22 | /*************** 23 | * Following is the Node class already written 24 | class LinkedListNode { 25 | T data; 26 | LinkedListNode next; 27 | 28 | public Node(T data) { 29 | this.data = data; 30 | } 31 | } 32 | ***************/ 33 | 34 | public class Solution { 35 | 36 | public static LinkedListNode deleteIthNode(LinkedListNode head, int i){ 37 | /* Your class should be named Solution 38 | * Don't write main(). 39 | * Don't read input, it is passed as function argument. 40 | * Return output and don't print it. 41 | * Taking input and printing output is handled automatically. 42 | */LinkedListNode temp=head; 43 | int counter=0; 44 | while(head!=null) 45 | {head=head.next; 46 | counter++;} 47 | 48 | head=temp; 49 | 50 | //if element present at Zeroth index 51 | 52 | if(i==0){ 53 | head=head.next; 54 | //return head; 55 | } 56 | 57 | //if element is present inbetween 58 | if(i1){ 61 | head=head.next; 62 | i--; 63 | } 64 | 65 | head.next=head.next.next; 66 | head=temp; 67 | //return head; 68 | 69 | } 70 | //if element is present at last 71 | if(i==counter){ 72 | while(i>1){ 73 | head=head.next; 74 | i--; 75 | } 76 | head.next=null; 77 | head=temp; 78 | } 79 | 80 | return head; 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Lecture 7: Linked List 1/Eliminate duplicates from LL: -------------------------------------------------------------------------------- 1 | // Eliminate duplicates from LL 2 | // Send Feedback 3 | // Given a sorted linked list (elements are sorted in ascending order). 4 | // Eliminate duplicates from the given LL, such that output LL contains only unique elements. 5 | // You don't need to print the elements, just remove duplicates and return the head of updated LL. 6 | // Input format : Linked list elements (separated by space and terminated by -1) 7 | 8 | // Sample Input 1 : 9 | // 1 2 3 3 3 4 4 5 5 5 7 -1 10 | // Sample Output 1 : 11 | // 1 2 3 4 5 7 12 | 13 | /* 14 | class LinkedListNode { 15 | public T data; 16 | public LinkedListNode next; 17 | 18 | public LinkedListNode(T data) { 19 | this.setData(data); 20 | this.next = null; 21 | } 22 | 23 | public T getData() { 24 | return data; 25 | } 26 | 27 | public void setData(T data) { 28 | this.data = data; 29 | } 30 | 31 | } 32 | * */ 33 | 34 | public class Solution { 35 | public static LinkedListNode removeDuplicates(LinkedListNode head) 36 | { 37 | 38 | if(head==null || head.next==null) 39 | return head; 40 | 41 | LinkedListNode pivot1=head; 42 | 43 | 44 | 45 | while(pivot1.next!=null) 46 | { 47 | if(pivot1.getData().equals(pivot1.next.getData())) 48 | { 49 | pivot1.next=pivot1.next.next; 50 | 51 | } 52 | else{ 53 | pivot1=pivot1.next; 54 | 55 | 56 | } 57 | } 58 | 59 | return head; 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Lecture 7: Linked List 1/Find a node in LL: -------------------------------------------------------------------------------- 1 | // Find a node in LL 2 | // Send Feedback 3 | // Given a linked list and an integer n you need to find and return index where n is present in the LL. Do this iteratively. 4 | // Return -1 if n is not present in the LL. 5 | // Indexing of nodes starts from 0. 6 | // Input format : 7 | // Line 1 : Linked list elements (separated by space and terminated by -1) 8 | // Line 2 : Integer n 9 | // Output format : 10 | // Index 11 | // Sample Input 1 : 12 | // 3 4 5 2 6 1 9 -1 13 | // 5 14 | // Sample Output 1 : 15 | // 2 16 | // Sample Input 2 : 17 | // 3 4 5 2 6 1 9 -1 18 | // 6 19 | // Sample Output 2 : 20 | // 4 21 | 22 | 23 | /*************** 24 | * Following is the Node class already written 25 | class LinkedListNode { 26 | T data; 27 | LinkedListNode next; 28 | 29 | public Node(T data) { 30 | this.data = data; 31 | } 32 | } 33 | ***************/ 34 | 35 | public class Solution { 36 | public static int indexOfNIter(LinkedListNode head, int n) { 37 | /* Your class should be named Solution 38 | * Don't write main(). 39 | * Don't read input, it is passed as function argument. 40 | * Return output and don't print it. 41 | * Taking input and printing output is handled automatically. 42 | */ 43 | 44 | LinkedListNode temp=head; 45 | int counter=0; 46 | while(head.data!=n) 47 | { 48 | if(head.next==null) 49 | return -1; 50 | 51 | head=head.next; 52 | counter++;} 53 | 54 | 55 | 56 | return counter; 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Lecture 7: Linked List 1/Length of LL: -------------------------------------------------------------------------------- 1 | // Length of LL 2 | // Send Feedback 3 | // Given a linked list, find and return the length of input LL. Do it iteratively. 4 | // Input format : 5 | // Linked list elements (separated by space and terminated by -1) 6 | // Output format : 7 | // Length of LL 8 | // Sample Input : 9 | // 3 4 5 2 6 1 9 -1 10 | // Sample Output : 11 | // 7 12 | 13 | 14 | 15 | 16 | /*************** 17 | * Following is the Node class already written 18 | class LinkedListNode { 19 | T data; 20 | LinkedListNode next; 21 | 22 | public LinkedListNode(T data) { 23 | this.data = data; 24 | } 25 | } 26 | ***************/ 27 | 28 | public class Solution { 29 | 30 | public static int length(LinkedListNode head){ 31 | /* Your class should be named Solution 32 | * Don't write main(). 33 | * Don't read input, it is passed as function argument. 34 | * Return output and don't print it. 35 | * Taking input and printing output is handled automatically. 36 | */ 37 | int counter=0; 38 | while(head!=null) 39 | {head=head.next; 40 | counter++;} 41 | 42 | return counter; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Lecture 7: Linked List 1/Palindrome LinkedList: -------------------------------------------------------------------------------- 1 | // Palindrome LinkedList 2 | // Send Feedback 3 | // Check if a given linked list is palindrome or not. Return true or false. 4 | // Indexing starts from 0. 5 | // Input format : Linked list elements (separated by space and terminated by -1) 6 | 7 | // Sample Input 1 : 8 | // 9 2 3 3 2 9 -1 9 | // Sample Output 1 : 10 | // true 11 | // Sample Input 2 : 12 | // 0 2 3 2 5 -1 13 | // Sample Output 2 : 14 | // false 15 | import java.util.*; 16 | /* 17 | class LinkedListNode { 18 | public T data; 19 | public LinkedListNode next; 20 | 21 | public LinkedListNode(T data) { 22 | this.setData(data); 23 | this.next = null; 24 | } 25 | 26 | public T getData() { 27 | return data; 28 | } 29 | 30 | public void setData(T data) { 31 | this.data = data; 32 | } 33 | 34 | } 35 | * */ 36 | public class Solution { 37 | public static int LengthIterative(LinkedListNode head){ 38 | int count=0; 39 | while(head!=null) 40 | { 41 | count++; 42 | head=head.next; 43 | } 44 | return count; 45 | } 46 | 47 | 48 | public static boolean isPalindrome_2(LinkedListNode root) { 49 | 50 | int length=LengthIterative(root); 51 | ArrayList list1=new ArrayList(length); 52 | for(int i=0;i { 26 | T data; 27 | LinkedListNode next; 28 | 29 | public Node(T data) { 30 | this.data = data; 31 | } 32 | } 33 | ***************/ 34 | 35 | public class Solution { 36 | 37 | public static void printIth(LinkedListNode head, int i){ 38 | /* Your class should be named Solution 39 | * Don't write main(). 40 | * Don't read input, it is passed as function argument. 41 | * Print output and don't return it. 42 | * Taking input is handled automatically. 43 | */ 44 | 45 | for(int j=0;j<=i && head!= null;j++) 46 | { if(j==i) 47 | System.out.println(head.data); 48 | head=head.next; 49 | } 50 | 51 | 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Lecture 7: Linked List 1/Print reverse LinkedList: -------------------------------------------------------------------------------- 1 | // Print reverse LinkedList 2 | // Send Feedback 3 | // Print a given linked list in reverse order. You need to print the tail first and head last. You can’t change any pointer in the linked list, just print it in reverse order. 4 | // Input format : Linked List elements (separated by space and terminated by -1) 5 | 6 | // Output format : Linked List elements in reverse order (separated by space) 7 | 8 | // Sample Input 1 : 9 | // 1 2 3 4 5 -1 10 | // Sample Output 1 : 11 | // 5 4 3 2 1 12 | // Sample Input 2 : 13 | // 1 2 3 -1 14 | // Sample Output 2 : 15 | // 3 2 1 16 | 17 | 18 | import java.util.*; 19 | /* 20 | class LinkedListNode { 21 | public T data; 22 | public LinkedListNode next; 23 | 24 | public LinkedListNode(T data) { 25 | this.setData(data); 26 | this.next = null; 27 | } 28 | 29 | public T getData() { 30 | return data; 31 | } 32 | 33 | public void setData(T data) { 34 | this.data = data; 35 | } 36 | 37 | } 38 | * */ 39 | public class Solution { 40 | 41 | public static int LengthIterative(LinkedListNode head){ 42 | int count=0; 43 | while(head!=null) 44 | { 45 | count++; 46 | head=head.next; 47 | } 48 | return count; 49 | } 50 | 51 | public static void printReverseRecursive(LinkedListNode root) { 52 | int length=LengthIterative(root); 53 | ArrayList list1=new ArrayList(length); 54 | for(int i=0;i=0;i--) 60 | { 61 | System.out.print(list1.get(i)+" "); 62 | 63 | } 64 | //ArrayList list=new ArrayList() 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Bubble Sort (Iterative) LinkedList: -------------------------------------------------------------------------------- 1 | // Bubble Sort (Iterative) LinkedList 2 | // Send Feedback 3 | // Sort a given linked list using Bubble Sort (iteratively). While sorting, you need to swap just the data. 4 | // You don't need to print the elements, just sort the elements and return the head of updated LL. 5 | // Input format : Linked list elements (separated by space and terminated by -1)` 6 | 7 | // Sample Input 1 : 8 | // 1 4 5 2 -1 9 | // Sample Output 1 : 10 | // 1 2 4 5 11 | 12 | 13 | public class Solution { 14 | 15 | 16 | 17 | public static LinkedListNode bubbleSort(LinkedListNode head ) 18 | { 19 | //Write your code here 20 | 21 | 22 | LinkedListNode current = head, index = null; 23 | int temp; 24 | 25 | if(head == null) { 26 | return head; 27 | } 28 | else 29 | { 30 | while(current != null) 31 | { 32 | //Node index will point to node next to current 33 | index = current.next; 34 | 35 | while(index != null) 36 | { 37 | //If current node's data is greater than index's node data, swap the data between them 38 | if(current.data > index.data) 39 | { 40 | temp = current.data; 41 | current.data = index.data; 42 | index.data = temp; 43 | } 44 | index = index.next; 45 | } 46 | current = current.next; 47 | } 48 | 49 | } return head; 50 | 51 | } 52 | 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Code : Merge Sort: -------------------------------------------------------------------------------- 1 | // Code : Merge Sort 2 | // Send Feedback 3 | // Sort a given linked list using Merge Sort. 4 | // You don't need to print the elements, just sort the elements and return the head of updated LL. 5 | // Input format : 6 | // Linked list elements (separated by space and terminated by -1) 7 | // Output format : 8 | // Updated LL elements (separated by space) 9 | // Constraints : 10 | // 1 <= Length of LL <= 1000 11 | // Sample Input 1 : 12 | // 1 4 5 2 -1 13 | // Sample Output 1 : 14 | // 1 2 4 5 15 | public class Solution { 16 | 17 | public static LinkedListNode mid(LinkedListNodehead) 18 | { 19 | LinkedListNodefast=head.next; 20 | LinkedListNodeslow=head; 21 | while(fast!=null&&fast.next!=null) 22 | { 23 | fast=fast.next.next; 24 | slow=slow.next; 25 | } 26 | return slow; //slow will always point to the left mid in case of even no. of nodes in the linked list 27 | 28 | } 29 | public static LinkedListNode mergeSortedLL(LinkedListNodefirstHead,LinkedListNodesecondHead){ 30 | LinkedListNodenewHead=null; 31 | LinkedListNodesorting=null; 32 | if(firstHead==null) 33 | return secondHead; 34 | else 35 | if(secondHead==null) 36 | return firstHead; 37 | else 38 | { 39 | if(firstHead.data<=secondHead.data) 40 | { 41 | sorting=firstHead; 42 | firstHead=firstHead.next; 43 | } 44 | else 45 | { 46 | sorting=secondHead; 47 | secondHead=secondHead.next; 48 | } 49 | newHead=sorting; 50 | while(firstHead!=null&&secondHead!=null) 51 | { 52 | if(firstHead.data<=secondHead.data) 53 | { 54 | sorting.next=firstHead; 55 | sorting=firstHead; 56 | firstHead=firstHead.next; 57 | } 58 | else 59 | { 60 | sorting.next=secondHead; 61 | sorting=secondHead; 62 | secondHead=secondHead.next; 63 | } 64 | } 65 | if(firstHead==null) 66 | { 67 | sorting.next=secondHead; 68 | } 69 | else if(secondHead==null) 70 | { 71 | sorting.next=firstHead; 72 | 73 | } 74 | return newHead; 75 | 76 | 77 | } 78 | } 79 | public static LinkedListNode mergeSort(LinkedListNode head) { 80 | if(head==null||head.next==null) 81 | { 82 | return head; 83 | } 84 | //do not use the list splitting method used in palindrome since the middle node will be lost; 85 | LinkedListNodemid=mid(head); 86 | LinkedListNodefirstHalfTail=mid; 87 | LinkedListNodesecondHalfHead=mid.next; 88 | firstHalfTail.next=null; 89 | LinkedListNodehead1=mergeSort(head); 90 | LinkedListNodehead2=mergeSort(secondHalfHead); 91 | LinkedListNodemergedListHead=mergeSortedLL(head1, head2); 92 | return mergedListHead; 93 | 94 | 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Code: Midpoint of the linked list: -------------------------------------------------------------------------------- 1 | // Code : Midpoint of Linked list 2 | // Send Feedback 3 | // Given a linked list, find and return the midpoint. 4 | // If the length of linked list is even, return the first mid point. 5 | // Input format : Linked list elements (separated by space and terminated by -1)` 6 | 7 | // Sample Input 1 : 8 | // 1 2 3 4 5 -1 9 | // Sample Output 1 : 10 | // 3 11 | // Sample Input 2 : 12 | // 1 2 3 4 -1 13 | // Sample Output 2 : 14 | // 2 15 | 16 | 17 | /* 18 | class LinkedListNode { 19 | public T data; 20 | public LinkedListNode next; 21 | 22 | public LinkedListNode(T data) { 23 | this.setData(data); 24 | this.next = null; 25 | } 26 | 27 | public T getData() { 28 | return data; 29 | } 30 | 31 | public void setData(T data) { 32 | this.data = data; 33 | } 34 | 35 | } 36 | * */ 37 | public class Solution { 38 | public static int printMiddel(LinkedListNode head) { 39 | 40 | if(head.next==null) 41 | return head.data; 42 | 43 | LinkedListNode slow=head; 44 | 45 | LinkedListNode fast=head; 46 | 47 | while(fast.next.next!=null && fast.next!=null) 48 | {slow=slow.next; 49 | fast=fast.next.next; 50 | } 51 | return slow.data; 52 | 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Delete every N nodes: -------------------------------------------------------------------------------- 1 | // Delete every N nodes 2 | // Send Feedback 3 | // Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same until end of the linked list. That is, in the given linked list you need to delete N nodes after every M nodes. 4 | // Input format : 5 | 6 | // Line 1 : Linked list elements (separated by space and terminated by -1) 7 | 8 | // Line 2 : M 9 | 10 | // Line 3 : N 11 | 12 | // Sample Input 1 : 13 | // 1 2 3 4 5 6 7 8 -1 14 | // 2 15 | // 2 16 | // Sample Output 1 : 17 | // 1 2 5 6 18 | // Sample Input 2 : 19 | // 1 2 3 4 5 6 7 8 -1 20 | // 2 21 | // 3 22 | // Sample Output 2 : 23 | // 1 2 6 7 24 | 25 | 26 | /* 27 | class LinkedListNode { 28 | public T data; 29 | public LinkedListNode next; 30 | 31 | public LinkedListNode(T data) { 32 | this.setData(data); 33 | this.next = null; 34 | } 35 | 36 | public T getData() { 37 | return data; 38 | } 39 | 40 | public void setData(T data) { 41 | this.data = data; 42 | } 43 | 44 | } 45 | * */ 46 | public class solution { 47 | public static LinkedListNode skipMdeleteN(LinkedListNode head, int M, int N) { 48 | 49 | if(M==0) 50 | return null; 51 | 52 | 53 | LinkedListNode curr = head, rem; 54 | int count; 55 | //Move M nodes and delete N nodes 56 | while(curr!=null) 57 | { 58 | for (count = 1; count temp = rem; 70 | rem = rem.next; 71 | 72 | } 73 | //link to remaining nodes 74 | //continue iteration for the remaining nodes 75 | curr.next = rem; 76 | curr = rem; 77 | } 78 | return head; 79 | } 80 | 81 | } 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Delete node (recursive): -------------------------------------------------------------------------------- 1 | // Delete node (recursive) 2 | // Send Feedback 3 | // Given a linked list and a position i, delete the node of ith position from Linked List recursively. 4 | // If position i is greater than length of LL, then you should return the same LL without any change. 5 | // Indexing starts from 0. You don't need to print the elements, just delete the node and return the head of updated LL. 6 | // Input format : 7 | // Line 1 : Linked list elements (separated by space and terminated by -1) 8 | // Line 2 : Integer i (position) 9 | // Output format : 10 | // Updated LL elements (separated by space) 11 | // Sample Input 1 : 12 | // 3 4 5 2 6 1 9 -1 13 | // 3 14 | // Sample Output 1 : 15 | // 3 4 5 6 1 9 16 | // Sample Input 2 : 17 | // 3 4 5 2 6 1 9 -1 18 | // 0 19 | // Sample Output 2 : 20 | // 4 5 2 6 1 9 21 | 22 | 23 | /*************** 24 | * Following is the Node class already written 25 | class LinkedListNode { 26 | T data; 27 | LinkedListNode next; 28 | 29 | public Node(T data) { 30 | this.data = data; 31 | } 32 | } 33 | ***************/ 34 | 35 | public class Solution { 36 | 37 | public static LinkedListNode deleteIthNodeRec(LinkedListNode head, int i){ 38 | /* Your class should be named Solution 39 | * Don't write main(). 40 | * Don't read input, it is passed as function argument. 41 | * Return output and don't print it. 42 | * Taking input and printing output is handled automatically. 43 | */ 44 | 45 | if(head==null) 46 | return null; 47 | 48 | if (i == 0){ return head.next; } 49 | head.next = deleteIthNodeRec(head.next, i-1); 50 | return head; 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Even after Odd LinkedList: -------------------------------------------------------------------------------- 1 | // Even after Odd LinkedList 2 | // Send Feedback 3 | // Arrange elements in a given Linked List such that, all even numbers are placed after odd numbers. Respective order of elements should remain same. 4 | // Note: Input and Output has already managed for you. You don't need to print the elements, instead return the head of updated LL. 5 | // Input format: 6 | // Linked list elements (separated by space and terminated by -1) 7 | // Output format: 8 | // Print the elements of updated Linked list. 9 | // Sample Input 1 : 10 | // 1 4 5 2 -1 11 | // Sample Output 1 : 12 | // 1 5 4 2 13 | // Sample Input 2 : 14 | // 1 11 3 6 8 0 9 -1 15 | // Sample Output 2 : 16 | // 1 11 3 9 6 8 0 17 | /* 18 | class LinkedListNode { 19 | public T data; 20 | public LinkedListNode next; 21 | 22 | public LinkedListNode(T data) { 23 | this.setData(data); 24 | this.next = null; 25 | } 26 | 27 | 28 | 29 | } 30 | * */ 31 | public class Solution { 32 | 33 | 34 | 35 | 36 | public static LinkedListNode sortEvenOdd(LinkedListNode head) { 37 | LinkedListNode odd = null, oddTail = null; 38 | LinkedListNode even = null, evenTail = null; 39 | LinkedListNode curr = head; 40 | 41 | while (curr != null) 42 | { 43 | if ((curr.data & 1) == 0) // current node is even 44 | { 45 | // handle head for first odd node 46 | if (odd == null) { 47 | odd = oddTail = curr; 48 | } 49 | else 50 | { 51 | oddTail.next = curr; 52 | oddTail = oddTail.next; 53 | } 54 | } 55 | else // current node is odd 56 | { 57 | // handle head for first even node 58 | if (even == null) { 59 | even = evenTail = curr; 60 | } 61 | else 62 | { 63 | evenTail.next = curr; 64 | evenTail = curr; 65 | } 66 | } 67 | curr = curr.next; 68 | } 69 | 70 | // if list contains at-least one even node 71 | if (even != null) 72 | { 73 | head = even; 74 | evenTail.next = odd; 75 | } 76 | // special case - list contains all odd nodes 77 | else { 78 | head = odd; 79 | } 80 | 81 | // null to terminate the list, 82 | // else it will go in infinite loop 83 | if (oddTail != null) { 84 | oddTail.next = null; 85 | } 86 | 87 | return head; 88 | } 89 | } 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Find a node in LL (recursive): -------------------------------------------------------------------------------- 1 | // Find a node in LL (recursive) 2 | // Send Feedback 3 | // Given a linked list and an integer n you need to find and return index where n is present in the LL. Do this recursively. 4 | // Return -1 if n is not present in the LL. 5 | // Indexing of nodes starts from 0. 6 | // Input format : 7 | // Line 1 : Linked list elements (separated by space and terminated by -1) 8 | // Line 2 : Integer n 9 | // Output format : 10 | // Index 11 | // Sample Input 1 : 12 | // 3 4 5 2 6 1 9 -1 13 | // 5 14 | // Sample Output 1 : 15 | // 2 16 | // Sample Input 2 : 17 | // 3 4 5 2 6 1 9 -1 18 | // 6 19 | // Sample Output 2 : 20 | // 4 21 | 22 | /*************** 23 | * Following is the Node class already written 24 | class LinkedListNode { 25 | T data; 26 | LinkedListNode next; 27 | 28 | public Node(T data) { 29 | this.data = data; 30 | } 31 | } 32 | ***************/ 33 | 34 | public class Solution { 35 | public static int i=0; 36 | public static int indexOfNRec(LinkedListNode head, int n) { 37 | /* Your class should be named Solution 38 | * Don't write main(). 39 | * Don't read input, it is passed as function argument. 40 | * Return output and don't print it. 41 | * Taking input and printing output is handled automatically. 42 | */ 43 | 44 | if(head==null ) 45 | return -1; 46 | 47 | if(head.data==n) 48 | return i; 49 | 50 | i++; 51 | return indexOfNRec(head.next,n); 52 | // return i; 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Merge two sorted LL: -------------------------------------------------------------------------------- 1 | /*************** 2 | Code : Merge two sorted LL 3 | Send Feedback 4 | Given two linked lists sorted in increasing order. Merge them in such a way that the result list is also sorted (in increasing order). 5 | Try solving with O(1) auxiliary space (in-place). You just need to return the head of new linked list, don't print the elements. 6 | Input format : 7 | Line 1 : Linked list 1 elements of length n (separated by space and terminated by -1) 8 | Line 2 : Linked list 2 elements of length m (separated by space and terminated by -1) 9 | Output format : 10 | Merged list elements (separated by space) 11 | Constraints : 12 | 1 <= n, m <= 10^4 13 | Sample Input : 14 | 2 5 8 12 -1 15 | 3 6 9 -1 16 | Sample Output : 17 | 2 3 5 6 8 9 12 18 | 19 | * Following is the Node class already written 20 | class LinkedListNode { 21 | T data; 22 | LinkedListNode next; 23 | 24 | public Node(T data) { 25 | this.data = data; 26 | } 27 | } 28 | ***************/ 29 | 30 | public class Solution { 31 | 32 | public static LinkedListNode mergeTwoList(LinkedListNode head1, LinkedListNode head2) { 33 | /* Your class should be named Solution 34 | * Don't write main(). 35 | * Don't read input, it is passed as function argument. 36 | * Return output and don't print it. 37 | * Taking input and printing output is handled automatically. 38 | */ 39 | LinkedListNode temp,header1,header2,head3; 40 | header1=head1; 41 | header2=head2; 42 | if(header1.data<=header2.data){ 43 | head3=header1; 44 | temp=head1; 45 | head1=head1.next; 46 | temp.next=null; 47 | }else{ 48 | head3=header2; 49 | temp=head2; 50 | head2=head2.next; 51 | temp.next=null; 52 | } 53 | while(head1!=null && head2!=null){ 54 | if(head1.data<=head2.data){ 55 | temp.next=head1; 56 | temp=head1; 57 | head1=head1.next; 58 | temp.next=null; 59 | }else{ 60 | temp.next=head2; 61 | temp=head2; 62 | head2=head2.next; 63 | temp.next=null; 64 | } 65 | } 66 | if(head1!=null){ 67 | temp.next=head1; 68 | } 69 | if(head2!=null){ 70 | temp.next=head2; 71 | } 72 | return head3; 73 | } 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Reverse LL (Iterative): -------------------------------------------------------------------------------- 1 | // Reverse LL (Iterative) 2 | // Send Feedback 3 | // Given a linked list, reverse it iteratively. 4 | // You don't need to print the elements, just reverse the LL duplicates and return the head of updated LL. 5 | // Input format : Linked list elements (separated by space and terminated by -1)` 6 | 7 | // Sample Input 1 : 8 | // 1 2 3 4 5 -1 9 | // Sample Output 1 : 10 | // 5 4 3 2 1 11 | /* 12 | class LinkedListNode { 13 | public T data; 14 | public LinkedListNode next; 15 | 16 | public LinkedListNode(T data) { 17 | this.setData(data); 18 | this.next = null; 19 | } 20 | 21 | public T getData() { 22 | return data; 23 | } 24 | 25 | public void setData(T data) { 26 | this.data = data; 27 | } 28 | 29 | } 30 | * */ 31 | public class Solution { 32 | public static LinkedListNode reverse_I(LinkedListNode head) { 33 | 34 | LinkedListNode curr =head; 35 | 36 | LinkedListNode prev=null; 37 | LinkedListNode temp; 38 | 39 | while(curr!=null) 40 | { 41 | temp=curr.next; 42 | curr.next=prev; 43 | prev=curr; 44 | curr=temp; 45 | } 46 | 47 | return prev; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Reverse LL (Recursive): -------------------------------------------------------------------------------- 1 | 2 | // Reverse LL (Recursive) 3 | // Send Feedback 4 | // Given a linked list, reverse it using recursion. 5 | // You don't need to print the elements, just reverse the LL duplicates and return the head of updated LL. 6 | // Input format : Linked list elements (separated by space and terminated by -1)` 7 | 8 | // Sample Input 1 : 9 | // 1 2 3 4 5 -1 10 | // Sample Output 1 : 11 | // 5 4 3 2 1 12 | 13 | /* 14 | class LinkedListNode { 15 | public T data; 16 | public LinkedListNode next; 17 | 18 | public LinkedListNode(T data) { 19 | this.setData(data); 20 | this.next = null; 21 | } 22 | 23 | public T getData() { 24 | return data; 25 | } 26 | 27 | public void setData(T data) { 28 | this.data = data; 29 | } 30 | 31 | } 32 | * */ 33 | public class Solution { 34 | 35 | public static LinkedListNode reverse_R(LinkedListNode head) { 36 | 37 | if(head==null || head.next==null) 38 | return head; 39 | 40 | 41 | 42 | LinkedListNode final_head= reverse_R(head.next); 43 | LinkedListNode temp=final_head; 44 | while(temp.next!=null) 45 | { 46 | temp=temp.next; 47 | } 48 | temp.next=head; 49 | head.next=null; 50 | 51 | return final_head; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/Swap two Node of LL: -------------------------------------------------------------------------------- 1 | // Swap two Node of LL 2 | // Send Feedback 3 | // Given a linked list, i & j, swap the nodes that are present at i & j position in the LL. You need to swap the entire nodes, not just the data. 4 | // Indexing starts from 0. You don't need to print the elements, just swap and return the head of updated LL. 5 | // Assume i & j given will be within limits. And i can be greater than j also. 6 | // Input format : 7 | 8 | // Line 1 : Linked list elements (separated by space and terminated by -1) 9 | 10 | // Line 2 : i and j (separated by space) 11 | 12 | // Sample Input 1 : 13 | // 3 4 5 2 6 1 9 -1 14 | // 3 4 15 | // Sample Output 1 : 16 | // 3 4 5 6 2 1 9 17 | // Sample Input 2 : 18 | // 3 4 5 2 6 1 9 -1 19 | // 2 4 20 | // Sample Output 2 : 21 | // 3 4 6 2 5 1 9 22 | 23 | 24 | /* 25 | class LinkedListNode { 26 | public T data; 27 | public LinkedListNode next; 28 | 29 | public LinkedListNode(T data) { 30 | this.setData(data); 31 | this.next = null; 32 | } 33 | 34 | public T getData() { 35 | return data; 36 | } 37 | 38 | public void setData(T data) { 39 | this.data = data; 40 | } 41 | 42 | } 43 | * */ 44 | public class Solution { 45 | public static LinkedListNode swap_nodes(LinkedListNode head,int i,int j){ 46 | LinkedListNode temp1=head; 47 | LinkedListNode node1=head; 48 | LinkedListNode node2=head; 49 | 50 | for(int a=0;a { 31 | public T data; 32 | public LinkedListNode next; 33 | 34 | public LinkedListNode(T data) { 35 | this.setData(data); 36 | this.next = null; 37 | } 38 | 39 | public T getData() { 40 | return data; 41 | } 42 | 43 | public void setData(T data) { 44 | this.data = data; 45 | } 46 | 47 | } 48 | * */ 49 | public class Solution { 50 | public static LinkedListNode kReverse(LinkedListNode head, int k) { 51 | 52 | LinkedListNode current =head; 53 | 54 | LinkedListNode prev=null; 55 | LinkedListNode next=null; 56 | int count = 0; 57 | 58 | /* Reverse first k nodes of linked list */ 59 | while (count < k && current != null) 60 | { 61 | next = current.next; 62 | current.next = prev; 63 | prev = current; 64 | current = next; 65 | count++; 66 | } 67 | 68 | /* next is now a pointer to (k+1)th node 69 | Recursively call for the list starting from current. 70 | And make rest of the list as next of first node */ 71 | if (next != null) 72 | head.next = kReverse(next, k); 73 | 74 | // prev is now head of input list 75 | return prev; 76 | 77 | 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Lecture 8 : Linked List 2/reverseLLBetter: -------------------------------------------------------------------------------- 1 | public static DoubleNode reverseLLBetter(Node head){ 2 | if(head == null || head.next == null){ 3 | DoubleNode ans = new DoubleNode(); 4 | ans.head = head; 5 | ans.tail = head; 6 | return ans; 7 | 8 | } 9 | 10 | DoubleNode smallAns = reverselLBetter(head.next); 11 | smallAns.tail.next = head; 12 | head.next = null; 13 | 14 | DoubleNode ans = new DoubleNode(); 15 | ans.head = smallAns.head; 16 | 17 | ans.tail = head; 18 | 19 | return ans; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/Check redundant brackets: -------------------------------------------------------------------------------- 1 | // Check redundant brackets 2 | // Send Feedback 3 | // Given a string mathematical expression, return true if redundant brackets are present in the expression. Brackets are redundant if there is nothing inside the bracket or more than one pair of brackets are present. 4 | // Assume the given string expression is balanced and contains only one type of bracket i.e. (). 5 | // Note: You will not get partial score for this problem. You will get marks only if all test cases are passed. 6 | // Input Format : 7 | // String s (Expression) 8 | // Output Format : 9 | // true or false 10 | // Sample Input 1: 11 | // ((a + b)) 12 | // Sample Output 1: 13 | // true 14 | // Sample Input 2: 15 | // (a+b) 16 | // Sample Output 2: 17 | // false 18 | 19 | import java.util.Stack; 20 | import java.util.*; 21 | public class solution { 22 | 23 | public static boolean checkRedundantBrackets(String input) { 24 | // Write your code here 25 | Stack stack=new Stack(); 26 | //Stack numbers = new Stack(); 27 | for(int i=0;i st = new Queue(); 38 | 39 | int choice = s.nextInt(); 40 | int input; 41 | 42 | while (choice !=-1) { 43 | if(choice == 1) { 44 | input = s.nextInt(); 45 | st.enqueue(input); 46 | } 47 | else if(choice == 2) { 48 | try { 49 | System.out.println(st.dequeue()); 50 | } catch (QueueEmptyException e) { 51 | System.out.println(-1); 52 | } 53 | } 54 | else if(choice == 3) { 55 | try { 56 | System.out.println(st.front()); 57 | } catch (QueueEmptyException e) { 58 | System.out.println(-1); 59 | } 60 | } 61 | else if(choice == 4) { 62 | System.out.println(st.size()); 63 | } 64 | else if(choice == 5) { 65 | System.out.println(st.isEmpty()); 66 | } 67 | choice = s.nextInt(); 68 | } 69 | } 70 | } 71 | 72 | class Node { 73 | T data; 74 | Node next; 75 | 76 | public Node(T data) { 77 | this.data = data; 78 | } 79 | } 80 | 81 | 82 | ***********/ 83 | public class Queue { 84 | 85 | private Node front; 86 | private Node rear; 87 | private int size; 88 | 89 | 90 | public Queue() { 91 | front=null; 92 | rear=null; 93 | size=0; 94 | 95 | } 96 | 97 | 98 | public int size() { 99 | return size; 100 | } 101 | 102 | 103 | public boolean isEmpty() { 104 | return (size==0); 105 | } 106 | 107 | 108 | public T front() throws QueueEmptyException { 109 | if(size==0) 110 | throw new QueueEmptyException(); 111 | return front.data; 112 | 113 | } 114 | 115 | public void enqueue(T data) 116 | { if(size==0) 117 | { 118 | Node newnode=new Node(data); 119 | front=newnode; 120 | rear=newnode; 121 | size++; 122 | } 123 | else{ 124 | Node newnode=new Node(data); 125 | rear.next=newnode; 126 | rear=rear.next; 127 | size++; 128 | 129 | } 130 | } 131 | 132 | 133 | public T dequeue() throws QueueEmptyException { 134 | if(size==0){ 135 | throw new QueueEmptyException(); 136 | } 137 | if(size==1) 138 | {T temp=front.data; 139 | front=null; 140 | rear=null; 141 | size=0; 142 | return temp; 143 | } 144 | else{ 145 | T temp=front.data; 146 | front=front.next; 147 | size--; 148 | return temp; 149 | } 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/Code : Stack Using LL: -------------------------------------------------------------------------------- 1 | // Code : Stack Using LL 2 | // Send Feedback 3 | // You need to implement a Stack class using linked list. 4 | // The data members should be private. 5 | // Implement the following public functions : 6 | // 1. Constructor - 7 | // Initialises the data member (i.e. head to null). 8 | // 2. push : 9 | // This function should take one argument of type T and has return type void. This function should insert an element in the stack. Time complexity should be O(1). 10 | // 3. pop : 11 | // This function takes no input arguments and has return type T. This should removes the last element which is entered and return that element as an answer. Time complexity should be O(1). 12 | // 4. top : 13 | // This function takes no input arguments and has return type T. This should return the last element which is entered and return that element as an answer. Time complexity should be O(1). 14 | // 5. size : 15 | // Return the size of stack i.e. count of elements which are present ins stack right now. Time complexity should be O(1). 16 | // 6. isEmpty : 17 | // Checks if the stack is empty or not. Return true or false. 18 | 19 | 20 | 21 | 22 | class StackEmptyException extends Exception { 23 | 24 | /** 25 | * 26 | */ 27 | private static final long serialVersionUID = 1L; 28 | 29 | 30 | } 31 | 32 | /*********** 33 | 34 | public static void main(String[] args) throws StackEmptyException { 35 | Scanner s = new Scanner(System.in); 36 | 37 | Stack st = new Stack(); 38 | 39 | int choice = s.nextInt(); 40 | int input; 41 | 42 | while (choice !=-1) { 43 | if(choice == 1) { 44 | input = s.nextInt(); 45 | st.push(input); 46 | } 47 | else if(choice == 2) { 48 | try { 49 | System.out.println(st.pop()); 50 | } catch (StackEmptyException e) { 51 | System.out.println(-1); 52 | } 53 | } 54 | else if(choice == 3) { 55 | try { 56 | System.out.println(st.top()); 57 | } catch (StackEmptyException e) { 58 | System.out.println(-1); 59 | } 60 | } 61 | else if(choice == 4) { 62 | System.out.println(st.size()); 63 | } 64 | else if(choice == 5) { 65 | System.out.println(st.isEmpty()); 66 | } 67 | choice = s.nextInt(); 68 | } 69 | } 70 | 71 | 72 | class Node { 73 | T data; 74 | Node next; 75 | 76 | public Node(T data) { 77 | this.data = data; 78 | } 79 | } 80 | 81 | ************/ 82 | 83 | public class Stack { 84 | 85 | 86 | private Node head; 87 | private int size; 88 | // private Stack top; 89 | // private Stack prev; 90 | //private Node tail; 91 | 92 | public Stack() { 93 | // top=null; 94 | head =null; 95 | size=0; 96 | // tail=null; 97 | 98 | } 99 | 100 | public int size() 101 | { 102 | return size; 103 | } 104 | 105 | public void push(T data) 106 | { 107 | Node newnode=new Node(data); 108 | newnode.next=head; 109 | head=newnode; 110 | size++; 111 | } 112 | 113 | public boolean isEmpty() { 114 | return (size==0); // head==null 115 | 116 | } 117 | 118 | public T pop() throws StackEmptyException { 119 | if(size==0){ 120 | //StackEmptyException e=new StackEmptyException(); 121 | // throw e; 122 | throw new StackEmptyException(); 123 | } 124 | T temp=head.data; 125 | head=head.next; 126 | size--; 127 | return temp; 128 | 129 | 130 | } 131 | 132 | public T top() throws StackEmptyException { 133 | if(size==0){ 134 | throw new StackEmptyException(); 135 | } 136 | return head.data; 137 | 138 | 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/Minimum bracket Reversal: -------------------------------------------------------------------------------- 1 | // Minimum bracket Reversal 2 | // Send Feedback 3 | // Given a string expression which consists only ‘}’ and ‘{‘. The expression may not be balanced. You need to find the minimum number of bracket reversals which are required to make the expression balanced. 4 | // Return -1 if the given expression can't be balanced. 5 | // Input Format : 6 | // String S 7 | // Output Format : 8 | // Required count 9 | // Sample Input 1 : 10 | // {{{ 11 | // Sample Output 1 : 12 | // -1 13 | // Sample Input 2 : 14 | // {{{{}} 15 | // Sample Output 2 : 16 | // 1 17 | 18 | import java.util.*; 19 | 20 | public class Solution { 21 | 22 | 23 | // Function returns -1 if brackets can't be balanced 24 | public static int countBracketReversals(String input){ 25 | 26 | int len = input.length(); 27 | 28 | // length of expression must be even to make 29 | // it balanced by using reversals. 30 | if (len%2 != 0) 31 | return -1; 32 | 33 | // After this loop, stack contains unbalanced 34 | // part of expression, i.e., expression of the 35 | // form "}}..}{{..{" 36 | Stack s=new Stack<>(); 37 | 38 | for (int i=0; i { 20 | 21 | public int size(); 22 | 23 | public boolean isEmpty(); 24 | 25 | public T front(); 26 | 27 | public void enqueue(T element); 28 | 29 | public T dequeue(); 30 | } 31 | 32 | **********************************/ 33 | 34 | 35 | 36 | public class Solution { 37 | 38 | public static void reverseQueue(Queue q) { 39 | // Write your code here 40 | 41 | 42 | if(q.size()==0) 43 | return; 44 | int temp=q.dequeue(); 45 | 46 | reverseQueue(q); 47 | 48 | q.enqueue(temp); 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/Reverse Stack: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | // Reverse Stack 3 | // Send Feedback 4 | // Reverse a given Stack with the help of another empty stack. Two stacks will be given. Out of which first contains some integers and second one is empty. You need to reverse the first one using second stack. Change in the given first stack itself. 5 | // Note : You don't need to print or return the stack, just reverse the given stack and it will be printed internally. 6 | // Input format : 7 | // Line 1 : Size of Stack 8 | // Line 2 : Stack elements (separated by space) 9 | // Sample Input 1 : 10 | // 4 11 | // 1 2 3 4 (4 is at top) 12 | // Sample Output 1 : 13 | // 1 2 3 4 (1 is at top) 14 | 15 | 16 | public class Solution { 17 | 18 | public static void reverseStack(Stack s1, Stack s2) { 19 | 20 | 21 | 22 | if(s1.size()==0 ||s1.size()==1 ) 23 | { return;} 24 | 25 | int temp=s1.pop(); 26 | 27 | reverseStack(s1,s2); 28 | 29 | while(!s1.isEmpty()) { 30 | s2.push(s1.pop()); 31 | } 32 | 33 | s1.push(temp); 34 | 35 | while(!s2.isEmpty()) { 36 | s1.push(s2.pop()); 37 | } 38 | 39 | 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/StackEmptyException.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackEmptyException extends Exception { 3 | 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 1L; 8 | 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/StackFullException.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackFullException extends Exception { 3 | 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 1L; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/StackUse.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackUse { 3 | 4 | public static void main(String[] args) throws StackFullException { 5 | StackUsingArray stack = new StackUsingArray(3); 6 | for(int i = 1; i <= 5; i++){ 7 | stack.push(i); 8 | } 9 | 10 | while(!stack.isEmpty()){ 11 | try { 12 | System.out.println(stack.pop()); 13 | } catch (StackEmptyException e) { 14 | // Never reach here 15 | } 16 | } 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/StackUsingArray.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackUsingArray { 3 | 4 | private int data[]; 5 | private int top; // is the index of topmost element of stack 6 | 7 | public StackUsingArray() { 8 | data = new int[10]; 9 | top = -1; 10 | } 11 | 12 | public StackUsingArray(int capacity) { 13 | data = new int[capacity]; 14 | top = -1; 15 | } 16 | 17 | public boolean isEmpty(){ 18 | // if(top == -1){ 19 | // return true; 20 | // }else{ 21 | // return false; 22 | // } 23 | return (top == -1); 24 | } 25 | 26 | public int size(){ 27 | return top + 1; 28 | } 29 | 30 | public int top() throws StackEmptyException{ 31 | if(size() == 0){ 32 | //StackEmptyException 33 | StackEmptyException e = new StackEmptyException(); 34 | throw e; 35 | } 36 | return data[top]; 37 | } 38 | 39 | public void push(int elem) throws StackFullException{ 40 | if(size() == data.length){ 41 | // Stack Full 42 | StackFullException e = new StackFullException(); 43 | throw e; 44 | } 45 | top++; 46 | data[top] = elem; 47 | } 48 | 49 | public int pop() throws StackEmptyException{ 50 | if(size() == 0){ 51 | //StackEmptyException 52 | StackEmptyException e = new StackEmptyException(); 53 | throw e; 54 | } 55 | int temp = data[top]; 56 | top--; 57 | return temp; 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Lecture 9 : Stacks and Queues/Stock Span: -------------------------------------------------------------------------------- 1 | 2 | // Stock Span 3 | // Send Feedback 4 | // The span si of a stock’s price on a certain day i is the minimum number of consecutive days (up to the current day) the price of the stock has been less than its price on that ith day. If for a particular day, if no stock price is greater then just count the number of days till 0th day including current day. 5 | // For eg. if given price array is {3, 6, 8, 1, 2}, span for 4th day (which has price 2) is 2 because minimum count of consecutive days (including 4th day itself) from current day which has price less than 4th day is 2 (i.e. day 3 & 4). Similarly, span for 2nd day is 3 because no stock price in left is greater than 2nd day's price. So count is 3 till 0th day. 6 | // Given an input array with all stock prices, you need to return the array with corresponding spans of each day. 7 | // Note : Try doing it in O(n). 8 | // Input format : 9 | // Line 1 : Integer n, Arrays Size 10 | // Line 2 : Price for n days (separated by space). It can contain duplicate values` 11 | // Constraints: 12 | // Time Limit: 1 second 13 | // Size of input array lies in the range: [1, 1000000] 14 | // Output format : 15 | // Return an array that contain span for each day 16 | // Sample Input 1 : 17 | // 8 18 | // 60 70 80 100 90 75 80 120 19 | // Sample Output 1 : 20 | // 1 2 3 4 1 1 2 8 21 | // Sample Input 2 : 22 | // 4 23 | // 1 1 1 1 24 | // Sample Output 2 : 25 | // 1 1 1 1 26 | 27 | 28 | import java.util.*; 29 | 30 | 31 | public class Solution { 32 | 33 | public static int[] stockSpan(int[] price) { 34 | // Write your code here 35 | 36 | // Create a stack and push index of first element 37 | // to it 38 | Stack st = new Stack<>(); 39 | st.push(0); 40 | int[] S=new int[price.length]; 41 | // Span value of first element is always 1 42 | S[0] = 1; 43 | 44 | // Calculate span values for rest of the elements 45 | for (int i = 1; i < price.length; i++) { 46 | 47 | // Pop elements from stack while stack is not 48 | // empty and top of stack is smaller than 49 | // price[i] 50 | while (!st.empty() && price[st.peek()] < price[i]) 51 | st.pop(); 52 | 53 | // If stack becomes empty, then price[i] is 54 | // greater than all elements on left of it, i.e., 55 | // price[0], price[1], ..price[i-1]. Else price[i] 56 | // is greater than elements after top of stack 57 | S[i] = (st.empty()) ? (i + 1) : (i - st.peek()); 58 | 59 | // Push this element to stack 60 | st.push(i); 61 | 62 | 63 | } 64 | return S; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding-Ninja-Data-Structure-In-Java 2 | 3 | 4 | This repository is for people who are going throught this course , all question with solutions are provided here. 5 | -------------------------------------------------------------------------------- /Test 1/Complexity of a Recurrence Relation: -------------------------------------------------------------------------------- 1 | Complexity of a Recurrence Relation 2 | Send Feedback 3 | Which one of the following correctly determines the solution of the recurrence relation with T(1) = 1? 4 | T(n) = 2T(n/2) + Logn 5 | Options 6 | O(N) ANSWER 7 | O(NlogN) 8 | O(N^2) 9 | O(log N) 10 | -------------------------------------------------------------------------------- /Test 1/Complexity of different operations in a sorted array.: -------------------------------------------------------------------------------- 1 | Complexity of different operations in a sorted array. 2 | Send Feedback 3 | Which of the following operations is not O(1) for an array of sorted data. You may assume that array elements are distinct. 4 | Options 5 | Find the ith largest element 6 | Delete an element ANSWER 7 | Find the ith smallest element 8 | All of the above 9 | -------------------------------------------------------------------------------- /Test 1/Does s contain t ?: -------------------------------------------------------------------------------- 1 | // Does s contain t ? 2 | // Send Feedback 3 | // 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). 4 | // Return true or false. 5 | // Do it recursively. 6 | // E.g. : s = “abchjsgsuohhdhyrikkknddg” contains all characters of t=”coding” in the same order. So function will return true. 7 | // Input Format : 8 | // Line 1 : String s 9 | // Line 2 : String t 10 | // Output Format : 11 | // true or false 12 | // Sample Input 1 : 13 | // abchjsgsuohhdhyrikkknddg 14 | // coding 15 | // Sample Output 1 : 16 | // true 17 | // Sample Input 2 : 18 | // abcde 19 | // aeb 20 | // Sample Output 2 : 21 | // false 22 | 23 | 24 | 25 | 26 | public class Solution { 27 | 28 | public static boolean isSubSequence(String str1, String str2, int m, int n) 29 | { 30 | // Base Cases 31 | if (m == 0) 32 | return true; 33 | if (n == 0) 34 | return false; 35 | 36 | // If last characters of two strings are matching 37 | if (str1.charAt(m-1) == str2.charAt(n-1)) 38 | return isSubSequence(str1, str2, m-1, n-1); 39 | 40 | // If last characters are not matching 41 | return isSubSequence(str1, str2, m, n-1); 42 | } 43 | 44 | 45 | public static boolean checkSequence(String a, String b) { 46 | /* Your class should be named Solution 47 | * Don't write main(). 48 | * Don't read input, it is passed as function argument. 49 | * Return output and don't print it. 50 | * Taking input and printing output is handled automatically. 51 | */ 52 | // if (a.length()==0) 53 | // return true; 54 | int m=a.length(); 55 | int n=b.length(); 56 | return isSubSequence(b,a,n,m); 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Test 1/Maximum Profit on App: -------------------------------------------------------------------------------- 1 | // Maximum Profit on App 2 | // Send Feedback 3 | // You have made a smartphone app and want to set its price such that the profit earned is maximised. There are certain buyers who will buy your app only if their budget is greater than or equal to your price. 4 | // You will be provided with a list of size N having budgets of buyers and you need to return the maximum profit that you can earn. 5 | // Lets say you decide that price of your app is Rs. x and there are N number of buyers. So maximum profit you can earn is : 6 | // m * x 7 | // where m is total number of buyers whose budget is greater than or equal to x. 8 | // Input format : 9 | // Line 1 : N (No. of buyers) 10 | // Line 2 : Budget of buyers (separated by space) 11 | // Output Format : 12 | // Maximum profit 13 | // Constraints : 14 | // 1 <= N <= 10^6 15 | // Sample Input 1 : 16 | // 4 17 | // 30 20 53 14 18 | // Sample Output 1 : 19 | // 60 20 | // Sample Output 1 Explanation : 21 | // Price of your app should be Rs. 20 or Rs. 30. For both prices, you can get the profit Rs. 60. 22 | // Sample Input 2 : 23 | // 5 24 | // 34 78 90 15 67 25 | // Sample Output 2 : 26 | // 201 27 | // Sample Output 2 Explanation : 28 | // Price of your app should be Rs. 67. You can get the profit Rs. 201 (i.e. 3 * 67). 29 | 30 | 31 | import java.util.*; 32 | public class solution { 33 | 34 | public static int maximumProfit(int budget[]) { 35 | // Write your code here 36 | int ans=Integer.MIN_VALUE; 37 | int n=budget.length; 38 | // sort(budget,budget+n); 39 | Arrays.sort(budget); 40 | for(int i=0;i { 22 | public T data; 23 | public LinkedListNode next; 24 | public LinkedListNode(T data) { 25 | this.setData(data); 26 | this.next = null; 27 | } 28 | public T getData() { 29 | return data; 30 | } 31 | public void setData(T data) { 32 | this.data = data; 33 | } 34 | } */ 35 | public class Solution { 36 | public static void deleteAlternateNodes(LinkedListNode head) 37 | { 38 | if(head.next==null || head.next.next==null) 39 | return ; 40 | 41 | 42 | LinkedListNode temp1=head; 43 | //LinkedListNode temp2; 44 | 45 | int count=0; 46 | 47 | while(head.next!=null) 48 | { 49 | 50 | if(count%2!=0) 51 | { temp1.next=head.next; 52 | 53 | } 54 | temp1=head; 55 | head=head.next; 56 | count++; 57 | } 58 | 59 | if(count%2!=0) 60 | { temp1.next=null; 61 | 62 | } 63 | 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Test 2/Next Number: -------------------------------------------------------------------------------- 1 | // Next Number 2 | // Send Feedback 3 | // 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). 4 | // Note: You don't need to print the elements, just update the elements and return the head of updated LL. 5 | // Input Constraints: 6 | // 1 <= Length of Linked List <=10^6. 7 | // Input format : 8 | // Line 1 : Linked list elements (separated by space and terminated by -1) 9 | // Output Format : 10 | // Line 1: Updated linked list elements 11 | // Sample Input 1 : 12 | // 3 9 2 5 -1 13 | // Sample Output 1 : 14 | // 3 9 2 6 15 | // Sample Input 2 : 16 | // 9 9 9 -1 17 | // Sample Output 1 : 18 | // 1 0 0 0 19 | 20 | 21 | /*************** 22 | * Following is the Node class already written 23 | class LinkedListNode { 24 | T data; 25 | LinkedListNode next; 26 | 27 | public LinkedListNode(T data) { 28 | this.data = data; 29 | } 30 | } 31 | ***************/ 32 | 33 | public class Solution { 34 | 35 | 36 | public static LinkedListNode nextLargeNumber(LinkedListNode n) 37 | { 38 | 39 | if(n== null) 40 | return n; 41 | 42 | LinkedListNode current=n; 43 | LinkedListNode prev=null; 44 | int length=0; 45 | LinkedListNode last=current; 46 | while(current!=null) 47 | { 48 | length++; 49 | if(current.data!=9) 50 | prev=current; 51 | 52 | last=current; 53 | current=current.next; 54 | }// Now last is pointing to last digit. 55 | // Prev is pointing to last non 9. 56 | if(prev==null) 57 | { 58 | //case when number is all 9 59 | LinkedListNode head=new LinkedListNode(1); 60 | head.next=n; 61 | 62 | while(n!=null) 63 | { 64 | n.data=0; 65 | n=n.next; 66 | } 67 | return head; 68 | }else 69 | { 70 | prev.data=prev.data+1; 71 | prev=prev.next; 72 | while(prev!=null) 73 | { 74 | prev.data=0; 75 | prev=prev.next; 76 | } 77 | return n; 78 | 79 | } 80 | } 81 | 82 | } 83 | --------------------------------------------------------------------------------