├── .gitignore ├── LICENSE ├── README.md ├── backtracking ├── PartitionOfArray.java └── ShortestPathInAMaze.java ├── comparatorsAndComparables ├── MainClass.java └── Student.java ├── deque ├── MainClass.java └── MyDeque.java ├── dp ├── DynamicProgrammingBasic.java └── ZeroOneKnapsack.java ├── graphs └── Graph.java ├── interfaces ├── Person.java ├── Student.java └── YouTuber.java ├── interviewQuestions ├── GroupAnagrams.java ├── SlidingWindowMaximum.java └── SubarrayWithZeroSum.java ├── linkedLists ├── MainLinkedList.java └── MyLinkedList.java ├── lists ├── MyArrayList.java └── Pair.java ├── maps ├── HashCodeAndEquals.java └── MainClass.java ├── maths └── MathematicsForCP.java ├── priorityQueues └── MainClass.java ├── queue ├── MainClass.java └── MyQueue.java ├── recursion ├── AdvancedQuestions.java └── MainClass.java ├── sets └── MainClass.java ├── trees └── Tree.java └── vectorAndStacks ├── MainClass.java └── MyStack.java /.gitignore: -------------------------------------------------------------------------------- 1 | ### Java ### 2 | # Compiled class file 3 | *.class 4 | 5 | # Log file 6 | *.log 7 | 8 | # BlueJ files 9 | *.ctxt 10 | 11 | # Mobile Tools for Java (J2ME) 12 | .mtj.tmp/ 13 | 14 | # Package Files # 15 | *.jar 16 | *.war 17 | *.nar 18 | *.ear 19 | *.zip 20 | *.tar.gz 21 | *.rar 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | 26 | ### Linux ### 27 | *~ 28 | 29 | # temporary files which can be created if a process still has a handle open of a deleted file 30 | .fuse_hidden* 31 | 32 | # KDE directory preferences 33 | .directory 34 | 35 | # Linux trash folder which might appear on any partition or disk 36 | .Trash-* 37 | 38 | # .nfs files are created when an open file is removed but is still being accessed 39 | .nfs* 40 | 41 | ### macOS ### 42 | # General 43 | .DS_Store 44 | .AppleDouble 45 | .LSOverride 46 | 47 | # Icon must end with two \r 48 | Icon 49 | 50 | # Thumbnails 51 | ._* 52 | 53 | # Files that might appear in the root of a volume 54 | .DocumentRevisions-V100 55 | .fseventsd 56 | .Spotlight-V100 57 | .TemporaryItems 58 | .Trashes 59 | .VolumeIcon.icns 60 | .com.apple.timemachine.donotpresent 61 | 62 | # Directories potentially created on remote AFP share 63 | .AppleDB 64 | .AppleDesktop 65 | Network Trash Folder 66 | Temporary Items 67 | .apdisk 68 | 69 | ### Windows ### 70 | # Windows thumbnail cache files 71 | Thumbs.db 72 | Thumbs.db:encryptable 73 | ehthumbs.db 74 | ehthumbs_vista.db 75 | 76 | # Dump file 77 | *.stackdump 78 | 79 | # Folder config file 80 | [Dd]esktop.ini 81 | 82 | # Recycle Bin used on file shares 83 | $RECYCLE.BIN/ 84 | 85 | # Windows Installer files 86 | *.cab 87 | *.msi 88 | *.msix 89 | *.msm 90 | *.msp 91 | 92 | # Windows shortcuts 93 | *.lnk -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures-Algorithms 2 | Implementation of Data structures and Algorithms.It covers all the important Data structures and Algorithms and also some problems which are really important from the interview point of view. 3 |
4 |

Installation

5 | 9 | 10 |
11 |

Topics Covered:

