├── Core Java Raj Handbook.pdf ├── EnterpriseJava └── JDBC │ ├── .vscode │ └── settings.json │ ├── README.md │ ├── bin │ ├── CRUD.class │ ├── ConnectionJDBC.class │ ├── CreatingTable.class │ ├── DisplayData.class │ ├── ImageSavetoDB.class │ ├── InsertDynamicInput.class │ ├── InsertingData.class │ ├── UpdateData.class │ └── pic.png │ └── src │ ├── ConnectionJDBC.class │ ├── ConnectionJDBC.java │ ├── CreatingTable.class │ ├── CreatingTable.java │ ├── DisplayData.class │ ├── DisplayData.java │ ├── ImageSavetoDB.class │ ├── ImageSavetoDB.java │ ├── InsertDynamicInput.class │ ├── InsertDynamicInput.java │ ├── InsertingData.class │ ├── InsertingData.java │ ├── UpdateData.class │ ├── UpdateData.java │ └── pic.png ├── Java 1 - Arrays Interview Questions.pdf ├── Java 2 - Strings Interview Questions.pdf ├── Java Advance Array and Strings.pdf ├── Java Arrays Interview Questions.pdf ├── Java CheatSheet.pdf ├── Java Interview Questions And Answers.pdf ├── Java Interview Questions.pdf ├── Java LeetCode Practice Set 1.pdf ├── Java LeetCode Practice Set 2 String.pdf ├── Java LeetCode Practice Set 3 - LinkedList.pdf ├── Java Strings Interview Questions.pdf ├── JavaArrayList └── Readme.md ├── JavaMath └── Readme.md ├── JavaPractice ├── 0-1_KnapsackProblem │ └── Readme.md ├── AddtwoNumbersRepresentedbyLinkedList │ └── Readme.md ├── BottomViewOfBinaryTree │ └── Readme.md ├── CheckIfSubtree │ └── Readme.md ├── CloneAStackWithoutUsingExtraSpace │ └── Readme.md ├── ConcatenateTwoNumbers │ └── Readme.md ├── CountInversion │ └── Readme.md ├── DetectCycleInaDirectedGraph │ └── readme.md ├── DetectCycleInanUndirectedGraph │ └── Readme.md ├── EscapeTheForbiddenForest │ └── Readme.md ├── ExpressAsSumOfPowerOfNaturalNumbers │ └── Readme.md ├── HeightOfBinaryTree │ └── Readme.md ├── HitMostBalloons │ └── Readme.md ├── InterleavedStrings │ └── Readme.md ├── IntersectionPointinYShappedLinkedLists │ └── Readme.md ├── LCSofThreeStrings │ └── Readme.md ├── LeftViewofBinaryTree │ └── Readme.md ├── LongestCommonSubsequence │ └── Readme.md ├── LongestPrefixSuffix │ └── Readme.md ├── LowestCommonAncestorInABinaryTree │ └── Readme.md ├── MaximumProductSubArray │ └── Readme.md ├── MaximumRectangularAreainaHistogram │ └── Readme.md ├── MaximumXORofTwoNumbersinanArray │ └── Readme.md ├── MinimumNumberOfJumps │ └── Readme.md ├── NextPermutation │ └── Readme.md ├── NodesAtGivenDistanceinBinaryTree │ └── Readme.md ├── OverlappingInterval │ └── Readme.md ├── PreorderTraversal(Iterative) │ └── Readme.md ├── Readme.md ├── RearrangeALinkedList │ └── Readme.md ├── RemoveloopinLinkedList │ └── Readme.md ├── ReturnTwoPrimeNumbers │ └── Readme.md ├── Robots │ └── Readme.md ├── RotateAndDelete │ └── Readme.md ├── RotateLinkedList │ └── Readme.md ├── SearchPattern(Z-algorithm) │ └── Readme.md ├── SmallestWindowContaining 0, 1 and 2 │ └── Readme.md ├── SpideySense │ └── Readme.md ├── TheCelebrityProblem │ └── Readme.md ├── TheFibonacci-primeNumber │ └── Readme.md └── ZeroSumSubArray │ └── Readme.md ├── JavaPre_Practice ├── ArmstrongNumber.java ├── ArmstrongRange.java ├── EvenOdd.java ├── FactorialOfNumber.java ├── FibonacciSeries.java ├── GreaterThree.java ├── GreatestTwoNumber.java ├── PalindromeNumber.java ├── PosNeg.java ├── PrimeNumber.java ├── ReverseNumber.java ├── SumInGivenRange.java ├── SumNnatural.java ├── kthMaxMin.java ├── leapOrNot.java ├── minMaxArray.java ├── primeNumberRange.java ├── printFirstN.java ├── reverseArray.java └── sumDigitsNumbers.java ├── JavaStrings └── Readme.md ├── LICENSE ├── LeetCode Practice Set 1.pdf ├── Oops in Depth by Raj using Java.pdf └── Readme.md /Core Java Raj Handbook.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Core Java Raj Handbook.pdf -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/CRUD.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/CRUD.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/ConnectionJDBC.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/ConnectionJDBC.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/CreatingTable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/CreatingTable.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/DisplayData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/DisplayData.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/ImageSavetoDB.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/ImageSavetoDB.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/InsertDynamicInput.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/InsertDynamicInput.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/InsertingData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/InsertingData.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/UpdateData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/UpdateData.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/bin/pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/bin/pic.png -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/ConnectionJDBC.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/ConnectionJDBC.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/ConnectionJDBC.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | public class ConnectionJDBC { 3 | public static void main(String[] args){ 4 | try{ 5 | // Load the Driver 6 | Class.forName("com.mysql.jdbc.Driver"); 7 | // Creating a connection 8 | String url="jdbc:mysql://localhost:3306/rajdatabase"; 9 | String username="root"; 10 | String password="root123"; 11 | Connection con = DriverManager.getConnection(url,username,password); 12 | if(con.isClosed()){ 13 | System.out.println("Connection is closed...."); 14 | }else{ 15 | System.out.println("Connection Created...."); 16 | } 17 | 18 | }catch (Exception e){ 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/CreatingTable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/CreatingTable.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/CreatingTable.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | public class CreatingTable { 3 | public static void main(String[] args) { 4 | try{ 5 | Class.forName("com.mysql.jdbc.Driver"); 6 | 7 | String url = "jdbc:mysql://localhost:3306/rajdatabase"; 8 | String username = "root"; 9 | String password = "root123"; 10 | 11 | Connection con = DriverManager.getConnection(url, username, password); 12 | 13 | String q = "create table MyInfo(uID int (20) primary key auto_increment, First_Name varchar(200) not null, Last_Name varchar(50))"; 14 | 15 | Statement stat = con.createStatement(); 16 | stat.executeUpdate(q); 17 | System.out.println("Table created successfully..."); 18 | con.close(); 19 | } 20 | catch(Exception e){ 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/DisplayData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/DisplayData.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/DisplayData.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | 3 | public class DisplayData { 4 | public static void main(String[] args) { 5 | 6 | try { 7 | Class.forName("com.mysql.jdbc.Driver"); 8 | Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rajdatabase", "root", "root123"); 9 | 10 | String query = "select* from myinfo"; 11 | Statement stmt = con.createStatement(); 12 | ResultSet set = stmt.executeQuery(query); 13 | 14 | while(set.next()){ 15 | int id = set.getInt(1); 16 | System.out.print("\tID: "+id); 17 | String fname = set.getString(2); 18 | System.out.print("\tFirst Name: "+fname); 19 | String lname = set.getString(3); 20 | System.out.print("\tLast Name: "+lname); 21 | System.out.println(); 22 | } 23 | con.close(); 24 | } catch (Exception e) { 25 | System.out.println(e); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/ImageSavetoDB.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/ImageSavetoDB.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/ImageSavetoDB.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | import java.io.*; 3 | 4 | public class ImageSavetoDB { 5 | public static void main(String[] args) { 6 | try { 7 | Class.forName("com.mysql.jdbc.Driver"); 8 | Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rajdatabase", "root", "root123"); 9 | // create table iamges(id int primary key auto_increment, pic blog); 10 | // blog -- binary large object 11 | 12 | String query = "insert into images(pic) value(?)"; 13 | 14 | PreparedStatement pstmt = con.prepareStatement(query); 15 | FileInputStream files = new FileInputStream("pic.png"); 16 | 17 | pstmt.setBinaryStream(1,files, files.available()); 18 | pstmt.executeUpdate(); 19 | 20 | System.out.println("Done..."); 21 | 22 | } catch (Exception e) { 23 | System.out.println(e); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/InsertDynamicInput.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/InsertDynamicInput.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/InsertDynamicInput.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | import java.io.*; 3 | public class InsertDynamicInput { 4 | public static void main(String[] args) { 5 | try { 6 | Class.forName("com.mysql.jdbc.Driver"); 7 | 8 | String url = "jdbc:mysql://localhost:3306/rajdatabase"; 9 | String username = "root"; 10 | String password = "root123"; 11 | 12 | Connection con = DriverManager.getConnection(url, username, password); 13 | 14 | String queryInsert = "insert into myinfo(First_Name,Last_Name) values (?,?)"; 15 | 16 | PreparedStatement pstmt = con.prepareStatement(queryInsert); 17 | 18 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 19 | 20 | System.out.print("Enter First Name: "); 21 | String fname = br.readLine(); 22 | System.out.print("Enter Last Name: "); 23 | String lname = br.readLine(); 24 | 25 | 26 | pstmt.setString(1, fname); 27 | pstmt.setString(2, lname); 28 | 29 | pstmt.executeUpdate(); 30 | System.out.println("Data Inserted successfully..."); 31 | 32 | ResultSet rs = pstmt.executeQuery("Select * from myinfo"); 33 | while(rs.next()) 34 | { 35 | System.out.print("First Name: " + rs.getString(2)); 36 | System.out.println("\t,Last Name: " + rs.getString(3)); 37 | } 38 | con.close(); 39 | } catch (Exception e) { 40 | e.printStackTrace(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/InsertingData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/InsertingData.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/InsertingData.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | 3 | public class InsertingData { 4 | public static void main(String[] args) { 5 | try { 6 | Class.forName("com.mysql.jdbc.Driver"); 7 | 8 | String url = "jdbc:mysql://localhost:3306/rajdatabase"; 9 | String username = "root"; 10 | String password = "root123"; 11 | 12 | Connection con = DriverManager.getConnection(url, username, password); 13 | 14 | String queryInsert = "insert into myinfo(First_Name,Last_Name) values (?,?)"; 15 | 16 | PreparedStatement pstmt = con.prepareStatement(queryInsert); 17 | 18 | pstmt.setString(1, "Raj"); 19 | pstmt.setString(2, "Singh"); 20 | 21 | pstmt.executeUpdate(); 22 | System.out.println("Data Inserted successfully..."); 23 | con.close(); 24 | } catch (Exception e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/UpdateData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/UpdateData.class -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/UpdateData.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.sql.*; 4 | 5 | public class UpdateData { 6 | public static void main(String[] args) { 7 | 8 | try { 9 | Class.forName("com.mysql.jdbc.Driver"); 10 | Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/rajdatabase", "root", "root123"); 11 | 12 | String query = "update myinfo set First_Name=?, Last_Name=? where uID=?"; 13 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 14 | 15 | System.out.print("Enter First Name: "); 16 | String fname = br.readLine(); 17 | 18 | System.out.print("Enter Last Name: "); 19 | String lname = br.readLine(); 20 | 21 | System.out.print("Enter the user Id: "); 22 | int id = Integer.parseInt(br.readLine()); 23 | 24 | PreparedStatement pstmt = con.prepareStatement(query); 25 | 26 | pstmt.setString(1, fname); 27 | pstmt.setString(2, lname); 28 | pstmt.setInt(3, id); 29 | 30 | pstmt.executeUpdate(); 31 | System.out.println("Changes Done..."); 32 | 33 | con.close(); 34 | } catch (Exception e) { 35 | System.out.println(e); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /EnterpriseJava/JDBC/src/pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/EnterpriseJava/JDBC/src/pic.png -------------------------------------------------------------------------------- /Java 1 - Arrays Interview Questions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java 1 - Arrays Interview Questions.pdf -------------------------------------------------------------------------------- /Java 2 - Strings Interview Questions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java 2 - Strings Interview Questions.pdf -------------------------------------------------------------------------------- /Java Advance Array and Strings.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java Advance Array and Strings.pdf -------------------------------------------------------------------------------- /Java Arrays Interview Questions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java Arrays Interview Questions.pdf -------------------------------------------------------------------------------- /Java CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java CheatSheet.pdf -------------------------------------------------------------------------------- /Java Interview Questions And Answers.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java Interview Questions And Answers.pdf -------------------------------------------------------------------------------- /Java Interview Questions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java Interview Questions.pdf -------------------------------------------------------------------------------- /Java LeetCode Practice Set 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java LeetCode Practice Set 1.pdf -------------------------------------------------------------------------------- /Java LeetCode Practice Set 2 String.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java LeetCode Practice Set 2 String.pdf -------------------------------------------------------------------------------- /Java LeetCode Practice Set 3 - LinkedList.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java LeetCode Practice Set 3 - LinkedList.pdf -------------------------------------------------------------------------------- /Java Strings Interview Questions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RajSDE/Java/c87234d6014d654ce44c2a8067e6b1c9351fcc01/Java Strings Interview Questions.pdf -------------------------------------------------------------------------------- /JavaArrayList/Readme.md: -------------------------------------------------------------------------------- 1 | ## Java ArrayList 2 | Java ArrayList class uses a `dynamic array` for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the `java.util` package. It is like the `Vector` in C++. 3 | 4 | The ArrayList in Java can have the duplicate elements also. An ArrayList class extends `AbstractList` class which implements `List interface`. The List interface extends the `Collection` and `Iterable interfaces` in hierarchical order. 5 | 6 | The important points about Java ArrayList class are: 7 | 8 | - Java ArrayList class can contain duplicate elements. 9 | - Java ArrayList class maintains insertion order. 10 | - Java ArrayList class is non synchronized. 11 | - Java ArrayList allows random access because array works at the index basis. 12 | - In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list. 13 | 14 | The difference between a `built-in array` and an `ArrayList` in Java, is that the size of an array cannot be modified (if we want to add or remove elements to/from an array, we have to create a new one). While elements can be added and removed from an ArrayList whenever we want. 15 | 16 | **ArrayList class declaration** 17 | Let's see the declaration for java.util.ArrayList class. 18 | 19 | ``` 20 | 21 | public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable 22 | ``` 23 | 24 | **Create an ArrayList object called list** 25 | Elements in an ArrayList are actually objects. To use other types, such as int, we must specify an equivalent wrapper class: `Integer`. For other primitive types, use: `Boolean` for boolean, `Character` for char, `Double` for double, etc: 26 | ``` 27 | import java.util.ArrayList; // import the ArrayList class 28 | ArrayList list1 = new ArrayList(); 29 | ArrayList list2 = new ArrayList(); 30 | ArrayList list3 = new ArrayList(); 31 | ArrayList list3 = new ArrayList(); 32 | ``` 33 | 34 | ## ArrayList Methods 35 | 36 | | Methods | Description| 37 | | :---------| :----------| 38 | | `add(int index, Object element)` | This method is used to insert a specific element at a specific position index in a list. | 39 | | `add(Object o)` | This method is used to append a specific element to the end of a list. | 40 | | `addAll(Collection C)` | This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator. | 41 | | `addAll(int index, Collection C)` | Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list. | 42 | | `clear()` | This method is used to remove all the elements from any list. | 43 | | `clone()` | This method is used to return a shallow copy of an ArrayList. | 44 | | `contains?(Object o)` | Returns true if this list contains the specified element. | 45 | | `ensureCapacity?(int minCapacity)` | Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. | 46 | | `forEach?(Consumer action)` | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. | 47 | | `get?(int index)` | Returns the element at the specified position in this list. | 48 | | `indexOf(Object O)` | The index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list. | 49 | | `isEmpty?()` | Returns true if this list contains no elements. | 50 | | `lastIndexOf(Object O)` | The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list. | 51 | | `listIterator?()` | Returns a list iterator over the elements in this list (in proper sequence). | 52 | | `listIterator?(int index)` | Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. | 53 | | `remove?(int index)` | Removes the element at the specified position in this list. | 54 | | `remove?(Object o)` | Removes the first occurrence of the specified element from this list, if it is present. | 55 | | `removeAll?(Collection c)` | Removes from this list all of its elements that are contained in the specified collection. | 56 | | `removeIf?(Predicate filter)` | Removes all of the elements of this collection that satisfy the given predicate. | 57 | | `removeRange?(int fromIndex, int toIndex)` | Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. | 58 | | `retainAll?(Collection c)` | Retains only the elements in this list that are contained in the specified collection. | 59 | | `set?(int index, E element)` | Replaces the element at the specified position in this list with the specified element. | 60 | | `size?()` | Returns the number of elements in this list. | 61 | | `spliterator?()` | Creates a late-binding and fail-fast Spliterator over the elements in this list. | 62 | | `subList?(int fromIndex, int toIndex)` | Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. | 63 | | `toArray()` | This method is used to return an array containing all of the elements in the list in the correct order. | 64 | | `toArray(Object[] O)` | It is also used to return an array containing all of the elements in this list in the correct order same as the previous method. | 65 | | `trimToSize()` | This method is used to trim the capacity of the instance of the ArrayList to the list’s current size. | 66 | 67 |
68 | 69 | 70 | ### `add()` 71 | It is used to append the specified element at the end of a list. 72 | ``` 73 | ArrayList cars = new ArrayList(); 74 | cars.add("Volvo"); 75 | cars.add("BMW"); 76 | cars.add("Ford"); 77 | cars.add("Mazda"); 78 | System.out.println(cars); 79 | ``` 80 | ### `add(int index, E element)` 81 | It is used to insert the specified element at the specified position in a list. 82 | ``` 83 | 84 | List colors = new ArrayList<>(); 85 | colors.add("red"); // ["red"] 86 | colors.add("blue"); // ["red" , "blue"] 87 | colors.add(1, "white"); // ["red" , "white", "blue"] 88 | colors.add(0, "black"); // ["black", "red" , "white", "blue"] 89 | System.out.println(colors); // ["black", "red" , "white", "blue"] 90 | ``` 91 | 92 | ### `addAll(Collection c)` 93 | 94 | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. 95 | ``` 96 | // boolean addAll(Collection c) 97 | // boolean addAll(int index, Collection c) 98 | 99 | ArrayList letters = new ArrayList<>(); 100 | letters.add("A"); 101 | letters.add("B"); 102 | letters.add("C"); 103 | System.out.println(letters); // [A, B, C] 104 | ArrayList words = new ArrayList<>(); 105 | words.add("Apple"); 106 | words.add("Ball"); 107 | words.add("Cat"); 108 | System.out.println(words); // [Apple, Ball, Cat] 109 | System.out.println (letters.addAll(words)); //true 110 | System.out.println(letters); // [A, B, C, Apple, Ball, Cat] 111 | ``` 112 | 113 | 114 | ### `get()` 115 | Access an Item 116 | ``` 117 | cars.get(0); 118 | ``` 119 | 120 | ### `set()` 121 | Change an Item 122 | ``` 123 | cars.set(0, "Opel"); 124 | ``` 125 | 126 | ### `remove()` 127 | Remove an Item 128 | ``` 129 | cars.remove(0); 130 | ``` 131 | 132 | ### `clear()` 133 | Remove all the elements 134 | ``` 135 | cars.clear(); 136 | ``` 137 | 138 | ### `size` 139 | ArrayList Size 140 | ``` 141 | cars.size(); 142 | ``` 143 | 144 | ### `sort()` 145 | 146 | - Sort an ArrayList in `Ascending Order` 147 | Another useful class in the java.util package is the `Collections class`, which include the sort() method for sorting lists alphabetically or numerically: 148 | ``` 149 | ArrayList cars = new ArrayList(); 150 | cars.add("Volvo"); 151 | cars.add("BMW"); 152 | cars.add("Ford"); 153 | cars.add("Mazda"); 154 | Collections.sort(cars); // Sort cars 155 | for (String i : cars) { 156 | System.out.println(i); 157 | ``` 158 | 159 | - Sort an ArrayList in `Descending Order` 160 | ``` 161 | Collections.sort(ArrayList, Collections.reverseOrder()); 162 | ``` 163 | 164 | ### `isEmpty()` 165 | It returns true if the list is empty, otherwise false. 166 | ``` 167 | // creating an Empty Integer ArrayList 168 | ArrayList arr = new ArrayList(10); 169 | 170 | // check if the list is empty or not using function 171 | boolean ans = arr.isEmpty(); 172 | 173 | if (ans == true) 174 | System.out.println("The ArrayList is empty"); 175 | else 176 | System.out.println("The ArrayList is not empty"); 177 | ``` 178 | 179 | ### `Iterator()` 180 | The ArrayList.Iterator () returns an iterator over the elements in this list. 181 | ``` 182 | ArrayListarrlist = new ArrayList(); 183 | arrlist.add("d"); 184 | arrlist.add("dd"); 185 | arrlist.add("ddd"); 186 | arrlist.add("dddd"); 187 | arrlist.add("ddddd"); 188 | System.out.println(arrlist); // [d, dd, ddd, dddd, ddddd] 189 | 190 | Iterator iterator = arrlist.iterator(); 191 | while (iterator.hasNext()) 192 | { 193 | String i = iterator.next(); 194 | System.out.println(i); 195 | ``` 196 | 197 | ### `listIterator()` 198 | The listIterator () method of Java ArrayList returns a list iterator over the elements in this list starting at the specified position in this list. 199 | ``` 200 | ArrayList arrlist = new ArrayList(); 201 | arrlist.add("d"); 202 | arrlist.add("dd"); 203 | arrlist.add("ddd"); 204 | arrlist.add("dddd"); 205 | arrlist.add("ddddd"); 206 | System.out.println(arrlist); // [d, dd, ddd, dddd, ddddd] 207 | 208 | ListIterator iterator = arrlist.listIterator(2); 209 | while (iterator.hasNext()) 210 | { 211 | String i = iterator.next(); 212 | System.out.println(i); 213 | } 214 | ``` 215 | Output: 216 | ``` 217 | [d, dd, ddd, dddd, ddddd] 218 | ddd 219 | dddd 220 | ddddd 221 | ``` 222 | 223 | ### `lastIndexOf() ` 224 | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. 225 | ``` 226 | ArrayList arr = new ArrayList(7); 227 | 228 | // using add() to initialize values 229 | arr.add(10); 230 | arr.add(20); 231 | arr.add(30); 232 | arr.add(40); 233 | arr.add(30); 234 | arr.add(30); 235 | arr.add(40); 236 | int element = arr.lastIndexOf(30); 237 | if (element != -1) 238 | System.out.println("the lastIndexof of + " 30 is " + element); 239 | else 240 | System.out.println("30 is not in" + " the list; 241 | 242 | // the lastIndexof of 30 is 5 243 | ``` 244 | 245 | ### `Object[] toArray()` 246 | It is used to return an array containing all of the elements in this list in the correct order. 247 | ``` 248 | List al = new ArrayList(); 249 | al.add(10); 250 | al.add(20); 251 | al.add(30); 252 | al.add(40); 253 | 254 | Object[] objects = al.toArray(); 255 | 256 | // Printing array of objects 257 | for (Object obj : objects) 258 | System.out.print(obj + " "); 259 | ``` 260 | **Note:** toArray() method returns an array of type Object(Object[]). We need to typecast it to Integer before using as Integer objects. 261 | ``` 262 | List al = new ArrayList(); 263 | al.add(10); 264 | al.add(20); 265 | al.add(30); 266 | al.add(40); 267 | 268 | // Error: incompatible types: Object[] 269 | // cannot be converted to Integer[] 270 | Integer[] objects = al.toArray(); 271 | 272 | for (Integer obj : objects) 273 | System.out.println(obj); 274 | ``` -------------------------------------------------------------------------------- /JavaMath/Readme.md: -------------------------------------------------------------------------------- 1 | ### Java Math Functions 2 | The Java Math class has many methods that allows you to perform mathematical tasks on numbers. 3 | 4 | | Method | Descriptions | Return Type | 5 | | :-------- | :------- | :------------------------- | 6 | |`abs(x)` | `Returns the absolute value of x` | double / float / int / long 7 | |`acos(x)` | `Returns the arccosine of x, in radians` | double 8 | |`asin(x)` | `Returns the arcsine of x, in radians` | double 9 | |`atan(x)` | `Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians` | double 10 | |`atan2(y,x)`| `Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).` | double 11 | |`cbrt(x)` | `Returns the cube root of x` | double 12 | |`ceil(x)` | `Returns the value of x rounded up to its nearest integer` | double 13 | |`copySign(x, y)` | `Returns the first floating point x with the sign of the second floating point y` | double 14 | |`cos(x)` | `Returns the cosine of x (x is in radians)` | double 15 | |`cosh(x)` | `Returns the hyperbolic cosine of a double value` | double 16 | |`exp(x)` | `Returns the value of E.pow(x)` | double 17 | |`expm1(x)` | `Returns e.pow(x) -1` | double 18 | |`floor(x)` | `Returns the value of x rounded down to its nearest integer` | double 19 | |`getExponent(x)` | `Returns the unbiased exponent used in x` | int 20 | | `hypot(x, y)` | `Returns sqrt(x2 +y2) without intermediate overflow or underflow` | double 21 | |`IEEEremainder(x, y)` | `Computes the remainder operation on x and y as prescribed by the IEEE 754 standard` | double 22 | |`log(x)` | `Returns the natural logarithm (base E) of x` | double 23 | |`log10(x)` | `Returns the base 10 logarithm of x` | double 24 | |`log1p(x)` | `Returns the natural logarithm (base E) of the sum of x and 1` | double 25 | |`max(x, y)` | `Returns the number with the highest value` | double / float / int / long 26 | |`min(x, y)` | `Returns the number with the lowest value` | double / float / int / long 27 | |`nextAfter(x, y)` | `Returns the floating point number adjacent to x in the direction of y` | double / float 28 | |`nextUp(x)` | `Returns the floating point value adjacent to x in the direction of positive infinity` | double / float 29 | |`pow(x, y)` | `Returns the value of x to the power of y` | double 30 | |`random()` | `Returns a random number between 0 and 1` | double 31 | |`round(x)` | `Returns the value of x rounded to its nearest integer` | int 32 | |`rint()` | `Returns the double value that is closest to x and equal to a mathematical integer` | double 33 | |`signum(x)` | `Returns the sign of x` | double 34 | |`sin(x)` | `Returns the sine of x (x is in radians)` | double 35 | |`sinh(x)` | `Returns the hyperbolic sine of a double value` | double 36 | |`sqrt(x)` | `Returns the square root of x` | double 37 | |`tan(x)` | `Returns the tangent of an angle` | double 38 | |`tanh(x)` | `Returns the hyperbolic tangent of a double value` | double 39 | |`toDegrees(x)` | `Converts an angle measured in radians to an approx. equivalent angle measured in degrees` | double 40 | |`toRadians(x)` | `Converts an angle measured in degrees to an approx. angle measured in radians` | double 41 | |`ulp(x)` | `Returns the size of the unit of least precision (ulp) of x` | double / float 42 | 43 | **Note:** All Math methods are `static`. 44 | 45 | **Math Class methods helps to perform the numeric operations like square, square root, cube, cube root, exponential and trigonometric operations** 46 | - **What is NaN argument?** 47 | A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L). 48 | 49 |
50 | 51 | ### `abs(), acos(), toRadians()` 52 | ``` 53 | // Declaring the variables 54 | int Vali = -1; 55 | float Valf = .5f; 56 | 57 | // Printing the values 58 | System.out.println("Initial value of int : "+Vali); 59 | System.out.println("Initial value of int : "+Valf); 60 | 61 | 62 | // Use of .abs() method to get the absoluteValue 63 | int Absi = Math.abs(Vali); 64 | float Absf = Math.abs(Valf); 65 | 66 | System.out.println("Absolute value of int : "+Absi); 67 | System.out.println("Absolute value of int : "+Absf); 68 | System.out.println(""); 69 | 70 | // Use of acos() method 71 | // Value greater than 1, so passing NaN 72 | double Acosi = Math.acos(60); 73 | System.out.println("acos value of Acosi : "+Acosi); 74 | double x = Math.PI; 75 | 76 | // Use of toRadian() method 77 | x = Math.toRadians(x); 78 | double Acosj = Math.acos(x); 79 | System.out.println("acos value of Acosj : "+Acosj); 80 | ``` 81 | 82 | **Output:** 83 | ``` 84 | Initial value of int : -1 85 | Initial value of int : 0.5 86 | Absolute value of int : 1 87 | Absolute value of int : 0.5 88 | 89 | acos value of Acosi : NaN 90 | acos value of Acosj : 1.5159376794536454 91 | ``` 92 | 93 |
94 | 95 | ### `asin(), cbrt()` 96 | ``` 97 | int a = 1, b = 8; 98 | int radd = a+b; 99 | 100 | // Use of asin() method 101 | // Value greater than 1, so passing NaN 102 | double Asini = Math.asin(radd); 103 | System.out.println("asin value of Asini : " + Asini); 104 | double x = Math.PI; 105 | 106 | // Use of toRadian() method 107 | x = Math.toRadians(x); 108 | double Asinj = Math.asin(x); 109 | System.out.println("asin value of Asinj : " + Asinj); 110 | System.out.println(""); 111 | 112 | // Use of cbrt() method 113 | double cbrtval = Math.cbrt(216); 114 | System.out.println("cube root : " + cbrtval); 115 | ``` 116 | **Output:** 117 | ``` 118 | asin value of Asini : NaN 119 | asin value of Asinj : 0.054858647341251204 120 | 121 | cube root : 6.0 122 | ``` 123 |
124 | 125 | ### `floor(), hypot(), IEEEremainder(), log()` 126 | 127 | ``` 128 | // Use of floor method 129 | double f1 = 30.56, f2 = -56.34; 130 | f1 =Math.floor(f1); 131 | System.out.println("Floor value of f1 : "+f1); 132 | 133 | f2 =Math.floor(f2); 134 | System.out.println("Floor value of f2 : "+f2); 135 | System.out.println(""); 136 | 137 | // Use of hypot() method 138 | double p = 12, b = -5; 139 | double h = Math.hypot(p, b); 140 | System.out.println("Hypotenuse : "+h); 141 | System.out.println(""); 142 | 143 | // Use of IEEEremainder() method 144 | double d1 = 105, d2 = 2; 145 | double r = Math.IEEEremainder(d1,d2); 146 | System.out.println("Remainder : "+r); 147 | System.out.println(""); 148 | 149 | // Use of log() method 150 | double l = 10; 151 | l = Math.log(l); 152 | System.out.println("Log value of 10 : "+l); 153 | ``` 154 | 155 | **Output:** 156 | ``` 157 | Floor value of f1 : 30.0 158 | Floor value of f2 : -57.0 159 | 160 | Hypotenuse : 13.0 161 | 162 | Remainder : 1.0 163 | 164 | Log value of 10 : 2.302585092994046 165 | ``` 166 |
167 | 168 | ### `atan(), ceil(), copySign() ` 169 | 170 | ``` 171 | // Use of atan() method 172 | double Atani = Math.atan(0); 173 | System.out.println("atan value of Atani : "+Atani); 174 | double x = Math.PI/2; 175 | 176 | // Use of toRadian() method 177 | x = Math.toRadians(x); 178 | double Atanj = Math.atan(x); 179 | System.out.println("atan value of Atanj : "+Atanj); 180 | System.out.println(""); 181 | 182 | 183 | // Use of ceil() method 184 | double val = 15.34 ,ceilval; 185 | ceilval = Math.ceil(val); 186 | System.out.println("ceil value of val : "+ceilval); 187 | System.out.println(""); 188 | 189 | double dblMag = val; 190 | double dblSign1 = 3; 191 | double dblSign2 = -3; 192 | 193 | 194 | // Use of copySign() method 195 | double result1 = Math.copySign(dblMag,dblSign1); 196 | System.out.println("copySign1 : "+result1); 197 | 198 | double result2 = Math.copySign(dblMag,dblSign2); 199 | System.out.println("copySign2 : "+result2); 200 | ``` 201 | 202 | **Output:** 203 | ``` 204 | atan value of Atani : 0.0 205 | atan value of Atanj : 0.0274087022410345 206 | 207 | ceil value of val : 16.0 208 | 209 | copySign1 : 15.34 210 | copySign2 : -15.34 211 | ``` -------------------------------------------------------------------------------- /JavaPractice/0-1_KnapsackProblem/Readme.md: -------------------------------------------------------------------------------- 1 | ## 0 - 1 Knapsack Problem 2 | You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item. 3 | In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or dont pick it (0-1 property). [🔗Goto](https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1/?page=2&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions#) 4 | 5 |
6 | Full Code 7 | 8 | ```java 9 | import java.util.*; 10 | import java.io.*; 11 | import java.lang.*; 12 | 13 | class gfg 14 | { 15 | public static void main(String args[])throws IOException 16 | { 17 | //reading input using BufferedReader class 18 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 19 | 20 | //reading total testcases 21 | int t = Integer.parseInt(read.readLine()); 22 | 23 | while(t-- > 0) 24 | { 25 | //reading number of elements and weight 26 | int n = Integer.parseInt(read.readLine()); 27 | int w = Integer.parseInt(read.readLine()); 28 | 29 | int val[] = new int[n]; 30 | int wt[] = new int[n]; 31 | 32 | String st[] = read.readLine().trim().split("\\s+"); 33 | 34 | //inserting the values 35 | for(int i = 0; i < n; i++) 36 | val[i] = Integer.parseInt(st[i]); 37 | 38 | String s[] = read.readLine().trim().split("\\s+"); 39 | 40 | //inserting the weigths 41 | for(int i = 0; i < n; i++) 42 | wt[i] = Integer.parseInt(s[i]); 43 | 44 | //calling method knapSack() of class Knapsack 45 | System.out.println(new Solution().knapSack(w, wt, val, n)); 46 | } 47 | } 48 | } 49 | ``` 50 |
51 | 52 | ```java 53 | class Solution 54 | { 55 | static int knapSack(int W, int wt[], int val[], int n) 56 | { 57 | int[][] dp = new int[n+1][W+1]; 58 | for(int i=1; i<=n; i++){ 59 | for(int j=1; j<=W; j++){ 60 | if(wt[i-1] <= j){ 61 | dp[i][j] = Math.max(val[i-1] + dp[i-1][j-wt[i-1]], dp[i-1][j]); 62 | } 63 | else{ 64 | dp[i][j] = dp[i-1][j]; 65 | } 66 | } 67 | } 68 | return dp[n][W]; 69 | } 70 | } 71 | ``` -------------------------------------------------------------------------------- /JavaPractice/AddtwoNumbersRepresentedbyLinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | ## Add two numbers represented by Linked List 2 | Given two numbers represented by two linked lists, write a function that returns Sum list. The sum list is linked list representation of addition of two input numbers. [🔗Goto](https://practice.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-list/1/?page=1&difficulty[]=1&category[]=Recursion&sortBy=submissions#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.io.*; 10 | 11 | class Node { 12 | int data; 13 | Node next; 14 | Node(){} 15 | Node(int d) { 16 | data = d; 17 | next = null; 18 | } 19 | } 20 | 21 | 22 | class LinkedList { 23 | Node head; 24 | void printList(Node head) { 25 | while (head != null) { 26 | System.out.print(head.data + " "); 27 | head = head.next; 28 | } 29 | System.out.println(); 30 | } 31 | 32 | 33 | public void push(int new_data) { 34 | Node new_node = new Node(new_data); 35 | new_node.next = head; 36 | head = new_node; 37 | } 38 | 39 | static int getsize(Node head) { 40 | int count = 0; 41 | while (head != null) { 42 | count++; 43 | head = head.next; 44 | } 45 | return count; 46 | } 47 | 48 | static void addTwoLists(LinkedList first, LinkedList second, LinkedList res, GfG g) { 49 | if (first.head == null) { 50 | res.head = second.head; 51 | return; 52 | } 53 | if (second.head == null) { 54 | res.head = first.head; 55 | return; 56 | } 57 | int size1 = getsize(first.head); 58 | int size2 = getsize(second.head); 59 | g.carry = 0; 60 | if (size1 == size2) { 61 | g.addSameSize(first.head, second.head, res); 62 | } else { 63 | if (size1 < size2) { 64 | Node temp = first.head; 65 | first.head = second.head; 66 | second.head = temp; 67 | } 68 | int diff = Math.abs(size1 - size2); 69 | Node temp = first.head; 70 | while (diff-- >= 0) { 71 | g.cur = temp; 72 | temp = temp.next; 73 | } 74 | g.addSameSize(g.cur, second.head, res); 75 | g.addCarryToRemaining(first.head, res); 76 | } 77 | if(g.carry > 0) 78 | res.push(g.carry); 79 | } 80 | 81 | public static void main(String[] args) throws IOException{ 82 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 83 | int t = Integer.parseInt(br.readLine().trim()); 84 | while(t-->0){ 85 | String[] inputline = br.readLine().trim().split(" "); 86 | int n1 = Integer.parseInt(inputline[0]); 87 | int n2 = Integer.parseInt(inputline[1]); 88 | 89 | inputline = br.readLine().trim().split(" "); 90 | LinkedList list1 = new LinkedList(); 91 | for (int i = n1 -1; i >=0 ; i--) { 92 | int a = Integer.parseInt(inputline[i]); 93 | list1.push(a); 94 | } 95 | 96 | inputline = br.readLine().trim().split(" "); 97 | LinkedList list2 = new LinkedList(); 98 | for(int i = n2-1; i >= 0; i--) { 99 | int b = Integer.parseInt(inputline[i]); 100 | list2.push(b); 101 | } 102 | LinkedList res = new LinkedList(); 103 | GfG g = new GfG(); 104 | addTwoLists(list1, list2, res, g); 105 | res.printList(res.head); 106 | } 107 | } 108 | } 109 | ``` 110 |
111 | 112 | ```java 113 | class GfG { 114 | 115 | Node cur; 116 | int carry; 117 | void addCarryToRemaining(Node head, LinkedList res) { 118 | if (head != cur){ 119 | addCarryToRemaining(head.next, res); 120 | int sum = carry + head.data; 121 | carry = sum / 10; 122 | sum %= 10; 123 | 124 | res.push(sum); 125 | } 126 | } 127 | void addSameSize(Node head1, Node head2, LinkedList res) { 128 | if (head1 == null) 129 | return; 130 | addSameSize(head1.next, head2.next, res); 131 | int sum = head1.data + head2.data + carry; 132 | carry = sum / 10; 133 | sum = sum % 10; 134 | res.push(sum); 135 | } 136 | } 137 | ``` -------------------------------------------------------------------------------- /JavaPractice/BottomViewOfBinaryTree/Readme.md: -------------------------------------------------------------------------------- 1 | ## Bottom View of Binary Tree 2 | GGiven a binary tree, print the bottom view from left to right. 3 | A node is included in bottom view if it can be seen when we look at the tree from bottom. [🔗Goto](https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1/?page=2&difficulty[]=1&status[]=unsolved&sortBy=submissions#) 4 | 5 |
6 | Full Code 7 | 8 | ```java 9 | import java.util.LinkedList; 10 | import java.util.Queue; 11 | import java.io.*; 12 | import java.util.*; 13 | 14 | class Node 15 | { 16 | int data; //data of the node 17 | int hd; //horizontal distance of the node 18 | Node left, right; //left and right references 19 | 20 | // Constructor of tree node 21 | public Node(int key) 22 | { 23 | data = key; 24 | hd = Integer.MAX_VALUE; 25 | left = right = null; 26 | } 27 | } 28 | 29 | 30 | 31 | class GfG { 32 | 33 | static Node buildTree(String str){ 34 | 35 | if(str.length()==0 || str.charAt(0)=='N'){ 36 | return null; 37 | } 38 | 39 | String ip[] = str.split(" "); 40 | // Create the root of the tree 41 | Node root = new Node(Integer.parseInt(ip[0])); 42 | // Push the root to the queue 43 | 44 | Queue queue = new LinkedList<>(); 45 | 46 | queue.add(root); 47 | // Starting from the second element 48 | 49 | int i = 1; 50 | while(queue.size()>0 && i < ip.length) { 51 | 52 | // Get and remove the front of the queue 53 | Node currNode = queue.peek(); 54 | queue.remove(); 55 | 56 | // Get the current node's value from the string 57 | String currVal = ip[i]; 58 | 59 | // If the left child is not null 60 | if(!currVal.equals("N")) { 61 | 62 | // Create the left child for the current node 63 | currNode.left = new Node(Integer.parseInt(currVal)); 64 | // Push it to the queue 65 | queue.add(currNode.left); 66 | } 67 | 68 | // For the right child 69 | i++; 70 | if(i >= ip.length) 71 | break; 72 | 73 | currVal = ip[i]; 74 | 75 | // If the right child is not null 76 | if(!currVal.equals("N")) { 77 | 78 | // Create the right child for the current node 79 | currNode.right = new Node(Integer.parseInt(currVal)); 80 | 81 | // Push it to the queue 82 | queue.add(currNode.right); 83 | } 84 | i++; 85 | } 86 | 87 | return root; 88 | } 89 | static void printInorder(Node root) 90 | { 91 | if(root == null) 92 | return; 93 | 94 | printInorder(root.left); 95 | System.out.print(root.data+" "); 96 | 97 | printInorder(root.right); 98 | } 99 | 100 | public static void main (String[] args) throws IOException{ 101 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 102 | 103 | int t=Integer.parseInt(br.readLine()); 104 | 105 | while(t-- > 0){ 106 | String s = br.readLine(); 107 | Node root = buildTree(s); 108 | Solution ob = new Solution(); 109 | ArrayList res = ob.bottomView(root); 110 | for (Integer num : res) System.out.print (num + " "); 111 | System.out.println(); 112 | } 113 | } 114 | } 115 | ``` 116 |
117 | 118 | ```java 119 | class Solution 120 | { 121 | //Function to return a list containing the bottom view of the given tree. 122 | public ArrayList bottomView(Node root) 123 | { 124 | ArrayList ans = new ArrayList<>(); 125 | if(root == null) return ans; 126 | Map map = new TreeMap<>(); 127 | Queue q = new LinkedList(); 128 | root.hd = 0; 129 | q.add(root); 130 | while(!q.isEmpty()) { 131 | Node temp = q.remove(); 132 | int hd = temp.hd; 133 | map.put(hd, temp.data); 134 | if(temp.left != null) { 135 | temp.left.hd = hd - 1; 136 | q.add(temp.left); 137 | } 138 | if(temp.right != null) { 139 | temp.right.hd = hd + 1; 140 | q.add(temp.right); 141 | } 142 | } 143 | 144 | for (Map.Entry entry : map.entrySet()) { 145 | ans.add(entry.getValue()); 146 | } 147 | return ans; 148 | } 149 | } 150 | 151 | ``` -------------------------------------------------------------------------------- /JavaPractice/CheckIfSubtree/Readme.md: -------------------------------------------------------------------------------- 1 | ## Check if subtree 2 | Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T. 3 | A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1. [🔗Goto](https://practice.geeksforgeeks.org/problems/check-if-subtree/1/?page=2&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions#) 4 | 5 |
6 | Full Code 7 | 8 | ```java 9 | import java.util.LinkedList; 10 | import java.util.Queue; 11 | import java.io.*; 12 | import java.util.*; 13 | 14 | class Node{ 15 | int data; 16 | Node left; 17 | Node right; 18 | Node(int data){ 19 | this.data = data; 20 | left=null; 21 | right=null; 22 | } 23 | } 24 | 25 | class GfG { 26 | 27 | static Node buildTree(String str){ 28 | 29 | if(str.length()==0 || str.charAt(0)=='N'){ 30 | return null; 31 | } 32 | 33 | String ip[] = str.split(" "); 34 | // Create the root of the tree 35 | Node root = new Node(Integer.parseInt(ip[0])); 36 | // Push the root to the queue 37 | 38 | Queue queue = new LinkedList<>(); 39 | 40 | queue.add(root); 41 | // Starting from the second element 42 | 43 | int i = 1; 44 | while(queue.size()>0 && i < ip.length) { 45 | 46 | // Get and remove the front of the queue 47 | Node currNode = queue.peek(); 48 | queue.remove(); 49 | 50 | // Get the current node's value from the string 51 | String currVal = ip[i]; 52 | 53 | // If the left child is not null 54 | if(!currVal.equals("N")) { 55 | 56 | // Create the left child for the current node 57 | currNode.left = new Node(Integer.parseInt(currVal)); 58 | // Push it to the queue 59 | queue.add(currNode.left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.length) 65 | break; 66 | 67 | currVal = ip[i]; 68 | 69 | // If the right child is not null 70 | if(!currVal.equals("N")) { 71 | 72 | // Create the right child for the current node 73 | currNode.right = new Node(Integer.parseInt(currVal)); 74 | 75 | // Push it to the queue 76 | queue.add(currNode.right); 77 | } 78 | i++; 79 | } 80 | 81 | return root; 82 | } 83 | static void printInorder(Node root){ 84 | if(root == null) 85 | return; 86 | 87 | printInorder(root.left); 88 | System.out.print(root.data+" "); 89 | 90 | printInorder(root.right); 91 | } 92 | 93 | public static void main (String[] args) throws IOException { 94 | BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); 95 | 96 | int t=Integer.parseInt(br.readLine()); 97 | while(t-- > 0){ 98 | String tt= br.readLine(); 99 | Node rootT = buildTree(tt); 100 | 101 | String s= br.readLine(); 102 | Node rootS = buildTree(s); 103 | // printInorder(root); 104 | 105 | Solution tr=new Solution(); 106 | boolean st=tr.isSubtree(rootT, rootS); 107 | if(st==true){ 108 | System.out.println("1"); 109 | }else{ 110 | System.out.println("0"); 111 | } 112 | } 113 | } 114 | } 115 | ``` 116 |
117 | 118 | ```java 119 | class Solution { 120 | 121 | public static boolean isIdentical(Node root,Node subRoot){ 122 | if(subRoot == null && root == null){ 123 | return true; 124 | } 125 | if(root == null || subRoot == null){ 126 | return false; 127 | } 128 | if(root.data == subRoot.data){ 129 | return isIdentical(root.left, subRoot.left) && isIdentical(root.right, subRoot.right); 130 | } 131 | return false; 132 | } 133 | 134 | 135 | public static boolean isSubtree(Node root, Node subRoot) { 136 | // add code here. 137 | if(subRoot == null){ 138 | return true; 139 | } 140 | if(root == null){ 141 | return false; 142 | } 143 | if(isIdentical(root, subRoot)){ 144 | return true; 145 | } 146 | return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); 147 | } 148 | } 149 | ``` -------------------------------------------------------------------------------- /JavaPractice/CloneAStackWithoutUsingExtraSpace/Readme.md: -------------------------------------------------------------------------------- 1 | ## Clone a stack without using extra space 2 | Given elements of a stack, clone the stack without using extra space. [🔗Goto](https://practice.geeksforgeeks.org/problems/clone-a-stack-without-usinig-extra-space/1/?page=1&difficulty[]=1&status[]=unsolved&sortBy=accuracy#) 3 | 4 | **Example 1:** 5 | 6 | >

Input:
7 | >N = 10
8 | >st[] = {1, 1, 2, 2, 3, 4, 5, 5, 6, 7}
9 | >Output:
10 | >1

11 | 12 |
13 | Full Code 14 | 15 | ```java 16 | import java.io.*; 17 | import java.util.*; 18 | 19 | class GFG { 20 | public static void main(String args[]) throws IOException { 21 | BufferedReader read = 22 | new BufferedReader(new InputStreamReader(System.in)); 23 | int t = Integer.parseInt(read.readLine()); 24 | while (t-- > 0) { 25 | int N = Integer.parseInt(read.readLine()); 26 | 27 | String S[] = read.readLine().split(" "); 28 | 29 | Stack st = new Stack(); 30 | ArrayList copy = new ArrayList<>(); 31 | 32 | for(int i=0; i cloned = new Stack(); 41 | 42 | Solution ob = new Solution(); 43 | 44 | ob.clonestack(st,cloned); 45 | 46 | ArrayList check = new ArrayList<>(); 47 | while(cloned.size() != 0) 48 | check.add(cloned.pop()); 49 | 50 | int flag = 0; 51 | 52 | if(copy.equals(check)) 53 | flag = 0; 54 | else 55 | flag = 1; 56 | 57 | System.out.println(1-flag); 58 | } 59 | } 60 | } 61 | ``` 62 |
63 | 64 | ```java 65 | class Solution { 66 | void clonestack(Stack st, Stack cloned) { 67 | // // approach 1: 68 | // if(st.isEmpty()) 69 | // return; 70 | // int top = st.peek(); 71 | // st.pop(); 72 | // clonestack(st,cloned); 73 | // cloned.push(top); 74 | 75 | // // approach 2: 76 | cloned.addAll(st); 77 | 78 | // // approach 3: 79 | // if(st.isEmpty()) 80 | // return; 81 | // int top = st.pop(); 82 | // clonestack(st,cloned); 83 | // cloned.push(top); 84 | 85 | // // approach 4: 86 | // for(int i=0; i 6 | Full Code 7 | 8 | ```java 9 | import java.io.*; 10 | import java.util.*; 11 | class GFG{ 12 | public static void main(String args[]) throws IOException { 13 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 14 | int t = Integer.parseInt(read.readLine()); 15 | 16 | while(t-- > 0){ 17 | 18 | String input_line[] = read.readLine().trim().split("\\s+"); 19 | int N = Integer.parseInt(input_line[0]); 20 | int X = Integer.parseInt(input_line[1]); 21 | 22 | input_line = read.readLine().trim().split("\\s+"); 23 | int numbers[]= new int[N]; 24 | for(int i = 0; i < N; i++) 25 | numbers[i] = Integer.parseInt(input_line[i]); 26 | 27 | Solution ob = new Solution(); 28 | long ans = ob.countPairs(N, X, numbers); 29 | System.out.println(ans); 30 | } 31 | } 32 | } 33 | ``` 34 | 35 | 36 | ```java 37 | class Solution 38 | { 39 | long countPairs(int N, int X, int numbers[]) 40 | { 41 | Map map = new HashMap<>(); 42 | for(int i:numbers){ 43 | map.put(Integer.toString(i), map.getOrDefault(Integer.toString(i),0)+1); 44 | } 45 | String st = Integer.toString(X); 46 | long count=0; 47 | 48 | for(int i=1; i a[j] and i < j. [🔗Goto](https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions#) 6 | 7 |
8 | Full Code 9 | 10 | ```java 11 | import java.util.*; 12 | import java.io.*; 13 | import java.lang.*; 14 | 15 | class Sorting 16 | { 17 | public static void main (String[] args) 18 | { 19 | Scanner sc = new Scanner(System.in); 20 | long t = sc.nextLong(); 21 | 22 | while(t-- > 0) 23 | { 24 | long n = sc.nextLong(); 25 | long arr[] = new long[(int)n]; 26 | 27 | for(long i = 0; i < n; i++) 28 | arr[(int)i] = sc.nextLong(); 29 | 30 | System.out.println(new Solution().inversionCount(arr, n)); 31 | 32 | } 33 | } 34 | } 35 | ``` 36 |
37 | 38 | ```java 39 | class Solution 40 | { 41 | static long inversionCount(long arr[], long N) 42 | { 43 | return sort(arr,0,(int)N-1); 44 | } 45 | static long sort(long[] arr, int l, int r){ 46 | long count =0; 47 | if(l 5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.io.*; 10 | import java.lang.*; 11 | 12 | class DriverClass { 13 | public static void main(String[] args) { 14 | Scanner sc = new Scanner(System.in); 15 | int t = sc.nextInt(); 16 | 17 | while (t-- > 0) { 18 | ArrayList> list = new ArrayList<>(); 19 | int V = sc.nextInt(); 20 | int E = sc.nextInt(); 21 | for (int i = 0; i < V + 1; i++) 22 | list.add(i, new ArrayList()); 23 | for (int i = 0; i < E; i++) { 24 | int u = sc.nextInt(); 25 | int v = sc.nextInt(); 26 | list.get(u).add(v); 27 | } 28 | if (new Solution().isCyclic(V, list) == true) 29 | System.out.println("1"); 30 | else 31 | System.out.println("0"); 32 | } 33 | } 34 | } 35 | ``` 36 | 37 | 38 | ```java 39 | class Solution { 40 | // Function to detect cycle in a directed graph. 41 | private boolean checkCycle(int node, ArrayList> adj, int vis[], int dfsVis[]) { 42 | vis[node] = 1; 43 | dfsVis[node] = 1; 44 | 45 | for(Integer it: adj.get(node)) { 46 | if(vis[it] == 0) { 47 | if(checkCycle(it, adj, vis, dfsVis) == true) { 48 | return true; 49 | } 50 | } else if(dfsVis[it] == 1) { 51 | return true; 52 | } 53 | } 54 | dfsVis[node] = 0; 55 | return false; 56 | } 57 | public boolean isCyclic(int N, ArrayList> adj) { 58 | int vis[] = new int[N]; 59 | int dfsVis[] = new int[N]; 60 | 61 | for(int i = 0;i 5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.lang.*; 10 | import java.io.*; 11 | class GFG { 12 | public static void main(String[] args) throws IOException { 13 | BufferedReader br = 14 | new BufferedReader(new InputStreamReader(System.in)); 15 | int T = Integer.parseInt(br.readLine().trim()); 16 | while (T-- > 0) { 17 | String[] s = br.readLine().trim().split(" "); 18 | int V = Integer.parseInt(s[0]); 19 | int E = Integer.parseInt(s[1]); 20 | ArrayList> adj = new ArrayList<>(); 21 | for (int i = 0; i < V; i++) adj.add(i, new ArrayList()); 22 | for (int i = 0; i < E; i++) { 23 | String[] S = br.readLine().trim().split(" "); 24 | int u = Integer.parseInt(S[0]); 25 | int v = Integer.parseInt(S[1]); 26 | adj.get(u).add(v); 27 | adj.get(v).add(u); 28 | } 29 | Solution obj = new Solution(); 30 | boolean ans = obj.isCycle(V, adj); 31 | if (ans) 32 | System.out.println("1"); 33 | else 34 | System.out.println("0"); 35 | } 36 | } 37 | } 38 | ``` 39 | 40 | 41 | ```java 42 | class Solution 43 | { 44 | public boolean checkForCycle(int node, int parent, boolean vis[], ArrayList> adj) { 45 | vis[node] = true; 46 | for(Integer it: adj.get(node)) { 47 | if(vis[it] == false) { 48 | if(checkForCycle(it, node, vis, adj) == true) 49 | return true; 50 | } 51 | else if(it!=parent) 52 | return true; 53 | } 54 | 55 | return false; 56 | } 57 | // 0-based indexing Graph 58 | public boolean isCycle(int V, ArrayList> adj) 59 | { 60 | boolean vis[] = new boolean[V]; 61 | 62 | for(int i = 0;i 8 | Full Code 9 | 10 | ```java 11 | import java.io.*; 12 | import java.util.*; 13 | class GfG 14 | { 15 | public static void main(String args[]) 16 | { 17 | Scanner sc = new Scanner(System.in); 18 | int t = sc.nextInt(); 19 | while(t-->0) 20 | { 21 | String str1 = sc.next(); 22 | String str2 = sc.next(); 23 | Sol obj = new Sol(); 24 | System.out.println(obj.build_bridges(str1,str2)); 25 | } 26 | } 27 | } 28 | ``` 29 | 30 | 31 | ```java 32 | class Sol 33 | { 34 | public static int build_bridges(String str1 , String str2) 35 | { 36 | int n1 = str1.length(), n2 = str2.length(); 37 | int[][] dp = new int[n1+1][n2+1]; 38 | 39 | for(int i=0; i<=n1; i++){ 40 | for(int j=0; j<=n2; j++){ 41 | if(i==0 || j==0) 42 | dp[i][j] = 0; 43 | else if(str1.charAt(i-1)==str2.charAt(j-1)) 44 | dp[i][j] = 1 + dp[i-1][j-1]; 45 | else 46 | dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); 47 | } 48 | } 49 | return dp[n1][n2]; 50 | } 51 | } 52 | ``` -------------------------------------------------------------------------------- /JavaPractice/ExpressAsSumOfPowerOfNaturalNumbers/Readme.md: -------------------------------------------------------------------------------- 1 | ## Express as sum of power of natural numbers 2 | Given two numbers n and x, find out the total number of ways n can be expressed as sum of xth power of unique natural numbers.As total number of ways can be very large ,so return the number of ways modulo 109 + 7. [🔗Goto](https://practice.geeksforgeeks.org/problems/express-as-sum-of-power-of-natural-numbers5647/1/?problemStatus=unsolved&difficulty[]=1&page=1&category[]=Recursion&query=problemStatusunsolveddifficulty[]1page1category[]Recursion#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.lang.*; 10 | import java.io.*; 11 | class ExpressSumPower 12 | { 13 | public static void main(String[] args) throws IOException 14 | { 15 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 16 | int T = Integer.parseInt(br.readLine().trim()); 17 | while(T-->0) 18 | { 19 | String[] input = new String[2]; 20 | input = br.readLine().split(" "); 21 | int n = Integer.parseInt(input[0]); 22 | int x = Integer.parseInt(input[1]); 23 | Solution ob = new Solution(); 24 | System.out.println(ob.numOfWays(n, x)); 25 | } 26 | } 27 | } 28 | ``` 29 |
30 | 31 | ```java 32 | class Solution 33 | { 34 | static int MOD = (int)(1e9 + 7); 35 | static int res = 0; 36 | static int numOfWays(int x, int n){ 37 | return (checkRecursive(x, x, 0, n)%MOD); 38 | } 39 | static int checkRecursive(int num, int x, int k, int n){ 40 | if (x == 0) 41 | res++; 42 | 43 | int r = (int)Math.floor(Math.pow(num, 1.0 / n)); 44 | 45 | for (int i = k + 1; i <= r; i++) { 46 | int a = x - (int)Math.pow(i, n); 47 | if (a >= 0) 48 | checkRecursive(num,x - (int)Math.pow(i, n), i, n); 49 | } 50 | return (res%MOD); 51 | } 52 | } 53 | ``` -------------------------------------------------------------------------------- /JavaPractice/HeightOfBinaryTree/Readme.md: -------------------------------------------------------------------------------- 1 | ## Height of Binary Tree 2 | Given a binary tree, find its height. [🔗Goto](https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1/?page=2&difficulty[]=1&status[]=unsolved&company[]=Amazon&company[]=Infosys&sortBy=submissions#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.LinkedList; 9 | import java.util.Queue; 10 | import java.io.*; 11 | import java.util.*; 12 | import java.lang.*; 13 | 14 | class Node{ 15 | int data; 16 | Node left; 17 | Node right; 18 | Node(int data){ 19 | this.data = data; 20 | left=null; 21 | right=null; 22 | } 23 | } 24 | 25 | class HeightOfBinaryTree { 26 | 27 | static Node buildTree(String str){ 28 | 29 | if(str.length()==0 || str.charAt(0)=='N'){ 30 | return null; 31 | } 32 | 33 | String ip[] = str.split(" "); 34 | // Create the root of the tree 35 | Node root = new Node(Integer.parseInt(ip[0])); 36 | // Push the root to the queue 37 | 38 | Queue queue = new LinkedList<>(); 39 | 40 | queue.add(root); 41 | // Starting from the second element 42 | 43 | int i = 1; 44 | while(queue.size()>0 && i < ip.length) { 45 | 46 | // Get and remove the front of the queue 47 | Node currNode = queue.peek(); 48 | queue.remove(); 49 | 50 | // Get the current node's value from the string 51 | String currVal = ip[i]; 52 | 53 | // If the left child is not null 54 | if(!currVal.equals("N")) { 55 | 56 | // Create the left child for the current node 57 | currNode.left = new Node(Integer.parseInt(currVal)); 58 | // Push it to the queue 59 | queue.add(currNode.left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.length) 65 | break; 66 | 67 | currVal = ip[i]; 68 | 69 | // If the right child is not null 70 | if(!currVal.equals("N")) { 71 | 72 | // Create the right child for the current node 73 | currNode.right = new Node(Integer.parseInt(currVal)); 74 | 75 | // Push it to the queue 76 | queue.add(currNode.right); 77 | } 78 | i++; 79 | } 80 | 81 | return root; 82 | } 83 | static void printInorder(Node root){ 84 | if(root == null) 85 | return; 86 | 87 | printInorder(root.left); 88 | System.out.print(root.data+" "); 89 | 90 | printInorder(root.right); 91 | } 92 | 93 | public static void main (String[] args) throws IOException{ 94 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 95 | int t=Integer.parseInt(br.readLine()); 96 | 97 | while(t > 0){ 98 | String s = br.readLine(); 99 | Node root = buildTree(s); 100 | 101 | Solution ob = new Solution(); 102 | System.out.println(ob.height(root)); 103 | t--; 104 | } 105 | } 106 | } 107 | ``` 108 |
109 | 110 | ```java 111 | class Solution { 112 | //Function to find the height of a binary tree. 113 | int height(Node node) 114 | { 115 | // code here 116 | if(node == null){ 117 | return 0; 118 | } 119 | int l = height(node.left); 120 | int r = height(node.right); 121 | if (l > r) 122 | return (l + 1); 123 | else 124 | return (r + 1); 125 | } 126 | } 127 | ``` -------------------------------------------------------------------------------- /JavaPractice/HitMostBalloons/Readme.md: -------------------------------------------------------------------------------- 1 | ## Hit most Balloons 2 | You are given an infinite two-dimensional grid. There are N balloons placed at certain coordinates of the grid. You have an arrow with yourself, which you will be using to shoot the balloons. You can select any point on the grid as your starting point and any point on the grid as the target point. When you fire the arrow, all ballons lying on the shortest path between the starting point and target point will be burst. Given the coordinates of the N ballons in an array arr, your task is to find out the maximum number of balloons that you can fire in one [🔗Goto](https://practice.geeksforgeeks.org/problems/4e75764f8f1638eb4f1c5478ca1986043e15e39a/1/?page=1&difficulty[]=1&sortBy=latest#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.lang.*; 10 | import java.io.*; 11 | 12 | class GFG { 13 | public static void main(String[] args) throws IOException { 14 | BufferedReader br = 15 | new BufferedReader(new InputStreamReader(System.in)); 16 | int t = 17 | Integer.parseInt(br.readLine().trim()); // Inputting the testcases 18 | while (t-- > 0) { 19 | 20 | int N = Integer.parseInt(br.readLine().trim()); 21 | 22 | int arr[][] = new int[(int)(N)][2]; 23 | 24 | for (int j = 0; j < 2; j++) { 25 | String inputLine2[] = br.readLine().trim().split(" "); 26 | for (int i = 0; i < N; i++) { 27 | arr[i][j] = Integer.parseInt(inputLine2[i]); 28 | } 29 | } 30 | Solution ob = new Solution(); 31 | System.out.println(ob.mostBalloons(N, arr)); 32 | } 33 | } 34 | } 35 | ``` 36 |
37 | 38 | ```java 39 | class Solution { 40 | public int getGCD(int a, int b) 41 | { 42 | if(b==0) 43 | return a; 44 | else 45 | return getGCD(b,a%b); 46 | } 47 | public int mostBalloons(int N, int arr[][]) { 48 | 49 | if (N <= 2) { 50 | return N; 51 | } 52 | int maxBalloons = 2; 53 | 54 | for (int i = 0; i < N; i++) { 55 | int horizontal = 0, vertical = 0, identical = 0; 56 | Map slope = new HashMap<>(); 57 | 58 | for (int j = 0; j < N; j++) { 59 | if (i != j) { 60 | if (arr[i][0] == arr[j][0] && arr[i][1] == arr[j][1]) { 61 | identical++; 62 | } else if (arr[i][0] == arr[j][0]) { 63 | vertical++; 64 | } else if (arr[i][1] == arr[j][1]) { 65 | horizontal++; 66 | } else { 67 | int ydiff = arr[i][1] - arr[j][1]; 68 | int xdiff = arr[i][0] - arr[j][0]; 69 | int gcd = getGCD(Math.abs(ydiff), Math.abs(xdiff)); 70 | ydiff /= gcd; 71 | xdiff /= gcd; 72 | if (xdiff < 0) { 73 | xdiff *= -1; 74 | ydiff *= -1; 75 | } 76 | // Hashing the pair 77 | String g = xdiff+"-"+ydiff; 78 | if (slope.containsKey(g)) { 79 | int value = slope.get(g); 80 | value++; 81 | slope.put(g, value); 82 | 83 | } else { 84 | slope.put(g, 1); 85 | } 86 | } 87 | } 88 | } 89 | int mostPointsOnSameLine = 1; 90 | for (Map.Entry item : slope.entrySet()) { 91 | mostPointsOnSameLine = 92 | Math.max(mostPointsOnSameLine, item.getValue()); 93 | } 94 | maxBalloons = 95 | Math.max(maxBalloons, 1 + identical + mostPointsOnSameLine); 96 | maxBalloons = Math.max( 97 | maxBalloons, 1 + identical + Math.max(horizontal, vertical)); 98 | } 99 | 100 | return maxBalloons; 101 | } 102 | } 103 | ``` -------------------------------------------------------------------------------- /JavaPractice/InterleavedStrings/Readme.md: -------------------------------------------------------------------------------- 1 | ## Interleaved Strings 2 | Given strings A, B, and C, find whether C is formed by an interleaving of A and B. 3 | 4 | An interleaving of two strings S and T is a configuration such that it creates a new string Y from the concatenation substrings of A and B and |Y| = |A + B| = |C| 5 | 6 | **For example:** 7 | 8 | >

A = "XYZ"
9 | >B = "ABC"

10 | 11 | so we can make multiple interleaving string Y like, XYZABC, XAYBCZ, AXBYZC, XYAZBC and many more so here your task is to check whether you can create a string Y which can be equal to C. 12 | 13 | Specifically, you just need to create substrings of string A and create substrings B and concatenate them and check whether it is equal to C or not. 14 | 15 | **Note:** a + b is the concatenation of strings a and b. 16 | 17 | Return true if C is formed by an interleaving of A and B, else return false.[🔗Goto](https://practice.geeksforgeeks.org/problems/interleaved-strings/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Amazon&category[]=Strings&sortBy=submissions#) 18 | 19 |
20 | Full Code 21 | 22 | ```java 23 | import java.util.*; 24 | import java.lang.*; 25 | class InterLeaveString 26 | { 27 | public static void main(String[] args) 28 | { 29 | Scanner sc=new Scanner(System.in); 30 | int t=sc.nextInt(); 31 | while(t>0) 32 | { 33 | String a =sc.next(); 34 | String b = sc.next(); 35 | String c = sc.next(); 36 | Solution g=new Solution(); 37 | 38 | System.out.println(g.isInterLeave(a,b,c)==true?1:0); 39 | t--; 40 | } 41 | } 42 | } 43 | ``` 44 |
45 | 46 | ```java 47 | class Solution { 48 | public boolean isInterLeave(String a,String b,String c) 49 | { 50 | Boolean[][] dp = new Boolean[a.length()+1][b.length()+1]; 51 | if(a.length() + b.length()!=c.length()){ 52 | return false; 53 | } 54 | return helperFunc(a, b, c, 0, 0, dp); 55 | } 56 | public static boolean helperFunc(String a, String b, String c, int i, int j, Boolean[][] dp){ 57 | if(i==a.length() && j==b.length()) 58 | return true; 59 | if(dp[i][j]!=null){ 60 | return dp[i][j]; 61 | } 62 | if((i**Input**:
6 | >LinkList1 = 3->6->9->common
7 | >LinkList2 = 10->common
8 | >common = 15->30->NULL
9 | >**Output**: 15
10 | 11 |
12 | Full Code 13 | 14 | ```java 15 | import java.util.*; 16 | 17 | 18 | class Node 19 | { 20 | int data; 21 | Node next; 22 | Node(int d) { 23 | data = d; 24 | next = null; 25 | } 26 | } 27 | 28 | class LinkedList_Intersection 29 | { 30 | Node head = null; 31 | Node tail = null; 32 | 33 | public void addToTheLast(Node node) 34 | { 35 | 36 | if (head == null) { 37 | head = node; 38 | tail = head; 39 | } else { 40 | //Node temp = head; 41 | //while (temp.next != null) 42 | //temp = temp.next; 43 | 44 | //temp.next = node; 45 | tail.next=node; 46 | tail = node; 47 | } 48 | } 49 | 50 | /* Function to print linked list */ 51 | void printList() 52 | { 53 | Node temp = head; 54 | while (temp != null) 55 | { 56 | System.out.print(temp.data+" "); 57 | temp = temp.next; 58 | } 59 | System.out.println(); 60 | } 61 | 62 | 63 | 64 | /* Driver program to test above functions */ 65 | public static void main(String args[]) 66 | { 67 | 68 | 69 | /* Constructed Linked List is 1->2->3->4->5->6-> 70 | 7->8->8->9->null */ 71 | Scanner sc = new Scanner(System.in); 72 | int t=sc.nextInt(); 73 | 74 | while(t>0) 75 | { 76 | int n1 = sc.nextInt(); 77 | int n2 = sc.nextInt(); 78 | int n3 = sc.nextInt(); 79 | LinkedList_Intersection llist1 = new LinkedList_Intersection(); 80 | LinkedList_Intersection llist2 = new LinkedList_Intersection(); 81 | LinkedList_Intersection llist3 = new LinkedList_Intersection(); 82 | 83 | int a1=sc.nextInt(); 84 | Node head1= new Node(a1); 85 | Node tail1= head1; 86 | 87 | for (int i = 1; i < n1; i++) 88 | { 89 | int a = sc.nextInt(); 90 | tail1.next = (new Node(a)); 91 | tail1= tail1.next; 92 | } 93 | 94 | 95 | int b1=sc.nextInt(); 96 | Node head2 = new Node(b1); 97 | Node tail2 = head2; 98 | for (int i = 1; i < n2; i++) 99 | { 100 | int b = sc.nextInt(); 101 | tail2.next = (new Node(b)); 102 | tail2= tail2.next; 103 | } 104 | 105 | int c1=sc.nextInt(); 106 | Node head3= new Node(c1); 107 | tail1.next = head3; 108 | tail2.next = head3; 109 | Node tail3=head3; 110 | for (int i = 1; i < n3; i++) 111 | { 112 | int c = sc.nextInt(); 113 | tail3.next = (new Node(c)); 114 | tail3= tail3.next; 115 | } 116 | 117 | Intersect obj = new Intersect(); 118 | System.out.println(obj.intersectPoint(head1, head2)); 119 | t--; 120 | } 121 | } 122 | } 123 | ``` 124 |
125 | 126 | ```java 127 | class Intersect 128 | { 129 | int intersectPoint(Node head1, Node head2) 130 | { 131 | Node p=head1; 132 | Node q=head2; 133 | Set a=new HashSet(); 134 | while(p!=null) 135 | { 136 | a.add(p); 137 | p=p.next; 138 | } 139 | while(q!=null) 140 | { 141 | if(a.contains(q)) 142 | break; 143 | q=q.next; 144 | } 145 | return q.data; 146 | } 147 | } 148 | 149 | ``` -------------------------------------------------------------------------------- /JavaPractice/LCSofThreeStrings/Readme.md: -------------------------------------------------------------------------------- 1 | ## LCS of three strings 2 | Given 3 strings A, B and C, the task is to find the longest common sub-sequence in all three given sequences [🔗Goto](https://practice.geeksforgeeks.org/problems/lcs-of-three-strings0028/1/?page=4&difficulty[]=1&status[]=unsolved&category[]=Arrays&category[]=Strings&sortBy=accuracy#) 3 | 4 | **Example 1:** 5 | 6 | >

Input: 7 | >A = "geeks", B = "geeksfor",
8 | >C = "geeksforgeeks"
9 | >Output: 5

10 | 11 | Explanation: "geeks"is the longest common 12 | subsequence with length 5. 13 | 14 |
15 | Full Code 16 | 17 | ```java 18 | import java.io.*; 19 | import java.util.*; 20 | class GFG{ 21 | public static void main(String args[]) throws IOException { 22 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 23 | int t = Integer.parseInt(read.readLine()); 24 | while(t-- > 0){ 25 | String input_line[] = read.readLine().trim().split("\\s+"); 26 | int n1 = Integer.parseInt(input_line[0]); 27 | int n2 = Integer.parseInt(input_line[1]); 28 | int n3 = Integer.parseInt(input_line[2]); 29 | input_line = read.readLine().trim().split("\\s+"); 30 | String A = input_line[0]; 31 | String B = input_line[1]; 32 | String C = input_line[2]; 33 | Solution obj = new Solution(); 34 | System.out.println(obj.LCSof3(A, B, C, n1, n2, n3)); 35 | } 36 | } 37 | } 38 | ``` 39 |
40 | 41 | ```java 42 | class Solution 43 | { 44 | int LCSof3(String A, String B, String C, int n1, int n2, int n3) 45 | { 46 | // code here 47 | int [][][]dp = new int[n1+1][n2+1][n3+1]; 48 | for(int i = 1;i<=n1;i++){ 49 | for(int j = 1;j<=n2;j++){ 50 | for(int k =1;k<=n3;k++){ 51 | if(A.charAt(i-1)==B.charAt(j-1) && B.charAt(j-1)==C.charAt(k-1)){ 52 | dp[i][j][k]=1+dp[i-1][j-1][k-1]; 53 | } 54 | else{ 55 | dp[i][j][k]=Math.max(dp[i-1][j][k],Math.max(dp[i][j-1][k],dp[i][j][k-1])); 56 | } 57 | } 58 | } 59 | } 60 | return dp[n1][n2][n3]; 61 | } 62 | } 63 | ``` -------------------------------------------------------------------------------- /JavaPractice/LeftViewofBinaryTree/Readme.md: -------------------------------------------------------------------------------- 1 | ## Left View of Binary Tree 2 | Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument. [🔗Goto](https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1/?page=2) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.LinkedList; 9 | import java.util.Queue; 10 | import java.io.*; 11 | import java.util.*; 12 | 13 | class Node{ 14 | int data; 15 | Node left; 16 | Node right; 17 | Node(int data){ 18 | this.data = data; 19 | left=null; 20 | right=null; 21 | } 22 | } 23 | 24 | class LeftViewBtree { 25 | 26 | static Node buildTree(String str){ 27 | 28 | if(str.length()==0 || str.charAt(0)=='N'){ 29 | return null; 30 | } 31 | 32 | String ip[] = str.split(" "); 33 | // Create the root of the tree 34 | Node root = new Node(Integer.parseInt(ip[0])); 35 | // Push the root to the queue 36 | 37 | Queue queue = new LinkedList<>(); 38 | 39 | queue.add(root); 40 | // Starting from the second element 41 | 42 | int i = 1; 43 | while(queue.size()>0 && i < ip.length) { 44 | 45 | // Get and remove the front of the queue 46 | Node currNode = queue.peek(); 47 | queue.remove(); 48 | 49 | // Get the current node's value from the string 50 | String currVal = ip[i]; 51 | 52 | // If the left child is not null 53 | if(!currVal.equals("N")) { 54 | 55 | // Create the left child for the current node 56 | currNode.left = new Node(Integer.parseInt(currVal)); 57 | // Push it to the queue 58 | queue.add(currNode.left); 59 | } 60 | 61 | // For the right child 62 | i++; 63 | if(i >= ip.length) 64 | break; 65 | 66 | currVal = ip[i]; 67 | 68 | // If the right child is not null 69 | if(!currVal.equals("N")) { 70 | 71 | // Create the right child for the current node 72 | currNode.right = new Node(Integer.parseInt(currVal)); 73 | 74 | // Push it to the queue 75 | queue.add(currNode.right); 76 | } 77 | i++; 78 | } 79 | 80 | return root; 81 | } 82 | static void printInorder(Node root) 83 | { 84 | if(root == null) 85 | return; 86 | 87 | printInorder(root.left); 88 | System.out.print(root.data+" "); 89 | 90 | printInorder(root.right); 91 | } 92 | 93 | public static void main (String[] args) throws IOException{ 94 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 95 | 96 | int t=Integer.parseInt(br.readLine()); 97 | 98 | while(t > 0){ 99 | String s = br.readLine(); 100 | Node root = buildTree(s); 101 | Tree g = new Tree(); 102 | ArrayList result = g.leftView(root); 103 | for(int value : result){ 104 | System.out.print(value + " "); 105 | } 106 | System.out.println(); 107 | t--; 108 | } 109 | } 110 | } 111 | ``` 112 |
113 | 114 | ```java 115 | class Tree 116 | { 117 | //Function to return list containing elements of left view of binary tree. 118 | ArrayList leftView(Node root) 119 | { 120 | ArrayList list = new ArrayList(); 121 | addLeft(list, root, 0); 122 | return list; 123 | } 124 | 125 | void addLeft(ArrayList list, Node root, int level){ 126 | if(root==null){ 127 | return; 128 | } 129 | if(list.size()==level) 130 | list.add(root.data); 131 | addLeft(list,root.left, level+1); 132 | addLeft(list,root.right, level+1); 133 | } 134 | 135 | } 136 | ``` -------------------------------------------------------------------------------- /JavaPractice/LongestCommonSubsequence/Readme.md: -------------------------------------------------------------------------------- 1 | ## Longest Common Subsequence 2 | 3 | Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase. [🔗Goto](https://practice.geeksforgeeks.org/problems/longest-common-subsequence-1587115620/1/?page=2&difficulty[]=1&status[]=unsolved&sortBy=submissions#) 4 | 5 |
6 | Full Code 7 | 8 | ```java 9 | import java.util.*; 10 | import java.lang.*; 11 | import java.io.*; 12 | 13 | class GFG { 14 | public static void main (String[] args) { 15 | 16 | Scanner sc=new Scanner(System.in); 17 | int test=sc.nextInt(); 18 | while(test-- > 0){ 19 | int p=sc.nextInt(); // Take size of both the strings as input 20 | int q=sc.nextInt(); 21 | 22 | String s1=sc.next(); // Take both the string as input 23 | String s2=sc.next(); 24 | 25 | Solution obj = new Solution(); 26 | 27 | System.out.println(obj.lcs(p, q, s1, s2)); 28 | } 29 | } 30 | } 31 | ``` 32 |
33 | 34 | ```java 35 | class Solution 36 | { 37 | static int lcs(int x, int y, String s1, String s2) 38 | { 39 | int[][]dp = new int[x+1][y+1]; 40 | 41 | for(int i=1;i 7 | Full Code 8 | 9 | ```java 10 | import java.io.*; 11 | import java.util.*; 12 | 13 | class GFG { 14 | public static void main(String args[]) throws IOException { 15 | BufferedReader read = 16 | new BufferedReader(new InputStreamReader(System.in)); 17 | int t = Integer.parseInt(read.readLine()); 18 | while (t-- > 0) { 19 | 20 | String s = read.readLine(); 21 | Solution ob = new Solution(); 22 | System.out.println(ob.lps(s)); 23 | } 24 | } 25 | } 26 | ``` 27 | 28 | 29 | ```java 30 | class Solution { 31 | int lps(String s) { 32 | // code here 33 | int n = s.length(); 34 | int i = 0 , j = 1; 35 | int[] lps = new int[n]; 36 | lps[0] = 0; 37 | while(j < n){ 38 | if(s.charAt(i) == s.charAt(j)){ 39 | lps[j] = i + 1; 40 | j++; 41 | i++; 42 | }else{ 43 | if(i == 0){ 44 | lps[j] = 0; 45 | j++; 46 | }else{ 47 | i = lps[i - 1]; 48 | } 49 | } 50 | } 51 | return lps[n - 1]; 52 | } 53 | } 54 | ``` -------------------------------------------------------------------------------- /JavaPractice/LowestCommonAncestorInABinaryTree/Readme.md: -------------------------------------------------------------------------------- 1 | ## Lowest Common Ancestor in a Binary Tree 2 | Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present.[🔗Goto](https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1/?page=2&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.LinkedList; 9 | import java.util.Queue; 10 | import java.io.*; 11 | import java.util.*; 12 | 13 | class Node{ 14 | int data; 15 | Node left; 16 | Node right; 17 | Node(int data){ 18 | this.data = data; 19 | left=null; 20 | right=null; 21 | } 22 | } 23 | 24 | class GfG { 25 | 26 | static Node buildTree(String str){ 27 | 28 | if(str.length()==0 || str.charAt(0)=='N'){ 29 | return null; 30 | } 31 | 32 | String ip[] = str.split(" "); 33 | // Create the root of the tree 34 | Node root = new Node(Integer.parseInt(ip[0])); 35 | // Push the root to the queue 36 | 37 | Queue queue = new LinkedList<>(); 38 | 39 | queue.add(root); 40 | // Starting from the second element 41 | 42 | int i = 1; 43 | while(queue.size()>0 && i < ip.length) { 44 | 45 | // Get and remove the front of the queue 46 | Node currNode = queue.peek(); 47 | queue.remove(); 48 | 49 | // Get the current node's value from the string 50 | String currVal = ip[i]; 51 | 52 | // If the left child is not null 53 | if(!currVal.equals("N")) { 54 | 55 | // Create the left child for the current node 56 | currNode.left = new Node(Integer.parseInt(currVal)); 57 | // Push it to the queue 58 | queue.add(currNode.left); 59 | } 60 | 61 | // For the right child 62 | i++; 63 | if(i >= ip.length) 64 | break; 65 | 66 | currVal = ip[i]; 67 | 68 | // If the right child is not null 69 | if(!currVal.equals("N")) { 70 | 71 | // Create the right child for the current node 72 | currNode.right = new Node(Integer.parseInt(currVal)); 73 | 74 | // Push it to the queue 75 | queue.add(currNode.right); 76 | } 77 | i++; 78 | } 79 | 80 | return root; 81 | } 82 | static void printInorder(Node root) 83 | { 84 | if(root == null) 85 | return; 86 | 87 | printInorder(root.left); 88 | System.out.print(root.data+" "); 89 | 90 | printInorder(root.right); 91 | } 92 | 93 | public static void main (String[] args) throws IOException{ 94 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 95 | 96 | int t=Integer.parseInt(br.readLine()); 97 | 98 | while(t-- > 0){ 99 | String input[] = br.readLine().trim().split(" "); 100 | int a = Integer.parseInt(input[0]); 101 | int b = Integer.parseInt(input[1]); 102 | String s = br.readLine(); 103 | Node root = buildTree(s); 104 | Solution g = new Solution(); 105 | Node k = g.lca(root,a,b); 106 | System.out.println(k.data); 107 | 108 | } 109 | } 110 | } 111 | ``` 112 |
113 | 114 | ```java 115 | class Solution 116 | { 117 | //Function to return the lowest common ancestor in a Binary Tree. 118 | Node lca(Node root, int n1,int n2) 119 | { 120 | // Your code here 121 | if(root == null || root.data == n1 || root.data == n2){ 122 | return root; 123 | } 124 | Node left = lca(root.left,n1,n2); 125 | Node right = lca(root.right,n1,n2); 126 | 127 | if(left == null){ 128 | return right; 129 | } 130 | if(right == null){ 131 | return left; 132 | } 133 | else{ 134 | return root; 135 | } 136 | } 137 | } 138 | ``` -------------------------------------------------------------------------------- /JavaPractice/MaximumProductSubArray/Readme.md: -------------------------------------------------------------------------------- 1 | ## Maximum Product SubArray 2 | Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray. [🔗Goto](https://practice.geeksforgeeks.org/problems/maximum-product-subarray3604/0/?page=1&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.io.*; 9 | import java.util.*; 10 | 11 | public class Main { 12 | 13 | public static void main(String[] args) throws Exception { 14 | BufferedReader br = 15 | new BufferedReader(new InputStreamReader(System.in)); 16 | int tc = Integer.parseInt(br.readLine()); 17 | while (tc-- > 0) { 18 | int n = Integer.parseInt(br.readLine()); 19 | int[] arr = new int[n]; 20 | String[] inputLine = br.readLine().split(" "); 21 | for (int i = 0; i < n; i++) { 22 | arr[i] = Integer.parseInt(inputLine[i]); 23 | } 24 | 25 | System.out.println(new Solution().maxProduct(arr, n)); 26 | } 27 | } 28 | } 29 | ``` 30 |
31 | 32 | ```java 33 | class Solution { 34 | long maxProduct(int[] arr, int n) { 35 | long min = arr[0]; 36 | long max = arr[0]; 37 | long ans = arr[0]; 38 | 39 | for(int i=1; i 5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.lang.*; 10 | import java.io.*; 11 | 12 | class GFG { 13 | 14 | 15 | public static void main (String[] args) throws IOException { 16 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 17 | int t = Integer.parseInt(br.readLine().trim()); 18 | while(t-->0){ 19 | long n = Long.parseLong(br.readLine().trim()); 20 | String inputLine[] = br.readLine().trim().split(" "); 21 | long[] arr = new long[(int)n]; 22 | for(int i=0; i 29 | 30 | ```java 31 | class Solution 32 | { 33 | //Function to find largest rectangular area possible in a given histogram. 34 | public static long getMaxArea(long hist[], long n) 35 | { 36 | long maxAns = 0; 37 | int ps[] = previousSmaller(hist); 38 | int ns[] = nextSmaller(hist); 39 | for(int i=0; i s = new Stack<>(); 48 | for(int i=0; i= hist[i]){ 50 | s.pop(); 51 | } 52 | if(s.isEmpty()){ 53 | ps[i] = -1; 54 | }else{ 55 | ps[i] = s.peek(); 56 | } 57 | s.push(i); 58 | } 59 | return ps; 60 | } 61 | public static int[] nextSmaller(long hist[]){ 62 | int[] ns = new int[hist.length]; 63 | Stack s = new Stack<>(); 64 | for(int i=hist.length-1; i>=0; i--){ 65 | while(!s.isEmpty() && hist[s.peek()] >= hist[i]){ 66 | s.pop(); 67 | } 68 | if(s.isEmpty()){ 69 | ns[i] = hist.length; 70 | }else{ 71 | ns[i] = s.peek(); 72 | } 73 | s.push(i); 74 | } 75 | return ns; 76 | } 77 | } 78 | ``` -------------------------------------------------------------------------------- /JavaPractice/MaximumXORofTwoNumbersinanArray/Readme.md: -------------------------------------------------------------------------------- 1 | ## Maximum XOR of two numbers in an array 2 | Given an array of non-negative integers of size N. Find the maximum possible XOR between two numbers present in the array. [🔗Goto](https://practice.geeksforgeeks.org/problems/maximum-xor-of-two-numbers-in-an-array/1/?page=2&difficulty[]=1&status[]=unsolved&sortBy=accuracy#) 3 | 4 | **Example 1:** 5 | 6 | >

Input:
7 | >Arr = {25, 10, 2, 8, 5, 3}
8 | >Output: 28
9 | >Explanation:
10 | >The maximum result is 5 ^ 25 = 28. 11 |

12 | 13 |
14 | Full Code 15 | 16 | ```java 17 | import java.util.*; 18 | import java.lang.*; 19 | import java.io.*; 20 | class GFG 21 | { 22 | public static void main(String[] args) throws IOException 23 | { 24 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 25 | int T = Integer.parseInt(br.readLine().trim()); 26 | while(T-->0) 27 | { 28 | int n = Integer.parseInt(br.readLine().trim()); 29 | String s = br.readLine(); 30 | String[] S = s.split(" "); 31 | int[] v = new int[n]; 32 | for(int i = 0; i < n; i++) 33 | { 34 | v[i] = Integer.parseInt(S[i]); 35 | } 36 | Solution ob = new Solution(); 37 | System.out.println(ob.max_xor(v, n)); 38 | 39 | } 40 | } 41 | } 42 | 43 | ``` 44 |
45 | 46 | ```java 47 | class Solution 48 | { 49 | public static int max_xor(int arr[], int n) 50 | { 51 | int maxXor = 0; 52 | for(int i=0; i 6 | Full Code 7 | 8 | ```java 9 | import java.lang.*; 10 | import java.io.*; 11 | import java.util.*; 12 | class GFG 13 | { 14 | public static void main (String[] args) throws IOException 15 | { 16 | 17 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 18 | int t = Integer.parseInt(br.readLine()); 19 | 20 | while(t-- > 0){ 21 | int size = Integer.parseInt(br.readLine()); 22 | String[] arrStr = ((String)br.readLine()).split("\\s+"); 23 | int[] arr= new int[size]; 24 | for(int i = 0;i 34 | 35 | ```java 36 | class Solution{ 37 | static int minJumps(int[] arr){ 38 | int i=0; 39 | int n = arr.length; 40 | int jumps = 0; 41 | if(n==1){ 42 | return 0; 43 | } 44 | while(i=n-1){ 50 | return jumps+1; 51 | } 52 | for(int j=i+1; j 5 | Full Code 6 | 7 | ```java 8 | import java.io.*; 9 | import java.util.*; 10 | 11 | class NextPermutation{ 12 | public static void main(String args[])throws IOException 13 | { 14 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 15 | int t = Integer.parseInt(in.readLine()); 16 | while(t-- > 0){ 17 | int N = Integer.parseInt(in.readLine()); 18 | String a[] = in.readLine().trim().split("\\s+"); 19 | int arr[] = new int[N]; 20 | for(int i = 0;i < N;i++) 21 | arr[i] = Integer.parseInt(a[i]); 22 | 23 | Solution ob = new Solution(); 24 | List ans = new ArrayList(); 25 | ans = ob.nextPermutation(N, arr); 26 | StringBuilder out = new StringBuilder(); 27 | for(int i = 0;i < N;i++) 28 | out.append(ans.get(i) + " "); 29 | System.out.println(out); 30 | } 31 | } 32 | } 33 | ``` 34 | 35 | 36 | ```java 37 | class Solution{ 38 | static List nextPermutation(int N, int arr[]){ 39 | int i=N-2; 40 | while(i>=0) 41 | { 42 | // get index of larger value 43 | if(arr[i]=0) 48 | { 49 | 50 | int j=N-1; 51 | while(arr[i]>=arr[j]) 52 | j--; 53 | swap(i,j,arr); 54 | } 55 | reverse(i+1,arr); 56 | ArrayList al=new ArrayList<>(); 57 | for(int a:arr) 58 | al.add(a); 59 | 60 | return al; 61 | } 62 | static void swap(int i,int j,int arr[]) 63 | { 64 | int temp=arr[i]; 65 | arr[i]=arr[j]; 66 | arr[j]=temp; 67 | } 68 | static void reverse(int i,int arr[]) 69 | { 70 | int start=i; 71 | int end=arr.length-1; 72 | while(start 7 | Full Code 8 | 9 | ```java 10 | import java.io.*; 11 | import java.util.*; 12 | 13 | class Node 14 | { 15 | int data; 16 | Node left, right; 17 | 18 | public Node(int d) 19 | { 20 | data = d; 21 | left = right = null; 22 | } 23 | } 24 | 25 | class GFG 26 | { 27 | static Node buildTree(String str) 28 | { 29 | // Corner Case 30 | if(str.length() == 0 || str.equals('N')) 31 | return null; 32 | String[] s = str.split(" "); 33 | 34 | Node root = new Node(Integer.parseInt(s[0])); 35 | Queue q = new LinkedList(); 36 | q.add(root); 37 | 38 | // Starting from the second element 39 | int i = 1; 40 | while(!q.isEmpty() && i < s.length) 41 | { 42 | // Get and remove the front of the queue 43 | Node currNode = q.remove(); 44 | 45 | // Get the current node's value from the string 46 | String currVal = s[i]; 47 | 48 | // If the left child is not null 49 | if(!currVal.equals("N")) 50 | { 51 | 52 | // Create the left child for the current node 53 | currNode.left = new Node(Integer.parseInt(currVal)); 54 | 55 | // Push it to the queue 56 | q.add(currNode.left); 57 | } 58 | 59 | // For the right child 60 | i++; 61 | if(i >= s.length) 62 | break; 63 | currVal = s[i]; 64 | 65 | // If the right child is not null 66 | if(!currVal.equals("N")) 67 | { 68 | 69 | // Create the right child for the current node 70 | currNode.right = new Node(Integer.parseInt(currVal)); 71 | 72 | // Push it to the queue 73 | q.add(currNode.right); 74 | } 75 | 76 | i++; 77 | } 78 | 79 | return root; 80 | } 81 | 82 | public static void main(String args[]) throws IOException 83 | { 84 | 85 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 86 | int t = Integer.parseInt(br.readLine().trim()); 87 | while(t>0) 88 | { 89 | String s = br.readLine().trim(); 90 | Node root = buildTree(s); 91 | Solution T = new Solution(); 92 | int target = Integer.parseInt(br.readLine().trim()); 93 | int k = Integer.parseInt(br.readLine().trim()); 94 | ArrayList res = new ArrayList(); 95 | res = T.KDistanceNodes(root,target,k); 96 | for(int i = 0;i 105 | 106 | ```java 107 | class Solution 108 | { 109 | 110 | public static ArrayListv = new ArrayList(); 111 | 112 | public static void findKDistanceDownNode(Node root, int k) 113 | /* Recursive function to find all the nodes at distance k in the 114 | tree (or subtree) rooted with given root. See */ 115 | { 116 | // Base Case 117 | if (root == null || k < 0) return; 118 | 119 | // If we reach a k distant node, add to vector 120 | if (k==0) 121 | { 122 | v.add(root.data); 123 | return; 124 | } 125 | 126 | // Recur for left and right subtrees 127 | findKDistanceDownNode(root.left, k-1); 128 | findKDistanceDownNode(root.right, k-1); 129 | } 130 | 131 | public static int findKDistanceNode(Node root, int target , int k) 132 | // Finds all nodes at distance k from a given target node. 133 | // The k distant nodes may be upward or downward. This function 134 | // Returns distance of root from target node, it returns -1 if target 135 | // node is not present in tree rooted with root. 136 | { 137 | // Base Case 1: If tree is empty, return -1 138 | if (root == null) return -1; 139 | 140 | // If target is same as root. Use the downward function 141 | // to find all nodes at distance k in subtree rooted with 142 | // target or root 143 | if (root.data == target) 144 | { 145 | findKDistanceDownNode(root, k); 146 | return 0; 147 | } 148 | 149 | // Recur for left subtree 150 | int dl = findKDistanceNode(root.left, target, k); 151 | 152 | // Check if target node was found in left subtree 153 | if (dl != -1) 154 | { 155 | // If root is at distance k from target, add root value to vector 156 | // Note that dl is Distance of root's left child from target 157 | if (dl + 1 == k) 158 | v.add(root.data); 159 | 160 | // Else go to right subtree and print all k-dl-2 distant nodes 161 | // Note that the right child is 2 edges away from left child 162 | else 163 | findKDistanceDownNode(root.right, k-dl-2); 164 | 165 | // Add 1 to the distance and return value for parent calls 166 | return 1 + dl; 167 | } 168 | 169 | // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE 170 | // Note that we reach here only when node was not found in left subtree 171 | int dr = findKDistanceNode(root.right, target, k); 172 | if (dr != -1) 173 | { 174 | if (dr + 1 == k) 175 | v.add(root.data); 176 | else 177 | findKDistanceDownNode(root.left, k-dr-2); 178 | return 1 + dr; 179 | } 180 | 181 | // If target was neither present in left nor in right subtree 182 | return -1; 183 | } 184 | 185 | 186 | 187 | public static ArrayList KDistanceNodes(Node root, int target , int k) 188 | { 189 | v.clear(); 190 | 191 | findKDistanceNode(root, target, k); 192 | 193 | Collections.sort(v); 194 | 195 | return v; 196 | } 197 | }; 198 | ``` -------------------------------------------------------------------------------- /JavaPractice/OverlappingInterval/Readme.md: -------------------------------------------------------------------------------- 1 | ## Overlapping Problem 2 | Given a collection of Intervals, the task is to merge all of the overlapping Intervals. [🔗Goto](https://practice.geeksforgeeks.org/problems/8a644e94faaa94968d8665ba9e0a80d1ae3e0a2d/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Microsoft&category[]=Arrays&category[]=Strings&sortBy=accuracy#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | import java.lang.*; 10 | import java.io.*; 11 | class GFG 12 | { 13 | public static void main(String[] args) throws IOException 14 | { 15 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 16 | int T = Integer.parseInt(br.readLine().trim()); 17 | while(T-->0) 18 | { 19 | int n = Integer.parseInt(br.readLine().trim()); 20 | String[] s = br.readLine().trim().split(" "); 21 | int[][] Intervals = new int[n][2]; 22 | int j = 0; 23 | for(int i = 0; i < n; i++){ 24 | Intervals[i][0] = Integer.parseInt(s[j]); 25 | j++; 26 | Intervals[i][1] = Integer.parseInt(s[j]); 27 | j++; 28 | } 29 | Solution obj = new Solution(); 30 | int[][] ans = obj.overlappedInterval(Intervals); 31 | for(int i = 0; i < ans.length; i++){ 32 | for(j = 0; j < ans[i].length; j++){ 33 | System.out.print(ans[i][j] + " "); 34 | } 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | } 40 | ``` 41 |
42 | 43 | ```java 44 | class Solution 45 | { 46 | public int[][] overlappedInterval(int[][] Intervals) 47 | { 48 | //sort according the first element 49 | Arrays.sort(Intervals, new Comparator(){ 50 | public int compare(int []arr1,int []arr2){ 51 | return arr1[0] - arr2[0]; 52 | } 53 | }); 54 | 55 | Stack st = new Stack<>(); 56 | //Iterate for each eleemnt and push into stack 57 | 58 | for(int[] arr:Intervals){ 59 | //if stack is empty then push first element 60 | if(st.empty()){ 61 | st.push(arr); 62 | } 63 | else{ 64 | int [] temp = st.peek(); 65 | 66 | //for a different range add the new range 67 | if(temp[1]=arr[0] && temp[1] < arr[1]){ 73 | int []popped = st.pop(); 74 | popped[1] = arr[1]; 75 | st.push(popped); 76 | } 77 | } 78 | } 79 | int ans[][]=new int[st.size()][2]; 80 | int i = 0; 81 | 82 | // Convert Stack Element into Array 83 | for(int[]arr : st){ 84 | ans[i] = arr; 85 | i++; 86 | } 87 | return ans; 88 | } 89 | } 90 | ``` -------------------------------------------------------------------------------- /JavaPractice/PreorderTraversal(Iterative)/Readme.md: -------------------------------------------------------------------------------- 1 | ## Preorder traversal (Iterative) 2 | Given a binary tree. Find the preorder traversal of the tree without using recursion. [🔗Goto](https://practice.geeksforgeeks.org/problems/preorder-traversal-iterative/1/?page=4&difficulty[]=1&status[]=unsolved&sortBy=accuracy#) 3 | 4 | 5 |
6 | Full Code 7 | 8 | ```java 9 | import java.util.LinkedList; 10 | import java.util.Queue; 11 | import java.io.*; 12 | import java.util.*; 13 | 14 | class Node{ 15 | int data; 16 | Node left; 17 | Node right; 18 | Node(int data){ 19 | this.data = data; 20 | left=null; 21 | right=null; 22 | } 23 | } 24 | 25 | class GfG { 26 | 27 | static Node buildTree(String str){ 28 | 29 | if(str.length()==0 || str.charAt(0)=='N'){ 30 | return null; 31 | } 32 | 33 | String ip[] = str.split(" "); 34 | // Create the root of the tree 35 | Node root = new Node(Integer.parseInt(ip[0])); 36 | // Push the root to the queue 37 | 38 | Queue queue = new LinkedList<>(); 39 | 40 | queue.add(root); 41 | // Starting from the second element 42 | 43 | int i = 1; 44 | while(queue.size()>0 && i < ip.length) { 45 | 46 | // Get and remove the front of the queue 47 | Node currNode = queue.peek(); 48 | queue.remove(); 49 | 50 | // Get the current node's value from the string 51 | String currVal = ip[i]; 52 | 53 | // If the left child is not null 54 | if(!currVal.equals("N")) { 55 | 56 | // Create the left child for the current node 57 | currNode.left = new Node(Integer.parseInt(currVal)); 58 | // Push it to the queue 59 | queue.add(currNode.left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.length) 65 | break; 66 | 67 | currVal = ip[i]; 68 | 69 | // If the right child is not null 70 | if(!currVal.equals("N")) { 71 | 72 | // Create the right child for the current node 73 | currNode.right = new Node(Integer.parseInt(currVal)); 74 | 75 | // Push it to the queue 76 | queue.add(currNode.right); 77 | } 78 | i++; 79 | } 80 | 81 | return root; 82 | } 83 | 84 | public static void main (String[] args) throws IOException{ 85 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 86 | 87 | int t=Integer.parseInt(br.readLine()); 88 | 89 | while(t > 0){ 90 | String s = br.readLine(); 91 | Node root = buildTree(s); 92 | Tree g = new Tree(); 93 | ArrayList res = g.preOrder(root); 94 | for (int i = 0; i < res.size (); i++) 95 | System.out.print (res.get (i) + " "); 96 | System.out.print("\n"); 97 | t--; 98 | } 99 | } 100 | } 101 | ``` 102 |
103 | 104 | ```java 105 | class Tree 106 | { 107 | ArrayList preOrder(Node root) 108 | { 109 | ArrayList res=new ArrayList<>(); 110 | Stack stack=new Stack<>(); 111 | Node node=root; 112 | while(node!=null || stack.size()>0) 113 | { 114 | while(node!=null) 115 | { 116 | res.add(node.data); 117 | stack.push(node); 118 | node=node.left; 119 | } 120 | node=stack.pop(); 121 | node=node.right; 122 | } 123 | return res; 124 | } 125 | } 126 | ``` -------------------------------------------------------------------------------- /JavaPractice/Readme.md: -------------------------------------------------------------------------------- 1 |

Visitor badge 2 | 3 | 4 | 5 | #

Welcome🙏🏻

Hi, I'm Raj!👋 6 | I'm a Computer Science Engineer, & I'm confident to work on the projects with my own experience & skills... 7 | 8 | - Web Development, 9 | - FrontEnd: HTML, CSS, JavaScript 10 | - BackEnd: Django 11 | - Database: MongoDB | OracleSQL 12 | - Android Application Development 13 | - Coding Skills in Java (DSA) 14 | - Additional Skills: JavaScript & Python 15 | 16 | 17 | 18 | ## My Skills 🛠 19 | 20 |

21 | Java 22 | 23 | python 24 | 25 | django 26 | 27 | nodejs 28 | 29 | react 30 | 31 | css3 32 | 33 | html5 34 | javascript 35 | mongodb 36 | mysql 37 | firebase 38 | 39 |

40 | 41 |
42 | 43 | ## Connect with me 🤝 44 | [![GitHub followers](https://img.shields.io/github/followers/AyeRaj?style=social)](https://www.github.com/AyeRaj) [![Linkedin Badge](https://img.shields.io/badge/-AyeRajKumar-blue?style=flat-square&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/in/ayerajkumar/)](https://www.linkedin.com/in/ayerajkumar/) [![Instagram Badge](https://img.shields.io/badge/-HeyRajSingh-black?style=flat-square&logo=Instagram&logoColor=white&link=https://www.instagram.com/heyrajsingh/)](https://www.instagram.com/heyrajsingh/) [![Twitter Follow](https://img.shields.io/twitter/follow/AyeRajSingh?style=social)](https://www.twitter.com/AyeRajSingh) [![Facebook Badge](https://img.shields.io/badge/-HeyRajSingh-blue?style=flat-square&logo=Facebook&logoColor=white&link=https://www.facebook.com/heyrajsingh)](https://www.facebook.com/heyrajsingh) 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /JavaPractice/RearrangeALinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | ## Rearrange a linked list 2 | Given a singly linked list, the task is to rearrange it in a way that all odd position nodes are together and all even positions node are together. 3 | Assume the first element to be at position 1 followed by second element at position 2 and so on. 4 | **Note:** You should place all odd positioned nodes first and then the even positioned ones. (considering 1 based indexing). Also, the relative order of odd positioned nodes and even positioned nodes should be maintained. [🔗Goto](https://practice.geeksforgeeks.org/problems/rearrange-a-linked-list/1/?page=8&difficulty[]=1&status[]=unsolved&sortBy=submissions#) 5 | 6 |
7 | Full Code 8 | 9 | ```java 10 | import java.util.*; 11 | import java.io.*; 12 | 13 | class Node{ 14 | int data; 15 | Node next; 16 | 17 | Node(int x){ 18 | data = x; 19 | next = null; 20 | } 21 | 22 | } 23 | class GFG{ 24 | static void printList(Node node) 25 | { 26 | while (node != null) 27 | { 28 | System.out.print(node.data + " "); 29 | node = node.next; 30 | } 31 | System.out.println(); 32 | } 33 | public static void main(String args[]) throws IOException { 34 | Scanner sc = new Scanner(System.in); 35 | int t = sc.nextInt(); 36 | while(t > 0){ 37 | int n = sc.nextInt(); 38 | Node head = new Node(sc.nextInt()); 39 | Node tail = head; 40 | for(int i=0; i 53 | 54 | ```java 55 | class Solution 56 | { 57 | void rearrangeEvenOdd(Node head) 58 | { 59 | Node odd = head; 60 | Node even = head.next; 61 | Node evenHead = head.next; 62 | while(even!=null && even.next!=null){ 63 | odd.next = even.next; 64 | even.next=even.next.next; 65 | odd = odd.next; 66 | even = even.next; 67 | } 68 | odd.next = evenHead; 69 | 70 | } 71 | } 72 | ``` -------------------------------------------------------------------------------- /JavaPractice/RemoveloopinLinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | ## Remove loop in Linked List 2 | Given a linked list of N nodes such that it may contain a loop. 3 | 4 | > A loop here means that the last node of the link list is connected to the node at position X. If the link list does not have any loop, X=0. 5 | 6 | Remove the loop from the linked list, if it is present. [🔗Goto](https://practice.geeksforgeeks.org/problems/remove-loop-in-linked-list/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions#) 7 | 8 |
9 | Full Code 10 | 11 | ```java 12 | import java.util.*; 13 | import java.io.*; 14 | import java.lang.*; 15 | 16 | class Node 17 | { 18 | int data; 19 | Node next; 20 | } 21 | 22 | class GFG 23 | { 24 | public static Node newNode(int data){ 25 | Node temp = new Node(); 26 | temp.data = data; 27 | temp.next = null; 28 | return temp; 29 | } 30 | 31 | public static void makeLoop(Node head, int x){ 32 | if (x == 0) 33 | return; 34 | Node curr = head; 35 | Node last = head; 36 | 37 | int currentPosition = 1; 38 | while (currentPosition < x) 39 | { 40 | curr = curr.next; 41 | currentPosition++; 42 | } 43 | 44 | while (last.next != null) 45 | last = last.next; 46 | last.next = curr; 47 | } 48 | 49 | public static boolean detectLoop(Node head){ 50 | Node hare = head.next; 51 | Node tortoise = head; 52 | while( hare != tortoise ) 53 | { 54 | if(hare==null || hare.next==null) return false; 55 | hare = hare.next.next; 56 | tortoise = tortoise.next; 57 | } 58 | return true; 59 | } 60 | 61 | public static int length(Node head){ 62 | int ret=0; 63 | while(head!=null) 64 | { 65 | ret += 1; 66 | head = head.next; 67 | } 68 | return ret; 69 | } 70 | 71 | public static void main (String[] args){ 72 | Scanner sc = new Scanner(System.in); 73 | int t = sc.nextInt(); 74 | 75 | while(t--> 0) 76 | { 77 | int n = sc.nextInt(); 78 | 79 | int num = sc.nextInt(); 80 | Node head = newNode(num); 81 | Node tail = head; 82 | 83 | for(int i=0; i 105 | 106 | ```java 107 | class Solution 108 | { 109 | public static void removeLoop(Node head){ 110 | Node low = head; 111 | Node high = head; 112 | while(low!=null && high != null && high.next != null){ 113 | low = low.next; 114 | high = high.next.next; 115 | if(low == high){ 116 | break; 117 | } 118 | } 119 | if(low == head){ 120 | while(high.next != low){ 121 | high = high.next; 122 | } 123 | high.next = null; 124 | }else if(low == high){ 125 | low = head; 126 | while(low.next != high.next){ 127 | low = low.next; 128 | high = high.next; 129 | } 130 | high.next = null; 131 | } 132 | } 133 | } 134 | ``` -------------------------------------------------------------------------------- /JavaPractice/ReturnTwoPrimeNumbers/Readme.md: -------------------------------------------------------------------------------- 1 | ## Return two prime numbers 2 | Given an even number N (greater than 2), return two prime numbers whose sum will be equal to given number. There are several combinations possible. Print only the pair whose minimum value is the smallest among all the minimum values of pairs and print the minimum element first. 3 | 4 | **NOTE:** A solution will always exist, read Goldbachs conjecture. [🔗Goto](https://practice.geeksforgeeks.org/problems/return-two-prime-numbers2509/1#) 5 | 6 |
7 | Full Code 8 | 9 | ```java 10 | import java.io.*; 11 | import java.util.*; 12 | 13 | class GFG{ 14 | public static void main(String args[])throws IOException 15 | { 16 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 17 | int t = Integer.parseInt(in.readLine()); 18 | while(t-- > 0){ 19 | int N = Integer.parseInt(in.readLine()); 20 | 21 | Solution ob = new Solution(); 22 | List ans = new ArrayList(); 23 | ans = ob.primeDivision(N); 24 | System.out.println(ans.get(0) + " " + ans.get(1)); 25 | } 26 | } 27 | } 28 | ``` 29 |
30 | 31 | ```java 32 | class Solution{ 33 | static List primeDivision(int N){ 34 | int i = 2; 35 | int j = N-1; 36 | List list = new ArrayList<>(); 37 | 38 | while(j>=i){ 39 | int sum=i+j; 40 | if(sum==N){ 41 | if(isPrime(i) && isPrime(j)){ 42 | list.add(i); 43 | list.add(j); 44 | return list; 45 | }else{ 46 | i++; 47 | j--; 48 | } 49 | } 50 | else if(sum>N){ 51 | j--; 52 | }else{ 53 | i++; 54 | } 55 | } 56 | return list; 57 | } 58 | static boolean isPrime(int N){ 59 | for(int i=2; i<=Math.sqrt(N); i++){ 60 | if(N%i==0){ 61 | return false; 62 | } 63 | } 64 | return true; 65 | } 66 | } 67 | ``` -------------------------------------------------------------------------------- /JavaPractice/Robots/Readme.md: -------------------------------------------------------------------------------- 1 | ## Robots 2 | There are two kinds of bots A and B in a 1-D array. A bot can only move left while B can only move right. There are also empty spaces in between represented by #. But its also given that the bots cannot cross over each other. 3 | 4 | Given the initial state and final state, we should tell if the transformation is possible. 5 | 6 | **NOTE:** There can be many bots of the same type in a particular array. [🔗Goto](https://practice.geeksforgeeks.org/problems/d35adfbe367861ec1e67bea6e0efebe0a0ee3550/1#) 7 | 8 |
9 | Full Code 10 | 11 | ```java 12 | import java.io.*; 13 | import java.util.*; 14 | 15 | class Solution{ 16 | public static String moveRobots(String s1, String s2){ 17 | int i=0, j=0, n=s1.length(); 18 | while(ij){ 29 | return "No"; // if same B in both, but i greater than j 30 | // that means, i is a left position than j 31 | // and B can't move left or back 32 | // So, return "No" 33 | }else if(s1.charAt(i)=='A' && i 0) 56 | { 57 | String s1=read.readLine(); 58 | String s2=read.readLine(); 59 | 60 | Solution ob = new Solution(); 61 | System.out.println(ob.moveRobots(s1, s2)); 62 | } 63 | } 64 | } 65 | ``` 66 |
67 | 68 | ```java 69 | class Solution{ 70 | public static String moveRobots(String s1, String s2){ 71 | int i=0, j=0, n=s1.length(); 72 | while(ij){ 83 | return "No"; // if same B in both, but i greater than j 84 | // that means, i is a left position than j 85 | // and B can't move left or back 86 | // So, return "No" 87 | }else if(s1.charAt(i)=='A' && i Right rotate the array clockwise by 1. 5 | > Delete the (n-k+1)th last element. 6 | > Now, find the element which is left at last. 7 | 8 | **Input:** 9 | 10 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follows. Each test case contains two lines. The first line of each test case contains an integer N. Then in the next line are N space separated values of the array arr[]. 11 | 12 | **Output:** 13 | 14 | For each test case in a new line print the required result. [🔗Goto](https://practice.geeksforgeeks.org/problems/rotate-and-delete-1587115621/1/?page=2&difficulty[]=1&status[]=unsolved&category[]=Arrays&category[]=Strings&sortBy=accuracy#) 15 | 16 |
17 | Full Code 18 | 19 | ```java 20 | import java.io.*; 21 | import java.util.*; 22 | 23 | class Main { 24 | 25 | public static void main (String[] args) throws IOException { 26 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 27 | int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases 28 | 29 | while(t-->0){ 30 | int n = Integer.parseInt(br.readLine().trim()); 31 | ArrayList arr = new ArrayList(n); 32 | String inputLine[] = br.readLine().trim().split(" "); 33 | for(int i=0; i 47 | 48 | ```java 49 | class Solution{ 50 | public static int rotateDelete(ArrayList ar, int n){ 51 | for(int i = 1; i < n; ++i){ 52 | int temp = ar.get((ar.size() - 1)); 53 | ar.add(0 , temp); 54 | ar.remove((ar.size() - 1)); 55 | if((ar.size() - i) < 0) 56 | ar.remove(0); 57 | else 58 | ar.remove(ar.size() - i); 59 | } 60 | return ar.get(0); 61 | } 62 | } 63 | ``` -------------------------------------------------------------------------------- /JavaPractice/RotateLinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | ## Rotate Linked List 2 | Given a singly linked list of size N. The task is to left-shift the linked list by k nodes, where k is a given positive integer smaller than or equal to length of the linked list. [🔗Goto](https://practice.geeksforgeeks.org/problems/rotate-a-linked-list/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Amazon&company[]=Infosys&sortBy=submissions#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.util.*; 9 | class Node { 10 | int data; 11 | Node next; 12 | Node(int d) { 13 | data = d; 14 | next = null; 15 | } 16 | } 17 | 18 | class Main { 19 | public static void main(String[] args) { 20 | 21 | Scanner sc = new Scanner(System.in); 22 | int t = sc.nextInt(); 23 | 24 | while (t-- > 0) { 25 | int n = sc.nextInt(); 26 | 27 | int a = sc.nextInt(); 28 | Node head = new Node(a); 29 | Node tail = head; 30 | 31 | for (int i=0; i 56 | 57 | ```java 58 | class Solution{ 59 | public Node rotate(Node head, int k) { 60 | if(head == null) return null; 61 | 62 | int n = 0; 63 | Node t = head; 64 | Node lastNode = head; 65 | while(t!=null){ 66 | n++; 67 | t = t.next; 68 | // move to the last node 69 | if(lastNode.next!= null) 70 | lastNode = lastNode.next; 71 | } 72 | if(k >= n){ 73 | return head; 74 | } 75 | Node temp = head; 76 | Node Head = head; 77 | int i = 0; 78 | while(i<(k-1)){ 79 | i++; 80 | temp = temp.next; 81 | } 82 | 83 | Node newHead = temp.next; 84 | temp.next = null; 85 | lastNode.next = Head; 86 | return newHead; 87 | } 88 | } 89 | ``` -------------------------------------------------------------------------------- /JavaPractice/SearchPattern(Z-algorithm)/Readme.md: -------------------------------------------------------------------------------- 1 | ## Search Pattern (Z-algorithm) 2 | Given two strings, one is a text string and other is a pattern string. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1. [🔗Goto](https://practice.geeksforgeeks.org/problems/8dcd25918295847b4ced54055eae35a8501181c1/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Microsoft&category[]=Arrays&category[]=Strings&sortBy=accuracy#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.io.*; 9 | import java.util.*; 10 | 11 | class GFG 12 | { 13 | public static void main(String args[])throws IOException 14 | { 15 | Scanner sc = new Scanner(System.in); 16 | int t = sc.nextInt(); 17 | while(t-- > 0) 18 | { 19 | String s, patt; 20 | s = sc.next(); 21 | patt = sc.next(); 22 | 23 | Solution ob = new Solution(); 24 | 25 | ArrayList res = ob.search(patt, s); 26 | 27 | if(res.size()==0) 28 | System.out.print("-1 "); 29 | else { 30 | for(int i = 0;i 39 | 40 | ```java 41 | class Solution 42 | { 43 | ArrayList search(String pat, String S) 44 | { 45 | // your code here 46 | String str = ""; 47 | int len = pat.length(); 48 | ArrayList list = new ArrayList(); 49 | for(int i = 0;i<=S.length()-len;i++){ 50 | if(S.charAt(i)==pat.charAt(0)){ 51 | str = S.substring(i,i+len); 52 | if(str.equals(pat)){ 53 | list.add(i+1); 54 | } 55 | } 56 | } 57 | return list; 58 | } 59 | } 60 | ``` -------------------------------------------------------------------------------- /JavaPractice/SmallestWindowContaining 0, 1 and 2/Readme.md: -------------------------------------------------------------------------------- 1 | ## Smallest window containing 0, 1 and 2 2 | Given a string S consisting of the characters 0, 1 and 2. Your task is to find the length of the smallest substring of string S that contains all the three characters 0, 1 and 2. If no such substring exists, then return -1. [🔗Goto](https://practice.geeksforgeeks.org/problems/d6e88f06b273a60ae83992314ac514f71841a27d/1#) 3 | 4 |
5 | Full Code 6 | 7 | ```java 8 | import java.io.*; 9 | import java.util.*; 10 | import java.lang.*; 11 | 12 | class GFG { 13 | public static void main(String args[]) throws IOException { 14 | BufferedReader read = 15 | new BufferedReader(new InputStreamReader(System.in)); 16 | int t = Integer.parseInt(read.readLine()); 17 | while (t-- > 0) { 18 | String S = read.readLine(); 19 | Solution ob = new Solution(); 20 | int ans = ob.smallestSubstring(S); 21 | 22 | System.out.println(ans); 23 | } 24 | } 25 | } 26 | ``` 27 |
28 | 29 | ```java 30 | class Solution { 31 | public int smallestSubstring(String S) { 32 | // Code here 33 | int len = S.length(); 34 | int zero = -1; 35 | int one = -1; 36 | int two = -1; 37 | int min = Integer.MAX_VALUE; 38 | for(int i =0;i=0 && one>=0 && two>=0){ 50 | 51 | int minpos = -1,maxpos = -1; 52 | if(zero<=one && zero <= two){ 53 | minpos = zero; 54 | } 55 | else if(one <= two && one <= two){ 56 | minpos = one; 57 | }else{ 58 | minpos = two; 59 | } 60 | 61 | if(zero>=one && zero >= two){ 62 | maxpos = zero; 63 | } 64 | else if(one >= two && one >= two){ 65 | maxpos = one; 66 | }else{ 67 | maxpos = two; 68 | } 69 | 70 | int y = (Math.abs(maxpos-minpos))+1; 71 | min = Math.min(min,y); 72 | } 73 | } 74 | 75 | if(min == Integer.MAX_VALUE){ 76 | min = -1; 77 | } 78 | return min; 79 | } 80 | }; 81 | ``` -------------------------------------------------------------------------------- /JavaPractice/SpideySense/Readme.md: -------------------------------------------------------------------------------- 1 | ## SpideSense 2 | Spiderman is stuck in a difficult situation. His arch-enemy the Green Goblin has planted several of his infamous Pumpkin Bombs in various locations in a building. Help Spiderman activate his Spidey Sense and identify the impact zones. 3 | He has a blueprint of the building which is a M x N matrix that is filled with the characters O, B, and W where: 4 | O represents an open space. 5 | B represents a bomb. 6 | W represents a wall. 7 | You have to replace all of the Os (open spaces) in the matrix with their shortest distance from a bomb without being able to go through any walls. Also, replace the bombs with 0 and walls with -1 in the resultant matrix. If no path exists between a bomb and an open space replace the corresponding 'O' with -1. [🔗Goto](https://practice.geeksforgeeks.org/problems/spidey-sense5556/1#) 8 | 9 |
10 | Full Code 11 | 12 | ```java 13 | import java.util.*; 14 | import java.math.*; 15 | 16 | class Pair{ 17 | 18 | int x,y; 19 | Pair(int x,int y) 20 | { 21 | this.x = x; 22 | this.y = y; 23 | } 24 | } 25 | 26 | class Gfg 27 | { 28 | public static void main(String args[]) 29 | { 30 | Scanner sc = new Scanner(System.in); 31 | int t = Integer.parseInt(sc.next()); 32 | while(t-- > 0) 33 | { 34 | int m = Integer.parseInt(sc.next()); 35 | int n = Integer.parseInt(sc.next()); 36 | char mat[][] = new char[m][n]; 37 | for(int i=0;i 61 | 62 | ```java 63 | class Solution 64 | { 65 | public static int[][] findDistance(char mat[][], int n,int m) 66 | { 67 | // Your code goes here 68 | int a[][] = new int [n][m]; 69 | for(int i = 0;i=n || j < 0 || j>=m){ 106 | return; 107 | } 108 | if(a[i][j] > a[x][y]){ 109 | a[i][j] = Math.min(a[i][j],a[x][y]+1); 110 | dfs(a,i+1,j,i,j,n,m); 111 | dfs(a,i-1,j,i,j,n,m); 112 | dfs(a,i,j+1,i,j,n,m); 113 | dfs(a,i,j-1,i,j,n,m); 114 | } 115 | } 116 | } 117 | ``` -------------------------------------------------------------------------------- /JavaPractice/TheCelebrityProblem/Readme.md: -------------------------------------------------------------------------------- 1 | ## The Celebrity Problem 2 | A celebrity is a person who is known to all but does not know anyone at a party. If you go to a party of N people, find if there is a celebrity in the party or not. 3 | A square NxN matrix M[][] is used to represent people at the party such that if an element of row i and column j is set to 1 it means ith person knows jth person. Here M[i][i] will always be 0. 4 | Note: Follow 0 based indexing. [🔗Goto](https://practice.geeksforgeeks.org/problems/the-celebrity-problem/1/?page=2&difficulty[]=1&status[]=unsolved&company[]=Amazon&company[]=Infosys&sortBy=submissions#) 5 | 6 |
7 | Full Code 8 | 9 | ```java 10 | import java.io.*; 11 | import java.util.*; 12 | 13 | class GFG{ 14 | public static void main(String args[]) throws IOException { 15 | Scanner sc = new Scanner(System.in); 16 | int t = sc.nextInt(); 17 | while(t>0) 18 | { 19 | int N = sc.nextInt(); 20 | int M[][] = new int[N][N]; 21 | for(int i=0; i 35 | 36 | ```java 37 | class Solution 38 | { 39 | //Function to find if there is a celebrity in the party or not. 40 | int celebrity(int arr[][], int n) 41 | { 42 | // code here 43 | Stack st = new Stack<>(); 44 | for(int i =0;i= 2 ){ 48 | int i = st.pop(); 49 | int j = st.pop(); 50 | 51 | if(arr[i][j] == 1){ 52 | st.push(j); 53 | } 54 | else{ 55 | st.push(i); 56 | } 57 | } 58 | 59 | int pot = st.pop(); 60 | for(int i =0;i

Input: N = "5"
7 | >Output: 1
8 | >Explanation: 5 is a Fibonacci number and prime too

9 | 10 |
11 | Full Code 12 | 13 | ```java 14 | import java.io.*; 15 | import java.util.*; 16 | 17 | class GFG { 18 | public static void main(String args[]) throws IOException { 19 | BufferedReader read = 20 | new BufferedReader(new InputStreamReader(System.in)); 21 | int t = Integer.parseInt(read.readLine()); 22 | while (t-- > 0) { 23 | String input = read.readLine(); 24 | 25 | Solution ob = new Solution(); 26 | int result = ob.fibonacciPrime(input); 27 | 28 | System.out.println(result); 29 | } 30 | } 31 | } 32 | ``` 33 |
34 | 35 | ```java 36 | class Solution { 37 | int fibonacciPrime(String N) { 38 | ArrayList list =new ArrayList(); 39 | list.add("2"); 40 | list.add("3"); 41 | list.add("5"); 42 | list.add("13"); 43 | list.add("89"); 44 | list.add("233"); 45 | list.add("1597"); 46 | list.add("28657"); 47 | list.add("514229"); 48 | list.add("433494437"); 49 | list.add("2971215073"); 50 | list.add("99194853094755497"); 51 | list.add("1066340417491710595814572169"); 52 | list.add("19134702400093278081449423917"); 53 | list.add("475420437734698220747368027166749382927701417016557193662268716376935476241"); 54 | for(int i = 0;i 5 | Full Code 6 | 7 | ```java 8 | import java.io.*; 9 | import java.util.*; 10 | class GFG { 11 | public static void main (String[] args) { 12 | Scanner sc=new Scanner(System.in); 13 | int t=sc.nextInt(); 14 | sc.nextLine(); 15 | while(t-->0) 16 | { 17 | int n; 18 | n=sc.nextInt(); 19 | 20 | long arr[]=new long[n]; 21 | 22 | 23 | for(int i=0;i 35 | 36 | ```java 37 | class Solution{ 38 | public static long findSubarray(long[] arr ,int n){ 39 | long count = 0; 40 | HashMap map = new HashMap<>(); 41 | int i = 0; 42 | int sum = 0; 43 | map.put(0,1); 44 | while(i0) { 12 | for (int i = a; i > 0; i--) { 13 | fact = fact * i; 14 | System.out.print(i); 15 | if (i!=1) 16 | System.out.print("x"); 17 | else 18 | System.out.print(" = "); 19 | } 20 | System.out.println(fact); 21 | } 22 | else if (a==0) 23 | System.out.println("1"); 24 | else 25 | System.out.println("Invalid Input"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /JavaPre_Practice/FibonacciSeries.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Fibonacci Series up to nth term 4 | public class FibonacciSeries { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter the Value of n: "); 8 | int a = sc.nextInt(); 9 | int b=0,c=1,z=0; 10 | System.out.print(b+", "+c+", "); 11 | if(a>0) { 12 | while (z <= a) { 13 | z = b + c; 14 | b = c; 15 | c = z; 16 | if (z<=a) { 17 | System.out.print(z + ", "); 18 | } 19 | } 20 | }else 21 | System.out.print("Input Error"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /JavaPre_Practice/GreaterThree.java: -------------------------------------------------------------------------------- 1 | import java.sql.SQLOutput; 2 | import java.util.Scanner; 3 | 4 | //Greatest of the Three numbers 5 | public class GreaterThree { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.print("Enter first number: "); 9 | int a = sc.nextInt(); 10 | System.out.print("Enter second number: "); 11 | int b = sc.nextInt(); 12 | System.out.print("Enter third number: "); 13 | int c = sc.nextInt(); 14 | if (a>b & a>c){ 15 | System.out.print("First number is greatest"); 16 | } 17 | else if (a < c){ 18 | System.out.print("Third number is greater"); 19 | } 20 | else if (a < b){ 21 | System.out.println("Second number is greater"); 22 | } 23 | else{ 24 | System.out.println("All are equal"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /JavaPre_Practice/GreatestTwoNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Greatest of two numbers: 4 | public class GreatestTwoNumber { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter 1st Number: "); 8 | int a = sc.nextInt(); 9 | System.out.print("Enter 2nd Number: "); 10 | int b = sc.nextInt(); 11 | 12 | if (a > b) { 13 | System.out.println(a + " is Greater"); 14 | } 15 | else if (b > a) { 16 | System.out.println(b + " is Greater"); 17 | } 18 | else{ 19 | System.out.println("Both are Equal"); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /JavaPre_Practice/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Palindrome number 4 | public class PalindromeNumber { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter a Palindrome number: "); 8 | String a = sc.next(); 9 | int len = a.length(); 10 | int c=0; 11 | for (int i= 0; i<=len/2; i++){ 12 | if (a.charAt(i) == a.charAt(len-1-i)){ 13 | c+=1; 14 | } 15 | else 16 | break; 17 | } 18 | if (c == len/2+1) { 19 | System.out.println("Yes! It is a Palindrome number"); 20 | } else { 21 | System.out.println("No, It is not a Palindrome"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /JavaPre_Practice/PosNeg.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PosNeg { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter a number: "); 7 | int a = sc.nextInt(); 8 | if (a >= 0) { 9 | System.out.println("Given number is positive"); 10 | } else { 11 | System.out.println("Given number is negative"); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /JavaPre_Practice/PrimeNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PrimeNumber { 4 | public static void main (String[] args){ 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter a number: "); 7 | int a = sc.nextInt(); 8 | int count = 0; 9 | for (int i = 1; i<=a; i++){ 10 | if (a%i==0){ 11 | count+=1; 12 | } 13 | } 14 | if (count==2) { 15 | System.out.println("It is a Prime number"); 16 | } 17 | else{ 18 | System.out.println("It is not a prime number"); 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /JavaPre_Practice/ReverseNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Reverse of a number 4 | public class ReverseNumber { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter the number to find the reverse: "); 8 | int a = sc.nextInt(); 9 | int b = String.valueOf(a).length(); 10 | int reverse=0; 11 | while (a!=0){ 12 | int c=a%10; 13 | b--; 14 | int d= (int) Math.pow(10,b); 15 | reverse+=c*d; 16 | a= a/10; 17 | 18 | } 19 | System.out.println("Reverse of the number is "+reverse); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /JavaPre_Practice/SumInGivenRange.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Sum of numbers in a given range: 4 | public class SumInGivenRange { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter the lower range: "); 8 | int a = sc.nextInt(); 9 | System.out.print("Enter the upper range: "); 10 | int b = sc.nextInt(); 11 | int sum=0; 12 | for (int i=a; i arr[i + 1]) { 18 | temp = arr[i]; 19 | arr[i] = arr[i + 1]; 20 | arr[i + 1] = temp; 21 | } 22 | } 23 | } 24 | for(int i = 0; i < n; i++){ 25 | System.out.print(arr[i] + " "); 26 | } 27 | System.out.println(); 28 | System.out.print("Position of Kth Smallest Element: "); 29 | int k = sc.nextInt(); 30 | System.out.println(arr[k-1]); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /JavaPre_Practice/leapOrNot.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Leap year or not 4 | public class leapOrNot { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter the year: "); 8 | int a = sc.nextInt(); 9 | if (a%4==0 && a%100!=0 || a%400==0){ 10 | System.out.println("It is a Leap year"); 11 | } 12 | else{ 13 | System.out.println("Oops! It is not a Leap year"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /JavaPre_Practice/minMaxArray.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class minMaxArray { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter the Size of Array: "); 7 | int n = sc.nextInt(); 8 | int[] arr = new int[n]; 9 | for(int i = 0; i arr[1]) { 15 | max = arr[0]; 16 | min = arr[1]; 17 | } 18 | else { 19 | max = arr[1]; 20 | min = arr[0]; 21 | } 22 | for(int i = 2; i max){ 24 | max=arr[i]; 25 | } 26 | else if (arr[i] < min){ 27 | min = arr[i]; 28 | } 29 | } 30 | System.out.println("Maximum of Array is: " + max); 31 | System.out.println("Minimum of Array is: " + min); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /JavaPre_Practice/primeNumberRange.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Prime number within a given range 4 | public class primeNumberRange { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter lower range: "); 8 | int a = sc.nextInt(); 9 | System.out.print("Enter upper range: "); 10 | int b = sc.nextInt(); 11 | for (int i = a; i <=b; i++){ 12 | int count = 0; 13 | for (int j=1; j<=i;j++ ){ 14 | if (i%j==0){ 15 | count+=1; 16 | } 17 | } 18 | if (count==2) 19 | System.out.print( i+ ", " ); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /JavaPre_Practice/printFirstN.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class printFirstN { 4 | public static void main(String[] args) { 5 | System.out.print("Enter the value of N: "); 6 | Scanner sc = new Scanner(System.in); 7 | int a = sc.nextInt(); 8 | int i=0; 9 | while (i 31 | 32 | **The String class has a set of built-in methods that we can use on strings.** 33 | ### charAt() 34 | Returns the character at the specified index (position) 35 | ``` 36 | String myStr = "Hello"; 37 | char result = myStr.charAt(0); 38 | System.out.println(result); 39 | ``` 40 | 41 | ### length() 42 | Returns the length of a specified string 43 | ``` 44 | String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 45 | System.out.println(txt.length()); 46 | ``` 47 | 48 | 49 | 50 | ### compareTo() 51 | Compares two strings lexicographically 52 | ``` 53 | String myStr1 = "Hello"; 54 | String myStr2 = "Hello"; 55 | System.out.println(myStr1.compareTo(myStr2)); 56 | ``` 57 | 58 | ### contains() 59 | Checks whether a string contains a sequence of characters 60 | ``` 61 | String myStr = "Hello"; 62 | System.out.println(myStr.contains("Hel")); // true 63 | System.out.println(myStr.contains("e")); // true 64 | System.out.println(myStr.contains("Hi")); // false 65 | ``` 66 | 67 | ### contentEquals() 68 | Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer 69 | ``` 70 | String myStr = "Hello"; 71 | System.out.println(myStr.contentEquals("Hello")); // true 72 | System.out.println(myStr.contentEquals("e")); // false 73 | System.out.println(myStr.contentEquals("Hi")); // false 74 | ``` 75 | 76 | ### copyValueOf() 77 | Returns a String that represents the characters of the character array 78 | ``` 79 | char[] myStr1 = {'H', 'e', 'l', 'l', 'o'}; 80 | String myStr2 = ""; 81 | myStr2 = myStr2.copyValueOf(myStr1, 0, 5); 82 | System.out.println("Returned String: " + myStr2); 83 | ``` 84 | 85 | ### endsWith() 86 | Checks whether a string ends with the specified character(s) 87 | ``` 88 | String myStr = "Hello"; 89 | System.out.println(myStr.endsWith("Hel")); // false 90 | System.out.println(myStr.endsWith("llo")); // true 91 | System.out.println(myStr.endsWith("o")); // true 92 | ``` 93 | 94 | ### equals() 95 | Compares two strings. Returns true if the strings are equal, and false if not 96 | ``` 97 | String myStr1 = "Hello"; 98 | String myStr2 = "Hello"; 99 | String myStr3 = "Another String"; 100 | System.out.println(myStr1.equals(myStr2)); // Returns true because they are equal 101 | System.out.println(myStr1.equals(myStr3)); // false 102 | ``` 103 | 104 | ### indexOf() 105 | Returns the position of the first found occurrence of specified characters in a string 106 | ``` 107 | String myStr = "Hello planet earth, you are a great planet."; 108 | System.out.println(myStr.indexOf("planet")); 109 | ``` 110 | 111 | ### lastIndexOf() 112 | Returns the position of the last found occurrence of specified characters in a string 113 | ``` 114 | String myStr = "Hello planet earth, you are a great planet."; 115 | System.out.println(myStr.lastIndexOf("planet")); 116 | ``` 117 | 118 | 119 | ### isEmpty() 120 | Checks whether a string is empty or not 121 | ``` 122 | String myStr1 = "Hello"; 123 | String myStr2 = ""; 124 | System.out.println(myStr1.isEmpty()); 125 | System.out.println(myStr2.isEmpty()); 126 | ``` 127 | ### replace() 128 | Searches a string for a specified value, and returns a new string where the specified values are replaced 129 | ``` 130 | String myStr = "Hello"; 131 | System.out.println(myStr.replace('l', 'p')); 132 | ``` 133 | 134 | ### startsWith() 135 | Checks whether a string starts with specified characters 136 | ``` 137 | String myStr = "Hello"; 138 | System.out.println(myStr.startsWith("Hel")); // true 139 | System.out.println(myStr.startsWith("llo")); // false 140 | System.out.println(myStr.startsWith("o")); // false 141 | ``` 142 | 143 | ### toLowerCase() 144 | Converts a string to lower case letters 145 | ``` 146 | String txt = "Hello World"; 147 | System.out.println(txt.toUpperCase()); 148 | System.out.println(txt.toLowerCase()); 149 | ``` 150 | 151 | ### toUpperCase() 152 | Converts a string to upper case letters 153 | ``` 154 | String txt = "Hello World"; 155 | System.out.println(txt.toUpperCase()); 156 | System.out.println(txt.toLowerCase()); 157 | ``` 158 | 159 | ### trim() 160 | Removes whitespace from both ends of a string 161 | ``` 162 | String myStr = " Hello World! "; 163 | System.out.println(myStr); 164 | System.out.println(myStr.trim()); 165 | ``` 166 | 167 | ### valueOf() 168 | Returns the string representation of the specified value 169 | ``` 170 | int value=30; 171 | String s1=String.valueOf(value); 172 | System.out.println(s1+10);//concatenating string with 10 173 | ``` 174 | 175 | 176 | 177 | ### toString() 178 | Returns the value of a String object 179 | ``` 180 | public static void main(String args[]) { 181 | String Str = new String("Welcome to My JavaNotes"); 182 | 183 | System.out.print("Return Value :"); 184 | System.out.println(Str.toString()); 185 | } 186 | ``` 187 | 188 | 189 | 190 | ### toCharArray() 191 | Converts this string to a new character array 192 | ``` 193 | String s1="hello"; 194 | char[] ch=s1.toCharArray(); 195 | for(int i=0;iVisitor badge 2 | 3 | ## Resources for Full Stack Java 📌 4 | 5 | - ### References 6 | - Java Language [Click here](https://www.youtube.com/playlist?list=PLsyeobzWxl7pe_IiTfNyr55kwJPWbgxB5) 7 | - Servlet and JSP [Click here](https://www.youtube.com/playlist?list=PLsyeobzWxl7pUPF2xjjJiG4BKC9x_GY46) 8 | - Spring [Click here](https://www.youtube.com/playlist?list=PL0zysOflRCekeiERASkpi-crREVensZGS) 9 | - Start with Spring Boot [Click here](https://www.youtube.com/watch?v=aS0t9HTO5V4&t=468s&ab_channel=KunalKushwaha) 10 | - Spring Boot [Click here](https://www.youtube.com/playlist?list=PL0zysOflRCelmjxj-g4jLr3WKraSU_e8q) 11 | - or Spring Boot [Click here](https://www.youtube.com/playlist?list=PLsyeobzWxl7oA8QOlMtQsRT_I7Rx2hoX4) 12 | - Microservice [Click here](https://www.youtube.com/watch?v=Nb2PPuqtL2g&ab_channel=LearnCodeWithDurgesh) 13 | 14 | 15 | 16 | #

Complete Java & DSA Syllabus🎓

17 | 18 | ## Syallbus📌 19 | 20 | - ### Functions 21 | - Scoping in Java 22 | - Shadowing 23 | - Variable Length Arguments 24 | - Overloading 25 | - ### Arrays 26 | - Memory management 27 | - Input and Output 28 | - ArrayList Introduction 29 | - Searching 30 | - Linear Search 31 | - Binary Search 32 | - Modified Binary Search 33 | - Binary Search on 2D Arrays 34 | - Sorting 35 | - Insertion Sort 36 | - Selection Sort 37 | - Bubble Sort 38 | - Cyclic Sort 39 | - ### Pattern questions(Self Practice) 40 | - ### Strings 41 | - How Strings work 42 | - Comparison of methods 43 | - Operations in Strings 44 | - StringBuilder in java 45 | - ### Maths for DSA 46 | - Complete Bitwise Operators 47 | - Range of numbers 48 | - Prime numbers 49 | - Sieve of Eratosthenes 50 | - Newton's Square Root Method 51 | - Factors 52 | - Modulo properties 53 | - Number Theory 54 | - HCF / LCM 55 | - Euclidean algorithm 56 | - ### Recursion 57 | - Flow of recursive programs - stack 58 | - Tree building of function calls 59 | - Tail recursion 60 | - Sorting 61 | - Merge Sort 62 | - Quick Sort 63 | - Backtracking 64 | - N-Queens 65 | - N-Knights 66 | - Sudoku Solver 67 | - Maze problems 68 | - Recursion String Problems 69 | - Recursion Google, Amazon Questions 70 | - Recursion Array Problems 71 | - Recursion Pattern Problems 72 | - Subset Questions 73 | - ### Space and Time Complexity Analysis 74 | - Comparisons of various cases 75 | - Solving Linear Recurrence Relations 76 | - Solving Divide and Conquer Recurrence Relations 77 | - Big-O, Big-Omega, Big-Theta Notations 78 | - Little Notations 79 | - Get equation of any relation easily - best and easiest approach 80 | - Complexity discussion of all the problems we do 81 | - Space Complexity 82 | - NP-Completeness Introduction 83 | - ### Object Oriented Programming 84 | - Classes & its instances 85 | - this keyword in Java 86 | - Properties 87 | - Inheritance 88 | - Abstraction 89 | - Polymorphism 90 | - Encapsulation 91 | - Overloading & Overriding 92 | - Static & Non-Static 93 | - Packages 94 | - Access Control 95 | - Interfaces 96 | - Abstract Classes 97 | - Annotations 98 | - Singleton Class 99 | - final, finalize, finally 100 | - Object Cloning 101 | - Object Class 102 | - Generics 103 | - Exception Handling 104 | - Collections Framework 105 | - Vector Class 106 | - Lambda Expression 107 | - Enums 108 | - ### Linked List 109 | - Singly + Doubly + Circular LinkedList 110 | - Fast and slow pointer 111 | - Cycle Detection 112 | - Reversal of LinkedList 113 | - Linked List + Recursion 114 | - ### Stacks & Queues 115 | - Push efficient 116 | - Pop efficient 117 | - Circular Queue 118 | - Queue using Stack and Vice versa 119 | - Interview problems 120 | - ### Trees 121 | - Binary Trees 122 | - Binary Search Trees 123 | - DFS 124 | - BFS 125 | - AVL Trees 126 | - Segment Tree 127 | - ### Heaps 128 | - Theory 129 | - Priority Queue 130 | - Heapsort 131 | - Two Heaps Method 132 | - k-way merge 133 | - Top k elements 134 | - Interval problems 135 | - ### HashMap 136 | - Theory - how it works 137 | - Comparisons of various forms 138 | - Limitations and how to solve 139 | - Map using LinkedList 140 | - Map using Hash 141 | - Count Sort 142 | - Radix Sort 143 | - Chaining 144 | - Probing 145 | - Huffman-Encoder 146 | - ### Subarray Questions: Sliding window, Two Pointer, Kadane's Algorithm 147 | - ### Graphs 148 | - BFS 149 | - DFS 150 | - Working with graph components 151 | - Minimum Spanning Trees 152 | - Kruskal Algorithm 153 | - Prims Algorithm 154 | - Dijkstra’s shortest path algorithm 155 | - Topological Sort 156 | - Bellman ford 157 | - A* pathfinding Algorithm 158 | - ### Dynamic Programming 159 | - Recursion + Recursion DP + Iteration + Iteration Space Optimized 160 | - Complexity Analysis 161 | - 0/1 Knapsack 162 | - Subset Questions 163 | - Unbounded Knapsack 164 | - Subsequence questions 165 | - String DP 166 | - ### Greedy Algorithms 167 | - ### Tries 168 | 169 | ## Advanced concepts apart from interviews 170 | - Fast IO 171 | - File handling 172 | - Bitwise + DP 173 | - Extended Euclidean algorithm 174 | - Modulo Multiplicative Inverse 175 | - Linear Diophantine Equations 176 | - Matrix Exponentiation 177 | - Mathematical Expectation 178 | - Catalan Numbers 179 | - Fermat’s Theorem 180 | - Wilson's Theorem 181 | - Euler's Theorem 182 | - Lucas Theorem 183 | - Chinese Remainder Theorem 184 | - Euler Totient 185 | - NP-Completeness 186 | - Multithreading 187 | - Fenwick Tree / Binary Indexed Tree 188 | - Square Root Decomposition 189 | --------------------------------------------------------------------------------