├── .gitignore ├── ArrayList └── ALUsingCollectionFramework.java ├── BasicConcepts&Questions ├── Arrays.java ├── BinarySearch.java ├── BitManipulations.java ├── CollectionsFramework.java ├── ForLoop.java ├── MatrixHourGlass.java ├── Rotate_Linked_List.c ├── SpiralMatrix.java ├── Strings.java └── functions.java ├── BrackTracking ├── AllPath.java ├── BacktrackQuestion.java └── NQueenBackTracking.java ├── Graph ├── BFS.java ├── GraphArray.java ├── GraphArrayList.java └── tempCodeRunnerFile.java ├── Hash ├── Hash_Map.java ├── Hashset.java └── Implement_HashMap.java ├── LinkedList ├── LLUsingCollectionFramework.java ├── LinkedLists1.java └── RemoveDuplicate.java ├── OOPs ├── Apna_College │ ├── bank │ │ └── OopsBank.java │ ├── oops1.java │ └── oops2.java └── oop_lab │ ├── Q1 │ └── OOPsClass.java │ ├── Q2 │ └── Q2.java │ ├── Q3 │ └── Q3.java │ ├── Q4 │ └── Q4.java │ ├── Q5 │ └── Q5.java │ └── Q6 │ └── Q6.java ├── Queue ├── CircularQueueUsingArray.java ├── QueueUsingArray.java ├── QueueUsingCollectionFramework.java ├── QueueUsingLinkedList.java └── QueueUsingTwoStack.java ├── README.md ├── Recursion ├── NumOfSteptoZero.java ├── PermutationBackTrack.java ├── PowerOfTwo.java ├── PowerOfthree.java ├── Practice.java ├── PracticeProblem.java ├── Question.java ├── SumUptoNum.java ├── TrickyProb.java ├── recursion2.java └── recursionAdvance.java ├── Sorting ├── BoubbleSort.java ├── InsertionSort.java ├── MargeSort.java ├── QuickSort.java └── SelectionSort.java ├── Stack ├── PushAtBottomOfStack.java ├── ReverseStack.java ├── StackUsingArrayList.java ├── StackUsingCollectionFramework.java └── StackUsingLinkedList.java ├── Tree ├── BST.java ├── BinaryTree.java ├── DiameterOfBT.java ├── KDistanceFromRoot.java └── LowestCommonAncestor.java └── Trie └── Trie.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class -------------------------------------------------------------------------------- /ArrayList/ALUsingCollectionFramework.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.Collections; 4 | 5 | public class ALUsingCollectionFramework { 6 | public static void main(String args[]){ 7 | ArrayList list = new ArrayList(); 8 | // ArrayList list2 = new ArrayList(); 9 | // ArrayList list3 = new ArrayList(); 10 | 11 | //add element ------------ 12 | list.add(1); 13 | list.add(5); 14 | list.add(7); 15 | list.add(9); 16 | 17 | System.out.println(list); 18 | 19 | 20 | //get element------------- 21 | int element =list.get(0); 22 | 23 | System.out.println(element); 24 | 25 | 26 | //add a element in between two ----------------- 27 | list.add(1, 3); /** here first is index number and secont is element */ 28 | 29 | System.out.println(list); 30 | 31 | 32 | //set element or change element-------------------- 33 | list.set(0, 2); 34 | 35 | System.out.println(list); 36 | 37 | 38 | //delete element------------------- 39 | list.remove(4); 40 | list.remove(2); 41 | 42 | System.out.println(list); 43 | 44 | 45 | //to count or know size of arrayList----------------------- 46 | System.out.println(list.size()); 47 | 48 | 49 | //loops--------------------- 50 | for(int i =0; i arr[mid] ){ 19 | start = mid + 1; 20 | }else { 21 | return mid; 22 | } 23 | } 24 | return -1; 25 | } 26 | } -------------------------------------------------------------------------------- /BasicConcepts&Questions/BitManipulations.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BitManipulations{ 4 | public static void main(String [] args){ 5 | Scanner sc = new Scanner(System.in); 6 | System.out.println("Enter a integer value : "); 7 | int n = sc.nextInt(); 8 | System.out.println("Enter position : "); 9 | int position = sc.nextInt(); 10 | int bitMask = 1< 1) operation(OR operation)---------- 22 | // int newNumber = bitMask | n; 23 | // System.out.println("set bit operational value is : " + newNumber); 24 | 25 | 26 | //clear bit(it will clear any bit that means change 1 -> 0) operation(AND with NOT operation)---------- 27 | // int notBitMusk = ~(bitMask); 28 | // int newNumber = notBitMusk & n; 29 | // System.out.println("clear bit operational value is : "+newNumber); 30 | 31 | 32 | //Update bit(it will update any bit to 0/1)operation(for 0 ->AND with NOT operation)(for 1 ->OR operation)----------- 33 | // System.out.println("Enter operation(0/1) to Update it to 0/1 : "); 34 | // int operation = sc.nextInt(); 35 | // if (operation == 1 ){ 36 | // int newNumber = bitMask | n; 37 | // System.out.println("Update bit operational value is : "+ newNumber); 38 | // }else{ 39 | // int notBitMusk = ~(bitMask); 40 | // int newNumber = notBitMusk & n; 41 | // System.out.println("Update bit operational value is : "+newNumber); 42 | // } 43 | 44 | 45 | 46 | 47 | 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /BasicConcepts&Questions/CollectionsFramework.java: -------------------------------------------------------------------------------- 1 | // Methods on Collection => add , size , remove , iterate , addAll , removeAll , clear 2 | 3 | // Iterable =>Collection -> (i) List, (ii) Queue, (iii) Set 4 | 5 | // List interface => (i)ArrayList , (ii)LinkedList , (iii)Vector -> Stack 6 | 7 | // Queue Interface (FIFO) => (i)PriorityQueue , (ii)LinkedList , (iii)Deque(Double Index Queue) -> ArrayDeque 8 | 9 | // Set Interface => (i)HashSet , (ii)LinkedHashSet , (iii)SortedSet -> TreeSet 10 | 11 | // Map Interface => (i)HashMap , (ii)LinkedHashMap , (iii)SortedMap -> TreeMap , (iv)HashTable 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /BasicConcepts&Questions/ForLoop.java: -------------------------------------------------------------------------------- 1 | // package JAVA-DSA.BasicConcepts&Questions; 2 | 3 | public class ForLoop { 4 | public static void main(String[] args) { 5 | int arr[] = {1,2,3,4,5}; 6 | for(int i = 0; ii && js/2 && js-1-i)//prints the elements other than the two diagonals in the rerquired places 32 | System.out.print(m[i][j]+" "); 33 | else 34 | System.out.print(" ");//prints space in rest of the places 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | public static void main(String[]args) 40 | { 41 | Scanner sc=new Scanner(System.in); 42 | System.out.println("Enter size of matrix"); 43 | int x=sc.nextInt(); 44 | if(x%2==0) 45 | { 46 | System.out.println("INVALID INPUT"); 47 | return; 48 | } 49 | MatrixHourGlass ob=new MatrixHourGlass(x); 50 | ob.input(); 51 | ob.modify(); 52 | } 53 | } -------------------------------------------------------------------------------- /BasicConcepts&Questions/Rotate_Linked_List.c: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.util.*; 3 | class Node { 4 | int data; 5 | Node next; 6 | Node(int d) { 7 | data = d; 8 | next = null; 9 | } 10 | } 11 | 12 | class Main { 13 | public static void main(String[] args) { 14 | 15 | Scanner sc = new Scanner(System.in); 16 | int t = sc.nextInt(); 17 | 18 | while (t-- > 0) { 19 | int n = sc.nextInt(); 20 | 21 | int a = sc.nextInt(); 22 | Node head = new Node(a); 23 | Node tail = head; 24 | 25 | for (int i=0; i= totalElement){ 35 | return; 36 | } 37 | minR++; 38 | 39 | //right wall 40 | for (int i = minR;i<=maxR;i++){ 41 | System.out.println(arr[i][maxC]+ " "); 42 | printedElement++; 43 | } 44 | 45 | if(printedElement >= totalElement){ 46 | return; 47 | } 48 | maxC--; 49 | 50 | //bottom wall 51 | for (int i = maxC;i>=minC;i--){ 52 | System.out.println(arr[maxR][i]+ " "); 53 | printedElement++; 54 | } 55 | 56 | if(printedElement >= totalElement){ 57 | return; 58 | } 59 | maxR--; 60 | 61 | //left wall 62 | for (int i = maxR;i>=minR;i--){ 63 | System.out.println(arr[i][minC]+ " "); 64 | printedElement++; 65 | } 66 | 67 | if(printedElement >= totalElement){ 68 | return; 69 | } 70 | minC++; 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /BasicConcepts&Questions/Strings.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Strings{ 3 | public static char getMaxOccuringChar(String line) 4 | { 5 | // Your code here 6 | int count=0; 7 | char ch=line.charAt(count) ; 8 | for(int i = 0; i =count && ch>=tempCh){ 17 | ch = tempCh; 18 | count = tempCount; 19 | } 20 | } 21 | return ch; 22 | } 23 | public static void main(String[] args){ 24 | Scanner sc = new Scanner(System.in); 25 | 26 | System.out.println(getMaxOccuringChar("testsample")); 27 | 28 | 29 | 30 | 31 | // String FirstName = "Kanailal"; 32 | // String LastName = "Manna"; 33 | // System.out.println(FirstName + LastName ); 34 | // System.out.println(FirstName.length()); 35 | // System.out.println(LastName.length()); 36 | // for (int i = 0; i North, S -> South, E -> East, W -> West 9 | Ne -> North-east, Nw -> North-west, Se -> South-east, Sw -> South-west */ 10 | int x1, y1, x2, y2; 11 | 12 | // start 13 | x1 = 1; y1 = 1; 14 | // target 15 | x2 = 3; y2 = 3; 16 | recList(new int[Math.abs(y1 - y2) + 1][Math.abs(x1 - x2) + 1], x1 - x2, y1 - y2, " ", x1 - x2 > 0 , y1 - y2 > 0, 0); 17 | System.out.println("============================="); 18 | 19 | // start 20 | x1 = 1; y1 = 3; 21 | // target 22 | x2 = 3; y2 = 1; 23 | recList(new int[Math.abs(y1 - y2) + 1][Math.abs(x1 - x2) + 1], x1 - x2, y1 - y2, " ", x1 - x2 > 0 , y1 - y2 > 0, 0); 24 | System.out.println("============================="); 25 | 26 | // start 27 | x1 = 3; y1 = 1; 28 | // target 29 | x2 = 1; y2 = 3; 30 | recList(new int[Math.abs(y1 - y2) + 1][Math.abs(x1 - x2) + 1], x1 - x2, y1 - y2, " ", x1 - x2 > 0 , y1 - y2 > 0, 0); 31 | System.out.println("============================="); 32 | 33 | // start 34 | x1 = 3; y1 = 3; 35 | // target 36 | x2 = 1; y2 = 1; 37 | recList(new int[Math.abs(y1 - y2) + 1][Math.abs(x1 - x2) + 1], x1 - x2, y1 - y2, " ", x1 - x2 > 0 , y1 - y2 > 0, 0); 38 | System.out.println("============================="); 39 | 40 | } 41 | 42 | static void recList (int[][] arr, int x, int y, String str, boolean bool1, boolean bool2, int count) { 43 | if (x == 0 && y == 0) { 44 | System.out.print("->"); 45 | System.out.println(Arrays.toString(arr[0])); 46 | for(int i = 1; i < arr.length; i++) { 47 | System.out.print(" "); 48 | System.out.println(Arrays.toString(arr[i])); 49 | } 50 | System.out.println(" " + str); 51 | arr = new int[arr[0].length][arr.length]; 52 | return; 53 | } if (!bool1) { 54 | if (!bool2) { 55 | if (-x < 0 || -x >= arr.length || -y < 0 || -y >= arr[0].length || arr[arr[0].length + y - 1][arr.length + x - 1] != 0){ 56 | return; 57 | } 58 | arr[arr[0].length + y - 1][arr.length + x - 1] = ++count; 59 | recList(arr, x + 1, y, str + "E", bool1, bool2, count); 60 | recList(arr, x - 1, y, str + "W", bool1, bool2, count); 61 | recList(arr, x, y + 1, str + "S", bool1, bool2, count); 62 | recList(arr, x, y - 1, str + "N", bool1, bool2, count); 63 | arr[arr[0].length + y - 1][arr.length + x - 1] = 0; 64 | --count; 65 | return; 66 | } if (bool2) { 67 | if (-x < 0 || -x >= arr.length || y < 0 || y >= arr[0].length || arr[y][arr.length + x - 1] != 0) { 68 | return; 69 | } 70 | arr[y][arr.length + x - 1] = ++count; 71 | recList(arr, x + 1, y, str + "E", bool1, bool2, count); 72 | recList(arr, x - 1, y, str + "W", bool1, bool2, count); 73 | recList(arr, x, y + 1, str + "S", bool1, bool2, count); 74 | recList(arr, x, y - 1, str + "N", bool1, bool2, count); 75 | arr[y][arr.length + x - 1] = 0; 76 | --count; 77 | return; 78 | } 79 | } if (bool1) { 80 | if (!bool2) { 81 | if (x < 0 || x >= arr.length || -y < 0 || -y >= arr[0].length || arr[arr[0].length + y - 1][x] != 0) { 82 | return; 83 | } 84 | arr[arr[0].length + y - 1][x] = ++count; 85 | recList(arr, x + 1, y, str + "E", bool1, bool2, count); 86 | recList(arr, x - 1, y, str + "W", bool1, bool2, count); 87 | recList(arr, x, y + 1, str + "S", bool1, bool2, count); 88 | recList(arr, x, y - 1, str + "N", bool1, bool2, count); 89 | arr[arr[0].length + y - 1][x] = 0; 90 | --count; 91 | return; 92 | } if (bool2) { 93 | if (x < 0 || x >= arr.length || y < 0 || y >= arr[0].length || arr[y][x] != 0) { 94 | return; 95 | } 96 | arr[y][x] = ++count; 97 | recList(arr, x + 1, y, str + "E", bool1, bool2, count); 98 | recList(arr, x - 1, y, str + "W", bool1, bool2, count); 99 | recList(arr, x, y + 1, str + "S", bool1, bool2, count); 100 | recList(arr, x, y - 1, str + "N", bool1, bool2, count); 101 | arr[y][x] = 0; 102 | --count; 103 | return; 104 | } 105 | } 106 | } 107 | 108 | } -------------------------------------------------------------------------------- /BrackTracking/BacktrackQuestion.java: -------------------------------------------------------------------------------- 1 | // package BrackTracking; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class BacktrackQuestion { 7 | public static void main (String[] args) { 8 | /* N -> North, S -> South, E -> East, W -> West 9 | Ne -> North-east, Nw -> North-west, Se -> South-east, Sw -> South-west */ 10 | boolean[][] arr = new boolean[][]{ 11 | {true, true, true}, 12 | {true, true, true}, 13 | {true, true, true} 14 | }; 15 | 16 | // start 17 | int x1 = 1, y1 = 1; 18 | // target 19 | int x2 = 3, y2 = 3; 20 | // System.out.println(recList(arr, x2 - x1, y2 - y1, "")); 21 | System.out.println(recList1(arr, x2 - x1, y2 - y1, "")); 22 | } 23 | 24 | static List recList (boolean[][] arr, int x, int y, String str) { 25 | List list = new ArrayList<>(); 26 | if (x == 0 && y == 0) { 27 | list.add(str); 28 | return list; 29 | } 30 | if (!arr[x][y]) { 31 | return list; 32 | } 33 | arr[x][y] = false; 34 | if (x < arr.length - 1) { 35 | list.addAll(recList(arr, x + 1, y, str + "E")); 36 | } if (x > 0) { 37 | list.addAll(recList(arr, x - 1, y, str + "W")); 38 | } if (y < arr[0].length - 1) { 39 | list.addAll(recList(arr, x, y + 1, str + "S")); 40 | } if (y > 0) { 41 | list.addAll(recList(arr, x, y - 1, str + "N")); 42 | } 43 | arr[x][y] = true; 44 | return list; 45 | } 46 | 47 | static List recList1 (boolean[][] arr, int x, int y, String str) { 48 | List list = new ArrayList<>(0); 49 | if (x == 0 && y == 0) { 50 | list.add(str); 51 | return list; 52 | } 53 | if (x < 0 || x >= arr.length || y < 0 || y >= arr[0].length || !arr[x][y]) { 54 | return list; 55 | } 56 | arr[x][y] = false; 57 | list.addAll(recList1(arr, x + 1, y, str + "E")); 58 | list.addAll(recList1(arr, x - 1, y, str + "W")); 59 | list.addAll(recList1(arr, x, y + 1, str + "S")); 60 | list.addAll(recList1(arr, x, y - 1, str + "N")); 61 | arr[x][y] = true; 62 | return list; 63 | } 64 | } -------------------------------------------------------------------------------- /BrackTracking/NQueenBackTracking.java: -------------------------------------------------------------------------------- 1 | package BrackTracking; 2 | import java.util.*; 3 | public class NQueenBackTracking { 4 | 5 | /** N-Queen problem:- check all posible safe position of n queen of n x n chease board(code is for online platform)---------------------- */ 6 | public List> solveNQueens(int n){ 7 | List> allBoard = new ArrayList<>(); 8 | char[][] board = new char[n][n]; 9 | helper(board, allBoard, 0); 10 | return allBoard; 11 | } 12 | public void helper(char[][] board , List> allBoard,int col){ 13 | if(col == board.length){ 14 | saveBoard(board,allBoard); 15 | return; 16 | } 17 | for(int row = 0; row< board.length;row++){ 18 | if(isSafe(row,col,board)){ 19 | board[row][col] = 'Q'; 20 | helper(board, allBoard, col+1); 21 | board[row][col] = '.'; 22 | } 23 | } 24 | } 25 | public boolean isSafe(int row, int col, char[][] board){ 26 | //horizontal 27 | for (int j = 0; j=0 && r>=0; c--,r--){ 41 | if(board[r][c] == 'Q'){ 42 | return false; 43 | } 44 | } 45 | //upper right 46 | r= row; 47 | for (int c =col ; c=0;r--,c++){ 48 | if(board[r][c] == 'Q'){ 49 | return false; 50 | } 51 | } 52 | // lower left 53 | r = row ; 54 | for (int c= col; c>=0&&r=0; r--,c++){ 62 | if(board[r][c] == 'Q'){ 63 | return false; 64 | } 65 | } 66 | return true; 67 | } 68 | public void saveBoard (char[][] board, List> allBoard){ 69 | String row =""; 70 | List newBoard = new ArrayList<>(); 71 | for(int i = 0; i> adj, int s, int d) { 8 | 9 | } 10 | public static void main(String[] args) { 11 | System.out.println("Hello, world!"); 12 | } 13 | } -------------------------------------------------------------------------------- /Graph/GraphArray.java: -------------------------------------------------------------------------------- 1 | 2 | public class GraphArray { 3 | 4 | public static void simpleGraph(int[][] edges) { 5 | // find the max node 6 | int max = 0; 7 | for (var edge : edges) { 8 | max = Math.max(max, Math.max(edge[0], edge[1])); 9 | } 10 | 11 | int adj[][] = new int[max + 1][max + 1]; 12 | 13 | for (var edge : edges) { 14 | adj[edge[0]][edge[1]] = 1; 15 | adj[edge[1]][edge[0]] = 1; 16 | } 17 | 18 | for (int i = 0; i <= max; i++) { 19 | for (int j = 0; j <= max; j++) { 20 | System.out.print(adj[i][j] + " "); 21 | } 22 | System.out.println(); 23 | } 24 | } 25 | 26 | public static void weightedGraph(int [][] edges ){ 27 | // find the max node 28 | int max = 0; 29 | for(var edge: edges){ 30 | max = Math.max(max, Math.max(edge[0], edge[1])); 31 | } 32 | 33 | int adj[][] = new int[max+1][max+1]; 34 | 35 | for(var edge: edges){ 36 | adj[edge[0]][edge[1]] = edge[2]; 37 | adj[edge[1]][edge[0]] = edge[2]; 38 | } 39 | 40 | for(int i = 0; i <= max; i++){ 41 | for(int j = 0; j <= max; j++){ 42 | System.out.print(adj[i][j] + " "); 43 | } 44 | System.out.println(); 45 | } 46 | } 47 | 48 | public static void main(String[] args) { 49 | int[][] edges = { { 5, 6 }, { 1, 2 }, { 1, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 5 } }; 50 | 51 | // consider first two elemets are nodes/vertices and the third element is the weight of the edge 52 | int[][] weightedEdges = { { 5, 6, 1 }, { 1, 2, 2 }, { 1, 3, 3 }, { 2, 4, 4 }, { 3, 4, 5 }, { 3, 5, 6 }, { 4, 5, 7 } }; 53 | 54 | System.out.println("----------Simple Graph----------"); 55 | simpleGraph(edges); 56 | System.out.println("----------Weighted Graph----------"); 57 | weightedGraph(weightedEdges); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Graph/GraphArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class GraphArrayList { 4 | 5 | public static void simpleGraph(int[][] edges) { 6 | // find the max node 7 | int max = 0; 8 | for (var edge : edges) { 9 | max = Math.max(max, Math.max(edge[0], edge[1])); 10 | } 11 | 12 | ArrayList> adj = new ArrayList<>(max + 1); 13 | 14 | for (int i = 0; i <= max; i++) { 15 | adj.add(new ArrayList()); 16 | } 17 | 18 | for (var edge : edges) { 19 | adj.get(edge[0]).add(edge[1]); 20 | adj.get(edge[1]).add(edge[0]); 21 | } 22 | System.out.println("-----------------Simple Graph-----------------"); 23 | System.out.println(adj); 24 | } 25 | 26 | public static void weightedGraph(int[][] edges) { 27 | // find the max node 28 | int max = 0; 29 | for (var edge : edges) { 30 | max = Math.max(max, Math.max(edge[0], edge[1])); 31 | } 32 | ArrayList> adj = new ArrayList<>(max + 1); 33 | 34 | for (int i = 0; i <= max; i++) { 35 | adj.add(new ArrayList()); 36 | } 37 | 38 | for (var edge : edges) { 39 | adj.get(edge[0]).add(new int[] { edge[1], edge[2] }); 40 | adj.get(edge[1]).add(new int[] { edge[0], edge[2] }); 41 | } 42 | 43 | System.out.println("-----------------Weighted Graph-----------------"); 44 | for (int i = 0; i < adj.size(); i++) { 45 | System.out.print(i + ": "); 46 | for (int[] pair : adj.get(i)) { 47 | System.out.print("(" + pair[0] + "," + pair[1] + ") "); 48 | } 49 | System.out.println(); 50 | } 51 | } 52 | 53 | public static void main(String[] args) { 54 | int[][] edges = { { 5, 6 }, { 1, 2 }, { 1, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 5 } }; 55 | 56 | simpleGraph(edges); 57 | 58 | int[][] weightedEdges = { { 1, 2, 10 }, { 1, 3, 20 }, { 2, 4, 30 }, { 3, 4, 40 }, { 3, 5, 50 }, { 4, 5, 60 }, 59 | { 5, 6, 70 } }; 60 | weightedGraph(weightedEdges); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Graph/tempCodeRunnerFile.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Hash/Hash_Map.java: -------------------------------------------------------------------------------- 1 | // package JAVA-DSA.Hash; 2 | 3 | import java.util.*; 4 | public class Hash_Map { 5 | public static void main(String[] args) { 6 | HashMap map = new HashMap<>(); 7 | 8 | //Insert 9 | map.put("India",120); 10 | map.put("US",30); 11 | map.put("Chaina",150); 12 | 13 | //Print 14 | System.out.println(map); 15 | 16 | //update or creat 17 | map.put("India",130); 18 | 19 | System.out.println(map); 20 | 21 | //Search or look up 22 | if(map.containsKey("India")){ 23 | System.out.println("India is present in the map"); 24 | } 25 | 26 | //get value from key 27 | System.out.println((map.get("India"))); 28 | 29 | 30 | //Iterator in HashMap throung entry set 31 | for(Map.Entry e : map.entrySet()){ 32 | System.out.println(e.getKey() + " : "+ e.getValue()); 33 | } 34 | System.out.println("-------------------------"); 35 | //Iterator in HashMap throung key set 36 | Set keys = map.keySet(); 37 | for(String key : keys){ 38 | System.out.println(key +" : "+map.get(key)); 39 | } 40 | 41 | 42 | //Remove 43 | map.remove("Chaina"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Hash/Hashset.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Iterator; 3 | public class Hashset{ 4 | public static void main(String[] args) { 5 | //creation O(1) 6 | HashSet set = new HashSet<>(); 7 | 8 | //Insert O(1) 9 | set.add(1); 10 | set.add(2); 11 | set.add(3); 12 | 13 | //Search O(1)-- contains 14 | if(set.contains(1)){ 15 | System.out.println("set contain 1"); 16 | } 17 | 18 | //Delete O(1) 19 | set.remove(1); 20 | if(! set.contains(1)){ 21 | System.out.println("now set does not contain 1"); 22 | } 23 | 24 | //size 25 | System.out.println("size of set : "+ set.size()); 26 | 27 | //Print 28 | System.out.println(set); 29 | 30 | //Iterator 31 | Iterator it = set.iterator(); 32 | while(it.hasNext()){ 33 | System.out.println(it.next()); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Hash/Implement_HashMap.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Implement_HashMap { 4 | static class HashMap{ //generics 5 | private class Node{ 6 | K key; 7 | V value; 8 | 9 | public Node(K key, V value){ 10 | this.key = key; 11 | this.value = value; 12 | } 13 | } 14 | 15 | private int n; // "n" is no of nodes 16 | private int N; // "N" is size of bucket 17 | private LinkedList buckets[]; 18 | 19 | @SuppressWarnings("unchecked") 20 | public HashMap(){ 21 | this.N = 4; 22 | this.buckets = new LinkedList[4]; 23 | for (int i = 0; i<4; i++){ 24 | this.buckets[i] = new LinkedList<>(); 25 | } 26 | } 27 | 28 | private int hashFunction( K key ){ 29 | int bi = key.hashCode(); 30 | return Math.abs(bi) % N; //Math.abs() is to make it positive number 31 | 32 | } 33 | 34 | private int searchInLL(K key , int bi ){ 35 | LinkedList ll = buckets[bi]; 36 | 37 | for(int i = 0; i oldBucket[] = buckets; 47 | buckets = new LinkedList[N*2]; 48 | for(int i = 0; i< N*2 ; i++){ 49 | buckets[i] = new LinkedList<>(); 50 | } 51 | 52 | for (int i =0 ; i < oldBucket.length; i++){ 53 | LinkedList ll = oldBucket[i]; 54 | for(int j = 0; j 2.0){ 76 | //rehashing 77 | rehash(); 78 | } 79 | } 80 | 81 | public boolean containKey (K key){ 82 | int bi = hashFunction(key); // bucket index 83 | int di = searchInLL(key, bi); //data index 84 | 85 | if(di == -1){ // key doesn't exist 86 | return false ; 87 | }else{ 88 | return true; 89 | } 90 | 91 | } 92 | 93 | public V remove (K key){ 94 | int bi = hashFunction(key); // bucket index 95 | int di = searchInLL(key, bi); //data index 96 | 97 | if(di == -1){ // key doesn't exist 98 | return null; 99 | }else{ 100 | Node data = buckets[bi].remove(di); 101 | n--; 102 | return data.value; 103 | } 104 | } 105 | 106 | public V get(K key){ 107 | int bi = hashFunction(key); // bucket index 108 | int di = searchInLL(key, bi); //data index 109 | 110 | if(di == -1){ // key doesn't exist 111 | return null; 112 | }else{ 113 | Node data = buckets[bi].get(di); 114 | return data.value; 115 | } 116 | 117 | } 118 | public ArrayList keySet(){ 119 | ArrayList keys = new ArrayList<>(); 120 | for(int i=0 ; i< buckets.length; i++){ 121 | LinkedList ll = buckets[i]; 122 | for(int j = 0; j map = new HashMap<>(); 137 | map.put("India", 130); 138 | map.put("US",30); 139 | map.put("Chaina",200); 140 | 141 | ArrayList keys = map.keySet(); 142 | for(int i = 0; i list = new LinkedList(); 7 | 8 | list.addFirst("a"); 9 | list.addFirst("is"); 10 | System.out.println(list); 11 | 12 | list.addLast("String"); 13 | list.add("list"); 14 | System.out.println(list); 15 | 16 | System.out.println(list.size()); 17 | 18 | list.get(1); 19 | list.get(2); 20 | 21 | for (int i = 0; i< list.size();i++){ 22 | System.out.print(list.get(i)+ " "); 23 | } 24 | System.out.println("-> null"); 25 | 26 | list.removeFirst(); // removeFirst is same as delete function on first 27 | System.out.println(list); 28 | 29 | list.removeLast(); // removeLast is same as delete function on last 30 | System.out.println(list); 31 | 32 | list.remove(1); // delete or remove an list element by it's index number 33 | System.out.println(list); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LinkedList/LinkedLists1.java: -------------------------------------------------------------------------------- 1 | 2 | /** Some Propaties of LinkedList => 3 | 1. Variable size 4 | 2. Non-contiguous Memory 5 | 3. insert in O(1) 6 | 4. Search in O(n) 7 | 8 | First node of LinkedList is called as "Head". 9 | Last node of LinkedList is called as "Tail". 10 | 11 | LinkList => 12 | 1. Singular 13 | 2. Double ended () 14 | 3. Circular (Head and tail is connected to each other) . That means it has not any null node 15 | 16 | 17 | */ 18 | 19 | // package LinkedList; 20 | public class LinkedLists1 { 21 | Node head; 22 | private int size; // we are creating a veriable which will help us to calculate size of the linked list 23 | 24 | LinkedLists1(){ //by this constructor we are asigning 0 as a size 25 | this.size = 0; 26 | } 27 | 28 | class Node{ 29 | String data; 30 | Node next; 31 | 32 | Node (String data){ 33 | this.data = data; 34 | this.next = null; 35 | size++; 36 | } 37 | } 38 | 39 | //add-first--------------------- 40 | public void addFirst(String data){ 41 | Node newNode = new Node(data); 42 | if(head == null){ 43 | head = newNode ; 44 | return; 45 | } 46 | newNode.next = head; 47 | head = newNode; 48 | } 49 | 50 | //add-last---------------------- 51 | public void addLast(String data){ 52 | Node newNode = new Node(data); 53 | if(head == null ){ 54 | head = newNode; 55 | return; 56 | } 57 | Node currNode = head; 58 | while(currNode.next != null){ 59 | currNode = currNode.next; 60 | } 61 | currNode.next = newNode; 62 | } 63 | 64 | 65 | //delete-first---------------- 66 | public void deleteFirst(){ 67 | if(head == null){ 68 | System.out.println("The list is empty "); 69 | return; 70 | } 71 | size--; 72 | head = head.next; 73 | } 74 | 75 | //delete-last--------------- 76 | public void deleteLast(){ 77 | if(head == null){ 78 | System.out.println("The list is empty "); 79 | return; 80 | } 81 | size--; 82 | if(head.next == null){ 83 | head = null; 84 | return; 85 | } 86 | Node secondLast = head; 87 | Node lastNode = head.next; //if head.next = null -> last.Next = null 88 | while (lastNode.next != null){ 89 | lastNode = lastNode.next; 90 | secondLast = secondLast.next; 91 | } 92 | secondLast.next = null; 93 | } 94 | // delete Last(Different process)------------- 95 | // public void deleteLast(){ 96 | // if(head == null){ 97 | // return; 98 | // } 99 | // if(head.next == null){ 100 | // head = null; 101 | // return ; 102 | // } 103 | // Node currNode = head; 104 | // while(currNode.next.next != null){ 105 | // currNode = currNode.next; 106 | // } 107 | // currNode.next = null; 108 | // } 109 | 110 | 111 | // raverse LinkedList impimentation by iterate way ------------------------ 112 | public void reverse(){ 113 | if(head == null || head.next == null){ 114 | return; 115 | } 116 | Node preNode = head; 117 | Node currNode = head.next; 118 | while(currNode != null){ 119 | Node nextNode = currNode.next; 120 | currNode.next = preNode; 121 | preNode = currNode; 122 | currNode = nextNode; 123 | } 124 | head.next = null; 125 | head = preNode; 126 | } 127 | 128 | 129 | //print------------------ 130 | public void printList(){ 131 | if(head == null){ 132 | System.out.println("List is empty "); 133 | return; 134 | } 135 | Node currNode = head; 136 | while(currNode != null){ 137 | System.out.print(currNode.data + " -> "); 138 | currNode = currNode.next; 139 | } 140 | System.out.println("NULL"); 141 | } 142 | 143 | // Return size----------------------------- 144 | public int getSize(){ 145 | return size; 146 | } 147 | public static void main(String[] args) { 148 | LinkedLists1 list = new LinkedLists1(); 149 | 150 | list.addFirst("a"); 151 | list.addFirst("is"); 152 | list.printList(); 153 | 154 | list.addLast("list"); 155 | list.printList(); 156 | 157 | list.addFirst("This"); 158 | list.printList(); 159 | 160 | list.deleteFirst(); 161 | list.printList(); 162 | 163 | list.deleteLast(); 164 | list.printList(); 165 | 166 | System.out.println(list.getSize()); 167 | 168 | 169 | list.reverse(); 170 | list.printList(); 171 | 172 | 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /LinkedList/RemoveDuplicate.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /OOPs/Apna_College/bank/OopsBank.java: -------------------------------------------------------------------------------- 1 | // package OOPs.Apna_College.bank; 2 | class Account { /**If we don't use any key word then it will asign as "default" then we can use it only in this file only */ 3 | public String name; /**we can use from any where by using "public" keyword */ 4 | protected String email; /**By using "protected" it will use in this package and in another package it will use with help of new sub-class*/ 5 | private String password; /**by using "private" keyword it will use only in this class , other class can not use without help of "getters" and "setters*/ 6 | 7 | //getters & setters 8 | public String getPassword(){ 9 | return this.password; 10 | } 11 | public void setPassword(String pass){ /**if we asign this "setPassword" as "private" then user cann't set any password and also cann't call from "main" class but we have to call this function from "getPassword" function */ 12 | this.password = pass; 13 | } 14 | } 15 | public class OopsBank{ 16 | public static void main(String[] args) { 17 | Account account1 = new Account(); 18 | account1.name = "Apna College"; 19 | account1.email = "apnacollege@gmail.com"; 20 | account1.setPassword("abcde"); 21 | account1.getPassword(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /OOPs/Apna_College/oops1.java: -------------------------------------------------------------------------------- 1 | // package OOPs.Apna_College; 2 | //Example -> 1 ------------------------------------------------------------------ 3 | class Pen{ 4 | String color; 5 | String type; // ballpen or gelpen 6 | public void write(){ 7 | System.out.println("Write something "); 8 | } 9 | 10 | public void printColor() { 11 | System.out.println(this.color); /*"this" comond will asign that which function is calling */ 12 | } 13 | public void printType(){ 14 | System.out.println(this.type); 15 | } 16 | } 17 | 18 | 19 | //Example -> 2 ---------------------------------------------------------------- 20 | class Student{ 21 | String name ; 22 | int age ; 23 | 24 | public void printInfo(){ 25 | System.out.println(this.name); 26 | System.out.println(this.age); 27 | } 28 | Student(String name , int age){ 29 | this.name = name; 30 | this.age = age; 31 | } 32 | } 33 | 34 | //Example -> 3 (copy construction)---------------------------------------------------- 35 | class Student1{ 36 | String name ; 37 | int age ; 38 | 39 | public void printInfo(){ 40 | System.out.println(this.name); 41 | System.out.println(this.age); 42 | } 43 | Student1(Student s2){ 44 | this.name = s2.name; 45 | this.age = s2.age; 46 | } 47 | 48 | Student1(){} 49 | 50 | } 51 | 52 | 53 | 54 | 55 | 56 | /* By convension in JAVA ---'class' name should start with 'Capitel letter' */ 57 | /* By convension in JAVA ---'function' name should start with 'Small letter' */ 58 | 59 | public class oops1{ 60 | public static void main(String[] args) { /** "static" means accsable for all class and all data will be same or common for all */ 61 | /** "static" can use in 4 type . 1->before propaty, 2->before function, 3->before any block , 4->before nested class */ 62 | 63 | //Example -> 1 --------------------------------- 64 | // Pen pen1 = new Pen(); 65 | // pen1.color = "Blue"; 66 | // pen1.type = "Ball Pen"; 67 | // System.out.println(pen1.type); 68 | // System.out.println(pen1.color); 69 | 70 | // Pen pen2 = new Pen(); 71 | // pen2.color = "Black"; 72 | // pen2.type = "Gel Pen"; 73 | // System.out.println(pen2.type); 74 | // System.out.println(pen2.color); 75 | 76 | 77 | // pen1.printColor(); 78 | // pen1.printType(); 79 | // pen2.printColor(); 80 | // pen2.printType(); 81 | 82 | 83 | 84 | //Example -> 2 -------------------------------- 85 | // Student s1 = new Student("Kanai", 18); 86 | // s1.printInfo(); 87 | 88 | 89 | //Example -> 3 (copy construction)-------------------------------- 90 | // Student1 s1 = new Student1(); 91 | // s1.name = "Kanai"; 92 | // s1.age = 18; 93 | 94 | // Student1 s2 = new Student1(s1); 95 | // s2.printInfo(); 96 | 97 | 98 | } 99 | } -------------------------------------------------------------------------------- /OOPs/Apna_College/oops2.java: -------------------------------------------------------------------------------- 1 | // package OOPs.Apna_College; 2 | /* 3 | in JAVA oops has 4 types of major concepts. 4 | 1 => Abstruction -> (it is use to show important data to user and hide all non-important data from user) 5 | 2 => incapsulation -> (it will help us to hide and control data like using --"public","protected","private" etc.) 6 | 3 => inheritance -> (it will inherite a class into another class with help of "extends" keyword) 7 | it has 4 type.=> 8 | i->single level , 9 | ii->multi level inheritance , 10 | iii->Hierarchial inheritance(one base class will use into many child class), 11 | iv -> Hybrid inheritance(all type of inheritance will use here) 12 | 4 => poly-morphism -> (same name function will use more time in one class) 13 | it has 2 types => 14 | 1->function over loading(run time poly-morphism) , 15 | 2->function over riding(compile time poly-morphism) 16 | */ 17 | 18 | 19 | 20 | import java.util.*; 21 | 22 | import OOPs.Apna_College.bank.*; 23 | 24 | 25 | /*poly-morphism("function over loading")------------------------------------------------*/ 26 | // class Student{ 27 | // String name ; 28 | // int age ; 29 | 30 | // public void printInfo(String name){ 31 | // System.out.println(this.name); 32 | // } 33 | // public void printInfo(int age){ 34 | // System.out.println(this.age); 35 | // } 36 | // public void printInfo(String name,int age){ 37 | // System.out.println(this.name + " "+this.age); 38 | // } 39 | // } 40 | 41 | 42 | /*Inheritance--------------------------------------------------------------------------*/ 43 | // class Shape{ 44 | // public void area(){ 45 | // System.out.println("Display area"); 46 | // } 47 | // } 48 | // class Triangle extends Shape{ /* here 'Shape' is called as 'base class' or 'parent class' and 'Triangle' is called as 'sub-class' or 'child class'*/ 49 | // public void area(int l , int h){ 50 | // System.out.println(1/2 * l * h); 51 | // } 52 | // } 53 | // class EquilatreralTriangle extends Triangle{ 54 | // public void area(int l , int h){ 55 | // System.out.println(1/2 * l * h); 56 | // } 57 | // } 58 | // class Circle extends Shape{ 59 | // public void area(int r){ 60 | // System.out.println((3.14)*r*r); 61 | // } 62 | // } 63 | 64 | 65 | /**Abstraction ------------------------------------------------------------------------- */ 66 | // abstract class Animal{ /** By using "abstract" key-word we can hide this concept*/ 67 | // abstract public void walk(); /** Basically abstract means we hiding a thing which is just a concept */ 68 | // Animal(){ 69 | // System.out.println("You are creating a new aimal"); 70 | // } 71 | // public void eat(){ 72 | // System.out.println("Animals eats"); 73 | // } 74 | // } 75 | // class Horse extends Animal{ 76 | // Horse (){ /**this function called in java as "constructor". for construction function at first main function will call base class's constructor and then it will call drive or child class's constructor class */ 77 | // System.out.println("Created a Horse"); 78 | // } 79 | // public void walk(){ 80 | // System.out.println("Walk on 4 legs"); 81 | // } 82 | // } 83 | // class chiken extends Animal{ 84 | // public void walk(){ 85 | // System.out.println("Walk on two legs"); 86 | // } 87 | // } 88 | 89 | // interface Animal{ /** "interface" is basically 'pure abstruction' where we cann't use non-abstracted function and also we cann't use "constructor" method or function */ 90 | // void walk(); /** "interface" is always "abstracted","public","static","final" by default */ 91 | // } 92 | // interface Herbivore{ 93 | 94 | // } 95 | // class Horse implements Animal , Herbivore{ /** for "interface" we cann't use "extends" key-word , here we have to use "implements" key-word */ 96 | // public void walk(){ /** by using interface we can use this type of multiple inheritance */ 97 | // System.out.println("Walk on 4 legs"); 98 | // } 99 | // } 100 | 101 | public class oops2 { 102 | public static void main(String[] args) { 103 | 104 | 105 | /*poly-morphism("function over loading")------------------------------------------------*/ 106 | // Student s1 = new Student(); 107 | // s1.name = "Kanai"; 108 | // s1.age = 18; 109 | 110 | // s1.printInfo(s1.name); 111 | // s1.printInfo(s1.age); 112 | // s1.printInfo(s1.name, s1.age); 113 | 114 | /*Inheritance--------------------------------------------------------------------------*/ 115 | // Triangle t1 = new Triangle(); 116 | 117 | //use package ----------------------------------------------- 118 | // bank.Account account1 = new bank.Account(); 119 | // account1.name = "customer1"; 120 | 121 | /**Abstruction ----------------------------------------- */ 122 | // Horse horse = new Horse(); 123 | // horse.walk(); /** we cann't use "Animal" class in "main" function function because it is alredy abstracted class . If we use it then it will be 'run time error' */ 124 | 125 | 126 | Horse horse = new Horse(); /**To use constroctor function we just nee to creat a object like this , in java it is called as "constructor chaining method' */ 127 | 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /OOPs/oop_lab/Q1/OOPsClass.java: -------------------------------------------------------------------------------- 1 | package Q1; 2 | class Person { 3 | String name; 4 | int age; 5 | 6 | 7 | public Person(String name, int age) { 8 | this.name = name; 9 | this.age = age; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return "Name: " + name + ", Age: " + age; 15 | } 16 | } 17 | 18 | class Student extends Person { 19 | int rollNumber; 20 | String department; 21 | 22 | public Student(String name, int age, int rollNumber, String department) { 23 | super(name, age); 24 | this.rollNumber = rollNumber; 25 | this.department = department; 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return super.toString() + ", Roll Number: " + rollNumber + ", Department: " + department; 31 | } 32 | } 33 | 34 | class Teacher extends Person { 35 | String subject; 36 | 37 | 38 | public Teacher(String name, int age, String subject) { 39 | super(name, age); 40 | this.subject = subject; 41 | } 42 | 43 | @Override 44 | public String toString() { 45 | return super.toString() + ", Subject: " + subject; 46 | } 47 | } 48 | 49 | public class OOPsClass { 50 | public static void main(String[] args) { 51 | Person[] people = new Person[4]; 52 | 53 | people[0] = new Student("Kanai", 20, 39, "CSE"); 54 | people[1] = new Student("Driptanil", 20, 168, "CSE"); 55 | people[2] = new Teacher("Sanjay Chakraborty", 30, "OOPs Lab"); 56 | people[3] = new Teacher("Pratima Sarkar", 30, "OOPs theory"); 57 | 58 | for (Person person : people) { 59 | System.out.println(person.toString()); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /OOPs/oop_lab/Q2/Q2.java: -------------------------------------------------------------------------------- 1 | class Employee { 2 | private int id; 3 | private String name; 4 | private String department; 5 | protected double salary; 6 | 7 | 8 | public Employee() { 9 | id = 0; 10 | name = ""; 11 | department = ""; 12 | salary = 0.0; 13 | } 14 | 15 | 16 | public Employee(int id, String name, String department, double salary) { 17 | this.id = id; 18 | this.name = name; 19 | this.department = department; 20 | this.salary = salary; 21 | } 22 | 23 | 24 | public void display() { 25 | System.out.println("ID: " + id); 26 | System.out.println("Name: " + name); 27 | System.out.println("Department: " + department); 28 | System.out.println("Salary: " + salary); 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "ID: " + id + ", Name: " + name + ", Department: " + department + ", Salary: " + salary; 34 | } 35 | } 36 | 37 | class Manager extends Employee { 38 | private double bonus; 39 | 40 | 41 | public Manager(int id, String name, String department, double salary, double bonus) { 42 | super(id, name, department, salary); 43 | this.bonus = bonus; 44 | } 45 | 46 | public double getTotalSalary() { 47 | return super.salary + bonus; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return super.toString() + ", Bonus: " + bonus; 53 | } 54 | } 55 | 56 | public class Q2 { 57 | public static void main(String[] args) { 58 | 59 | Manager[] managers = new Manager[3]; 60 | 61 | 62 | managers[0] = new Manager(1, "Pancho", "Sales", 50000, 10000); 63 | managers[1] = new Manager(2, "Anubrate", "Marketing", 60000, 12000); 64 | managers[2] = new Manager(3, "Tousif", "Finance", 70000, 15000); 65 | 66 | 67 | Manager maxSalaryManager = managers[0]; 68 | for (int i = 1; i < 3; i++) { 69 | if (managers[i].getTotalSalary() > maxSalaryManager.getTotalSalary()) { 70 | maxSalaryManager = managers[i]; 71 | } 72 | } 73 | 74 | System.out.println("Details of Manager with Maximum Total Salary: "+ maxSalaryManager.toString()); 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /OOPs/oop_lab/Q3/Q3.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Vehicle { 4 | static int nextId = 100001; 5 | 6 | int id; 7 | String companyName; 8 | double price; 9 | 10 | public Vehicle(String companyName, double price) { 11 | this.id = nextId++; 12 | this.companyName = companyName; 13 | this.price = price; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return "ID: " + id + ", Company Name: " + companyName + ", Price: " + price; 19 | } 20 | } 21 | 22 | class LightMotorVehicle extends Vehicle { 23 | double mileage; 24 | 25 | public LightMotorVehicle(String companyName, double price, double mileage) { 26 | super(companyName, price); 27 | this.mileage = mileage; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return super.toString() + ", Mileage: " + mileage; 33 | } 34 | } 35 | 36 | class HeavyMotorVehicle extends Vehicle { 37 | private double capacityInTons; 38 | 39 | public HeavyMotorVehicle(String companyName, double price, double capacityInTons) { 40 | super(companyName, price); 41 | this.capacityInTons = capacityInTons; 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return super.toString() + ", Capacity in Tons: " + capacityInTons; 47 | } 48 | } 49 | 50 | public class Q3 { 51 | public static void main(String[] args) { 52 | Scanner scanner = new Scanner(System.in); 53 | 54 | System.out.print("Enter the number of vehicles: "); 55 | int n = scanner.nextInt(); 56 | 57 | Vehicle[] vehicles = new Vehicle[n]; 58 | 59 | for (int i = 0; i < n; i++) { 60 | System.out.print("Enter vehicle type (1 for Light, 2 for Heavy): "); 61 | int vehicleType = scanner.nextInt(); 62 | scanner.nextLine(); 63 | 64 | System.out.print("Enter company name: "); 65 | String companyName = scanner.nextLine(); 66 | 67 | System.out.print("Enter price: "); 68 | double price = scanner.nextDouble(); 69 | 70 | if (vehicleType == 1) { 71 | System.out.print("Enter mileage: "); 72 | double mileage = scanner.nextDouble(); 73 | vehicles[i] = new LightMotorVehicle(companyName, price, mileage); 74 | } else if (vehicleType == 2) { 75 | System.out.print("Enter capacity in tons: "); 76 | double capacityInTons = scanner.nextDouble(); 77 | vehicles[i] = new HeavyMotorVehicle(companyName, price, capacityInTons); 78 | } else { 79 | System.out.println("Invalid vehicle type"); 80 | i--; 81 | } 82 | } 83 | 84 | System.out.println("\nVehicle Information:\n"); 85 | for (Vehicle vehicle : vehicles) { 86 | 87 | System.out.println(vehicle.toString()); 88 | 89 | } 90 | 91 | scanner.close(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /OOPs/oop_lab/Q4/Q4.java: -------------------------------------------------------------------------------- 1 | class Vehicle{ 2 | protected int regnNumber; 3 | protected int speed; 4 | protected String ownerName; 5 | public Vehicle(int regnNumber, int speed, String ownerName){ 6 | this.regnNumber = regnNumber; 7 | this.speed = speed; 8 | this.ownerName = ownerName; 9 | } 10 | public void showData(){ 11 | System.out.println("Regn Number: " + regnNumber+ " , Speed: " + speed + " , Owner Name: " + ownerName); 12 | } 13 | } 14 | 15 | class Car extends Vehicle{ 16 | private String manufacturerName; 17 | 18 | public Car(int regnNumber, int speed, String ownerName, String manufacturerName) { 19 | super(regnNumber, speed, ownerName); 20 | this.manufacturerName = manufacturerName; 21 | } 22 | 23 | @Override 24 | public void showData(){ 25 | super.showData(); 26 | System.out.println("Manufacturer Name: " + manufacturerName); 27 | } 28 | } 29 | 30 | class Bus extends Vehicle{ 31 | private int routeNumber; 32 | 33 | public Bus(int regnNumber, int speed, String ownerName, int routeNumber) { 34 | super(regnNumber, speed, ownerName); 35 | this.routeNumber = routeNumber; 36 | } 37 | @Override 38 | public void showData(){ 39 | super.showData(); 40 | System.out.println("Route Number: " + routeNumber); 41 | } 42 | } 43 | 44 | public class Q4 { 45 | public static void main(String[] args) { 46 | 47 | Car c = new Car(1001, 100, "Kanai", "Maruti"); 48 | c.showData(); 49 | 50 | Bus b = new Bus(2001, 80, "Pancho", 1); 51 | b.showData(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /OOPs/oop_lab/Q5/Q5.java: -------------------------------------------------------------------------------- 1 | class A{ 2 | int a; 3 | public A(int a){ 4 | this.a = a; 5 | } 6 | public void show(){ 7 | System.out.print("A: "+ a); 8 | } 9 | } 10 | 11 | class B extends A{ 12 | int b; 13 | public B(int a, int b){ 14 | super(a); 15 | this.b = b; 16 | } 17 | 18 | @Override 19 | public void show(){ 20 | super.show(); 21 | System.out.println("B: "+ b); 22 | } 23 | } 24 | 25 | class C extends B{ 26 | int c; 27 | public C(int a, int b, int c){ 28 | super(a,b); 29 | this.c = c; 30 | } 31 | @Override 32 | public void show(){ 33 | super.show(); 34 | System.out.println("C: "+ c); 35 | } 36 | } 37 | 38 | public class Q5 { 39 | 40 | public static void main(String[] args) { 41 | A a = new A(1); 42 | a.show(); 43 | 44 | B b = new B(10, 20); 45 | b.show(); 46 | 47 | C c = new C(100, 200, 300); 48 | c.show(); 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /OOPs/oop_lab/Q6/Q6.java: -------------------------------------------------------------------------------- 1 | // Interface Sports 2 | interface Sports { 3 | int getSportWeight(); 4 | } 5 | 6 | // Class Student 7 | class Student { 8 | String name; 9 | int rollNo; 10 | String department; 11 | int marks1; 12 | int marks2; 13 | 14 | public Student(String name, int rollNo, String department, int marks1, int marks2) { 15 | this.name = name; 16 | this.rollNo = rollNo; 17 | this.department = department; 18 | this.marks1 = marks1; 19 | this.marks2 = marks2; 20 | } 21 | } 22 | 23 | // Class Marks inheriting from Student 24 | class Marks extends Student { 25 | int totalMarks; 26 | 27 | public Marks(String name, int rollNo, String department, int marks1, int marks2) { 28 | super(name, rollNo, department, marks1, marks2); 29 | totalMarks = marks1 + marks2; 30 | } 31 | 32 | public void getDetails() { 33 | System.out.println("Name: " + name); 34 | System.out.println("Roll No: " + rollNo); 35 | System.out.println("Department: " + department); 36 | System.out.println("Marks 1: " + marks1); 37 | System.out.println("Marks 2: " + marks2); 38 | } 39 | 40 | public void putDetails() { 41 | System.out.println("Total Marks: " + totalMarks); 42 | } 43 | } 44 | 45 | // Class Result inheriting from Marks and implementing Sports 46 | class Result extends Marks implements Sports { 47 | int sportWeight; 48 | 49 | public Result(String name, int rollNo, String department, int marks1, int marks2, int sportWeight) { 50 | super(name, rollNo, department, marks1, marks2); 51 | this.sportWeight = sportWeight; 52 | } 53 | 54 | @Override 55 | public int getSportWeight() { 56 | return sportWeight; 57 | } 58 | } 59 | 60 | // Main class 61 | public class Q6{ 62 | public static void main(String[] args) { 63 | Result studentResult = new Result("John", 123, "Computer Science", 85, 90, 5); 64 | 65 | studentResult.getDetails(); 66 | studentResult.putDetails(); 67 | System.out.println("Sport Weight: " + studentResult.getSportWeight()); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Queue/CircularQueueUsingArray.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class CircularQueueUsingArray { 4 | public static class Queue{ 5 | static int arr[]; 6 | static int rear = -1; 7 | static int front = -1; 8 | static int size ; 9 | Queue(int n){ 10 | arr = new int[n]; 11 | this.size = n; 12 | } 13 | 14 | public static boolean isEmpty(){ 15 | return front == -1 && rear == -1; 16 | } 17 | 18 | public static boolean isFull(){ 19 | return (rear+1)%size == front; 20 | } 21 | 22 | public static void add(int data){ 23 | if(isFull()){ 24 | System.out.println("Full Queue "); 25 | return; 26 | } 27 | if( front == -1){ 28 | front = 0; 29 | } 30 | rear = (rear+1)%size; 31 | arr[rear] = data; 32 | } 33 | 34 | public static int remove(){ 35 | if(isEmpty()){ 36 | System.out.println("Empty Queue "); 37 | return -1; 38 | } 39 | int value = arr[front]; 40 | // if only 1 element is present 41 | if(front == rear){ 42 | front = rear = -1; 43 | }else{ 44 | front = (front+1)%size; 45 | } 46 | return value; 47 | } 48 | 49 | public static int peek(){ 50 | if(isEmpty()){ 51 | System.out.println("Empty Queue "); 52 | return -1; 53 | } 54 | return arr[front]; 55 | } 56 | } 57 | 58 | public static void main(String[] args) { 59 | Queue q = new Queue(5); 60 | 61 | q.add(1); 62 | q.add(2); 63 | q.add(3); 64 | q.add(4); 65 | 66 | while(! q.isEmpty()){ 67 | System.out.println(q.peek()); 68 | q.remove(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Queue/QueueUsingArray.java: -------------------------------------------------------------------------------- 1 | public class QueueUsingArray{ 2 | 3 | public static class Queue{ 4 | 5 | static int arr[]; 6 | static int size; 7 | static int rear = -1 ; 8 | 9 | Queue(int n){ 10 | arr = new int[n]; 11 | this.size = n; 12 | } 13 | 14 | public static boolean isEmpty(){ 15 | return rear == -1; 16 | } 17 | 18 | public static boolean isFull(){ 19 | return size== -1; 20 | } 21 | 22 | // enqueue 23 | public static void add(int data){ 24 | if(isFull()){ 25 | System.out.println("Full Queue "); 26 | return ; 27 | } 28 | arr[++rear] = data; 29 | } 30 | 31 | // dequeue 32 | public static int remove(){ 33 | if(isEmpty()){ 34 | System.out.println("Empty Queue "); 35 | return -1; 36 | } 37 | int front = arr[0]; 38 | for(int i =0 ; i q = new LinkedList<>(); 7 | // Queue q = new ArrayDeque<>(); 8 | 9 | //search in google , diff. of LinkedList & ArrayDeque & why interface and class are different 10 | 11 | 12 | q.add(1); 13 | q.add(2); 14 | q.add(3); 15 | q.add(4); 16 | while(! q.isEmpty()){ 17 | System.out.println(q.peek()); 18 | q.remove(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Queue/QueueUsingLinkedList.java: -------------------------------------------------------------------------------- 1 | public class QueueUsingLinkedList { 2 | public static class Node { 3 | int data ; 4 | Node next ; 5 | 6 | Node(int data){ 7 | this.data = data; 8 | this.next = null; 9 | } 10 | } 11 | public static class Queue{ 12 | static Node head = null; 13 | static Node tail = null; 14 | 15 | public static boolean isEmpty(){ 16 | return head == null && tail == null; 17 | } 18 | 19 | public static void add(int data){ 20 | Node newNode = new Node(data); 21 | if(isEmpty()){ 22 | head = tail = newNode; 23 | }else{ 24 | tail.next = newNode; 25 | tail = newNode; 26 | } 27 | } 28 | 29 | public static int remove(){ 30 | if(isEmpty()){ 31 | return -1; 32 | } 33 | //one element 34 | if(head == tail){ 35 | tail =null; 36 | } 37 | int value = head.data; 38 | head = head.next; 39 | return value; 40 | } 41 | public static int peek(){ 42 | if(isEmpty()){ 43 | System.out.println("Empty Queue"); 44 | return -1; 45 | } 46 | return head.data; 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | Queue q = new Queue(); 52 | 53 | q.add(1); 54 | q.add(2); 55 | q.add(3); 56 | q.add(4); 57 | 58 | while(! q.isEmpty()){ 59 | System.out.println(q.peek()); 60 | q.remove(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Queue/QueueUsingTwoStack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class QueueUsingTwoStack { 4 | 5 | public static class Queue{ 6 | 7 | static Stack s1 = new Stack<>(); 8 | static Stack s2 = new Stack<>(); 9 | 10 | public static boolean isEmpty(){ 11 | return s1.isEmpty(); 12 | } 13 | 14 | public static void add(int data){ 15 | while(! s1.isEmpty()){ 16 | s2.push(s1.pop()); 17 | } 18 | s1.push(data); 19 | while(! s2.isEmpty()){ 20 | s1.push(s2.pop()); 21 | } 22 | } 23 | 24 | public static int remove(){ 25 | if(s1.isEmpty()){ 26 | System.out.println("Empty Queue "); 27 | return -1; 28 | } 29 | return s1.pop(); 30 | } 31 | 32 | public static int peek(){ 33 | if(s1.isEmpty()){ 34 | System.out.println("Empty Queue "); 35 | return -1; 36 | } 37 | return s1.peek(); 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | Queue q = new Queue(); 43 | q.add(1); 44 | q.add(2); 45 | q.add(3); 46 | q.add(4); 47 | q.add(5); 48 | 49 | while(! q.isEmpty()){ 50 | System.out.println(q.peek()); 51 | q.remove(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # JAVA-DSA 3 | 4 | 5 |

6 | 7 |

Learning Data Structure and algorithms

8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |

Resources : 16 |
17 | 18 | Youtube Apna College Youtube Playlist 19 |
20 | 21 | Youtube Kunal Khushwaha Youtube Playlist 22 |


23 | 24 | 25 |

⠀Tools I use :

26 | 27 | 28 |

29 | 30 | VsCode Visual Studio Code 31 |

32 | -------------------------------------------------------------------------------- /Recursion/NumOfSteptoZero.java: -------------------------------------------------------------------------------- 1 | // package Recursion; 2 | public class NumOfSteptoZero { 3 | 4 | public static int res(int num , int count){ 5 | if(num == 0){ 6 | return count; 7 | } 8 | if (num %2 == 0){ 9 | return res(num/2,count +1); 10 | }else return res(num-1, count+1); 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(res(15, 0)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Recursion/PermutationBackTrack.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | public class PermutationBackTrack { 3 | 4 | /** permutation problem ------------------- */ 5 | public static void printPermutation(String str , String perm,int idx){ 6 | if(str.length() == 0){ 7 | System.out.println(perm); 8 | return; 9 | } 10 | for (int i = 0; i= 2){ 11 | if(n%2 == 0){ 12 | if(n/2 == 1){ 13 | return true; 14 | } 15 | }else return false ; 16 | } 17 | 18 | return isPowerOfTwo(n/2); 19 | } 20 | } 21 | 22 | 23 | -------------------------------------------------------------------------------- /Recursion/PowerOfthree.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | public class PowerOfthree { 3 | public static void main(String[] args) { 4 | System.out.println(isPowerOfThree(675)); 5 | } 6 | public static boolean isPowerOfThree(int n) { 7 | 8 | if(n<=0 ){ 9 | return false; 10 | }else if (n == 1 || n ==3){ 11 | return true; 12 | }else if(n >= 3){ 13 | if (n%3 == 0){ 14 | if(n/3 == 1){ 15 | return true; 16 | } 17 | }else return false; 18 | } 19 | 20 | return isPowerOfThree(n/3); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Recursion/Practice.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | import java.util.*; 3 | public class Practice { 4 | 5 | // Q1. reverse array element----- 6 | /* static void revArr(int Arr[] , int idx){ 7 | if(idx < 0){ 8 | 9 | return; 10 | } 11 | System.out.print(" " + Arr[idx]); 12 | revArr(Arr, idx-1); 13 | }*/ 14 | 15 | //Q2. find minimum in Array---------- 16 | // static int findMin(int Arr[], int idx ){ 17 | // if(idx == 0 ){ 18 | // return Arr[0]; 19 | // } 20 | // return Math.min(Arr[idx-1], findMin(Arr, idx-1)); 21 | // } 22 | 23 | //Q3. find maximum in Array----- 24 | // static int findMax(int Arr[], int idx ){ 25 | // if(idx == 0 ){ 26 | // return Arr[0]; 27 | // } 28 | // return Math.max(Arr[idx-1], findMax(Arr, idx-1)); 29 | // } 30 | 31 | 32 | public static void main(String[] args) { 33 | 34 | int Arr[] = {9,2,3,4,0,6}; 35 | int idx = Arr.length -1; 36 | 37 | //Ans1---- 38 | // revArr(Arr, idx); 39 | 40 | //Ans2---- 41 | // System.out.println(findMin(Arr, idx)); 42 | 43 | //Ans3---- 44 | System.out.println(findMax(Arr, idx)); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Recursion/PracticeProblem.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | import java.util.*; 4 | 5 | public class PracticeProblem { 6 | 7 | /*1.print all uper case of a string--------------------------------------------*/ 8 | // public static void uperCase(String str , int idx){ 9 | // if(idx < 0){ 10 | // return; 11 | // } 12 | // else if(str.charAt(idx) >= 65 && str.charAt(idx) <= 90){ 13 | // System.out.println(str.charAt(idx)); 14 | // } 15 | // uperCase(str, idx-1); 16 | // } 17 | 18 | /*2.find fibonachi by its index number----------------------------------------*/ 19 | // public static int fibonachi(int n ){ 20 | // if(n<2){ 21 | // return n; 22 | // } 23 | // return fibonachi(n-1)+fibonachi(n-2); 24 | // } 25 | 26 | /*3.reverse String------------------------------------------------------------- */ 27 | // public static void reverseString(String str ,int idx , String newStr){ 28 | // if(idx < 0){ 29 | // System.out.println(newStr); 30 | // return; 31 | // } 32 | // char currChar = str.charAt(idx); 33 | // reverseString(str, idx-1, newStr + currChar); 34 | // } 35 | 36 | /*4.reverse character array--------------------------------------------------- */ 37 | // public static void revArr(char chr[], int idx,int a){ 38 | // if(a>=idx){ 39 | // System.out.println(chr); 40 | // return; 41 | // } 42 | 43 | // char temp =chr[a]; 44 | // chr[a]=chr[idx]; 45 | // chr[idx]=temp; 46 | // revArr(chr, idx-1, a+1); 47 | // } 48 | 49 | /*5.print upto N number-------------------------------------------------------*/ 50 | // public static void printNM(int N,int a){ 51 | // if(N < 0){ 52 | // return; 53 | // } 54 | // System.out.print(a+" "); 55 | // printNM(N-1, a+1); 56 | // } 57 | 58 | /*6. bouble sort using recursion----------------------------------------------*/ 59 | // public static void boubleSort(int Arr[],int n){ 60 | // if(n == 0){ 61 | // System.out.println(Arrays.toString(Arr)); 62 | // return; 63 | // } 64 | // for(int i = 0; i < n ; i++){ 65 | // if(Arr[i]>Arr[i+1]){ 66 | // int temp = Arr[i+1]; 67 | // Arr[i+1] = Arr[i]; 68 | // Arr[i]=temp; 69 | // } 70 | // System.out.println(Arrays.toString(Arr)); 71 | 72 | // } 73 | // boubleSort(Arr, n-1); 74 | // } 75 | 76 | /*7.Sum of digit of number ----------------------------------------- */ 77 | // public static void sumOfNum(int num , int res){ 78 | // if(num == 0){ 79 | // System.out.println(res); 80 | // return; 81 | // } 82 | 83 | // sumOfNum(num/10 , res+(num%10)); 84 | // } 85 | 86 | /*8.product of two number using recursion----------------------------------- */ 87 | // public static int productOfTwoNum(int x , int y){ 88 | // return (x*y); 89 | // } 90 | 91 | /*9.check prime or not using recursion------------------------------- */ 92 | // public static void primeOrNot(int num , int count){ 93 | // if(count == num/2){ 94 | // System.out.println("It is a prime number :)"); 95 | // return; 96 | // } 97 | // if(num <= 2){ 98 | // System.out.println("Please re-Enter a integer value of more than 2 :("); 99 | // return; 100 | // }else if(num % count == 0){ 101 | // System.out.println("It is not a prime number :( "); 102 | // return; 103 | // } 104 | // primeOrNot(num, count+1); 105 | // } 106 | 107 | /*10.sum of N natural number using recursion--------------------------------------- */ 108 | // public static int sumOfNNum(int num ,int idx , int result){ 109 | // if(idx > num){ 110 | // return result; 111 | // } 112 | // return sumOfNNum(num, idx+1, result += idx); 113 | // } 114 | 115 | /**11.calculate power of two --------------------------------------------------- */ 116 | // public static int powOfTwo(int pow , int res){ 117 | // if(pow == 0){ 118 | // return res; 119 | // } 120 | // return powOfTwo(pow-1, res *= 2); 121 | // } 122 | 123 | // /**12.calculate factorial of a number------------------------- */ 124 | public static int facNum(int num , int res){ 125 | if(num == 0){ 126 | return res; 127 | } 128 | return facNum(num-1, res *= num); 129 | } 130 | 131 | // /**13. combination sum ----------------------------------------- */ 132 | // public static void comSum(int[] arr, int target){ 133 | 134 | 135 | // } 136 | 137 | 138 | public static void main(String[] args) { 139 | 140 | 141 | 142 | 143 | /**12.calculate factorial of a number--------------------- */ 144 | System.out.println(facNum(5, 1 )); 145 | 146 | /**11.calculate power of two ------------------------- */ 147 | // System.out.println(powOfTwo(5, 1)); 148 | 149 | /**10.sun upto N th natural number--------------------- */ 150 | // System.out.println(sumOfNNum(10, 0, 0)); 151 | 152 | /**9.check prime or not ------------------ */ 153 | // primeOrNot(13, 2); 154 | 155 | /**8.product of two number -------------------*/ 156 | // System.out.println(productOfTwoNum(5, 5)); 157 | 158 | /**7. sum of digits of a number------------------ */ 159 | // int num = 18452; 160 | // sumOfNum(num,0); 161 | 162 | /**6. boubble sort using recursion--------------- */ 163 | // int[] Arr = {6,2,9,8,3}; 164 | // boubleSort(Arr, Arr.length-1); 165 | 166 | /**5. print upto n natural number---------------- */ 167 | // printNM(10, 0); 168 | 169 | /**4.reverse Array------------------- */ 170 | // char[] chr = {'k','a','n','a','i'}; 171 | // int idx = chr.length - 1; 172 | // revArr(chr, idx,0); 173 | 174 | /**3.rever String---------------- */ 175 | // String str = "KanailalManna"; 176 | // int idx = str.length()-1; 177 | // reverseString(str, idx,""); 178 | 179 | /**2.find fibonachi--------------------- */ 180 | // int res =fibonachi(5); 181 | // System.out.println(res); 182 | 183 | /**1. uper csae---------------------------- */ 184 | // String str = "kanialalManna"; 185 | // int idx = str.length() - 1; 186 | // uperCase(str, idx); 187 | 188 | 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /Recursion/Question.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Question { 3 | 4 | 5 | // public static int sumOfNM(int n){ 6 | // if(n <= 1){ 7 | // return n; 8 | // } 9 | // return n = n+sumOfNM(n-1); 10 | // } 11 | 12 | // public static void revString(String str ){ 13 | 14 | // if (str == null || str.length() <= 1){ 15 | // System.out.println(str); 16 | // return ; 17 | // }else{ 18 | // System.out.print(str.charAt(str.length()-1)); 19 | // revString(str.substring(0, str.length()-1)); 20 | // } 21 | 22 | // } 23 | 24 | // public static void isPalindrom(String str, int a , int b){ 25 | 26 | 27 | // System.out.println(a + "&" + b); 28 | // if(a >= b){ 29 | // System.out.println("The String is a palindrom :) "); 30 | // return; 31 | // } 32 | // if (str.charAt(a) != str.charAt(b)){ 33 | // System.out.println(str.charAt(a) +" # " +a); 34 | // System.out.println(str.charAt(b) + " # "+b); 35 | // System.out.println("The Stirng is not a Palindrom :("); 36 | // return; 37 | // }else{ 38 | // isPalindrom(str, a+1, b-1); 39 | // } 40 | // } 41 | 42 | //Q1------ 43 | static void printDigit(int ipt ){ 44 | if(ipt < 10){ 45 | System.out.print(ipt); 46 | return; 47 | } 48 | 49 | int opt = ipt%10; 50 | System.out.print(" "+opt); 51 | printDigit(ipt/10); 52 | 53 | } 54 | 55 | public static void main(String[] args) { 56 | Scanner sc = new Scanner(System.in); 57 | System.out.println("Enter a Integer value : "); 58 | // String strs = sc.nextLine(); 59 | // isPalindrom(strs, 0, strs.length() - 1); 60 | int ipt = sc.nextInt(); 61 | int n = ipt.size; 62 | printDigit(ipt); 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /Recursion/SumUptoNum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class SumUptoNum { 3 | 4 | public static void sumOfNumber(int n,int result){ 5 | if(n == 0){ 6 | System.out.println(result); 7 | return; 8 | } 9 | sumOfNumber(n-1, result += n); 10 | } 11 | public static void main(String[] args) { 12 | Scanner sc = new Scanner(System.in); 13 | System.err.println("Enter number :"); 14 | int n = sc.nextInt(); 15 | sumOfNumber(n, 0); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Recursion/TrickyProb.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class TrickyProb{ 3 | public static void fun(int n){ 4 | if( n == 0){ 5 | return; 6 | } 7 | fun(n-1); 8 | System.out.println(n); 9 | } 10 | public static void main(String args[]){ 11 | Scanner sc = new Scanner(System.in); 12 | System.err.println("Enter number "); 13 | int n = sc.nextInt(); 14 | fun(n); 15 | 16 | } 17 | } -------------------------------------------------------------------------------- /Recursion/recursion2.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashSet; 3 | public class recursion2 { 4 | // Qs:-print all the subsequences of a string =================== 5 | // public static void subsequences(String str , int idx , String newString,HashSet set){ 6 | // if(idx == str.length()){ 7 | // if(set.contains(newString)){ 8 | // return; 9 | // }else{ 10 | // System.out.println(newString); 11 | // set.add(newString); 12 | // return; 13 | // } 14 | 15 | // } 16 | // char currChar = str.charAt(idx); 17 | // subsequences(str, idx+1, newString+currChar,set); 18 | // subsequences(str, idx+1, newString,set); 19 | // } 20 | 21 | 22 | // public static boolean[] map = new boolean[26]; 23 | // public static void removeDup(String str , int idx , String newString){ 24 | // if(idx == str.length()){ 25 | // System.err.println(newString); 26 | // return; 27 | // } 28 | // char currChar = str.charAt(idx); 29 | // if (map[currChar - 'a']){ 30 | // removeDup(str, idx+1, newString); 31 | // }else{ 32 | // newString += currChar; 33 | // map[currChar - 'a'] = true; 34 | // removeDup(str, idx+1, newString); 35 | // } 36 | // } 37 | 38 | 39 | public static String[] keypad = {".","abc","def","ghi","jkl","mno","pqrs","tu","vwx","yz"}; 40 | public static void printComb(String str, int idx, String combination){ 41 | if(idx == str.length()){ 42 | System.out.println(combination); 43 | return; 44 | } 45 | char currChar = str.charAt(idx); 46 | String mapping = keypad[currChar - '0']; 47 | for(int i = 1 ; i<=mapping.length(); i++){ 48 | printComb(str, idx + 1, combination + mapping.charAt(i)); 49 | } 50 | } 51 | public static void main(String[] args) { 52 | // String str = "abcde"; 53 | HashSet set= new HashSet<>(); 54 | // subsequences(str,0, "",set); 55 | // String str = "bcdabdbaabcbacdbd"; 56 | // removeDup(str, 0,""); 57 | String str = "23"; 58 | printComb(str, 0, ""); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Recursion/recursionAdvance.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class recursionAdvance { 3 | // public static void printPermutation(String str, String permutation ){ 4 | // if (str.length() == 0 ){ 5 | // System.err.println(permutation); 6 | // return; 7 | // } 8 | // for(int i = 0 ; i arr[j+1]){ 16 | //swap 17 | int temp = arr[j]; 18 | arr[j] = arr[j+1]; 19 | arr[j+1] = temp; 20 | } 21 | } 22 | } 23 | printArray(arr); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Sorting/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | public static void printArray(int arr[]){ 3 | for(int i = 0 ; i=0 && current < arr[j]){ 15 | arr[j+1] = arr[j]; 16 | j--; 17 | } 18 | //placement 19 | arr[j+1]=current; 20 | } 21 | 22 | 23 | 24 | printArray(arr); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Sorting/MargeSort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class MargeSort { 5 | public static void conqure(int arr[],int start, int mid, int end) { 6 | int mar[]=new int[end -start+1]; 7 | int idx1 = start; 8 | int idx2 = mid+1; 9 | int x = 0; 10 | while(idx1 <= mid && idx2 <= end){ 11 | if(arr[idx1] <= arr[idx2]){ 12 | mar[x++] = arr[idx1++]; 13 | }else{ 14 | mar[x++] = arr[idx2++]; 15 | } 16 | } 17 | 18 | while (idx1 <= mid){ 19 | mar[x++] = arr[idx1++]; 20 | } 21 | 22 | while (idx2 <= end){ 23 | mar[x++] = arr[idx2++]; 24 | } 25 | 26 | //coping the whole auxilary array to main array 27 | for(int i=0,j=start ; i < mar.length ; i++,j++){ 28 | arr[j]= mar[i]; 29 | } 30 | } 31 | 32 | 33 | 34 | 35 | 36 | public static void divide(int arr[] , int start , int end){ 37 | if(start >= end){ 38 | return; 39 | } 40 | 41 | int mid = start + (end - start)/2; 42 | divide(arr,start,mid); 43 | divide(arr,mid+1,end); 44 | conqure(arr,start,mid,end); 45 | } 46 | 47 | public static void main(String[] args) { 48 | Scanner sc = new Scanner(System.in); 49 | 50 | System.out.println("Enter size of array : "); 51 | int size = sc.nextInt(); 52 | int arr[] = new int [size]; 53 | for(int i = 0; iarr[j]){ 15 | smallest = j; 16 | } 17 | } 18 | int temp = arr[smallest]; 19 | arr[smallest] = arr[i]; 20 | arr[i]=temp; 21 | } 22 | printArray(arr); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Stack/PushAtBottomOfStack.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class PushAtBottomOfStack { 5 | 6 | public static void pushAtBottom(int data , Stack s){ 7 | if(s.isEmpty()){ 8 | s.push(data); 9 | return; 10 | } 11 | int top = s.pop(); 12 | pushAtBottom(data, s); 13 | s.push(top); 14 | } 15 | 16 | public static void main(String[] args) { 17 | Stack s = new Stack<>(); 18 | 19 | 20 | s.push(1); 21 | s.push(2); 22 | s.push(3); 23 | s.push(4); 24 | 25 | pushAtBottom(0, s); 26 | while(! s.isEmpty()){ 27 | System.out.println(s.peek()); 28 | s.pop(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Stack/ReverseStack.java: -------------------------------------------------------------------------------- 1 | import java.util.* ; 2 | 3 | public class ReverseStack { 4 | 5 | public static void pushAtBottom(int data , Stack s){ 6 | if(s.isEmpty()){ 7 | s.push(data); 8 | return; 9 | } 10 | int top = s.pop(); 11 | pushAtBottom(data, s); 12 | s.push(top); 13 | } 14 | 15 | public static void reverse(Stack s){ 16 | if(s.isEmpty()){ 17 | return ; 18 | } 19 | int top = s.pop(); 20 | reverse(s); 21 | pushAtBottom(top ,s); 22 | } 23 | 24 | public static void main(String[] args) { 25 | Stack s = new Stack<>(); 26 | 27 | 28 | s.push(1); 29 | s.push(2); 30 | s.push(3); 31 | s.push(4); 32 | 33 | reverse(s); 34 | 35 | while(! s.isEmpty()){ 36 | System.out.println(s.peek()); 37 | s.pop(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Stack/StackUsingArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class StackUsingArrayList { 4 | 5 | public static class Stack{ 6 | static ArrayList list = new ArrayList<>(); 7 | 8 | public static boolean isEmpty(){ 9 | return list.size()==0; 10 | } 11 | 12 | // PUSH operation is used to insert an element into the stack---- 13 | public static void push(int data){ 14 | list.add(data); 15 | } 16 | 17 | // POP operation is uesd to dalate top most element---------- 18 | public static int pop(){ 19 | if(isEmpty()){ 20 | return -1; 21 | } 22 | int value = list.remove(list.size()-1); 23 | return value; 24 | } 25 | 26 | // PEEP operation is used to return topmost value without deleting it------- 27 | public static int peek(){ 28 | if(isEmpty()){ 29 | return -1; 30 | } 31 | return list.get(list.size() -1); 32 | } 33 | } 34 | 35 | 36 | 37 | public static void main(String[] args) { 38 | Stack stack = new Stack(); 39 | 40 | stack.push(1); 41 | stack.push(2); 42 | stack.push(3); 43 | stack.push(4); 44 | 45 | while(! stack.isEmpty()){ 46 | System.out.println(stack.peek()); 47 | stack.pop(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Stack/StackUsingCollectionFramework.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class StackUsingCollectionFramework{ 4 | 5 | public static void main(String[] args) { 6 | Stack s = new Stack<>(); 7 | 8 | // PUSH operation is used to insert an element into the stack---- 9 | s.push(1); 10 | s.push(2); 11 | s.push(3); 12 | s.push(4); 13 | 14 | // POP operation is uesd to dalate top most element---------- 15 | // PEEP operation is used to return topmost value without deleting it------- 16 | while(! s.isEmpty()){ 17 | System.out.println(s.peek()); 18 | s.pop(); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Stack/StackUsingLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public class UsingLinkedList{ 3 | 4 | public static class Node{ 5 | int data; 6 | Node next; 7 | Node(int data){ 8 | this.data = data; 9 | this.next = null; 10 | } 11 | } 12 | 13 | static class Stack{ 14 | public static Node head = null; 15 | 16 | public static boolean isEmpty(){ 17 | return head==null; 18 | } 19 | 20 | // PUSH operation is used to insert an element into the stack---- 21 | public static void push(int data){ 22 | Node newNode = new Node(data); 23 | if(isEmpty()){ 24 | head = newNode; 25 | return ; 26 | } 27 | newNode.next = head; 28 | head = newNode; 29 | } 30 | 31 | // POP operation is uesd to dalate top most element---------- 32 | public static int pop(){ 33 | if(isEmpty()){ 34 | return -1; 35 | } 36 | int value = head.data; 37 | head = head.next; 38 | return value; 39 | } 40 | 41 | // PEEP operation is used to return topmost value without deleting it------- 42 | public static int peek(){ 43 | if(isEmpty()){ 44 | return -1; 45 | } 46 | return head.data; 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | Stack stack = new Stack(); 52 | 53 | stack.push(1); 54 | stack.push(2); 55 | stack.push(3); 56 | stack.push(4); 57 | 58 | while(! stack.isEmpty()){ 59 | System.out.println(stack.peek()); 60 | stack.pop(); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /Tree/BST.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | //search time == O(hight of tree) 4 | public class BST { 5 | 6 | public static class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | 15 | // Build the Binary search tree-------------------------------------- 16 | public static Node insert(Node root,int data){ 17 | if(root == null){ 18 | root = new Node(data); 19 | return root; 20 | } 21 | if(root.data>data){ 22 | root.left = insert(root.left , data); 23 | }else{ 24 | root.right = insert(root.right , data); 25 | } 26 | return root; 27 | } 28 | 29 | 30 | //search any element ---------------------------------------- 31 | public static boolean search (Node root ,int data){ 32 | if(root == null){ 33 | return false; 34 | } 35 | if(root.data == data){ 36 | return true; 37 | }else if (root.data > data){ 38 | return search(root.left , data); 39 | }else{ 40 | return search(root.right, data); 41 | } 42 | } 43 | 44 | // Delete a number or value from the tree----------------------------- 45 | public static Node delete(Node root , int data){ 46 | if(root.data>data){ 47 | root.left = delete(root.left, data); 48 | }else if(root.data=x && root.data<=y){ 83 | printInRange(root.left, x, y); 84 | System.out.print(root.data + " "); 85 | printInRange(root.right, x, y); 86 | }else if(root.data >= y){ 87 | printInRange(root.left, x, y); 88 | }else{ 89 | printInRange(root.right, x, y); 90 | } 91 | } 92 | 93 | 94 | //root to leaf all paths-------------------------------- 95 | public static void printPath(ArrayList path){ 96 | for(int i = 0 ; i"); 98 | } 99 | System.out.println(); 100 | } 101 | public static void printRoot2Leaf(Node root,ArrayList path) { 102 | if(root == null){ 103 | return ; 104 | } 105 | path.add(root.data); 106 | //leaf 107 | if(root.left == null && root.right == null){ 108 | printPath(path); 109 | }else{ //non-leaf 110 | printRoot2Leaf(root.left,path); 111 | printRoot2Leaf(root.right,path); 112 | } 113 | path.remove(path.size()-1); 114 | } 115 | 116 | 117 | 118 | 119 | //to get sixe of a tree----------------------- 120 | public static int size(Node root ){ 121 | if (root == null){ 122 | return 0; 123 | } 124 | return size(root.left) + size(root.right) + 1; 125 | } 126 | 127 | 128 | //find maximum value of a tree------------------ 129 | public static int maximum(Node root){ 130 | if(root == null){ 131 | return Integer.MIN_VALUE; 132 | } 133 | return Math.max(root.data, Math.max(maximum(root.left),maximum(root.right))); 134 | } 135 | 136 | //find minimum value of a tree--------------- 137 | public static int minimum(Node root){ 138 | if(root == null){ 139 | return Integer.MAX_VALUE; 140 | } 141 | return Math.min(root.data, Math.min(minimum(root.left),minimum(root.right))); 142 | } 143 | 144 | 145 | // Print the whole tree with inorderSequence--------------------- 146 | public static void inorder(Node root){ 147 | if(root == null){ 148 | return; 149 | } 150 | inorder(root.left); 151 | System.out.print(root.data + " "); 152 | inorder(root.right); 153 | } 154 | //print preorder ------------------- 155 | public static void preorder(Node root){ 156 | if(root == null){ 157 | return ; 158 | } 159 | System.out.println(root.data); 160 | preorder(root.left); 161 | preorder(root.left); 162 | } 163 | 164 | //print post order ---------------------- 165 | public static void postorder(Node root){ 166 | if(root == null){ 167 | return ; 168 | } 169 | postorder(root.left); 170 | postorder(root.right); 171 | System.out.println(root.data); 172 | } 173 | 174 | //print data level order------------------------ 175 | public static void levelOrder(Node root){ 176 | Queue q = new LinkedList<>(); 177 | q.add(root); 178 | while(!q.isEmpty()){ 179 | Node curr = q.poll(); 180 | System.out.print(curr.data + " "); 181 | if(curr.left != null){ 182 | q.add(curr.left); 183 | } 184 | if(curr.right != null){ 185 | q.add(curr.right); 186 | } 187 | } 188 | } 189 | 190 | 191 | //print left view of a tree------------------- 192 | // public static void leftView(Node root){ 193 | // leftViewUtil(root,1); 194 | // } 195 | // public static void leftViewUtil(Node root, int level){ 196 | // if(root == null){ 197 | // return ; 198 | // } 199 | // if(list.get(level) == null){ 200 | // list.add(root); 201 | // } 202 | // leftViewUtil(root.left, List, level+1); 203 | // leftViewUtil(root.right, List, level+1); 204 | // } 205 | 206 | 207 | //return total height of a tree----------------- 208 | public static int height(Node root){ 209 | if(root == null){ 210 | return 0; 211 | } 212 | return Math.max(height(root.left),height(root.right))+1; 213 | } 214 | 215 | //return total sum value of a tree---------------- 216 | public static int sumOfTree(Node root){ 217 | if(root == null){ 218 | return 0; 219 | } 220 | return root.data+sumOfTree(root.left)+sumOfTree(root.right); 221 | } 222 | 223 | // Diameter of a tree ----O(n)------------------------------------- 224 | // by this way we are calculation height and diameter simulteniously----- 225 | public static class TreeInfo{ 226 | int height; 227 | int diameter; 228 | TreeInfo(int height,int diam){ 229 | this.height = height; 230 | this.diameter = diam; 231 | } 232 | } 233 | public static TreeInfo heightDiameter(Node root){ 234 | if(root == null){ 235 | return new TreeInfo(0, 0); 236 | } 237 | TreeInfo left = heightDiameter(root.left); 238 | TreeInfo right = heightDiameter(root.right); 239 | int height = Math.max(left.height,right.height)+1; 240 | int dim1 = left.diameter, dim2 = right.diameter, dim3 = left.height+right.height+1; 241 | int diameter = Math.max(dim1,Math.max(dim2,dim3)); 242 | return new TreeInfo(height, diameter); 243 | } 244 | 245 | public static void main(String[] args) { 246 | int value[] = {3,7,2,6,1,4,5}; 247 | Node root = null; 248 | for(int i = 0 ; i path = new ArrayList(); 262 | // printRoot2Leaf(root,path); 263 | 264 | 265 | System.out.println(); 266 | System.out.println("Size: "+ size(root) ); 267 | System.out.println("Max: "+ maximum(root) ); 268 | System.out.println("Min: "+ minimum(root) ); 269 | System.out.println("Level Order :"); 270 | levelOrder(root); 271 | 272 | // System.out.println("Left View: "+leftView(root);); 273 | 274 | System.out.println("Height : "+height(root)); 275 | 276 | System.out.println("Sum of tree : "+sumOfTree(root)); 277 | 278 | TreeInfo heightDiameter = heightDiameter(root); 279 | System.out.println("Height : "+heightDiameter.height+"\nDiameter : "+heightDiameter.diameter); 280 | 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /Tree/BinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BinaryTree { 4 | 5 | static class Node{ 6 | int data ; 7 | Node right ; 8 | Node left; 9 | Node(int data){ 10 | this.data = data; 11 | this.right = null; 12 | this.left = null; 13 | } 14 | } 15 | 16 | static class Tree{ 17 | static int idx = -1; 18 | 19 | //Building a tree--------------------- 20 | public static Node buildTree(int nodes[]){ 21 | idx++; 22 | if(nodes[idx] == -1){ 23 | return null; 24 | } 25 | Node newNode = new Node(nodes[idx]); 26 | newNode.left = buildTree(nodes); 27 | newNode.right = buildTree(nodes); 28 | 29 | return newNode; 30 | } 31 | 32 | //pre-Order Traversal(1.Root , 2.Left subtree , 3.Right subtree)--------------------- 33 | public static void preOrder(Node root){ 34 | if(root == null){ 35 | return; 36 | } 37 | System.out.print(root.data + " "); 38 | preOrder(root.left); 39 | preOrder(root.right); 40 | } 41 | 42 | // Inorder Traversal(1.left subtree , 2.Root , 3.Right Subtree)--------------- 43 | public static void inOrder(Node root){ 44 | if(root == null){ 45 | return; 46 | } 47 | inOrder(root.left); 48 | System.out.print(root.data + " "); 49 | inOrder(root.right); 50 | } 51 | 52 | // postorder Traversal(1.left subtree , 2.Right subtree , 3.Root)------------ 53 | public static void postOrder(Node root){ 54 | if(root == null){ 55 | return ; 56 | } 57 | postOrder(root.left); 58 | postOrder(root.right); 59 | System.out.print(root.data+" "); 60 | } 61 | 62 | // Level-order Traersal(1.root , 2.next child , 3.next child , ......)------ 63 | public static void levelOrder(Node root){ 64 | Queue q = new LinkedList<>(); 65 | q.add(root); 66 | // q.add(null); 67 | 68 | // while(! q.isEmpty()){ 69 | // Node currNode = q.remove(); 70 | // if(currNode == null){ 71 | // System.out.println(); 72 | // if(q.isEmpty()){ 73 | // break; 74 | // }else{ 75 | // q.add(null); 76 | // } 77 | // }else{ 78 | // System.out.print(currNode.data +" "); 79 | // if(currNode.left != null){ 80 | // q.add(currNode.left); 81 | // } 82 | // if(currNode.right != null){ 83 | // q.add(currNode.right); 84 | // } 85 | // } 86 | // } 87 | while(!q.isEmpty()){ 88 | Node curr = q.poll(); 89 | System.out.println(curr.data+" "); 90 | if(curr.left != null){ 91 | q.add(curr.left); 92 | } 93 | if(curr.right != null){ 94 | q.add(curr.right); 95 | } 96 | } 97 | } 98 | 99 | // Count the numbers of nodes in a tree---------------------------- 100 | public static int countNode(Node root){ 101 | if(root == null){ 102 | return 0; 103 | } 104 | int leftNode = countNode(root.left); 105 | int rightNode = countNode(root.right); 106 | 107 | return leftNode + rightNode +1 ; 108 | } 109 | 110 | // Sum of tree --------------------------------------- 111 | public static int sumOfTree(Node root){ 112 | if(root == null){ 113 | return 0; 114 | } 115 | int leftSum = sumOfTree(root.left); 116 | int rightSum = sumOfTree(root.right); 117 | 118 | return leftSum + rightSum + root.data; 119 | } 120 | 121 | // Height of Tree --------------------------------- 122 | public static int heightOfTree(Node root){ 123 | if(root == null){ 124 | return 0; 125 | } 126 | int leftHeight = heightOfTree(root.left); 127 | int rightHeight = heightOfTree(root.right); 128 | 129 | int myHeight = Math.max(leftHeight,rightHeight)+1; 130 | return myHeight; 131 | } 132 | 133 | //Diameter of a tree ---O(n^2)---------------------------------- 134 | // this is not optimized way to calculate diameter try another one--------------- 135 | // public static int diameter(Node root){ 136 | // if(root == null){ 137 | // return 0; 138 | // } 139 | // int dia1 = diameter(root.left); 140 | // int dia2 = diameter(root.right); 141 | // int dia3 = heightOfTree(root.left)+heightOfTree(root.right)+1; 142 | 143 | // return Math.max(dia1,Math.max(dia2, dia3)); 144 | // } 145 | 146 | 147 | // Diameter of a tree ----O(n)------------------------------------- 148 | // by this way we are calculation height and diameter simulteniously----- 149 | static class TreeInfo{ 150 | int height; 151 | int diam; 152 | TreeInfo(int height , int diam){ 153 | this.height = height; 154 | this.diam = diam; 155 | } 156 | } 157 | public static TreeInfo diameter2(Node root){ 158 | if(root == null){ 159 | return new TreeInfo(0,0); 160 | } 161 | TreeInfo left = diameter2(root.left); 162 | TreeInfo right = diameter2(root.right); 163 | 164 | int myHeight = Math.max(left.height ,right.height)+1; 165 | 166 | int diam1 = left.diam; 167 | int diam2 = right.diam; 168 | int diam3 = left.height+right.height+1; 169 | 170 | int myDiam = Math.max(Math.max(diam1,diam2),diam3); 171 | 172 | TreeInfo myInfo = new TreeInfo(myHeight,myDiam); 173 | 174 | return myInfo; 175 | } 176 | 177 | } 178 | 179 | 180 | //delete a node from a tree-------------------- 181 | public static Node delete(Node root , int val ){ 182 | if (root.data > val){ 183 | root.left = delete(root.left,val); 184 | }else if(root.data < val){ 185 | root.right = delete(root.right, val); 186 | }else{ 187 | //for leaf node 188 | if(root.left==null && root.right==null){ 189 | return null; 190 | } 191 | //if one chile is there 192 | if(root.left == null){ 193 | return root.right; 194 | }else if(root.right == null){ 195 | return root.left; 196 | } 197 | //if both child is there 198 | Node iS = inorderSuccessor(root.right); 199 | root.data = iS.data; 200 | root.right = delete(root.right,val); 201 | 202 | } 203 | return root; 204 | } 205 | public static Node inorderSuccessor(Node root){ 206 | while(root.left!=null){ 207 | root = root.left; 208 | } 209 | return root; 210 | } 211 | 212 | public static void main(String[] args) { 213 | int nodes[] = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1}; 214 | Tree tree = new Tree(); 215 | Node root = tree.buildTree(nodes); 216 | System.out.println("Main Root :\n"+root.data); 217 | 218 | System.out.println("Pre-Order :"); 219 | tree.preOrder(root); 220 | 221 | System.out.println("\nIn-Order :"); 222 | tree.inOrder(root); 223 | 224 | System.out.println("\nPost-Order :"); 225 | tree.postOrder(root); 226 | 227 | System.out.println("\nLevel-Order :"); 228 | tree.levelOrder(root); 229 | 230 | System.out.println("Total Number of Nodes :\n"+ tree.countNode(root)); 231 | 232 | System.out.println("Sum of the Tree : \n"+tree.sumOfTree(root)); 233 | 234 | System.out.println("Height of the Tree : \n"+tree.heightOfTree(root)); 235 | 236 | // System.out.println("Diameter of the Tree : \n"+tree.diameter(root)); 237 | 238 | 239 | // we are calculating height and diameter both simulteniously--------- 240 | System.out.println("Diamater of the tree : \n"+tree.diameter2(root).diam); 241 | System.out.println("Height of the tree : \n"+tree.diameter2(root).height); 242 | 243 | 244 | } 245 | 246 | } 247 | -------------------------------------------------------------------------------- /Tree/DiameterOfBT.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial Template for Java 3 | 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | import java.io.*; 7 | import java.util.*; 8 | 9 | class Node { 10 | int data; 11 | Node left; 12 | Node right; 13 | Node(int data) { 14 | this.data = data; 15 | left = null; 16 | right = null; 17 | } 18 | } 19 | 20 | class DiameterOfBT { 21 | static Node buildTree(String str) { 22 | 23 | if (str.length() == 0 || str.charAt(0) == 'N') { 24 | return null; 25 | } 26 | 27 | String ip[] = str.split(" "); 28 | // Create the root of the tree 29 | Node root = new Node(Integer.parseInt(ip[0])); 30 | // Push the root to the queue 31 | 32 | Queue queue = new LinkedList<>(); 33 | 34 | queue.add(root); 35 | // Starting from the second element 36 | 37 | int i = 1; 38 | while (queue.size() > 0 && i < ip.length) { 39 | 40 | // Get and remove the front of the queue 41 | Node currNode = queue.peek(); 42 | queue.remove(); 43 | 44 | // Get the current node's value from the string 45 | String currVal = ip[i]; 46 | 47 | // If the left child is not null 48 | if (!currVal.equals("N")) { 49 | 50 | // Create the left child for the current node 51 | currNode.left = new Node(Integer.parseInt(currVal)); 52 | // Push it to the queue 53 | queue.add(currNode.left); 54 | } 55 | 56 | // For the right child 57 | i++; 58 | if (i >= ip.length) break; 59 | 60 | currVal = ip[i]; 61 | 62 | // If the right child is not null 63 | if (!currVal.equals("N")) { 64 | 65 | // Create the right child for the current node 66 | currNode.right = new Node(Integer.parseInt(currVal)); 67 | 68 | // Push it to the queue 69 | queue.add(currNode.right); 70 | } 71 | i++; 72 | } 73 | 74 | return root; 75 | } 76 | static void printInorder(Node root) { 77 | if (root == null) return; 78 | 79 | printInorder(root.left); 80 | System.out.print(root.data + " "); 81 | 82 | printInorder(root.right); 83 | } 84 | 85 | public static void main(String[] args) throws IOException { 86 | BufferedReader br = 87 | new BufferedReader(new InputStreamReader(System.in)); 88 | 89 | int t = Integer.parseInt(br.readLine()); 90 | 91 | while (t > 0) { 92 | String s = br.readLine(); 93 | Node root = buildTree(s); 94 | Solution g = new Solution(); 95 | System.out.println(g.diameter(root)); 96 | t--; 97 | } 98 | } 99 | } 100 | 101 | // } Driver Code Ends 102 | 103 | 104 | // User function Template for Java 105 | 106 | /*class Node { 107 | int data; 108 | Node left; 109 | Node right; 110 | Node(int data) { 111 | this.data = data; 112 | left = null; 113 | right = null; 114 | } 115 | }*/ 116 | 117 | class Solution { 118 | // Function to return the diameter of a Binary Tree. 119 | int diameter(Node root) { 120 | if(root == null) return 0; 121 | int lh = height(root.left); 122 | int rh = height(root.right); 123 | return Math.max(lh+rh+1 ,Math.max(diameter(root.right), diameter(root.left))); 124 | } 125 | 126 | static int height(Node root) { 127 | if(root == null) return 0; 128 | return Math.max(height(root.left), height(root.right))+1; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /Tree/KDistanceFromRoot.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import java.io.*; 6 | import java.util.*; 7 | 8 | class Node{ 9 | int data; 10 | Node left; 11 | Node right; 12 | Node(int data){ 13 | this.data = data; 14 | left=null; 15 | right=null; 16 | } 17 | } 18 | 19 | class KDistanceFromRoot { 20 | 21 | static Node buildTree(String str){ 22 | 23 | if(str.length()==0 || str.charAt(0)=='N'){ 24 | return null; 25 | } 26 | 27 | String ip[] = str.split(" "); 28 | // Create the root of the tree 29 | Node root = new Node(Integer.parseInt(ip[0])); 30 | // Push the root to the queue 31 | 32 | Queue queue = new LinkedList<>(); 33 | 34 | queue.add(root); 35 | // Starting from the second element 36 | 37 | int i = 1; 38 | while(queue.size()>0 && i < ip.length) { 39 | 40 | // Get and remove the front of the queue 41 | Node currNode = queue.peek(); 42 | queue.remove(); 43 | 44 | // Get the current node's value from the string 45 | String currVal = ip[i]; 46 | 47 | // If the left child is not null 48 | if(!currVal.equals("N")) { 49 | 50 | // Create the left child for the current node 51 | currNode.left = new Node(Integer.parseInt(currVal)); 52 | // Push it to the queue 53 | queue.add(currNode.left); 54 | } 55 | 56 | // For the right child 57 | i++; 58 | if(i >= ip.length) 59 | break; 60 | 61 | currVal = ip[i]; 62 | 63 | // If the right child is not null 64 | if(!currVal.equals("N")) { 65 | 66 | // Create the right child for the current node 67 | currNode.right = new Node(Integer.parseInt(currVal)); 68 | 69 | // Push it to the queue 70 | queue.add(currNode.right); 71 | } 72 | i++; 73 | } 74 | 75 | return root; 76 | } 77 | 78 | public static void main (String[] args) throws IOException{ 79 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 80 | 81 | int t=Integer.parseInt(br.readLine()); 82 | 83 | while(t > 0){ 84 | String X[] = br.readLine().trim().split(" "); 85 | int k = Integer.parseInt(X[0]); 86 | String s = br.readLine(); 87 | Node root = buildTree(s); 88 | Tree g = new Tree(); 89 | ArrayList nodes = g.Kdistance(root,k); 90 | for(int i = 0;i Kdistance(Node root, int k){ 116 | Queue PQ = new LinkedList<>(); 117 | PQ.add(new pair(root, 0)); 118 | 119 | ArrayList adj = new ArrayList<>(); 120 | 121 | while(!PQ.isEmpty()){ 122 | pair curr = PQ.poll(); 123 | if(curr.level == k) { 124 | adj.add(curr.node.data); 125 | } 126 | 127 | if(curr.level > k) break; 128 | 129 | if(curr.node.left != null) PQ.add(new pair(curr.node.left, curr.level+1)); 130 | if(curr.node.right != null) PQ.add(new pair(curr.node.right, curr.level+1)); 131 | } 132 | 133 | return adj; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /Tree/LowestCommonAncestor.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class Node{ 6 | int data; 7 | Node left; 8 | Node right; 9 | Node(int data){ 10 | this.data = data; 11 | left=null; 12 | right=null; 13 | } 14 | } 15 | 16 | class LowestCommonAncestor { 17 | 18 | static Node buildTree(String str){ 19 | 20 | if(str.length()==0 || str.charAt(0)=='N'){ 21 | return null; 22 | } 23 | 24 | String ip[] = str.split(" "); 25 | // Create the root of the tree 26 | Node root = new Node(Integer.parseInt(ip[0])); 27 | // Push the root to the queue 28 | 29 | Queue queue = new LinkedList<>(); 30 | 31 | queue.add(root); 32 | // Starting from the second element 33 | 34 | int i = 1; 35 | while(queue.size()>0 && i < ip.length) { 36 | 37 | // Get and remove the front of the queue 38 | Node currNode = queue.peek(); 39 | queue.remove(); 40 | 41 | // Get the current node's value from the string 42 | String currVal = ip[i]; 43 | 44 | // If the left child is not null 45 | if(!currVal.equals("N")) { 46 | 47 | // Create the left child for the current node 48 | currNode.left = new Node(Integer.parseInt(currVal)); 49 | // Push it to the queue 50 | queue.add(currNode.left); 51 | } 52 | 53 | // For the right child 54 | i++; 55 | if(i >= ip.length) 56 | break; 57 | 58 | currVal = ip[i]; 59 | 60 | // If the right child is not null 61 | if(!currVal.equals("N")) { 62 | 63 | // Create the right child for the current node 64 | currNode.right = new Node(Integer.parseInt(currVal)); 65 | 66 | // Push it to the queue 67 | queue.add(currNode.right); 68 | } 69 | i++; 70 | } 71 | 72 | return root; 73 | } 74 | static void printInorder(Node root) 75 | { 76 | if(root == null) 77 | return; 78 | 79 | printInorder(root.left); 80 | System.out.print(root.data+" "); 81 | 82 | printInorder(root.right); 83 | } 84 | 85 | public static void main (String[] args) throws IOException{ 86 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 87 | 88 | int t=Integer.parseInt(br.readLine()); 89 | 90 | while(t-- > 0){ 91 | String input[] = br.readLine().trim().split(" "); 92 | int a = Integer.parseInt(input[0]); 93 | int b = Integer.parseInt(input[1]); 94 | String s = br.readLine(); 95 | Node root = buildTree(s); 96 | Solution g = new Solution(); 97 | Node k = g.lca(root,a,b); 98 | System.out.println(k.data); 99 | 100 | } 101 | } 102 | } 103 | 104 | 105 | class Solution 106 | 107 | { 108 | 109 | //Function to return the lowest common ancestor in a Binary Tree. 110 | 111 | Node lca(Node root, int n1,int n2) 112 | 113 | { 114 | 115 | 116 | if(root == null || root.data == n1 || root.data == n2) return root; 117 | 118 | Node left = lca(root.left,n1,n2); 119 | 120 | Node right = lca(root.right,n1,n2); 121 | 122 | if(left == null) return right; 123 | 124 | if(right == null) return left; 125 | 126 | else return root; 127 | 128 | 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /Trie/Trie.java: -------------------------------------------------------------------------------- 1 | class Trie{ 2 | Trie child[]; 3 | boolean isEnd; 4 | Trie(){ 5 | child = new Trie[26]; 6 | isEnd = false; 7 | } 8 | public void insert(String word){ 9 | Trie curr = this; 10 | for(char c : word.toCharArray()){ 11 | int idx = c-'a'; 12 | if(curr.child[idx] == null){ 13 | curr.child[idx] = new Trie(); 14 | } 15 | curr = curr.child[idx]; 16 | } 17 | curr.isEnd = true; 18 | } 19 | public boolean search(String word){ 20 | Trie curr = this; 21 | for(char c : word.toCharArray()){ 22 | int idx = c-'a'; 23 | if(curr.child[idx] == null){ 24 | return false; 25 | } 26 | curr = curr.child[idx]; 27 | } 28 | return curr.isEnd; 29 | } 30 | public boolean startsWith(String prefix){ 31 | Trie curr = this; 32 | for(char c : prefix.toCharArray()){ 33 | int idx = c-'a'; 34 | if(curr.child[idx] == null){ 35 | return false; 36 | } 37 | curr = curr.child[idx]; 38 | } 39 | return true; 40 | } 41 | 42 | public static void main(String[] args) { 43 | Trie root = new Trie(); 44 | 45 | String [] sen = {"my", "name", "is", "kanai"}; 46 | for(String s: sen){ 47 | root.insert(s); 48 | } 49 | 50 | System.out.println(root.search("kanai")); 51 | System.out.println(root.search("kan")); 52 | System.out.println(root.startsWith("naruto")); 53 | 54 | } 55 | } --------------------------------------------------------------------------------