12 | 26 |
27 | -------------------------------------------------------------------------------- /backtracking/PartitionOfArray.java: -------------------------------------------------------------------------------- 1 | package backtracking; 2 | 3 | import java.util.*; 4 | 5 | public class PartitionOfArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | int a[] = {2, 1, 2, 3, 4, 8}; 10 | int sum = 0; 11 | for(int i = 0; i ans = new ArrayList<>(); 16 | boolean isPossible = (sum&1) == 0 && 17 | partition(a, sum/2, 0, ans); 18 | 19 | if(isPossible) { 20 | for(int e: ans) { 21 | System.out.print(e+" "); 22 | } 23 | } else { 24 | System.out.println("not possible"); 25 | } 26 | 27 | } 28 | 29 | static boolean partition(int a[], int sum, int i, ArrayList ans) { 30 | 31 | if(i >= a.length || sum < 0) return false; 32 | if(sum == 0) return true; 33 | 34 | ans.add(a[i]); 35 | boolean leftPossible = partition(a, sum-a[i], i+1, ans); 36 | 37 | if(leftPossible) return true; 38 | 39 | //this makes backtracking possible 40 | ans.remove(ans.size()-1); 41 | return partition(a, sum, i+1, ans); 42 | } 43 | 44 | 45 | } 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /backtracking/ShortestPathInAMaze.java: -------------------------------------------------------------------------------- 1 | package backtracking; 2 | 3 | public class ShortestPathInAMaze { 4 | 5 | public static void main(String[] args) { 6 | int a[][] = 7 | { 8 | { 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 }, 9 | { 0, 1, 1, 1, 1, 1, 0, 1, 0, 1 }, 10 | { 0, 0, 1, 0, 1, 1, 1, 0, 0, 1 }, 11 | { 1, 0, 1, 1, 1, 0, 1, 1, 0, 1 }, 12 | { 0, 0, 0, 1, 0, 0, 0, 1, 0, 1 }, 13 | { 1, 0, 1, 1, 1, 0, 0, 1, 1, 0 }, 14 | { 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 15 | { 0, 1, 1, 1, 1, 1, 1, 1, 0, 0 }, 16 | { 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 }, 17 | { 0, 0, 1, 0, 0, 1, 1, 0, 0, 1 }, 18 | }; 19 | 20 | int result = shortestPath(a, 0, 0, 0, 9); 21 | if(result >= 1000000) { 22 | System.out.println("No path possible"); 23 | } else { 24 | System.out.println(result); 25 | } 26 | 27 | } 28 | 29 | static int shortestPath(int a[][], int i, int j, int x, int y) { 30 | 31 | int rows = a.length; 32 | int cols = a[0].length; 33 | 34 | boolean vis[][] = new boolean[rows][cols]; 35 | 36 | return shortestPath(a, i, j, x, y, vis); 37 | 38 | } 39 | 40 | static boolean isValid(int a[][], int i, int j, boolean vis[][]) { 41 | int rows = a.length; 42 | int cols = a[0].length; 43 | 44 | return i >= 0 && j >= 0 && i < rows && j < cols && a[i][j] == 1 && 45 | !vis[i][j]; 46 | } 47 | 48 | static int shortestPath(int a[][], int i, int j, int x, int y, boolean vis[][]) { 49 | 50 | if(!isValid(a, i, j, vis)) return 1000000; 51 | if(i == x && j == y) return 0; 52 | 53 | vis[i][j] = true; 54 | int left = shortestPath(a, i, j-1, x, y, vis) + 1; 55 | int bottom = shortestPath(a, i+1, j, x, y, vis)+1; 56 | int right = shortestPath(a, i, j+1, x, y, vis)+1; 57 | int top = shortestPath(a, i-1, j, x, y, vis)+1; 58 | 59 | // This line makes backtracking work 60 | vis[i][j] = false; 61 | return Math.min(Math.min(left, bottom), Math.min(right, top)); 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /comparatorsAndComparables/MainClass.java: -------------------------------------------------------------------------------- 1 | package comparatorsAndComparables; 2 | 3 | import java.util.*; 4 | 5 | public class MainClass { 6 | 7 | public static void main(String[] args) { 8 | 9 | List students = new ArrayList<>(); 10 | 11 | students.add(new Student(23, "Ram")); 12 | students.add(new Student(35, "Shaym")); 13 | students.add(new Student(83, "Aman")); 14 | students.add(new Student(13, "Rohit")); 15 | students.add(new Student(65, "Anuj")); 16 | 17 | // Collections.sort(students); // It accept a List type argument which must extends comparable 18 | 19 | students.forEach(System.out::println); // LAMBDA FUNCTION 20 | /* 21 | * Here we are going inside the students , and iterating previously what we are 22 | * doing is iterate inside the students and print its element one by one what 23 | * lambda function does here-- the "println" function which is present inside 24 | * "System.out", we used the student property on the student or whatever it is.. 25 | */ 26 | 27 | // Lets suppose the student class do not extend the comparable then we can sort 28 | // it using comparator class in this way 29 | 30 | Collections.sort(students, new SortByNameThenMarks()); 31 | students.forEach(System.out::println); // LAMBDA FUNCTION 32 | 33 | // LETS SUPPOSE I DONT WANT TO MAKE A SEPARATE NEW CLASS FOR COMPARATOR, THEN 34 | // HOW CAN WE DO IT??? 35 | // BY USING AN anonymous CLASS , in this way 36 | 37 | Collections.sort(students, new Comparator() { 38 | 39 | @Override 40 | public int compare(Student o1, Student o2) { 41 | if (o1.name.equals(o2.name)) { 42 | return o1.marks - o2.marks; 43 | } else { 44 | return o1.name.compareTo(o2.name); 45 | } 46 | 47 | } 48 | 49 | }); 50 | 51 | // AFTER JAVA -8 , LAMBDA FUNCTION INTRODUCED WHICH MAKE THIS ABOVE THING MORE 52 | // EASY 53 | Collections.sort(students, (o1, o2) -> { 54 | 55 | if (o1.name.equals(o2.name)) { 56 | return o1.marks - o2.marks; 57 | } else { 58 | return o1.name.compareTo(o2.name); 59 | } 60 | }); 61 | 62 | /* 63 | * ACCORDING TO LAMBDA FUNCTION , If we already know that the next argument is 64 | * gonna be comparator, then we can ignore writing it We already know that the 65 | * method is going to be "compare" so we can also ignore it the access modifiers 66 | * and return type are also known so we can erase it too just one addition "->" 67 | * to define lambda function Object type can also be removed because it is 68 | * already known that which type of object it gonna be 69 | */ 70 | 71 | // IF WE WISH TO SORT IT ACCORDING TO NAME ONLY 72 | Collections.sort(students, (o1, o2) -> o1.name.compareTo(o2.name)); 73 | 74 | // IF WE WISH TO SORT BY NAME USING KEY EXTRACTOR 75 | Collections.sort(students, Comparator.comparing(Student::getName)); // Comparator.comparing(keyExtractor) 76 | 77 | // IF WE WISH TO SORT BY NAME THEN MARKS 78 | Collections.sort(students, Comparator.comparing(Student::getName).thenComparing(Student::getMarks)); 79 | 80 | // IF WE WANT TO REVERSE THE DEFINED SORTING ORDER WE CAN USE "reversed" 81 | // function 82 | Collections.sort(students, Comparator.comparing(Student::getName).thenComparing(Student::getMarks).reversed()); 83 | } 84 | 85 | } 86 | 87 | // COMPARATORS CLASS 88 | class SortByNameThenMarks implements Comparator { 89 | 90 | @Override 91 | public int compare(Student o1, Student o2) { 92 | if (o1.name.equals(o2.name)) { 93 | return o1.marks - o2.marks; 94 | } else { 95 | return o1.name.compareTo(o2.name); 96 | } 97 | 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /comparatorsAndComparables/Student.java: -------------------------------------------------------------------------------- 1 | package comparatorsAndComparables; 2 | 3 | public class Student { 4 | 5 | int marks; 6 | String name; 7 | 8 | public Student(int marks, String name) { 9 | super(); 10 | this.marks = marks; 11 | this.name = name; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return "Student [marks=" + marks + ", name=" + name + "]"; 17 | } 18 | 19 | public int getMarks() { 20 | return marks; 21 | } 22 | 23 | public void setMarks(int marks) { 24 | this.marks = marks; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public int compareTo(Student obj) { 36 | return this.marks - obj.marks; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /deque/MainClass.java: -------------------------------------------------------------------------------- 1 | package deque; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | public class MainClass { 6 | 7 | public static void main(String[] args) { 8 | 9 | ArrayDeque ad = new ArrayDeque<>(); 10 | 11 | 12 | //push method to push the element in the array double ended queue 13 | ad.push(12); 14 | ad.push(23); 15 | ad.push(34); 16 | 17 | //pop method to pop the element at the beginning of a array double ended queue 18 | 19 | System.out.println(ad.pop()); 20 | System.out.println(ad.pop()); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /deque/MyDeque.java: -------------------------------------------------------------------------------- 1 | package deque; 2 | 3 | public class MyDeque { 4 | 5 | Node head, tail; 6 | 7 | public static class Node{ 8 | Node next, prev; 9 | E data; 10 | public Node(E data) { 11 | this.data = data; 12 | this.next = this.prev = null; 13 | } 14 | } 15 | 16 | public boolean isEmpty() { 17 | return head == null; 18 | } 19 | 20 | 21 | public void addFirst(E data) { 22 | Node toAdd = new Node<>(data); 23 | if(head == null) { 24 | head = tail = toAdd; 25 | } 26 | head.next = toAdd; 27 | toAdd.prev = head; 28 | head = toAdd; 29 | } 30 | 31 | public void addLast(E data) { 32 | Node toAdd = new Node<>(data); 33 | if(tail == null) { 34 | tail = head = toAdd; 35 | return; 36 | } 37 | tail.prev = toAdd; 38 | toAdd.next = tail; 39 | tail = toAdd; 40 | } 41 | 42 | public E removeLast() { 43 | if(head == null) { 44 | return null; 45 | } 46 | if(tail.next == null) { 47 | Node toRemove = tail; 48 | tail = head = null; 49 | return toRemove.data; 50 | } 51 | Node toRemove = tail; 52 | tail = tail.next; 53 | tail.prev = null; 54 | return toRemove.data; 55 | } 56 | public E removeFirst() { 57 | if(head == null) { 58 | return null; 59 | } 60 | if(head.prev == null) { 61 | Node toRemove = head; 62 | head = tail = null; 63 | return toRemove.data; 64 | } 65 | Node toRemove = head; 66 | head = head.prev; 67 | head.next = null; 68 | return toRemove.data; 69 | } 70 | 71 | void push(E data) { 72 | addFirst(data); 73 | } 74 | 75 | E pop() { 76 | return removeFirst(); 77 | } 78 | 79 | public E peekLast() { 80 | return tail.data; 81 | } 82 | 83 | public E peekFirst() { 84 | return head.data; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /dp/DynamicProgrammingBasic.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | import java.util.Arrays; 4 | 5 | public class DynamicProgrammingBasic { 6 | 7 | public static void main(String[] args) { 8 | 9 | int n = 18; 10 | int a[] = {7, 5, 1}; 11 | 12 | int dp[] = new int[n+1]; 13 | Arrays.fill(dp, -1); 14 | dp[0] = 0; 15 | 16 | int ans = minCoins(n, a, dp); 17 | System.out.println(ans); 18 | 19 | for(int x: dp) { 20 | System.out.print(x+" "); 21 | } 22 | } 23 | 24 | static int minCoins(int n, int a[], int dp[]) { 25 | 26 | if(n == 0) return 0; 27 | 28 | int ans = Integer.MAX_VALUE; 29 | 30 | for(int i = 0; i= 0) { 32 | int subAns = 0; 33 | if(dp[n-a[i]] != -1) { 34 | subAns = dp[n-a[i]]; 35 | } else { 36 | subAns = minCoins(n-a[i], a, dp); 37 | } 38 | if(subAns != Integer.MAX_VALUE && 39 | subAns + 1 < ans) { 40 | ans = subAns + 1; 41 | } 42 | } 43 | } 44 | return dp[n] = ans; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /dp/ZeroOneKnapsack.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | public class ZeroOneKnapsack { 4 | 5 | public static void main(String[] args) { 6 | 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /graphs/Graph.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | import java.util.*; 4 | 5 | public class Graph { 6 | 7 | private LinkedList adj[]; 8 | 9 | public Graph(int v) { 10 | adj = new LinkedList[v]; 11 | for(int i = 0; i(); 13 | } 14 | } 15 | 16 | public void addEdge(int source, int destination) { 17 | adj[source].add(destination); 18 | adj[destination].add(source); 19 | } 20 | 21 | public int bfs(int source, int destination) { 22 | 23 | boolean vis[] = new boolean[adj.length]; 24 | int parent[] = new int[adj.length]; 25 | Queue q = new LinkedList<>(); 26 | 27 | q.add(source); 28 | parent[source] = -1; 29 | vis[source] = true; 30 | 31 | while(!q.isEmpty()) { 32 | int cur = q.poll(); 33 | if(cur == destination) break; 34 | 35 | for(int neighbor: adj[cur]) { 36 | if(!vis[neighbor]) { 37 | vis[neighbor] = true; 38 | q.add(neighbor); 39 | parent[neighbor] = cur; 40 | } 41 | } 42 | } 43 | 44 | int cur = destination; 45 | int distance = 0; 46 | 47 | 48 | while(parent[cur] != -1) { 49 | System.out.print(cur+" -> "); 50 | cur = parent[cur]; 51 | distance++; 52 | } 53 | 54 | return distance; 55 | } 56 | 57 | private boolean dfsUtil(int source, int destination, boolean vis[]) { 58 | if(source == destination) return true; 59 | 60 | for(int neighbor: adj[source]) { 61 | if(!vis[neighbor]) { 62 | vis[neighbor] = true; 63 | boolean isConnected = dfsUtil(neighbor, destination, vis); 64 | if(isConnected) return true; 65 | } 66 | } 67 | 68 | return false; 69 | } 70 | 71 | public boolean dfsStack(int source, int destination) { 72 | boolean vis[] = new boolean[adj.length]; 73 | vis[source] = true; 74 | Stack stack = new Stack<>(); 75 | 76 | stack.push(source); 77 | 78 | while(!stack.isEmpty()) { 79 | int cur = stack.pop(); 80 | 81 | if(cur == destination) return true; 82 | 83 | for(int neighbor: adj[cur]) { 84 | if(!vis[neighbor]) { 85 | vis[neighbor] = true; 86 | stack.push(neighbor); 87 | } 88 | } 89 | } 90 | 91 | return false; 92 | } 93 | 94 | public boolean dfs(int source, int destination) { 95 | boolean vis[] = new boolean[adj.length]; 96 | vis[source] = true; 97 | 98 | return dfsUtil(source, destination, vis); 99 | } 100 | 101 | 102 | public static void main(String args[]) { 103 | Scanner sc = new Scanner(System.in); 104 | 105 | System.out.println("Enter number of vertices and edges"); 106 | 107 | int v = sc.nextInt(); 108 | int e = sc.nextInt(); 109 | 110 | Graph graph = new Graph(v); 111 | System.out.println("Enter "+ e +" edges"); 112 | for(int i = 0; i> ans = groupAnagrams(strs); 10 | 11 | for (List list : ans) { 12 | System.out.println(list); 13 | } 14 | } 15 | 16 | public static List> groupAnagrams(String[] strs) { 17 | Map> map = new HashMap<>(); 18 | for (String s : strs) { 19 | int count[] = new int[26]; 20 | for (int i = 0; i < s.length(); i++) { 21 | count[s.charAt(i) - 'a']++; 22 | } 23 | String key = Arrays.toString(count); 24 | List list = map.getOrDefault(key, new LinkedList()); 25 | 26 | list.add(s); 27 | map.put(key, list); 28 | } 29 | 30 | return new LinkedList<>(map.values()); 31 | } 32 | } -------------------------------------------------------------------------------- /interviewQuestions/SlidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | package interviewQuestions; 2 | 3 | import java.util.*; 4 | 5 | public class SlidingWindowMaximum { 6 | 7 | public static void main(String[] args) { 8 | 9 | Solution solution = new Solution(); 10 | int a[] = { 4, 3, 1, 2, 5, 3, 4, 7, 1, 9 }; 11 | int ans[] = solution.maxSlidingWindow(a, 4); 12 | 13 | for (int x : ans) { 14 | System.out.print(x + " "); 15 | } 16 | } 17 | 18 | static class Solution { 19 | public int[] maxSlidingWindow(int[] a, int k) { 20 | int n = a.length; 21 | 22 | if (n == 0) { 23 | return a; 24 | } 25 | 26 | Deque dq = new LinkedList<>(); 27 | int ans[] = new int[n - k + 1]; 28 | 29 | int i = 0; 30 | for (; i < k; i++) { 31 | // Adding the index of element in decreasing order of the number present at the 32 | // index till k 33 | /* 34 | * If a number at index 2 is greater than the number at index 1 then remove the 35 | * index 1 and add 2 at the place 36 | */ 37 | /* 38 | * Keep on removeing the index till the number at the index you want to insert 39 | * is greater than the present index number in the dqueue 40 | */ 41 | while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) { 42 | dq.removeLast(); 43 | } 44 | dq.addLast(i); 45 | } 46 | 47 | for (; i < n; i++) { 48 | // Adding the max value in first window to answer array 49 | ans[i - k] = a[dq.peekFirst()]; 50 | 51 | // Chechking if the index in the queue is out of the window we are current in. 52 | // If yes remove the the index from the front 53 | while (!dq.isEmpty() && dq.peekFirst() <= i - k) { 54 | dq.removeFirst(); 55 | } 56 | 57 | /* 58 | * Doing the same thing of chechking the value of current index is greater than 59 | * the value of index present in the dequeue 60 | */ 61 | while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) { 62 | dq.removeLast(); 63 | } 64 | dq.addLast(i); 65 | } 66 | 67 | ans[i - k] = a[dq.peekFirst()]; 68 | 69 | // Returning the ans Array. 70 | return ans; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /interviewQuestions/SubarrayWithZeroSum.java: -------------------------------------------------------------------------------- 1 | package interviewQuestions; 2 | 3 | /* 4 | * Given an array, find if there exists a subarray with sum equals to zero. 5 | * n < 10^5 6 | */ 7 | 8 | import java.util.*; 9 | 10 | public class SubarrayWithZeroSum { 11 | 12 | public static void main(String[] args) { 13 | 14 | int[] a = { 2, 1, 3, -4, -2 }; 15 | int k = -3; 16 | boolean found = false; 17 | 18 | // for(int i = 0; i set = new HashSet<>(); 31 | int sum = 0; 32 | for (int element : a) { 33 | set.add(sum); 34 | sum += element; 35 | //Zero sum will only exist if the cumulative sum of the elements excluding the current element 36 | //and after including the current element are equal 37 | if (set.contains(sum - k)) { 38 | found = true; 39 | break; 40 | } 41 | } 42 | 43 | System.out.println("found " + found); 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /linkedLists/MainLinkedList.java: -------------------------------------------------------------------------------- 1 | package linkedLists; 2 | 3 | import java.util.*; 4 | 5 | public class MainLinkedList { 6 | 7 | public static void main(String[] args) { 8 | 9 | MyLinkedList myLL = new MyLinkedList(); 10 | 11 | 12 | for (int i = 0; i < 10; i++) { 13 | // add method use to add a element in the last node of the linked list 14 | myLL.add(i + "added"); 15 | 16 | } 17 | // print method use to print the linked list 18 | myLL.print(); 19 | } 20 | 21 | } 22 | 23 | -------------------------------------------------------------------------------- /linkedLists/MyLinkedList.java: -------------------------------------------------------------------------------- 1 | package linkedLists; 2 | 3 | public class MyLinkedList { 4 | 5 | 6 | //E is the Class defining the type of the inputs accepted 7 | Node head; 8 | 9 | public void add(E data) { 10 | Node toAdd = new Node(data); 11 | 12 | if (isEmpty()) { 13 | head = toAdd; 14 | return; 15 | } 16 | 17 | //initialising temp as head to traverse the Linked list without breaking the chain 18 | Node temp = head; 19 | // control from loop exits as soon as next element becomes null 20 | while (temp.next != null) { 21 | 22 | temp = temp.next; 23 | } 24 | // adding the new node after reaching to the end of linked list 25 | temp.next = toAdd; 26 | } 27 | 28 | void print() { 29 | Node temp = head; 30 | while (temp != null) { 31 | System.out.print(temp.data + " "); 32 | temp = temp.next; 33 | } 34 | } 35 | 36 | public boolean isEmpty() { 37 | return head == null; 38 | } 39 | 40 | public E removeLast() throws Exception { 41 | Node temp = head; 42 | 43 | if (temp == null) { 44 | throw new Exception("Cannot remove last element from empty linked list"); 45 | } 46 | 47 | if (temp.next == null) { 48 | Node toRemove = head; 49 | head = null; 50 | return toRemove.data; 51 | } 52 | 53 | while (temp.next.next != null) { 54 | temp = temp.next; 55 | } 56 | Node toRemove = temp.next; 57 | temp.next = null; // changing the pointer of temp.next from toRemove to null,and garbage collection is done automatically 58 | return toRemove.data; 59 | } 60 | 61 | public E getLast() throws Exception { 62 | Node temp = head; 63 | 64 | if (temp == null) { 65 | throw new Exception("Cannot peek last element from empty linked list"); 66 | } 67 | while (temp.next != null) { 68 | temp = temp.next; 69 | } 70 | return temp.data; 71 | } 72 | 73 | public static class Node { 74 | public E data; 75 | public Node next; 76 | 77 | //constructor 78 | public Node(E data) { 79 | 80 | this.data = data; 81 | next = null; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /lists/MyArrayList.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | public class MyArrayList { 8 | 9 | public static void main(String[] args) { 10 | 11 | List fruits = new LinkedList(); 12 | 13 | //method to add the element in the list 14 | fruits.add("Apple"); 15 | fruits.add("Orange"); 16 | fruits.add("Hi"); 17 | 18 | String temp[] = new String[fruits.size()]; 19 | 20 | fruits.toArray(temp); 21 | 22 | for (String e : temp) { 23 | System.out.println(e); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /lists/Pair.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | public class Pair { 4 | 5 | X x; 6 | Y y; 7 | 8 | public Pair(X x, Y y) { 9 | this.x = x; 10 | this.y = y; 11 | } 12 | 13 | public void getDescription() { 14 | System.out.println(x + " and " + y); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /maps/HashCodeAndEquals.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class HashCodeAndEquals { 7 | 8 | public static void main(String[] args) { 9 | 10 | Pen pen1 = new Pen(10, "blue"); 11 | Pen pen2 = new Pen(10, "blue"); 12 | 13 | System.out.println(pen1); 14 | System.out.println(pen2); 15 | 16 | // System.out.println(pen1.equals(pen2)); 17 | 18 | Set pens = new HashSet<>(); 19 | pens.add(pen1); 20 | pens.add(pen2); 21 | 22 | System.out.println(pens); 23 | } 24 | 25 | } 26 | 27 | class Pen { 28 | 29 | int price; 30 | String color; 31 | 32 | public Pen(int price, String color) { 33 | this.price = price; 34 | this.color = color; 35 | } 36 | 37 | @Override 38 | public int hashCode() { 39 | final int prime = 31; 40 | int result = 1; 41 | result = prime * result + ((color == null) ? 0 : color.hashCode()); 42 | result = prime * result + price; 43 | return result; 44 | } 45 | 46 | @Override 47 | public boolean equals(Object obj) { 48 | if (this == obj) 49 | return true; 50 | if (obj == null) 51 | return false; 52 | if (getClass() != obj.getClass()) 53 | return false; 54 | Pen other = (Pen) obj; 55 | if (color == null) { 56 | if (other.color != null) 57 | return false; 58 | } else if (!color.equals(other.color)) 59 | return false; 60 | if (price != other.price) 61 | return false; 62 | return true; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /maps/MainClass.java: -------------------------------------------------------------------------------- 1 | package maps; 2 | 3 | import java.util.*; 4 | import java.util.Map.Entry; 5 | 6 | public class MainClass { 7 | 8 | public static void main(String[] args) { 9 | 10 | // Map numbers = new HashMap<>(); 11 | // 12 | // numbers.put("one", 1); 13 | // numbers.put("two", 2); 14 | // numbers.put("five", 5); 15 | // 16 | // numbers.remove("two", 4); 17 | // 18 | // System.out.println(numbers); 19 | // System.out.println(numbers.keySet()); 20 | // System.out.println(numbers.values()); 21 | // System.out.println(numbers.entrySet()); 22 | // 23 | // Set> entries = numbers.entrySet(); 24 | // 25 | // for(Entry entry: entries) { 26 | // entry.setValue(entry.getValue() * 100); 27 | // } 28 | // 29 | // System.out.println(numbers); 30 | 31 | System.out.println(getHash("GOD")); 32 | } 33 | 34 | public static int getHash(String s) { 35 | int hash = 0; 36 | for(int i = 0; i 0) { 25 | 26 | if ( (b&1) != 0) { 27 | res = (res * a % n) % n; 28 | } 29 | 30 | a = (a % n * a % n) % n; 31 | b = b >> 1; 32 | } 33 | 34 | return res; 35 | 36 | } 37 | 38 | 39 | static int gcd(int a, int b) { 40 | 41 | return a % b == 0 ? b : gcd ( b, a%b); 42 | } 43 | 44 | 45 | 46 | 47 | static boolean[] seiveOfEratoSthenes(int n) { 48 | 49 | boolean isPrime[] = new boolean[n+1]; 50 | 51 | Arrays.fill(isPrime, true); 52 | 53 | isPrime[0] = false; 54 | isPrime[1] = false; 55 | 56 | for(int i = 2; i * i <= n; i++) { 57 | 58 | 59 | for(int j = 2*i; j<=n; j += i) { 60 | isPrime[j] = false; 61 | } 62 | 63 | } 64 | 65 | return isPrime; 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /priorityQueues/MainClass.java: -------------------------------------------------------------------------------- 1 | package priorityQueues; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class MainClass { 6 | 7 | public static void main(String[] args) { 8 | 9 | PriorityQueue pq = new PriorityQueue<>(); 10 | 11 | pq.add(45); 12 | pq.add(12); 13 | pq.add(1); 14 | pq.add(100); 15 | 16 | System.out.println(pq); 17 | 18 | System.out.println(pq.remove()); 19 | System.out.println(pq.remove()); 20 | System.out.println(pq.remove()); 21 | System.out.println(pq.remove()); 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /queue/MainClass.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | public class MainClass { 4 | 5 | public static void main(String[] args) { 6 | 7 | MyQueue mq = new MyQueue<>(); 8 | 9 | // method to add element in queue 10 | mq.enqueue(12); 11 | mq.enqueue(2); 12 | mq.enqueue(123); 13 | mq.enqueue(45); 14 | 15 | //printing the element removed from the beginning of queue 16 | System.out.println(mq.dequeue()); 17 | System.out.println(mq.dequeue()); 18 | System.out.println(mq.dequeue()); 19 | System.out.println(mq.dequeue()); 20 | System.out.println(mq.dequeue()); 21 | 22 | mq.enqueue(451); 23 | System.out.println(mq.dequeue()); 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /queue/MyQueue.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import linkedLists.MyLinkedList.Node; 4 | 5 | public class MyQueue { 6 | 7 | private Node head, rear; 8 | 9 | public void enqueue(E e) { 10 | 11 | Node toAdd = new Node<>(e); 12 | if (head == null) { 13 | head = rear = toAdd; 14 | return; 15 | } 16 | 17 | rear.next = toAdd; 18 | rear = rear.next; 19 | 20 | } 21 | 22 | public E dequeue() { 23 | 24 | if (head == null) { 25 | return null; 26 | } 27 | 28 | Node temp = head; 29 | head = head.next; 30 | 31 | if (head == null) { 32 | rear = null; 33 | } 34 | 35 | return temp.data; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /recursion/AdvancedQuestions.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.*; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class AdvancedQuestions { 8 | 9 | static Set set = new HashSet<>(); 10 | 11 | public static void main(String[] args) { 12 | // int a[][] = {{1, 1, 1, 1, 1, 1, 1, 1}, 13 | // {1, 1, 1, 1, 1, 1, 0, 0}, 14 | // {1, 0, 0, 1, 1, 0, 1, 1}, 15 | // {1, 2, 2, 2, 2, 0, 1, 0}, 16 | // {1, 1, 1, 2, 2, 0, 1, 0}, 17 | // {1, 1, 1, 2, 2, 2, 2, 0}, 18 | // {1, 1, 1, 1, 1, 2, 1, 1}, 19 | // {1, 1, 1, 1, 1, 2, 2, 1}, 20 | // }; 21 | 22 | // floodFill(a, 0, 0, 3, 1); 23 | // printMatrix(a); 24 | 25 | // permutations("abcc", 0, 3); 26 | 27 | int a[] = {1, 5, 700, 2}; 28 | System.out.println(coinMax(a, 0, a.length-1)); 29 | 30 | } 31 | 32 | static int coinMax(int a[], int l, int r) { 33 | if(l+1 == r) { 34 | return Math.max(a[l], a[r]); 35 | } 36 | 37 | return Math.max(a[l] + Math.min(coinMax(a, l+2, r), coinMax(a, l+1, r-1)), 38 | a[r] + Math.min(coinMax(a, l+1, r-1), coinMax(a, l, r-2))); 39 | } 40 | 41 | static void permutations(String s, int l, int r) { 42 | if(l == r) { 43 | if(set.contains(s)) return; 44 | set.add(s); 45 | System.out.println(s); 46 | return; 47 | } 48 | 49 | for(int i = l; i<=r; i++) { 50 | s = interchangeChar(s, l, i); 51 | permutations(s, l+1, r); 52 | s = interchangeChar(s, l, i); 53 | } 54 | } 55 | 56 | static String interchangeChar(String s, int a, int b) { 57 | char array[] = s.toCharArray(); 58 | char temp = array[a]; 59 | array[a] = array[b]; 60 | array[b] = temp; 61 | return String.valueOf(array); 62 | } 63 | 64 | 65 | static void floodFill(int a[][], int r, int c, int toFill, int prevFill) { 66 | int rows = a.length; 67 | int cols = a[0].length; 68 | 69 | if(r < 0 || r >= rows || c < 0 || c >= cols) { 70 | return; 71 | } 72 | if(a[r][c] != prevFill) { 73 | return; 74 | } 75 | a[r][c] = toFill; 76 | 77 | floodFill(a, r-1, c, toFill, prevFill); 78 | floodFill(a, r, c-1, toFill, prevFill); 79 | floodFill(a, r+1, c, toFill, prevFill); 80 | floodFill(a, r, c+1, toFill, prevFill); 81 | } 82 | 83 | static void printMatrix(int a[][]) { 84 | for(int[] array: a) { 85 | for(int element: array) { 86 | System.out.print(element +" "); 87 | } 88 | System.out.println(); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /recursion/MainClass.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | public class MainClass { 4 | 5 | static int stepCount = 0; 6 | 7 | public static void main(String[] args) { 8 | 9 | // System.out.println(sum(15)); 10 | 11 | // System.out.println(pow(3, 10000)); 12 | // System.out.println("steps " + stepCount); 13 | // 14 | // stepCount = 0; 15 | // System.out.println(fastPow(3, 10000)); 16 | // System.out.println("steps " + stepCount); 17 | 18 | System.out.println(path(200, 1)); 19 | 20 | } 21 | 22 | static int sum(int n) { 23 | if(n == 1) { 24 | return 1; 25 | } 26 | 27 | return n + sum(n-1); 28 | } 29 | 30 | static int pow(int a, int b) { 31 | stepCount++; 32 | if(b == 0) { 33 | return 1; 34 | } 35 | 36 | return a * pow(a, b-1); 37 | } 38 | 39 | static int fastPow(int a, int b) { 40 | System.out.println(b); 41 | stepCount++; 42 | if(b == 0) { 43 | return 1; 44 | } 45 | if(b%2 ==0) { 46 | return fastPow(a*a, b/2); 47 | } 48 | return a*fastPow(a, b-1); 49 | } 50 | //recursive method to find total no.paths to travel from top left corner to bottom right corner in a n*m grid 51 | static int path(int n, int m) { 52 | if(n == 1 || m == 1) return 1; 53 | 54 | return path(n, m-1) + path(m, n-1); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /sets/MainClass.java: -------------------------------------------------------------------------------- 1 | package sets; 2 | 3 | import java.util.*; 4 | 5 | public class MainClass { 6 | 7 | public static void main(String[] args) { 8 | 9 | Set x = new HashSet<>(); 10 | x.add(23); 11 | x.add(1); 12 | x.add(6); 13 | 14 | Set y = new HashSet<>(); 15 | y.add(1); 16 | y.add(12); 17 | 18 | System.out.println(x.containsAll(y)); 19 | 20 | System.out.println(x); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /trees/Tree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Tree { 6 | 7 | static Scanner sc = null; 8 | public static void main(String[] args) { 9 | sc = new Scanner(System.in); 10 | 11 | Node root = createTree(); 12 | inOrder(root); 13 | System.out.println(); 14 | preOrder(root); 15 | System.out.println(); 16 | postOrder(root); 17 | System.out.println(); 18 | } 19 | 20 | static Node createTree() { 21 | 22 | Node root = null; 23 | System.out.println("Enter data: "); 24 | int data = sc.nextInt(); 25 | 26 | if(data == -1) return null; 27 | 28 | root = new Node(data); 29 | 30 | System.out.println("Enter left for " + data); 31 | root.left = createTree(); 32 | 33 | System.out.println("Enter right for "+ data); 34 | root.right = createTree(); 35 | 36 | return root; 37 | } 38 | 39 | static void inOrder(Node root) { 40 | if(root == null) return; 41 | 42 | inOrder(root.left); 43 | System.out.print(root.data+" "); 44 | inOrder(root.right); 45 | } 46 | 47 | static void preOrder(Node root) { 48 | if(root == null) return; 49 | System.out.print(root.data+" "); 50 | preOrder(root.left); 51 | preOrder(root.right); 52 | } 53 | 54 | static void postOrder(Node root) { 55 | if(root == null) return; 56 | 57 | postOrder(root.left); 58 | postOrder(root.right); 59 | System.out.print(root.data+" "); 60 | } 61 | } 62 | 63 | class Node { 64 | Node left, right; 65 | int data; 66 | 67 | public Node(int data) { 68 | this.data = data; 69 | } 70 | } -------------------------------------------------------------------------------- /vectorAndStacks/MainClass.java: -------------------------------------------------------------------------------- 1 | package vectorAndStacks; 2 | 3 | public class MainClass { 4 | 5 | public static void main(String[] args) throws Exception { 6 | 7 | MyStack stack = new MyStack<>(); 8 | 9 | // delete the top element of the stack. 10 | int popped = stack.pop(); 11 | 12 | //print the last popped element of the stack. 13 | System.out.println(popped); 14 | 15 | //print the top element of the stack. 16 | int peeked = stack.peek(); 17 | 18 | System.out.println(peeked); 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /vectorAndStacks/MyStack.java: -------------------------------------------------------------------------------- 1 | package vectorAndStacks; 2 | 3 | import linkedLists.MyLinkedList; 4 | 5 | public class MyStack { 6 | 7 | private MyLinkedList ll = new MyLinkedList<>(); 8 | 9 | void push(E e) { 10 | ll.add(e);//adding the element in the last node of the linked list 11 | } 12 | 13 | E pop() throws Exception { 14 | //handling the empty linked list while trying to pop 15 | if(ll.isEmpty()) { 16 | throw new Exception("Popping from empty stack is not allowed"); 17 | 18 | } 19 | return ll.removeLast(); 20 | } 21 | 22 | E peek() throws Exception { 23 | //handling the empty linked list while trying to peek 24 | if(ll.isEmpty()) { 25 | throw new Exception("Peeking from empty stack is not allowed"); 26 | 27 | } 28 | return ll.getLast(); 29 | } 30 | 31 | } 32 | --------------------------------------------------------------------------------