├── OOPs └── Welcome.txt ├── Basic Codes ├── Welcome.txt ├── multiple_of_two.java ├── Greaterno.java ├── Positive_Negative.java ├── Factorial.java ├── factorial-by-loops.java ├── Swapnum.java ├── greaterOrLesserThan10.java ├── swap2.java ├── fibonacci.java ├── RootsOfQuadraticEqn.java └── TempConversion.java ├── CodeChef ├── Welcome.txt └── MakeitDivisible.java ├── CodeForces └── Welcome.txt ├── Game Theory └── Welcome.txt ├── Hackerearth └── Welcome.txt ├── Hackerrank ├── Welcome.txt ├── End_of_file_solution.java ├── birthday.java └── java_exception_handling(try-catch).java ├── LeetCode ├── Welcome.txt ├── count1s.java ├── Missing Number ├── bitwiseand.java ├── Search2DMatrix.java ├── DeleteNode.java ├── DuplicateNumber.java ├── Pow.java ├── minCostClimbingStairs.java ├── FindAllDuplicatesinanArray.java ├── MissingNumber.java ├── MoveZeros.Java ├── SortedSquares.java ├── perfectSquare.java ├── uniqueBString.java ├── Best Time to Buy and Sell Stock III.java ├── FindPeak.java ├── MaximumSubarray.java ├── rotate_Array_By_K.java ├── MergeKSortedLists.java ├── AllMissingNumber.java ├── mergeInterval.java ├── First Missing Positive.java ├── Binary Tree Maximum Path Sum ├── Container With Most Water.java ├── Consecutive_Numbers_Sum.java ├── Majority_Element.java ├── Maximum_Product_of_Three_Numbers.java ├── Product_of_Array_Except_Self.java ├── constructBinarySearchTree.java ├── NextGreaterElement.java ├── Burst_Balloon.java ├── PointInsideCircle.java ├── ThreeSum.java ├── deletionOfNode.java ├── Sort colors.java ├── Max_Chunks_To_Make_Sorted.java ├── Reorder_List.java ├── wordCount.java ├── Letter_Combination_of_a_phone_number.java ├── Majority_Element_II.java ├── LongestCommonSubsequence.java ├── Max_Chunks_To_Make_Sorted_II.java └── Partition_Labels.java ├── Recursion ├── Welcome.txt ├── MinMaxRecursion.java └── FibonacciSeries.java ├── Searching ├── Welcome.txt ├── stringsearch.java ├── searchinrange.java ├── binarysearch.java └── LinearSearchJava.java ├── Sorting ├── Welcome.txt ├── insertion_sort.java ├── ShellSort.java ├── selection_Sort.java ├── CyclicSort.java ├── InsertionSort.java ├── RadixSort.java ├── import java.util.Scanner;.java ├── Bubble Sort.java ├── quickSort.java ├── merge-Sort.java └── semisort1.java ├── Arrays ├── 1D Arrays │ ├── Welcome.txt │ ├── maxLength_Of_Subarray.java │ ├── Maximum_Product_Adjacent_Elements.java │ └── intersectionOfTwoArrays.java └── 2D Arrays │ ├── Welcome.txt │ ├── Wavetraversal.java │ ├── matrixAddition.java │ ├── Spiraltraversal.java │ └── pattern387.java ├── Bit Manipulation ├── Welcome.txt ├── CheckOddEven.java ├── PrintBinary.java ├── PowerSet.java └── IsNthBitSet.java ├── File Handling └── Welcome.txt ├── String Handling ├── Welcome.txt ├── stringPalindrome.java ├── Max_Freq_Character.java ├── StringReverse.java ├── Permutation.java └── isomorphicString.java ├── Data Structure ├── Heap │ ├── Welcome.txt │ └── kthLargestElement.java ├── Stack │ └── Welcome.txt ├── Trees │ ├── AVL Trees │ │ └── Welcome.txt │ ├── B+ Trees │ │ └── Welcome.txt │ ├── Binary Trees │ │ ├── Welcome.txt │ │ └── BinarySearchTree.java │ └── Red Black Trees │ │ └── Welcome.txt ├── Graph │ ├── Directed Graph │ │ ├── Welcome.txt │ │ └── directedGraph.java │ └── Undirected Graph │ │ ├── Welcome.txt │ │ └── undirectedGraph.java ├── Queue │ ├── Basic Queue │ │ └── Welcome.txt │ ├── Circular Queue │ │ └── Welcome.txt │ └── Priority Queue │ │ └── Welcome.txt └── Linked List │ ├── Doubly Linked List │ └── Welcome.txt │ ├── Single Linked List │ ├── Welcome.txt │ └── Remove_Nth_Node_from_the_end.java │ └── Circular Linked List │ └── Welcome.txt ├── Dynamic Programming └── Welcome.txt ├── Exception Handling ├── Welcome.txt └── zeroerror_exceptionhandling.java ├── Interview Questions └── Welcome.txt ├── GeeksForGeeks ├── welcome.txt ├── replacepi.java ├── SearchInInfiniteSortedArray.java ├── Rotate_Matrix_by_90deg.java ├── Inversion_Count.java ├── CountText.java ├── minimum_Jumps.java └── LongestCommonSubsequence.java ├── Theory Questions and Answers └── Welcome.txt ├── Questions.xlsx ├── Website Logo.png ├── .vscode └── settings.json ├── Parallel Programming ├── Addition │ ├── adder.java │ ├── how to run.txt │ ├── AddR.java │ ├── myserver.java │ └── myclient.java └── Subtraction │ ├── subtract.java │ ├── how to run.txt │ ├── SubR.java │ ├── subserver.java │ └── subclient.java ├── .github └── ISSUE_TEMPLATE │ ├── suggest-an-idea.md │ └── add-a-question.md ├── website_name.txt ├── ReasonBehindCreatingTheLogo.txt ├── Pattern_Printing ├── Z.java ├── Letter_T.java ├── Inner_Diamond.java ├── Outer_Diamond.java ├── Letter_L.java ├── Letter_B.java ├── Letter_E.java ├── Letter_Y.java ├── Letter_F.java ├── Letter_W.java ├── Letter_K.java ├── Letter_X.java ├── Letter_H.java ├── Letter_M.java ├── Letter_I.java └── C.java ├── Number Theory ├── KeprekarNo.java ├── SpecialNo.java ├── ArmstrongNumber.java ├── Fascno.java ├── PrimePal.java ├── Emirp.java ├── ModularExp.java └── nextpermutation.java ├── pull_request_template.md ├── LICENSE.md ├── Java_abstract_class[Hackerrank].java └── Coding Application(Games and more) └── DigitalClock.java /OOPs/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Basic Codes/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CodeChef/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CodeForces/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Game Theory/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Hackerearth/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Hackerrank/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /LeetCode/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Recursion/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Searching/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Sorting/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/1D Arrays/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/2D Arrays/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Bit Manipulation/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /File Handling/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /String Handling/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Heap/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Stack/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Dynamic Programming/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Exception Handling/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Interview Questions/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /GeeksForGeeks/welcome.txt: -------------------------------------------------------------------------------- 1 | hello 2 | -------------------------------------------------------------------------------- /Data Structure/Trees/AVL Trees/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Trees/B+ Trees/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Theory Questions and Answers/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Graph/Directed Graph/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Queue/Basic Queue/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Queue/Circular Queue/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Queue/Priority Queue/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Trees/Binary Trees/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Trees/Red Black Trees/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Graph/Undirected Graph/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Linked List/Doubly Linked List/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Linked List/Single Linked List/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Data Structure/Linked List/Circular Linked List/Welcome.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Questions.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SarthakKeshari/Java-Questions-and-Solutions/HEAD/Questions.xlsx -------------------------------------------------------------------------------- /Website Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SarthakKeshari/Java-Questions-and-Solutions/HEAD/Website Logo.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": [ 3 | "Sorting", 4 | "Number Theory", 5 | "Basic Codes", 6 | "Pattern_Printing" 7 | ] 8 | } -------------------------------------------------------------------------------- /Parallel Programming/Addition/adder.java: -------------------------------------------------------------------------------- 1 | // Addition using parallel programming 2 | 3 | import java.rmi.*; 4 | import java.util.*; 5 | public interface adder extends Remote{ //connecting to remote 6 | public int add(int x,int y) throws RemoteException; 7 | } 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/suggest-an-idea.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Suggest an idea 3 | about: What more can be implemented in this repository to help students 4 | title: "[Idea Title]" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### A brief about your proposal - 11 | Your answer 12 | -------------------------------------------------------------------------------- /Parallel Programming/Subtraction/subtract.java: -------------------------------------------------------------------------------- 1 | //Performing subtraction of two numbers using parallel programming 2 | import java.rmi.*; 3 | import java.util.*; 4 | public interface subtract extends Remote{//remote declaration 5 | public int sub(int x,int y) throws RemoteException;//passing arg... 6 | } 7 | -------------------------------------------------------------------------------- /Basic Codes/multiple_of_two.java: -------------------------------------------------------------------------------- 1 | class multiple_of_two { 2 | public static void main(String args[]) { 3 | int a = 2; 4 | if (a % 2 == 0) { 5 | System.out.print("Multiple of two"); 6 | } else { 7 | System.out.print("Not multiple of two "); 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /Parallel Programming/Addition/how to run.txt: -------------------------------------------------------------------------------- 1 | Open 3 terminals at a same time 2 | 3 | run the commands in terminal-1: 4 | javac adder.java 5 | javac AddR.java 6 | javac myserver.java 7 | javac myclient.java 8 | rmiregistry 5000 9 | 10 | 11 | run this command in terminal 2: 12 | java myserver 13 | 14 | run this command in terminal 3: 15 | java myclient 16 | -------------------------------------------------------------------------------- /Basic Codes/Greaterno.java: -------------------------------------------------------------------------------- 1 | 2 | public class Greaterno { 3 | 4 | public static void main (String[] args) { 5 | 6 | int num=110; 7 | System.out.println(num); 8 | if(num>100) 9 | { 10 | System.out.println("Number is Greater than 100"); 11 | } 12 | else { 13 | System.out.println("Number is Less than 100"); 14 | } 15 | 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Parallel Programming/Subtraction/how to run.txt: -------------------------------------------------------------------------------- 1 | Open 3 terminals at a same time 2 | 3 | run the commands in terminal-1: 4 | javac subtractr.java 5 | javac SubR.java 6 | javac subserver.java 7 | javac subclient.java 8 | rmiregistry 5000 9 | 10 | 11 | run this command in terminal 2: 12 | java subserver 13 | 14 | run this command in terminal 3: 15 | java subclient 16 | -------------------------------------------------------------------------------- /website_name.txt: -------------------------------------------------------------------------------- 1 | Website Name : Coding Library 2 | A library is a place which is collection of books of all types which gives students all the necessary knowledge required. 3 | This website is going to serve as a single collection of useful codes from different people with different knowledge . 4 | So I thought "Coding Library" is going to be best suited name for website 5 | . -------------------------------------------------------------------------------- /Parallel Programming/Addition/AddR.java: -------------------------------------------------------------------------------- 1 | // Addition using parallel programming 2 | import java.rmi.*; 3 | import java.rmi.server.*; 4 | import java.util.*; 5 | public class AddR extends UnicastRemoteObject implements adder{ 6 | AddR() throws RemoteException{ 7 | super(); 8 | } 9 | public int add(int x,int y){ 10 | return x+y;// performing addition 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/add-a-question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Add a question 3 | about: Propose your own question 4 | title: "[Question Title]" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Enter your question - 11 | Your answer 12 | 13 | ### Enter link to the question(if question belongs to any online platform) - 14 | Your answer 15 | 16 | ### Tags for the question(eg - Array, Basic, Stack, etc.) - 17 | Your answer 18 | -------------------------------------------------------------------------------- /Parallel Programming/Subtraction/SubR.java: -------------------------------------------------------------------------------- 1 | //Performing subtraction of two numbers using parallel programming 2 | import java.rmi.*; 3 | import java.rmi.server.*; 4 | import java.util.*; 5 | public class SubR extends UnicastRemoteObject implements subtract{//declaring remote 6 | SubR () throws RemoteException{ 7 | super(); 8 | } 9 | public int sub(int x,int y){// passing values 10 | return x-y;//performing operation 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Basic Codes/Positive_Negative.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Positive_Negative { 3 | public static void main(String args[]){ 4 | Scanner sc=new Scanner(System.in); 5 | System.out.println("Enter any number"); 6 | int n=sc.nextInt(); 7 | if(n>=0){ 8 | System.out.println("Positive"); 9 | } 10 | else { 11 | System.out.println("Negative"); 12 | 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Parallel Programming/Addition/myserver.java: -------------------------------------------------------------------------------- 1 | // Addition using parallel programming 2 | import java.rmi.*; 3 | import java.rmi.registry.*; 4 | import java.util.*; 5 | public class myserver{ 6 | public static void main(String args[]){ 7 | try{ 8 | adder stub= new AddR();//fetching remote 9 | Naming.rebind("rmi://localhost:5000/sonoo",stub); 10 | System.out.println("Connected to server.....");// displaying once server started 11 | }catch(Exception e){System.out.println(e);} 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Basic Codes/Factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Factorial { 4 | public static void main(String[] args) { 5 | System.out.print("Enter number : "); 6 | 7 | Scanner in = new Scanner(System.in); 8 | int num = in.nextInt(); 9 | int ans = factorialRecursion(num); 10 | System.out.print(num+"! = " +ans); 11 | 12 | } 13 | static int factorialRecursion(int i){ 14 | if(i==1) 15 | return 1; 16 | 17 | return i*factorialRecursion(i-1); 18 | } 19 | } -------------------------------------------------------------------------------- /Parallel Programming/Subtraction/subserver.java: -------------------------------------------------------------------------------- 1 | //Performing subtraction of two numbers using parallel programming 2 | import java.rmi.*; 3 | import java.rmi.registry.*; 4 | import java.util.*; 5 | public class subserver{ 6 | public static void main(String args[]){ 7 | try{ 8 | subtract stub= new SubR();//passing through SubR 9 | Naming.rebind("rmi://localhost:5000/sonoo",stub);//rebinding the server 10 | System.out.println("Connected to subtractinng server.....");//Displaying after server started 11 | }catch(Exception e){System.out.println(e);} 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /LeetCode/count1s.java: -------------------------------------------------------------------------------- 1 | //Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). 2 | public class Solution { 3 | // you need to treat n as an unsigned value 4 | public int hammingWeight(int n) { 5 | 6 | int cnt=0; 7 | int len=0; 8 | while(len<32) 9 | { 10 | if((n&1)==1) //perform bitwise AND and count 1's 11 | { 12 | cnt++; 13 | } 14 | n=n>>1; //right shift digit by one bit 15 | len++; 16 | } 17 | return cnt; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Parallel Programming/Addition/myclient.java: -------------------------------------------------------------------------------- 1 | // Addition using parallel programming 2 | import java.rmi.*; 3 | import java.util.*; 4 | public class myclient{ 5 | public static void main(String args[]){ 6 | try{ 7 | adder stub=(adder)Naming.lookup("rmi://localhost:5000/sonoo");//fetching adder 8 | Scanner sc=new Scanner(System.in);// taking input 9 | System.out.println("Enter 1st no: "); 10 | int x=sc.nextInt();//1st no. input 11 | System.out.println("\nEnter 2nd no: "); 12 | int y=sc.nextInt();//2nd no. input 13 | System.out.println("\nsum is: ");//showing output 14 | System.out.println(stub.add(x,y)); 15 | }catch(Exception e){} 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Parallel Programming/Subtraction/subclient.java: -------------------------------------------------------------------------------- 1 | //Performing subtraction of two numbers using parallel programming 2 | import java.rmi.*; 3 | import java.util.*; 4 | public class subclient{ 5 | public static void main(String args[]){ 6 | try{ 7 | subtract stub=(subtract)Naming.lookup("rmi://localhost:5000/sonoo"); 8 | Scanner sc=new Scanner(System.in);//taking input 9 | System.out.println("Enter 1st no: "); 10 | int x=sc.nextInt();//input 1st num 11 | System.out.println("\nEnter 2nd no: "); 12 | int y=sc.nextInt();//input 2nd num 13 | System.out.println("\ndifference is: "); 14 | System.out.println(stub.sub(x,y));//passing the values 15 | }catch(Exception e){} 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/Missing Number: -------------------------------------------------------------------------------- 1 | // link - https://leetcode.com/problems/missing-number/ 2 | 3 | 4 | // Approach: 5 | // Since the array contains distinct numbers in the range [0, n] hence if we calculate xor of all the numbers in this 6 | // range and then xor it with the actual elements present in the array it will give us the element which is missing. 7 | // This is because x ^ x = 0, so all the numbers will result in 0 except the one which is missing. 8 | 9 | class Solution { 10 | public int missingNumber(int[] nums) { 11 | int n = nums.length; 12 | int ans = n; 13 | 14 | for (int i = 0; i < n; i++) { 15 | ans ^= nums[i] ^ i; 16 | } 17 | return ans; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ReasonBehindCreatingTheLogo.txt: -------------------------------------------------------------------------------- 1 | Inspiration and reason behind creating the website logo 2 | 3 | The reason of the logo is to demonstrate the people what content the website have from noob to pro 4 | level of programming that means from beginner friendly level programming to high level Artificial 5 | Intelligence. 6 | 7 | While making this logo I have learned the editing, how to mix colours in logo (gradient), 8 | The logo is made from PicsArt android appliction. 9 | 10 | The Biggest motivation behind creating the logo and participating in open sorce is that I want 11 | to learn in public, exploring the computer science world and to expand my knowledge in copmuter field. 12 | 13 | Thank you. -------------------------------------------------------------------------------- /Basic Codes/factorial-by-loops.java: -------------------------------------------------------------------------------- 1 | //Question: You have to make an algorithm to find factorial of a given number; 2 | 3 | //factorial of n is n*(n-1)*.....*2*1; 4 | package com.company; 5 | 6 | import java.util.Scanner; 7 | 8 | public class Factorial { 9 | public Factorial() { 10 | } 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | System.out.println("you want factorial of which number"); 15 | 16 | //input of given number 17 | int n = in.nextInt(); 18 | int fact = 1; 19 | for(int i = n; 1 <= i; --i) { 20 | fact *= i; 21 | } 22 | 23 | System.out.println("the factorial of " + n + " is " + fact); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Basic Codes/Swapnum.java: -------------------------------------------------------------------------------- 1 | // Write a program to swap two numbers (with the help of third variable). 2 | import java.util.Scanner; 3 | 4 | class Swapnum 5 | { 6 | public static void main(String args[]) 7 | { 8 | int num1, num2, temp; //create temp variable for storing value 9 | System.out.println("Enter number1 and number2"); 10 | Scanner in = new Scanner(System.in); 11 | 12 | num1 = in.nextInt(); 13 | num2 = in.nextInt(); 14 | 15 | System.out.println("Before Swapping\nnum1 = "+num1+"\nnum2 = "+num2); //before swap 16 | 17 | temp = num1; //temp assign to num1 18 | num1 = num2; 19 | num2 = temp; 20 | 21 | System.out.println("After Swapping\nnum1 = "+num1+"\nnum2 = "+num2); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/bitwiseand.java: -------------------------------------------------------------------------------- 1 | /* Question :https://leetcode.com/problems/bitwise-and-of-numbers-range/ 2 | Given two integers left and right that represent the range [left, right], 3 | return the bitwise AND of all numbers in this range, inclusive. 4 | */ 5 | 6 | 7 | class Solution { 8 | public int rangeBitwiseAnd(int left, int right) { 9 | int c=0; 10 | while(left!=right) //continue till the both numbers are equal 11 | { 12 | left>>=1; //right shifting left most element by one digit 13 | right>>=1; // right shifting right most element by one digit 14 | c++; //counting no:of ones in given number 15 | } 16 | return left< 10 11 | if(num>10){ 12 | System.out.println("Number is Greater than 10."); 13 | } 14 | //Checking whether num = 10 15 | if(num==10){ 16 | System.out.println("Number is Equal to 10."); 17 | } 18 | //Checking whether num < 10 19 | else if (num<10){ 20 | System.out.println("Number is Less than 10."); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Pattern_Printing/Z.java: -------------------------------------------------------------------------------- 1 | // Write a program to print letter Z exactly 2 | class Z{ 3 | public static void main(String args[]){ 4 | 5 | 6 | for(int x=0;x<8;x++){ //for iteration of lines from top to bottom 7 | for(int y=0;y<9;y++){ //for iteration of lines from left to right 8 | if(x==0 || x==7){ 9 | System.out.print("@"); //to print @ where necessary 10 | } 11 | else if(x+y==7 || x+y==8){ 12 | System.out.print("#"); //to print # where necessary 13 | } 14 | else{ 15 | System.out.print(" "); //to print spaces where necessary 16 | } 17 | } 18 | System.out.println(); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /String Handling/stringPalindrome.java: -------------------------------------------------------------------------------- 1 | //Created a program to check whether given string is palindrome or not. 2 | import java.util.*; 3 | public class Main 4 | { 5 | public static void main(String[] args) { 6 | Scanner sc=new Scanner(System.in); 7 | System.out.println("Enter a String"); 8 | String s=sc.nextLine(); 9 | int l=s.length(); 10 | int temp=0; 11 | for(int i=0,j=l-1;i<=j;i++,j--) //Traverse string from start and end 12 | { 13 | if(s.charAt(i)!=s.charAt(j)) //Check Each Character From start and end 14 | { 15 | System.out.println("Not Palindrome"); //if condition fails it displays not palindrome 16 | temp=1; 17 | break; 18 | } 19 | } 20 | if(temp==0) //if abpve condition does not satisfies then print palindrome 21 | System.out.println("Palindrome"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Number Theory/KeprekarNo.java: -------------------------------------------------------------------------------- 1 | //Write a program to check if a number is Keprekar or not 2 | import java.util.*; 3 | class Keprekar{ 4 | public static void main(String args[]){ 5 | Scanner sc=new Scanner(System.in); 6 | System.out.println("Enter any number"); //Input number from the user 7 | int n=sc.nextInt(); 8 | 9 | String s=String.valueOf(n); 10 | int l=s.length(); 11 | int sq=n*n; 12 | int sum=(sq/(int)(Math.pow(10,l)))+(sq%(int)(Math.pow(10,l))); // Find the sum of the two divided parts of the number 13 | if(sum==n){ // Compare whether the sum is equal to the number or not 14 | System.out.println(n+" is a Keprekar Number"); 15 | } 16 | else{ 17 | System.out.println(n+" is not a Keprekar Number"); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /GeeksForGeeks/replacepi.java: -------------------------------------------------------------------------------- 1 | //Replacing the char"pi" with the value "3.14". if not no change 2 | public class replacepi { 3 | 4 | //This function is main logic of the solution woth replace the "pi" with "3.14". 5 | public static String pi(String str) { 6 | if(str.length()<2){ //base case 7 | return str; 8 | } 9 | else{ 10 | String firsttwo=str.substring(0, 2); 11 | if(firsttwo.equals("pi")){ //if "pi" is found than replace 12 | return "3.14"+pi(str.substring(2)); 13 | } 14 | else{ 15 | return str.charAt(0)+pi(str.substring(1)); //"if not than no change" 16 | } 17 | } 18 | } 19 | public static void main(String[] args) { 20 | String str="xpix"; // The string 21 | String ans=pi(str); 22 | System.out.println(ans); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Searching/stringsearch.java: -------------------------------------------------------------------------------- 1 | // Seaching the character present in string or not 2 | package com.company; 3 | 4 | public class stringsearch { 5 | public static void main(String[] args) { 6 | String str= "hello word "; 7 | char want= 'k'; 8 | boolean ans=ss(str,want ); 9 | if (ans==true){ 10 | System.out.println("Expected character is present in given string"); 11 | } 12 | else { 13 | System.out.println("Expected character not there in given string"); 14 | } 15 | 16 | } 17 | 18 | static boolean ss(String str,char target ){ 19 | if(str.length()==0){ //if string length is 0 20 | return false; 21 | } 22 | for(int i=0;i target) return false; 18 | } 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Pattern_Printing/Letter_T.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | // Write a program to print letter T exactly as shown below - 4 | 5 | public class Letter_T { 6 | // Driver code 7 | public static void main(String[] args) { 8 | // Number of lines for the Letter 9 | int height = 7; 10 | 11 | int i, j; 12 | // Pattern printing 13 | for (i = 0; i < height; i++) { 14 | for (j = 0; j < height; j++) { 15 | if (i == 0) 16 | System.out.printf("$$"); 17 | else if (j == height / 2) 18 | System.out.printf("@@"); 19 | else 20 | System.out.printf(" "); 21 | } 22 | System.out.printf("\n"); 23 | } 24 | } 25 | } 26 | 27 | // Output : 28 | /* 29 | $$$$$$$$$$$$$$ 30 | @@ 31 | @@ 32 | @@ 33 | @@ 34 | @@ 35 | @@ 36 | @@ 37 | */ -------------------------------------------------------------------------------- /LeetCode/DeleteNode.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | // O(n) solution 3 | 4 | //Aproach: The question gives access to the node to be deleted instead of the head node. The node to be deleted will not 5 | //be a tail node hence we will set the value of the current node to be that of the next node and set the next of the 6 | //current node to the next of it's next. Simple and efficient solution, 0ms runtime. 7 | 8 | public class DeleteNode { 9 | public class ListNode { 10 | int val; 11 | ListNode next; 12 | 13 | ListNode(int x) { 14 | this.val = x; 15 | } 16 | } 17 | public void delete(ListNode node) { 18 | if (node.next.next != null) { 19 | node.val = node.next.val; 20 | node.next = node.next.next; 21 | } else if (node.next.next == null) { 22 | node.val = node.next.val; 23 | node.next = null; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode/DuplicateNumber.java: -------------------------------------------------------------------------------- 1 | //leetcode question - https://leetcode.com/problems/find-the-duplicate-number/ 2 | 3 | public class DuplicateNumber { 4 | public static void main(String[] args) { 5 | int[] arr = {1,3,4,2,2}; //leetcode sample case1 6 | int ans =findDuplicate(arr); 7 | System.out.println(ans); 8 | 9 | } 10 | 11 | static int findDuplicate(int[] nums) { //cyclic sort 12 | int i =0; 13 | while(i < nums.length){ 14 | int correct = nums[i] -1; 15 | if(nums[i] != nums[correct]){ 16 | swap(nums,i,correct); 17 | }else{ 18 | i++; 19 | } 20 | } 21 | 22 | return nums[nums.length -1]; 23 | 24 | } 25 | 26 | static void swap(int[] arr,int first,int second){ //function to swap 2 numbers in array 27 | int temp = arr[first]; 28 | arr[first] = arr[second]; 29 | arr[second] = temp; 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Bit Manipulation/CheckOddEven.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /* 4 | Given a number 'n' check if the number is odd or even using bit manipulation. 5 | Idea: If a number is even then its LSB must be unset and if the number is odd its LSB must be set. 6 | We can use bitwise AND with 1 to check this condition. 7 | */ 8 | public class CheckOddEven { 9 | public static void main(String[] args) { 10 | Scanner sc = new Scanner(System.in); 11 | 12 | int n = sc.nextInt(); 13 | 14 | if (isEven(n)) { 15 | System.out.println(n + " is even"); 16 | } else { 17 | System.out.println(n + " is odd"); 18 | } 19 | } 20 | 21 | static boolean isEven(int n) { 22 | //If n is even then LSB must be unset(0) therefore bitwise AND with 1 must be 0 as (0 & 1) == 0 23 | //If If n is odd then LSB must be set(1) therefore bitwise AND with 1 must be 1 as (1 & 1) == 1 24 | return (n & 1) == 0; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode/Pow.java: -------------------------------------------------------------------------------- 1 | //Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 2 | //example input 2 2 3 | //output = 4 4 | 5 | //exmple input 2 10 6 | //output = 1024 7 | 8 | 9 | 10 | import java.util.*; 11 | public class POW { 12 | static int pwr(int x, int n) 13 | { 14 | //if power is zero return 1 15 | if (n == 0) 16 | return 1; 17 | else if (n % 2 == 0) 18 | // lwt if x = 2 & n = 8 which is divisible by 2 - returns 2^4 * 2^4 = 2^8 19 | return pwr(x, n / 2) * pwr(x, n / 2); 20 | else 21 | return x * pwr(x, n / 2) * pwr(x, n / 2); 22 | //if n = 7 returns 2*(2^3 * 2^3) = 2^7 23 | } 24 | 25 | public static void main(String[] args) 26 | { 27 | //take input x,n 28 | Scanner sc = new Scanner(System.in); 29 | int x = sc.nextInt(); 30 | int n = sc.nextInt(); 31 | 32 | System.out.printf("%d", pwr(x, n)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LeetCode/minCostClimbingStairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array cost where cost[i] is the cost of ith step on a staircase. 3 | Once you pay the cost, you can either climb one or two steps. 4 | 5 | You can either start from the step with index 0, or the step with index 1. 6 | 7 | Return the minimum cost to reach the top of the floor. 8 | */ 9 | class Solution { 10 | public int minCostClimbingStairs(int[] cost) { 11 | int l=cost.length; 12 | int dp[]=new int[l];//creating an array of size of cost 13 | dp[0]=cost[0]; //initializing cost of 0th index to dp of 0th index 14 | if(l>1) 15 | dp[1]=cost[1]; //if l greater than one than copying the 1st index value respectively 16 | for(int i=2;idp[l-2]?dp[l-2]:dp[l-1]; //returning the smallest value between i-1 and i-1 index 21 | } 22 | } -------------------------------------------------------------------------------- /Pattern_Printing/Inner_Diamond.java: -------------------------------------------------------------------------------- 1 | // Write a program to print a diamond void on a 7 x 7 grid matrix 2 | class Inner_Diamond{ 3 | public static void main(String args[]){ 4 | 5 | 6 | 7 | 8 | 9 | for(int x=0;x<7;x++){ //to iterate the rows 10 | for(int y=0;y<7;y++){ //to iterate the columns 11 | if(x+y>=3 && x+y<=9 && y-x<=3 && y-x>=-3){ //to make the area of the diamond with the equations of the boundary lines 12 | System.out.print(" "); //to print spaces wherever necessary 13 | } 14 | else{ 15 | System.out.print("*"); //to print asterisks wherever necessary 16 | } 17 | } 18 | System.out.println(); //to change rows after completion of all columns in a particular row 19 | } 20 | 21 | 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /Pattern_Printing/Outer_Diamond.java: -------------------------------------------------------------------------------- 1 | // Write a program to print a diamond void on a 7 x 7 grid matrix 2 | class Outer_Diamond{ 3 | public static void main(String args[]){ 4 | 5 | 6 | 7 | 8 | 9 | for(int x=0;x<7;x++){ //to iterate the rows 10 | for(int y=0;y<7;y++){ //to iterate the columns 11 | if(x+y>=3 && x+y<=9 && y-x<=3 && y-x>=-3){ //to make the area of the diamond with the equations of the boundary lines 12 | System.out.print("*"); //to print asterisks wherever necessary 13 | } 14 | else{ 15 | System.out.print(" "); //to print spaces wherever necessary 16 | } 17 | } 18 | System.out.println(); //to change rows after completion of all columns in a particular row 19 | } 20 | 21 | 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /LeetCode/FindAllDuplicatesinanArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/problems/find-all-duplicates-in-an-array/ 3 | */ 4 | 5 | class Solution { 6 | public List findDuplicates(int[] nums) { 7 | //we are solving this question using cyclic sort 8 | int i=0; 9 | while(i ans=new ArrayList<>(); 19 | for(int j=0;j 12 | 13 | ### Checklist: 14 | Eg - If your code follow the below guidelines. Kindly change [] to [x] 15 | 16 | All the conditions should be fulfilled for considering your code for merging - 17 | 18 | - [] I have mentioned the question as comment in my solution file.
19 | - [] My code follows the guidelines of this project.
20 | - [] I have performed a self-review of my own code.
21 | - [] I have commented my code.
22 | - [] My code gives the correct output.
23 | - [] I confirm that I have not copied the code from anywhere. In case its found that I have copied even after successful merge then I can be banned from the repository and hacktoberfest.
24 | 25 | 26 | - [] I affirm that I strictly follow contributing guidelines and code of conduct. 27 | -------------------------------------------------------------------------------- /LeetCode/MissingNumber.java: -------------------------------------------------------------------------------- 1 | //Q. Find the missing number from the given Array[0,n],N being the number of length. 2 | import java.util.Arrays; 3 | 4 | public class MissingNumber { 5 | public static void main(String[] args) { 6 | int a[]={0,1,2,4};//Input Arrray 7 | int n=a.length; 8 | int missing=-1;//Setting n value 9 | Arrays.sort(a);//this will sort the array. 10 | //This function will check if index number 11 | // and value is same or not, if not same assign the value to missing. 12 | for(int i=0;i ls=new ArrayList(); 9 | //Here if it is non zero then add to list 10 | for(int i=0;i= 0 && arr[j] > m) { 12 | arr[j + 1] = arr[j]; 13 | j = j - 1; 14 | } 15 | arr[j + 1] = m; 16 | } 17 | } 18 | // function to print the array 19 | static void printArray(int arr[]) 20 | { 21 | int n = arr.length; 22 | for (int i = 0; i < n; ++i) 23 | System.out.print(arr[i] + " "); 24 | 25 | System.out.println(); 26 | } 27 | 28 | // main method where we take input and call the function from above 29 | public static void main(String args[]) 30 | { 31 | int arr[] = { 34, 1, 130, 15, 6 }; 32 | 33 | InsertionSort ob = new InsertionSort(); 34 | ob.sort(arr); 35 | 36 | printArray(arr); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Basic Codes/swap2.java: -------------------------------------------------------------------------------- 1 | //A program to swap two numbers without using another variable. 2 | import java.io.*; 3 | class swap2 4 | { 5 | void swap(int x, int y) 6 | { 7 | if(x>=0 && y>=0) //If the numbers are both positive.. 8 | { 9 | x=x+y; 10 | y=x-y; 11 | x=x-y; 12 | } 13 | else //if any of the number is negative or both are negative.. 14 | { 15 | x=x+y; 16 | y=y-x; 17 | x=x+y; 18 | y=-y; 19 | } 20 | System.out.println("After swap \n"+"x= "+x+"\ny= "+y); 21 | } 22 | public static void main(String args[])throws IOException 23 | { 24 | InputStreamReader inp=new InputStreamReader(System.in); 25 | BufferedReader br=new BufferedReader(inp); 26 | int x=Integer.parseInt(br.readLine()); // Accepting the numbers and storing them 27 | int y=Integer.parseInt(br.readLine()); 28 | System.out.println("Before swap \n"+"x= "+x+"\ny= "+y); 29 | swap2 obj=new swap2(); 30 | obj.swap(x,y); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Bit Manipulation/PrintBinary.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number print its Binary Representation using Bit Manipulation 3 | Examples: 4 | 5 | Input: 2 6 | Output: 10 7 | 8 | Input: 64 9 | Output: 1000000 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class PrintBinary { 15 | 16 | public static void main(String[] args) { 17 | 18 | Scanner sc = new Scanner(System.in); 19 | 20 | int num = sc.nextInt(); 21 | 22 | printBinary(num); 23 | } 24 | 25 | public static void printBinary(int num) { 26 | 27 | if (num == 0) { 28 | System.out.print(0); 29 | return; 30 | } 31 | 32 | //Number of bits needed to represent a number in Binary 33 | int bits = (int) (Math.log(num) / Math.log(2)) + 1; 34 | 35 | for (int i = bits - 1; i >= 0; --i) { 36 | //ith bit is set 37 | if ((num & (1 << i)) != 0) { 38 | System.out.print("1"); 39 | } 40 | //ith bit is not set 41 | else { 42 | System.out.print("0"); 43 | } 44 | } 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Number Theory/SpecialNo.java: -------------------------------------------------------------------------------- 1 | //Write a program to check if a number is Special or not 2 | import java.util.Scanner; 3 | 4 | public class SpecialNo { 5 | public static void main(String[] args) { 6 | Scanner in=new Scanner(System.in); 7 | int num, digit, sum=0, temp; 8 | 9 | 10 | System.out.println("Enter any number"); // Input the number from user 11 | num = in.nextInt(); 12 | temp = num; 13 | 14 | 15 | while(temp != 0){ 16 | digit = temp%10; //Find the factorial of its digits. 17 | sum += factorial(digit); // Add all the factorial. 18 | temp = temp/10; 19 | } 20 | 21 | 22 | if(sum == num) //Check if the computed sum is equal to the original number. 23 | System.out.println("Given number is Special Number"); 24 | else 25 | System.out.println("Not a Special Number"); 26 | 27 | } 28 | 29 | 30 | private static int factorial(int n){ //function to compute the factorial of the digits 31 | int f=1; 32 | for(int i=2; i<=n; i++){ 33 | f = f*i; 34 | } 35 | return f; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 SarthakKeshari 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Number Theory/ArmstrongNumber.java: -------------------------------------------------------------------------------- 1 | //Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers; 2 | /* 153 = (1*1*1)+(5*5*5)+(3*3*3) 3 | where: 4 | (1*1*1)=1 5 | (5*5*5)=125 6 | (3*3*3)=27 7 | So: 8 | 1+125+27=153 */ 9 | 10 | public class ArmstrongNumber { 11 | public ArmstrongNumber() { 12 | } 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | int num = in.nextInt(); 17 | int temp = num; 18 | 19 | int result; 20 | //we will break the number into individual digits and cube it and then 21 | //sum the cubes of individual digits 22 | for(result = 0; 0 < num; num /= 10) { 23 | int rem = num % 10; 24 | result += rem * rem * rem; 25 | } 26 | // we check if the number is armstrong or not 27 | if (temp == result) { 28 | System.out.println(temp + " is a armstrong number"); 29 | } else { 30 | System.out.println(temp + " is not a armstrong number"); 31 | } 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Bit Manipulation/PowerSet.java: -------------------------------------------------------------------------------- 1 | /* Question 2 | Generate Power set using Bitwise operator 3 | 4 | Sample Case 5 | Input="ab" 6 | Output="","a","b","ab" */ 7 | 8 | package javaquestion; 9 | 10 | import java.util.*; 11 | 12 | public class power { 13 | static void subset(String s) { 14 | //To find the length of string 15 | int a = s.length(); 16 | 17 | // To get total number of subsets 18 | int pow = (int) Math.pow(2, a); 19 | 20 | //Outer loop from 0 to pow-1 21 | for (int counter = 0; counter < pow; counter++) { 22 | 23 | //inner loop for length of string 24 | for (int j = 0; j < a; j++) { 25 | 26 | //To check if nth bit is set or not 27 | if ((counter & (1 << j)) != 0) { 28 | 29 | //To print that set bit from string 30 | System.out.print(s.charAt(j)); 31 | 32 | } 33 | } 34 | //will print line to separate subsets 35 | System.out.println(); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | Scanner sc = new Scanner(System.in); 41 | String s = sc.next(); 42 | subset(s); 43 | } 44 | } 45 | 46 | // Time complexity- Theta(2^n*n) 47 | -------------------------------------------------------------------------------- /Exception Handling/zeroerror_exceptionhandling.java: -------------------------------------------------------------------------------- 1 | ///zeroerror_exceptionhandling 2 | 3 | import java.util.*; 4 | ///handling exception of dividing a number by zero 5 | public class MyClass { 6 | 7 | static int Dividebyzero(int x) { 8 | ///dividing the given x value by zero 9 | int value =0; 10 | 11 | try 12 | { 13 | value = x / 0; //provoking the error 14 | } 15 | catch(NumberFormatException knownerror) 16 | { 17 | System.out.println(knownerror.getMessage()); // identifying the error 18 | } 19 | 20 | return value; 21 | } 22 | 23 | public static void main(String args[]) { 24 | 25 | Scanner sc=new Scanner(System.in); 26 | System.out.print("Enter the number - "); // printing statement to recieve an input 27 | 28 | 29 | int x = sc.nextInt(); //getting an input and assigned it to x 30 | 31 | try 32 | { 33 | int value = Dividebyzero(x); // dividing x by zero 34 | 35 | } 36 | catch(ArithmeticException errormessage) 37 | { 38 | System.out.println("Error is " + errormessage.getMessage()); /// getting the error and printing it 39 | } 40 | 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Number Theory/Fascno.java: -------------------------------------------------------------------------------- 1 | //Find given number is Fascinating Number or not 2 | 3 | import java.util.*; 4 | public class Fascno 5 | { 6 | public static void main(String args[]) 7 | { 8 | int n1, n2, n3; 9 | Scanner sc=new Scanner(System.in); 10 | System.out.print("Enter any Number: "); 11 | n1 = sc.nextInt(); 12 | n2 = n1 * 2; 13 | n3 = n1 * 3; //concatenating n1, n2, and n3 user input 14 | 15 | String concatstr = n1 + "" + n2 + n3; 16 | boolean found = true; 17 | 18 | for(char c = '1'; c <= '9'; c++) //checks all digits from 1 to 9 are present or not 19 | { 20 | int count = 0; 21 | 22 | for(int i = 0; i < concatstr.length(); i++) //loop counts the frequency of each digit 23 | { 24 | char ch = concatstr.charAt(i); 25 | 26 | if(ch == c) 27 | 28 | count++; 29 | } //returns true if any of the condition returns true 30 | 31 | if(count > 1 || count == 0) 32 | { 33 | found = false; 34 | break; 35 | } 36 | } 37 | if(found) 38 | System.out.println(n1 + " is a fascinating number."); 39 | else 40 | System.out.println(n1 + " is not a fascinating number."); 41 | } 42 | } 43 | 44 | //by Dinesh -------------------------------------------------------------------------------- /Searching/searchinrange.java: -------------------------------------------------------------------------------- 1 | //Searching element in an array within given range. 2 | package com.company; 3 | 4 | public class searchinrange { 5 | public static void main(String[] args) { 6 | int[] arr={12,1,4,45,84,65,41,23,78,98}; 7 | int target=98; 8 | int ans=rser(arr,target,1,5); //passing values to the function 9 | if(ans==0){ 10 | System.out.println("Array is empty"); 11 | } 12 | if (ans==1){ 13 | System.out.println("Target element present in an array within given range"); 14 | } 15 | if (ans==2){ 16 | System.out.println("Target element not there in an array within given range"); 17 | } 18 | 19 | } 20 | static int rser(int[] arr,int target,int start,int end ){ //declaring function 21 | if(arr.length==0){ // checking array size 22 | return 0; 23 | } 24 | for(int i=start;i<=end;i++){ // loop for array to check in range 25 | int elem=arr[i]; 26 | if(elem==target){ // target element found 27 | return 1; 28 | } 29 | } 30 | return 2;// loop out target is not there 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LeetCode/SortedSquares.java: -------------------------------------------------------------------------------- 1 | 2 | // Java program to Sort the square of the numbers 3 | // of the array 4 | import java.util.*; 5 | import java.io.*; 6 | public class sortsq 7 | { 8 | // Function to sort an square array 9 | public static void sortSquares(int arr[]) 10 | { 11 | int n = arr.length; 12 | // First convert each array elements 13 | // into its square 14 | for (int i = 0 ; i < n ; i++) 15 | arr[i] = arr[i] * arr[i]; 16 | 17 | // using "inbuild sort function" for sorting 18 | // in Arrays class. 19 | Arrays.sort(arr); 20 | } 21 | //sample driver program 22 | public static void main (String[] args) 23 | { 24 | int arr[] = { -17 , -12 , -1 , 4 , 8 , 15 }; 25 | int n = arr.length; 26 | 27 | System.out.println("Original "); 28 | for (int i = 0; i < n; i++) 29 | System.out.print(arr[i] + " "); 30 | 31 | sortSquares(arr); 32 | System.out.println(""); 33 | System.out.println("Implementing sort"); 34 | for (int i = 0 ; i < n ; i++) 35 | System.out.print(arr[i] + " "); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Pattern_Printing/Letter_B.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | // Write a program to print letter B exactly as shown below - 4 | 5 | public class Letter_B { 6 | // Driver code 7 | public static void main(String[] args) { 8 | // Number of lines for the Letter 9 | int height = 7; 10 | 11 | for (int i=0;i= 0; j--) { 42 | System.out.println(mat[j][i]); 43 | } 44 | } 45 | } 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /LeetCode/perfectSquare.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return the least number of perfect square numbers that sum to n. 3 | 4 | A perfect square is an integer that is the square of an integer; in other words, 5 | it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares 6 | while 3 and 11 are not. 7 | */ 8 | 9 | class Solution { 10 | public int numSquares(int n) { 11 | int dp[]=new int[n+1]; //created an array of length n+1 12 | dp[0]=0; //initalized 0th position with 0 13 | dp[1]=1; //initialized 1st position with 1 14 | 15 | for(int i=2;i<=n;i++) //initialized for loop from 2 to n 16 | { 17 | int ans=Integer.MAX_VALUE; // assume ans is the maximum value 18 | for(int j=1;j*j<=i;j++) //traversing j loop as perfect square 19 | { 20 | int rem=i-j*j; //if remainder is remaing 21 | if(dp[rem]0) 15 | ans1=String.format( "%0" +a+ "d%s" , 0, ans); //adding zeros before the conferted string 16 | else 17 | ans1=ans; 18 | int cnt=0; 19 | for(int j=0;j0 ; gap/=2) 15 | { 16 | for(int i= gap ; i=gap && arr[j - gap]> temp ; j-=gap) 21 | { 22 | arr[j] = arr[j - gap]; 23 | } 24 | arr[j] = temp; 25 | } 26 | } 27 | 28 | } 29 | 30 | static void print(int arr[] , int n) 31 | { 32 | for (int i=0 ; i map = new HashMap<>(); 21 | int sum = 0, maxLen = 0; // sum = prefix sum which stores sum of every element, maxlen = maximum length of sub array 22 | for(int i = 0; i < n; i++){ 23 | sum += arr[i]; 24 | if(sum==k){ 25 | maxLen = i + 1; // if k itself is present in the array then length will start from 0 to index of k 26 | } 27 | if(!map.containsKey(sum)){ // putting frequencies of every sum 28 | map.put(sum, i); 29 | } 30 | if(map.containsKey(sum-k)){ 31 | if(maxLen < (i-map.get(sum-k))){ // updating the maxlen variable from starting point of sub array to end point 32 | maxLen = i - map.get(sum-k); 33 | } 34 | } 35 | } 36 | 37 | return maxLen; 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /String Handling/Max_Freq_Character.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class Max_Freq_Character { 5 | 6 | public static void main(String[] args) { 7 | 8 | Scanner sc = new Scanner(System.in); 9 | String str = sc.next(); 10 | System.out.println(maxFreqChar(str)); 11 | sc.close(); 12 | 13 | } 14 | 15 | private static char maxFreqChar(String str) { 16 | 17 | HashMap map = new HashMap<>(); // creating a hashmap which store frequency of each characters 18 | 19 | for(int i = 0; i < str.length(); i++) { 20 | char ch = str.charAt(i); 21 | if(map.containsKey(ch)) { 22 | map.put(ch, map.getOrDefault(ch,0)+1); // incrementing frequency of each character 23 | }else { 24 | map.put(ch, 1); 25 | } 26 | } 27 | 28 | Set keys = map.keySet(); // making a set of distinct character(non repeating) 29 | char maxChar = ' '; 30 | int maxFreq = Integer.MIN_VALUE; 31 | for(char key: keys) { // iterating each distinct character from the set 32 | if(map.get(key)>maxFreq) { // getting frequency of each character and checking if it is the largest or not 33 | maxFreq = map.get(key); // updating the maximum fequency of the character 34 | maxChar = key; // updating the maximum occurring character 35 | } 36 | } 37 | return maxChar; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /String Handling/StringReverse.java: -------------------------------------------------------------------------------- 1 | // Write a java program to reverse the string without using the inbuilt function. 2 | 3 | import java.util.Scanner; 4 | 5 | class StringReverse { 6 | public static void main(String [] args) 7 | { 8 | Scanner scan = new Scanner(System.in); 9 | System.out.println("Enter a String:"); 10 | String str = scan.nextLine(); 11 | System.out.println("-----------------------"); 12 | System.out.println("Sting Before Reversing:"); 13 | System.out.println(str); 14 | 15 | // Converting the string into character array 16 | char arr1[] = str.toCharArray(); 17 | 18 | // Creating the new array to store the character while reversing 19 | char arr2[] = new char[arr1.length]; 20 | 21 | // The j value will be used to start storing the character from last index in arr2 22 | int j = arr2.length - 1; 23 | 24 | // Using for loop to traverse through the arr1 25 | // In each iteration the character in arr1 is stored in the arr2 from last index in each iteration the j value decrements 26 | for (int i = 0; i <= arr1.length-1; i++) { 27 | arr2[j] = arr1[i]; 28 | j--; 29 | } 30 | 31 | // Creating the string using the character array arr2 32 | str = new String(arr2); 33 | System.out.println("-----------------------"); 34 | System.out.println("String After Reversing:"); 35 | System.out.println(str); 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/FindPeak.java: -------------------------------------------------------------------------------- 1 | public class FindPeak { 2 | 3 | public static void main(String[] args) { // Question: Find peak value in zig-zag array 4 | // In this problem we are using binary search 5 | 6 | int[] arr = {1, 2, 4, 5, 3, 2, 1, 2}; 7 | // int[] arr = {2, 5, 7, 8, 10, 7, 6, 3, 2, 3, 4, 6, 10, 7, 3, 1,}; 8 | System.out.println(peak(arr)); // Calling the function and printing the return value 9 | } 10 | 11 | // Method to find index of the peak value 12 | public static int peak(int[] arr) { 13 | 14 | int startIndex = 0; 15 | int LastIndex = arr.length - 1; 16 | 17 | while (startIndex < LastIndex) { 18 | 19 | int midElement = startIndex + (LastIndex - startIndex) / 2; // Finding middle element 20 | 21 | if(arr[midElement] > arr[midElement + 1]) { //whole logic 22 | 23 | LastIndex = midElement; // of the 24 | 25 | } else if(arr[midElement] < arr[midElement + 1]){ // program 26 | 27 | startIndex = midElement + 1; // is enclosed in this block 28 | } 29 | } 30 | return LastIndex; // At the end startIndex and LastIndex will point at same index so return LastIndex or startIndex. 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LeetCode/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Question Link - https://leetcode.com/problems/maximum-subarray/ 3 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 4 | A subarray is a contiguous part of an array. 5 | Example 1: 6 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 7 | Output: 6 8 | Explanation: [4,-1,2,1] has the largest sum = 6. 9 | Example 2: 10 | Input: nums = [1] 11 | Output: 1 12 | Example 3: 13 | Input: nums = [5,4,-1,7,8] 14 | Output: 23 15 | Constraints: 16 | 1 <= nums.length <= 105 17 | -104 <= nums[i] <= 104 18 | */ 19 | 20 | class Solution { 21 | public int maxSubArray(int[] nums) { 22 | int max = nums[0]; 23 | int maxOverall = nums[0]; // Assigning first element as maximum 24 | 25 | // if upon adding the current element, 26 | // we find that the sum exceeds the maximum sum, 27 | // we add the current element to the longest subsequence. 28 | // Otherwise, drop the previous sum, and replace it 29 | // with the current element instead. 30 | 31 | for (int i=1; i 1 to length -1 5 | Assign key = A[i]; 6 | j = i - 1; 7 | Loop j >= 0 and A[j] > key 8 | A[j + 1] = A[j]; 9 | j = j - 1; 10 | End Loop 11 | A[j + 1] = key; 12 | End Iterate.*/ 13 | public class InsertionSort { 14 | 15 | public static void main(String[] args) { 16 | 17 | // input array 18 | int[] inputArray = { 6, 5, 3, 1, 8, 7, 2, 4 }; 19 | int length = inputArray.length; 20 | int j = 0; 21 | 22 | System.out.print("Before Sorting: "); 23 | printArray(inputArray); 24 | System.out.print("\nValues for each Iteration"); 25 | //loop to show different iterations/steps 26 | for (int i = 1; i < length; i++) { 27 | j = i - 1; 28 | int key = inputArray[i];//taking the input 29 | while (j >= 0 && inputArray[j] > key) { 30 | inputArray[j + 1] = inputArray[j];//comparing the neighbour elements 31 | j = j - 1; 32 | } 33 | inputArray[j + 1] = key; 34 | System.out.println(); 35 | printArray(inputArray); 36 | } 37 | 38 | System.out.print("\nAfter sorting: ");//printing the sorted array 39 | printArray(inputArray); 40 | 41 | } 42 | 43 | private static void printArray(int[] inputArray) { 44 | for (int value : inputArray) { 45 | System.out.print(value + " "); 46 | } 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /Number Theory/PrimePal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to check a number for palindrome prime. 3 | 4 | Palindrome - A palindromic number is a number (such as 16461) that remains the same when its digits are reversed. 5 | Prime - a whole number greater than 1 that cannot be exactly divided by any whole number other than itself and 1 6 | */ 7 | 8 | import java.io.*; 9 | import java.util.*; 10 | public class PrimePal 11 | { 12 | public static void main(String args[]) 13 | { 14 | Scanner in= new Scanner(System.in); 15 | int nm,pn,rev,s=0,i,c=0; 16 | System.out.println("Enter No."); 17 | nm= in.nextInt(); // User input 18 | pn=nm; // store the entered number in "pn" variable 19 | for(i=1;i<=pn;i++) 20 | { 21 | if(pn%i==0) 22 | { 23 | c++; 24 | } 25 | } 26 | while(nm>0) 27 | { 28 | rev=nm%10; // extract last digit of the number 29 | s=s*10+rev; // store the digit last digit 30 | nm=nm/10; // extract all digit except the last 31 | } 32 | if(pn==s&&c==2) // comparing with original number 33 | { 34 | System.out.println("Number is PalPrime : "+pn); 35 | } 36 | else 37 | { 38 | System.out.println("Number is not PalPrime : "+pn); 39 | } 40 | } // end of main method 41 | } // end of class 42 | -------------------------------------------------------------------------------- /Pattern_Printing/Letter_E.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | ##$$$$$$$ 5 | ## 6 | ## 7 | ## 8 | ##$$$$$$$ 9 | ## 10 | ## 11 | ## 12 | ##$$$$$$$ 13 | */ 14 | public class Letter_E { 15 | //declaring constants for HASH && DOLLAR 16 | public static final String HASH = "#"; 17 | public static final String DOLLAR = "$"; 18 | public static void main(String[] args) { 19 | //calling function printE with n = 5 as total no of rows in the pattern is 2*n-1 . 20 | // In this case no of rows is 2*5-1 i.e 9 so n is 5 21 | printE(5); 22 | } 23 | 24 | public static void printE(int n){ 25 | //looping over rows from 0 to 2*n-1 26 | for (int row = 0; row <= 2*n-1; row++) { 27 | //looping over column from 0 to 2*n-1 28 | for (int col = 0; col < 2*n-1; col++) { 29 | //print constant hash in column 0 and column 1 for each row 30 | if(col ==0 || col ==1) { 31 | System.out.print(HASH); 32 | } 33 | //print constant dollar in column 2 onwards for rows 0,n-1 and 2*n-1 34 | if(row == 0|| row ==n-1 || row == 2*n-1){ 35 | if(col > 1 ){ 36 | System.out.print(DOLLAR); 37 | } 38 | } 39 | } 40 | //Moving to next line after printing each row 41 | System.out.println(); 42 | 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode/rotate_Array_By_K.java: -------------------------------------------------------------------------------- 1 | // issue #411 rotate array by k times 2 | // time complexity : O(n) 3 | // space complexity : O(1) 4 | // https://leetcode.com/problems/rotate-array/ 5 | 6 | public class RotateArray { 7 | public static void main(String args[]) 8 | { 9 | int num[]= {1,2,3,4,5,6,7}; 10 | int k=500; 11 | System.out.print("before rotate the Array:"); 12 | for(int el:num){ 13 | System.out.print(el+" "); //1 2 3 4 5 6 7 14 | } 15 | System.out.println(); 16 | 17 | rotate(num,k); 18 | 19 | System.out.print("After rotate the Array:"); 20 | for(int ell:num){ 21 | System.out.print(ell + " "); // 5 6 7 1 2 3 4 22 | } 23 | } 24 | public static void rotate(int[] num, int k) 25 | { 26 | 27 | int n = num.length; // 7 28 | k = k%n; // after n times array will be in original position so we here taking the modulus of k 29 | reverseArray(num,0,n-1); // reverse whole array 30 | reverseArray(num,0,k-1); // here we are reversing the array from (0) index to k-1 (2) index 31 | reverseArray(num,k,n-1); // here we are reversing the array from k(3) to n-1 (6) index 32 | 33 | } 34 | public static void reverseArray(int[] nums,int s, int l) 35 | { 36 | for(int i=s,j=l;i nums[mid]) { 28 | Fisrt = mid + 1; 29 | } else { 30 | return mid; 31 | } 32 | } 33 | return -1; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Data Structure/Heap/kthLargestElement.java: -------------------------------------------------------------------------------- 1 | /*Find k’th largest element in an array 2 | Input: 3 | 4 | arr = [7, 4, 6, 3, 9, 1] 5 | k = 2 6 | 7 | Output: 8 | 9 | The 2nd largest array element is 7 10 | */ 11 | 12 | import java.util.*; 13 | class kthLargestElement 14 | { 15 | public static void main (String args[]) 16 | { 17 | int n,k; 18 | // using max heap to solve and find kth largest element 19 | Scanner s= new Scanner(System.in); 20 | PriorityQueue < Integer > queue = 21 | new PriorityQueue < Integer > (Comparator.reverseOrder ()); 22 | //using PriorityQueue as a heap data structure 23 | System.out.println("enter the array length:"); 24 | n=s.nextInt(); //taking array length as a input 25 | System.out.println("enter the element:"); 26 | for(int i=0;in){ 31 | System.out.println("the value of k should not be more than array length!! error"); 32 | return; // k must be less than n 33 | } 34 | while(k>1){ 35 | queue.poll (); //removing (k-1) elements from max heap 36 | k--; //so that next max element is the kth largest 37 | } 38 | System.out.println ("the kth largest element is:" + queue.peek ());//to get the max element in max heap (root element) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Hackerrank/End_of_file_solution.java: -------------------------------------------------------------------------------- 1 | /* "In computing, End Of File (commonly abbreviated EOF) is a condition in a computer operating system where no more data can be read from a data source. 2 | The challenge here is to read lines of input until you reach EOF, then number and print all lines of content. 3 | 4 | Input Format 5 | Read some unknown lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String. 6 | Output Format 7 | For each line, print the line number, followed by a single space, and then the line content received as input. 8 | 9 | Sample Input 10 | 11 | Hello world 12 | I am a file 13 | Read me until end-of-file. 14 | 15 | Sample Output 16 | 1 Hello world 17 | 2 I am a file 18 | 3 Read me until end-of-file. */ 19 | 20 | import java.io.*; 21 | import java.util.*; 22 | import java.text.*; 23 | import java.math.*; 24 | import java.util.regex.*; //The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. 25 | 26 | public class End_of_file_solution { 27 | 28 | public static void main(String[] args) { 29 | Scanner sc=new Scanner(System.in); //creating new scanner object for taking input from user 30 | int i = 0; 31 | while (sc.hasNextLine()) { //checking for the next input token until the loop ends 32 | System.out.printf("%d %s\n",++i,sc.nextLine()); // print the output 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /GeeksForGeeks/SearchInInfiniteSortedArray.java: -------------------------------------------------------------------------------- 1 | //Question : You have to search for an element in an infinitely sorted array and return the position of the given element; 2 | 3 | public class InfiniteArray { 4 | public static void main(String[] args) { 5 | int arr[]={1,3,4,5,6,8,12,31,34,45,67,123,231,454,676}; 6 | System.out.println(ans(arr,123)); 7 | } 8 | //you have to search in chunks in order to find the element , in order to do that you have to find the range in which your target element is there; 9 | static int ans(int nums[],int target){ 10 | 11 | int start=0; 12 | int end=1; 13 | while(nums[end] " ").limit(x).collect(joining()); 24 | } 25 | 26 | private static String printY() { 27 | int leftOffset = 0; 28 | StringBuilder generateY = new StringBuilder(); 29 | 30 | // This loop generates the V shape of Y 31 | for (int middleOffset = 8; middleOffset >= 0; middleOffset -= 2, leftOffset++) { 32 | generateY.append(generateEmptyStringOfLengthX(leftOffset) + "@@" + generateEmptyStringOfLengthX(middleOffset) + "##\n"); 33 | } 34 | 35 | // This loop generates the lower part of Y 36 | for (int i = 0; i < 4; i++) { 37 | generateY.append(generateEmptyStringOfLengthX(leftOffset) + "@@\n"); 38 | } 39 | return generateY.toString(); 40 | } 41 | 42 | public static void main(String[] args) { 43 | System.out.println(printY()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode/MergeKSortedLists.java: -------------------------------------------------------------------------------- 1 | //Solution to https://leetcode.com/problems/merge-k-sorted-lists/ 2 | //Approach: We use the logic behind merging two sorted lists to merge k number of lists in sorted order. 3 | //Pair up k lists and merge each pair. 4 | //After the first pairing, k lists are merged into k/2 lists with average 2N/k length, then k/4, k/8 and so on. 5 | //This is repeated until we get the final sorted linked list. 6 | 7 | class Solution { 8 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 9 | ListNode h = new ListNode(0); 10 | ListNode ans=h; 11 | while (l1 != null && l2 != null) { 12 | if (l1.val < l2.val) { 13 | h.next = l1; 14 | h = h.next; 15 | l1 = l1.next; 16 | } else { 17 | h.next = l2; 18 | h = h.next; 19 | l2 = l2.next; 20 | } 21 | } 22 | if(l1==null){ 23 | h.next=l2; 24 | } 25 | if(l2==null){ 26 | h.next=l1; 27 | } 28 | return ans.next; 29 | } 30 | public ListNode mergeKLists(ListNode[] lists) { 31 | if(lists.length==0){ 32 | return null; 33 | } 34 | int interval = 1; 35 | while(interval x=(x–2)+(x-1) 35 | fibo2 = fibo1 + fibo2; 36 | fibo1 = fibo2 - fibo1; 37 | } 38 | System.out.println(); 39 | } 40 | } -------------------------------------------------------------------------------- /LeetCode/AllMissingNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class AllMissingNumber { // Question: Find all missing number in the array in O(log n) timeComplexity 4 | public static void main(String[] args) { 5 | 6 | int[] arr = {2, 1, 3, 6, 4, 9, 5, 3, 2}; 7 | 8 | System.out.println(missingNumber(arr)); 9 | } 10 | 11 | // method to sort the array using cyclic sort and to find missing number 12 | public static ArrayList missingNumber(int[] arr) { // Here we use ArrayList because we don`t know how many numbers are missing 13 | 14 | int i = 0; 15 | while (i < arr.length) { 16 | 17 | int index = arr[i] - 1; 18 | 19 | if(arr[i] != arr[index]) { 20 | 21 | swap(arr, i, index); 22 | }else { 23 | 24 | i++; 25 | } 26 | } 27 | 28 | // Finding missing number 29 | ArrayList nums = new ArrayList<>(); 30 | for (int j = 0; j < arr.length; j++) { 31 | 32 | if(arr[j] != j + 1) { 33 | 34 | nums.add(j + 1); // Adding the numbers into the list 35 | }else { 36 | 37 | j++; 38 | } 39 | } 40 | return nums; 41 | } 42 | 43 | // Method to swap the numbers 44 | public static void swap(int[] arr, int first, int second) { 45 | 46 | int temp = arr[first]; 47 | arr[first] = arr[second]; 48 | arr[second] = temp; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode/mergeInterval.java: -------------------------------------------------------------------------------- 1 | /*Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, 2 | and return an array of the non-overlapping intervals that cover all the intervals in the input. 3 | 4 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 5 | Output: [[1,6],[8,10],[15,18]] 6 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 7 | 8 | 9 | 10 | Sorting takes O(n log(n)) and merging the intervals takes O(n). So, the resulting algorithm i.e. sorting, takes O(n log(n)). 11 | */ 12 | 13 | 14 | class Solution { 15 | 16 | public int[][] merge(int[][] intervals) { 17 | if (intervals.length <= 1) 18 | return intervals; 19 | 20 | // Sort on th basis of ascending starting point 21 | Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0])); 22 | 23 | List result = new ArrayList<>(); 24 | int[] newInterval = intervals[0]; 25 | result.add(newInterval); 26 | 27 | 28 | for (int[] interval : intervals) { 29 | if (interval[0] <= newInterval[1]) 30 | // Overlapping intervals, move the end if needed 31 | // overlap condition (update the end pointer) 32 | 33 | newInterval[1] = Math.max(newInterval[1], interval[1]); 34 | 35 | else { 36 | // Disjoint intervals, add the new interval to the list 37 | 38 | newInterval = interval; 39 | result.add(newInterval); 40 | } 41 | } 42 | 43 | return result.toArray(new int[result.size()][]); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Pattern_Printing/Letter_W.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to print letter W exactly as shown below - 3 | @@ # @@ 4 | @@ # # @@ 5 | @@ # # @@ 6 | @@ # # @@ 7 | @@ # # @@ 8 | @@ @@ 9 | */ 10 | public class Letter_W { 11 | 12 | public static void main(String[] args) { 13 | int height = 6; //height of pattern 14 | int i, j; 15 | // Pattern printing 16 | //here if row=height then col=height*4-1 17 | for (i = 0; i < height; i++) { //traversing each row 18 | for (j = 0; j <(height*4-1); j++) {//traversing each col 19 | if(i==j) //diagonally printing @@ symbol 20 | { 21 | System.out.print("@@"); 22 | } 23 | else if(j==4*(height-1)-i) //for printing the @@ symbol reverse diagonally 24 | { 25 | System.out.print("@@"); 26 | } 27 | else if(j==((height*4-3)/2)+i) //for printing the # symbol diagonally 28 | { 29 | System.out.print('#'); 30 | } 31 | else if (j==((height*4-3)/2)-i)//for printing the # symbol reverse diagonally 32 | { 33 | System.out.print('#'); 34 | } 35 | else //spacing 36 | System.out.print(" "); 37 | } 38 | System.out.printf("\n"); //for next line 39 | } 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Pattern_Printing/Letter_K.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | /* 4 | Write a program to print letter K exactly as shown below - 5 | 6 | ## @@ 7 | ## @@ 8 | ## @@ 9 | ## @@ 10 | ##@@ 11 | ## @@ 12 | ## @@ 13 | ## @@ 14 | ## @@ 15 | 16 | */ 17 | 18 | 19 | 20 | import java.util.Scanner; 21 | 22 | public class Letter_K{ 23 | 24 | public static void main(String[] args){ 25 | 26 | Scanner scan =new Scanner(System.in); 27 | System.out.println("Please specify the height of the alphabet greater than 0"); 28 | 29 | int patternHeight = scan.nextInt(); 30 | 31 | if(patternHeight<1){ 32 | System.out.println("Please specify the height of the alphabet greater than 0"); 33 | } 34 | else{ 35 | printK(patternHeight); 36 | } 37 | } 38 | 39 | // main logic 40 | public static void printK(int n){ 41 | // part 1 upper half 42 | for(int i = 0; i< n; i++){ 43 | System.out.printf("##"); 44 | for(int j =0; j<(n-i+1); j++){ 45 | System.out.printf(" "); 46 | } 47 | System.out.printf("@@"); 48 | System.out.println(); 49 | } 50 | //part 2 middle pattern 51 | System.out.println("##@@"); 52 | 53 | //part 3 lower half 54 | for(int i = 1; i<= n; i++){ 55 | System.out.printf("##"); 56 | for(int j =1; j<=i; j++){ 57 | System.out.printf(" "); 58 | } 59 | System.out.printf("@@"); 60 | System.out.println(); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /LeetCode/First Missing Positive.java: -------------------------------------------------------------------------------- 1 | // Question : https://leetcode.com/problems/first-missing-positive/ 2 | 3 | //Example : 4 | /** 5 | * Example 1: 6 | * Input: nums = [1,2,0] 7 | * Output: 3 8 | * 9 | * Example 2: 10 | * nput: nums = [3,4,-1,1] 11 | * Output: 2 12 | */ 13 | 14 | // Solution : 15 | 16 | import java.*; 17 | import java.util.Scanner; 18 | 19 | class Solution { 20 | public static int firstMissingPositive(int[] nums) { 21 | int n = nums.length; 22 | 23 | // First of all sort the array using cyclic sort 24 | 25 | for(int i = 0; i < n; i++) 26 | while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) { 27 | int temp1 = nums[i]; 28 | int temp2 = nums[nums[i] - 1]; 29 | nums[i] = temp2; 30 | nums[temp1 - 1] = temp1; 31 | } 32 | 33 | // Find out first missing positive integer from sorted nums. 34 | 35 | for(int j = 0; j < n; j++) 36 | if(nums[j] != j + 1) 37 | return j + 1; 38 | 39 | return n + 1; 40 | } 41 | 42 | public static void main(String[] args) { 43 | Scanner sc = new Scanner(System.in); 44 | 45 | int n = sc.nextInt(); 46 | int[] nums = new int[n]; 47 | 48 | for(int i = 0; i < n ; i ++) 49 | nums[i] = sc.nextInt(); 50 | 51 | System.out.println(firstMissingPositive(nums)); 52 | 53 | sc.close(); 54 | } 55 | } 56 | 57 | // Time complexity : O(n) 58 | // Space complexity : O(1) 59 | -------------------------------------------------------------------------------- /LeetCode/Binary Tree Maximum Path Sum: -------------------------------------------------------------------------------- 1 | // link- https://leetcode.com/problems/binary-tree-maximum-path-sum/ 2 | 3 | // Approach: 4 | // Since a binary tree can have max 2 children so the path with max sum can either include both the children or one 5 | // depending upon the max value that can be generated. 6 | // The same logic has been implemented in the following code which stores the final answer in the variable max 7 | 8 | 9 | /** 10 | * Definition for a binary tree node. 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode() {} 16 | * TreeNode(int val) { this.val = val; } 17 | * TreeNode(int val, TreeNode left, TreeNode right) { 18 | * this.val = val; 19 | * this.left = left; 20 | * this.right = right; 21 | * } 22 | * } 23 | */ 24 | class Solution { 25 | int max = -1001; 26 | 27 | private int solve(TreeNode root) { 28 | if(root == null) return 0; 29 | 30 | int ans_left = 0, ans_right = 0; 31 | if(root.left != null) ans_left = Math.max(solve(root.left), 0); 32 | if(root.right != null) ans_right = Math.max(solve(root.right), 0); 33 | 34 | int temp = root.val + Math.max(ans_left, ans_right); 35 | max = Math.max(temp, max); 36 | max = Math.max(root.val + ans_left + ans_right, max); 37 | return temp; 38 | 39 | } 40 | 41 | public int maxPathSum(TreeNode root) { 42 | max = -1001; 43 | solve(root); 44 | return max; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Basic Codes/RootsOfQuadraticEqn.java: -------------------------------------------------------------------------------- 1 | //Find the roots of the quadratic Equation 2 | import java.util.Scanner; 3 | 4 | public class quadratic_roots { 5 | 6 | public static void main(String[] args) { 7 | Scanner reader = new Scanner(System.in); 8 | double a = 0; 9 | double b = 0; 10 | double c = 0; 11 | double root1, root2; 12 | 13 | System.out.println("Quadratic Equation : a(x)^2 + b(x) + c = 0"); 14 | System.out.println("Enter value of a: "); 15 | a = reader.nextDouble(); 16 | System.out.println("Enter value of b: "); 17 | b = reader.nextDouble(); 18 | System.out.println("Enter value of c: "); 19 | c = reader.nextDouble(); 20 | 21 | // d stands for determinant 22 | double d = (b * b) - 4 * (a * c); 23 | 24 | //if d = 0 roots are equal and real, id d>0 roots are real and distinct 25 | if (d >= 0) { 26 | root1 = (-b + Math.sqrt(d)) / (2 * a); 27 | root2 = (-b - Math.sqrt(d)) / (2 * a); 28 | 29 | System.out.println("root1 = "+root1+ "\nroot2 = "+ root2); 30 | if (root1 == root2) { 31 | System.out.println("Both roots are equal and real!"); 32 | } 33 | 34 | else{ 35 | System.out.println("Roots are real and distinct"); 36 | } 37 | } 38 | //d<0, roots are imaginary 39 | else { 40 | double real = -b / (2 * a); 41 | double imaginary = Math.sqrt(-d) / (2 * a); 42 | System.out.println("root1 = "+real+ " + " +imaginary+"i"); 43 | System.out.println("root2 = "+real+ " - " +imaginary+"i"); 44 | System.out.println("Roots are imaginary!"); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Hackerrank/birthday.java: -------------------------------------------------------------------------------- 1 | /* You are in charge of the cake for a child's birthday. You have decided the cake will have one candle 2 | for each year of their total age. They will only be able to blow out the tallest of the candles. 3 | Count how many candles are tallest. A Program to input candle heights and print the total number 4 | of tallest candles present on the cake*/ 5 | import java.io.*; 6 | import java.util.Arrays; 7 | class birthday 8 | { 9 | int candle_count(int [] a, int x) //a method to sort and calculate the number of candles. 10 | { 11 | Arrays.sort(a); //to sort the elements in ascending order 12 | int c=0; 13 | int lst= a[x-1]; 14 | for(int i=x-1;i>=0;i--) 15 | { 16 | if(a[i]==lst) 17 | {c++;} 18 | } 19 | return c; 20 | } 21 | public static void main() throws IOException 22 | { 23 | int ln; //a variable of integer type to store the length of array(i,e number of candles) 24 | InputStreamReader inp=new InputStreamReader(System.in); 25 | BufferedReader br=new BufferedReader(inp); 26 | ln=Integer.parseInt(br.readLine()); 27 | int [] cdl=new int[ln]; //an array to store the candles height 28 | for(int i=0;iheight[l]) 33 | l++; 34 | else 35 | r--; 36 | } 37 | 38 | return sum; 39 | } 40 | 41 | public static void main(String[] args) { 42 | Scanner sc = new Scanner(System.in); 43 | 44 | int n = sc.nextInt(); 45 | int[] height = new int[n]; 46 | 47 | for(int i = 0; i < n; i ++) 48 | height[i] = sc.nextInt(); 49 | 50 | System.out.println( maxArea(height) ); 51 | 52 | sc.close(); 53 | } 54 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Rotate_Matrix_by_90deg.java: -------------------------------------------------------------------------------- 1 | //Question : you are given an 2D array , you have to rotate the Matrix bt 90deg and return it; 2 | 3 | public class ArrayPermutation { 4 | public static void main(String[] args) { 5 | int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 6 | //array before rotation 7 | for (int i = 0; i < array.length; i++) { 8 | for (int j = 0; j < array.length; j++) { 9 | System.out.print(array[i][j] + " "); 10 | } 11 | System.out.println(); 12 | } 13 | rotate(array); 14 | System.out.println("==========================================================="); 15 | System.out.println("after Rotation"); 16 | 17 | for (int i = 0; i < array.length; i++) { 18 | for (int j = 0; j < array.length; j++) { 19 | System.out.print(array[i][j] + " "); 20 | } 21 | System.out.println(); 22 | } 23 | } 24 | 25 | //this functon will rotate the array by 90deg by taking transpose the array and rotate each row 26 | static void rotate(int[][] matrix) { 27 | int n = matrix.length; 28 | for (int i = 0; i < (n + 1) / 2; i++) { 29 | for (int j = 0; j < n / 2; j++) { 30 | int temp = matrix[n - 1 - j][i]; 31 | matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1]; 32 | matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i]; 33 | matrix[j][n - 1 - i] = matrix[i][j]; 34 | matrix[i][j] = temp; 35 | } 36 | } 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Searching/LinearSearchJava.java: -------------------------------------------------------------------------------- 1 | //Performing Linear search of any number entered by user in an Array 2 | import java.util.Scanner; 3 | public class linearSearch { 4 | 5 | public static void main(String[] args) { 6 | Scanner reader = new Scanner(System.in); 7 | int num[]; 8 | int i; 9 | int search; 10 | //(optional) count is required to print how many times an element occurs in an array 11 | int count=0; 12 | 13 | // Declaring array of n numbers 14 | System.out.println("enter number of elements in array :"); 15 | int n = reader.nextInt(); 16 | num = new int[n]; 17 | 18 | //Taking input for elements of array from user 19 | System.out.println("Enter elements in array: "); 20 | for (i=0;i max) { 41 | max = numbers[i] * numbers[i + 1]; 42 | } 43 | } 44 | 45 | // Get max value 46 | return max; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Recursion/FibonacciSeries.java: -------------------------------------------------------------------------------- 1 | // Program to display the Fibonacci series from 0 to limit provided by the user in input using reucrssion 2 | 3 | import java.util.Scanner; 4 | 5 | public class FibonacciSeries { 6 | 7 | static int number1 = 0; // Declaring and initializing the variables 8 | static int number2 = 1, number3 = 0; 9 | 10 | // Main method 11 | public static void main(String[] args) { // Question: Display the fibonacci numbers from 1 to n, where n is 12 | // limit of the fibonacci series, provided by the user as input 13 | // Using recursion. 14 | System.out.println("Enter the limit of fibonacci number"); // Telling the user to enter the limit. 15 | 16 | Scanner input = new Scanner(System.in); 17 | int n = input.nextInt(); // Taking the input from user 18 | 19 | System.out.print(0 + " "); // Printing the first number 20 | System.out.print(1 + ""); // printing second number 21 | fibonacciNumber(n); // Function call to print the fibonacci series 22 | } 23 | 24 | // Method to print fibonacci series (Recursion) 25 | public static void fibonacciNumber(int n) { 26 | 27 | if(n > 2) { 28 | 29 | number3 = number1 + number2; 30 | number1 = number2; 31 | number2 = number3; 32 | 33 | System.out.print(" " + number3); // Printing the number of fibonacci series one by one. 34 | 35 | fibonacciNumber(n - 1); // Function call (Recursive call) 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LeetCode/Consecutive_Numbers_Sum.java: -------------------------------------------------------------------------------- 1 | //829. Consecutive Numbers Sum 2 | 3 | //Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers. 4 | 5 | //Example 1: 6 | 7 | //Input: n = 5 8 | //Output: 2 9 | //Explanation: 5 = 2 + 3 10 | 11 | //Example 2: 12 | 13 | //Input: n = 9 14 | //Output: 3 15 | //Explanation: 9 = 4 + 5 = 2 + 3 + 4 16 | 17 | //Example 3: 18 | 19 | //Input: n = 15 20 | //Output: 4 21 | //Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 22 | 23 | //Constraints: 24 | 25 | //1 <= n <= 109 26 | 27 | import java.util.Scanner; 28 | 29 | public class Consecutive_Numbers_Sum { 30 | 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | System.out.print("Enter the number : "); 34 | int num = sc.nextInt(); 35 | int ans = consecutiveNumbersSum(num); 36 | System.out.println("Ans : " + ans); 37 | } 38 | 39 | private static int consecutiveNumbersSum(int num) { 40 | int count = 0; 41 | 42 | // for finding the upperlimit of k 43 | // sequance is start with x, consicutive upperlimit k 44 | // x + (x+1) + (x+2) + ... + x(k-1) = num 45 | // kx + k(k-1)/2 = num 46 | // x = (num - k(k-1)/2)/k 47 | // if integer is positive so x>0 48 | // so we got the cnditition 2*num>k(k-1) 49 | for (int k = 1; 2 * num > k * (k - 1); k++) { 50 | 51 | // Ans x is valid when the x is integer 52 | // so we got numanator = (num - k(k-1)/2) 53 | // denomator = k 54 | int numenator = num - (k * (k - 1) / 2); 55 | 56 | // for x integer = condition numenator % k == 0 57 | 58 | if (numenator % k == 0) 59 | count++; 60 | } 61 | return count; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Sorting/RadixSort.java: -------------------------------------------------------------------------------- 1 | 2 | //Write a program to sort an array using Radix Sort Algorithm. 3 | 4 | 5 | public class Radix { 6 | public static void main(String[] args) { 7 | int[] arr={ 4725, 4586, 1330, 8792, 1594, 5729}; 8 | radixsort(arr, 4, 10); 9 | 10 | for (int i= 0 ; i=0 ; k--){ 37 | temp[--countArr[getDigit(pos, arr[k], radix)]]= arr[k]; 38 | } 39 | //coping temporary array to original array 40 | for (int i=0 ; i HEIGHT/2){ 44 | //set up spacing 45 | var leadingSpace = 8-i; 46 | var centerSpace = i*2 - HEIGHT; 47 | //build output 48 | out.append(" ".repeat(leadingSpace)); 49 | out.append(HASHS); 50 | out.append(" ".repeat(centerSpace)); 51 | out.append(ATS); 52 | //print line 53 | System.out.println(out); 54 | }else{ 55 | //center line 56 | System.out.println(" @@@" ); 57 | } 58 | } 59 | 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /LeetCode/Maximum_Product_of_Three_Numbers.java: -------------------------------------------------------------------------------- 1 | //628. Maximum Product of Three Numbers 2 | 3 | //Given an integer array nums, find three numbers whose product is maximum and return the maximum product. 4 | 5 | //Example 1: 6 | 7 | //Input: nums = [1,2,3] 8 | //Output: 6 9 | 10 | //Example 2: 11 | 12 | //Input: nums = [1,2,3,4] 13 | //Output: 24 14 | 15 | //Example 3: 16 | 17 | //Input: nums = [-1,-2,-3] 18 | //Output: -6 19 | 20 | import java.util.Arrays; 21 | import java.util.Collections; 22 | import java.util.Scanner; 23 | 24 | public class Maximum_Product_of_Three_Numbers { 25 | 26 | public static void main(String[] args) { 27 | Scanner sc = new Scanner(System.in); 28 | 29 | System.out.println("Enter Number of element : "); 30 | int n = sc.nextInt(); 31 | if (n < 3) { 32 | System.out.println("you must enter atlist 3 numbers"); 33 | } else { 34 | int nums[] = new int[n]; 35 | System.out.println("Enter " + n + " values :"); 36 | for (int i = 0; i < n; i++) { 37 | nums[i] = sc.nextInt(); 38 | } 39 | int ans = maximumProduct(nums); 40 | 41 | System.out.println("Maximun product of three numbers : " + ans); 42 | } 43 | } 44 | 45 | private static int maximumProduct(int[] nums) { 46 | 47 | // if the numbers is negative and so it will be the first index position second index position after sorting 48 | // take that two numbers and Array's last index number 49 | // compair with the last three index numbers which are largest in the array after sorting 50 | // using the math.max function we got maximun from them 51 | Arrays.sort(nums); 52 | int mul = Math.max(nums[0] * nums[1] * nums[nums.length - 1], nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]); 53 | return mul; 54 | 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Pattern_Printing/Letter_H.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program to print letter H exactly as shown below - 4 | 5 | ## ## 6 | ## ## 7 | ## ## 8 | ## ## 9 | ## $ $ $ ## 10 | ## ## 11 | ## ## 12 | ## ## 13 | ## ## 14 | 15 | */ 16 | 17 | import java.util.*; 18 | 19 | public class Letter_H{ 20 | 21 | public static void main(String args[]){ 22 | 23 | Scanner sc = new Scanner(System.in); 24 | int n = sc.nextInt(); 25 | printPattern(n); 26 | sc.close(); 27 | 28 | } 29 | 30 | static void printPattern(int N){ 31 | 32 | // Declaring the values of left, 33 | // middle, right side 34 | String left = "##", middle = "$", right = "##"; 35 | 36 | // Main Row Loop 37 | for (int row = 0; row < 2 * N - 1; row++) { 38 | 39 | // Condition for the left Values 40 | if (row < N) 41 | System.out.print(left); 42 | else 43 | System.out.print(left); 44 | 45 | // Loop for the middle values 46 | for (int col = 1; col < N - 1; col++) { 47 | 48 | // Condition for the middleValues 49 | if (row != N - 1) 50 | 51 | // Two spaces for perfect alignment 52 | System.out.print(" "); 53 | 54 | else 55 | System.out.print(" " +middle); 56 | } 57 | 58 | // Condition for the right Values 59 | if (row < N) 60 | System.out.print(" " + right); 61 | else 62 | System.out.print(" " + right); 63 | System.out.println(); 64 | } 65 | 66 | } 67 | } -------------------------------------------------------------------------------- /Basic Codes/TempConversion.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class TempConversion { 4 | public static void main(String[] args) { 5 | // Question: Convert the temperature from celsius to fahrenheit and Fahrenheit to 6 | // Celsius according to the user`s choice provided by the input 7 | 8 | System.out.println("To convert from Celsius to Fahrenheit Enter 0\n" + "To convert from Fahrenheit to Celsius enter 1"); // Asking user for input 9 | 10 | Scanner input = new Scanner(System.in); 11 | int n = input.nextInt(); // Taking input to choose the temperature conversion 12 | 13 | switch (n) { 14 | 15 | case 0: 16 | System.out.println("Enter the temperature in Celsius"); 17 | 18 | float temp = input.nextFloat(); // Taking the temperature in celsius 19 | double ans = ((temp * 9) / 5) + 32; // Formula to calculate the temperature in celsius 20 | 21 | System.out.printf("The %.3f degree celsius = %.3f Fahrenheit", temp, ans); 22 | break; 23 | 24 | case 1: 25 | System.out.println("Enter the temperature in Fahrenheit"); 26 | 27 | temp = input.nextFloat(); // Taking the temperature in celsius 28 | ans = ((temp - 32) * 5) / 9; // Formula to calculate the temperature in celsius 29 | 30 | System.out.printf("The %.3f = %.3f degree celsius", temp, ans); 31 | break; 32 | 33 | default: // Showing the message if user provides invalid argument 34 | System.out.println("Enter valid input"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LeetCode/Product_of_Array_Except_Self.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. 3 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 4 | You must write an algorithm that runs in O(n) time and without using the division operation. 5 | 6 | https://leetcode.com/problems/product-of-array-except-self/ 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class Product_of_Array_Except_Self { 12 | 13 | public static void main(String[] args) { 14 | Scanner sc = new Scanner(System.in); 15 | 16 | System.out.println("Enter Number of element : "); 17 | int n = sc.nextInt(); 18 | 19 | int nums[] = new int[n]; 20 | System.out.println("Enter " + n + " values :"); 21 | for (int i = 0; i < n; i++) { 22 | nums[i] = sc.nextInt(); 23 | } 24 | int[] ans = productExceptSelf(nums); 25 | 26 | System.out.println(" Ans : "); 27 | for(int i=0;i=0;i--) { 37 | prod*=nums[i]; 38 | right[i]=prod; 39 | } 40 | 41 | // make the result array with using of left array 42 | prod=1; 43 | int[] result=new int[nums.length]; 44 | for(int i=0;ia[j]){ 27 | int temp=a[i]; 28 | a[i]=a[j]; 29 | a[j]=temp; 30 | count++; 31 | } 32 | } 33 | System.out.println("The Answer is: "); 34 | System.out.println(count);//The final answer is printed using this line 35 | } 36 | public static void main(String[] args) { 37 | 38 | Scanner sc=new Scanner(System.in); 39 | System.out.println("Enter number of test cases you want to perform: "); 40 | int t = sc.nextInt();//"t " stores the number of test cases you want to perform 41 | for (int p = 0; p < t; p++) { 42 | int a[] = input(); 43 | inversecount(a); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /LeetCode/constructBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), 3 | construct the tree and return its root. 4 | 5 | It is guaranteed that there is always possible to find a binary search tree with the given requirements 6 | for the given test cases. 7 | 8 | A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly 9 | less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. 10 | 11 | A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, 12 | then traverses Node.right. 13 | */ 14 | 15 | class Solution { 16 | public TreeNode bstFromPreorder(int[] preorder) { 17 | int[] index = new int[]{0}; //creating an array of index of root node 18 | return helper(preorder, index, Integer.MIN_VALUE, Integer.MAX_VALUE); //calling the function helper 19 | } 20 | 21 | TreeNode helper(int[] preorder, int[] index, int minValue, int maxValue) { 22 | if(index[0] == preorder.length) //if index at 0th position is equal to length of tree return null 23 | return null; 24 | 25 | if(preorder[index[0]] < minValue || preorder[index[0]] > maxValue) //if preorder index of 0 is smaller than or greater than max value return null 26 | return null; 27 | 28 | int rootVal = preorder[index[0]]; //root value will be assign as the top most index 29 | index[0]++; 30 | 31 | TreeNode node = new TreeNode(rootVal); //creating a new treenode of root value 32 | node.left = helper(preorder, index, minValue, rootVal); //traversing left child 33 | node.right = helper(preorder, index, rootVal, maxValue); //traversing right child 34 | 35 | return node; 36 | } 37 | } -------------------------------------------------------------------------------- /Number Theory/ModularExp.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: Given three numbers 'a', 'b' and 'm' calculate a^b under modulo m. 3 | Constraints: a<=10^9, b<=10^9, m<=10^9 4 | 5 | Idea: Any number can be represented in sum of powers of 2. The idea is to represent the power 'b' in sum of 6 | powers of 2. 7 | 8 | Example: 3^11 can be written as 3^(1011) where power is in binary. 9 | = 3^(1*(2^3) + 0*(2^2) + 1*(2^1) + 1*(2^0)) 10 | = 3^(1*8 + 0*4 + 1*2 + 1*1) 11 | = 3^8 * 3^0 * 3^2 * 3^1 12 | = 6561 * 1 * 9 * 3 13 | = 177417 14 | 15 | Why use modulo m? 16 | Answer: Since the multiplication operation in lines 48 and 51 can easily exceed 'm' modulo is taken. 17 | 18 | Complexity: O(Log(b)) 19 | Reason: The while loop will run for number of bits in 'b' which is Log(b) 20 | 21 | Modulo properties used: 22 | (a * b * c *d) % m = ((( a * b ) % m) * c) % m) * d) % m 23 | */ 24 | 25 | import java.util.Scanner; 26 | 27 | public class ModularExp { 28 | public static void main(String[] args) { 29 | Scanner sc = new Scanner(System.in); 30 | 31 | long a = sc.nextLong(); 32 | long b = sc.nextLong(); 33 | long m = sc.nextLong(); 34 | 35 | long result = modularExp(a, b, m); 36 | 37 | System.out.println(result); 38 | } 39 | 40 | public static long modularExp(long a, long b, long m) { 41 | long ans = 1; 42 | 43 | //handle case where 'a' is large 44 | a = a % m; 45 | 46 | while (b > 0) { 47 | //LSB is set 48 | if ((b & 1) == 1) { 49 | //multiply current base with ans if bit is set 50 | ans = (ans * a) % m; 51 | } 52 | //drop LSB by right-shifing by 1 53 | b >>= 1; 54 | //increase base with every iteration 55 | a = (a * a) % m; 56 | } 57 | 58 | return ans; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Hackerrank/java_exception_handling(try-catch).java: -------------------------------------------------------------------------------- 1 | /*Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. (Wikipedia) 2 | 3 | Java has built-in mechanism to handle exceptions. Using the try statement we can test a block of code for errors. The catch block contains the code that says what to do if exception occurs. 4 | 5 | This problem will test your knowledge on try-catch block. 6 | 7 | You will be given two integers and as input, you have to compute . If and are not bit signed integers or if is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions. 8 | */ 9 | 10 | import java.io.*; 11 | import java.util.*; 12 | import java.text.*; 13 | import java.math.*; 14 | import java.util.regex.*; 15 | 16 | public class Solution { 17 | 18 | public static void main(String[] args) { 19 | 20 | 21 | Scanner scan = new Scanner(System.in); 22 | try { 23 | //taking 2 numbers inputs 24 | int x = scan.nextInt(); 25 | int y = scan.nextInt(); 26 | //dividing 2 numbers 27 | System.out.println(x / y); 28 | } 29 | catch(ArithmeticException | InputMismatchException e) { 30 | if (e instanceof ArithmeticException) { 31 | //if there is arithmetic exception occured in try block then it will be catched here 32 | System.out.println("java.lang.ArithmeticException: / by zero"); 33 | } else if (e instanceof InputMismatchException){ 34 | System.out.println("java.util.InputMismatchException"); 35 | //if there is inputmismatch exception occured in try block then it will be catched here 36 | } 37 | } 38 | scan.close(); 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Data Structure/Graph/Directed Graph/directedGraph.java: -------------------------------------------------------------------------------- 1 | // Java code to demonstrate Graph representation 2 | // using ArrayList in Java 3 | 4 | import java.util.*; 5 | 6 | public class directedGraph 7 | { 8 | int size; // stores number of vertices in graph 9 | LinkedList adjacencyList[]; // stores the connected vertices with vertex i 10 | 11 | // constructor to initialize instance variables 12 | directedGraph(int n) 13 | { 14 | size = n; 15 | adjacencyList = new LinkedList[n]; 16 | for (int i=0; i=0 && arr[i]>=arr[i+1]) 37 | i--; 38 | // according top test case returning the -1 39 | if(i==-1) 40 | return -1; 41 | 42 | int k = arr.length-1; 43 | while(arr[i]>=arr[k]) 44 | k--; 45 | // swap the values of ith and kth 46 | char temp = arr[i]; 47 | arr[i] = arr[k]; 48 | arr[k] = temp; 49 | 50 | // Storing the values of 0 to i in res 51 | String res = ""; 52 | for(int j=0;j<=i;j++) 53 | res+=arr[j]; 54 | // for nearest greater integer store it in the reverse order 55 | for(int j=arr.length-1;j>i;j--) 56 | res+=arr[j]; 57 | 58 | 59 | // typecast to Long 60 | long ans = Long.parseLong(res); 61 | if(ans<=2147483647) 62 | return (int) ans; 63 | else 64 | return -1; 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /Arrays/1D Arrays/intersectionOfTwoArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two arrays arr1 and arr2. We need to find the intersection of both the arrays and return the result as a list. 3 | */ 4 | 5 | import java.util.*; 6 | 7 | public class intersectionOfTwoArrays{ 8 | 9 | public static void main(String[] args){ 10 | Scanner sc = new Scanner(System.in); 11 | int n1 = sc.nextInt(); 12 | int[] arr1 = new int[n1]; 13 | int n2 = sc.nextInt(); 14 | int[] arr2 = new int[n2]; 15 | for(int i = 0; i < n1; i++){ 16 | arr1[i] = sc.nextInt(); 17 | } 18 | for(int i = 0; i < n1; i++){ 19 | arr2[i] = sc.nextInt(); 20 | } 21 | intersection(arr1, arr2, n1, n2); 22 | sc.close(); 23 | } 24 | 25 | public static void intersection(int[] a,int[] b, int n, int m){ 26 | HashMap map = new HashMap<>(); // created a hashmap which will store distinct elements with their frequencies 27 | for(int i = 0; i < n; i++){ 28 | map.put(a[i],map.getOrDefault(a[i],0)+1); // updating frequencies of each element 29 | } 30 | int[] arr = new int[100001]; // created an array which will store the elements which are present in both the arrays 31 | Arrays.fill(arr,0); 32 | for(int i = 0; i < m; i++){ 33 | if(map.containsKey(b[i])){ // updating array which contains elements that are present in both the arrays 34 | arr[b[i]] = 1; 35 | } 36 | } 37 | ArrayList al = new ArrayList<>(); // creating a list 38 | for(int i = 0; i < m; i++){ 39 | if(arr[b[i]]==1){ // checking if the element is present in both the arrays or not 40 | al.add(b[i]); // adding the elements to the list 41 | } 42 | } 43 | System.out.println(al); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /LeetCode/Burst_Balloon.java: -------------------------------------------------------------------------------- 1 | / // Leetcode Ques No. : 312 2 | // Problem Link: https://leetcode.com/problems/burst-balloons/ 3 | 4 | 5 | ***** problem statement ***** 6 | 7 | /* 8 | You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. 9 | If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. 10 | Return the maximum coins you can collect by bursting the balloons wisely. 11 | */ 12 | 13 | 14 | ***** Solution ***** 15 | 16 | 17 | 18 | public int maxCoins_memo(int[] nums , int si , int ei , int[][] dp){ //si = starting index , ei = ending index 19 | if(dp[si][ei] != 0) 20 | return dp[si][ei]; 21 | 22 | int lele = si == 0 ? 1 : nums[si - 1]; //lele = leftelement 23 | int rele = ei == nums.length - 1 ? 1 : nums[ei + 1]; //rele = rightelement 24 | 25 | int maxCoin = 0; 26 | for(int cut = si; cut <= ei; cut++){ 27 | int lcost = cut == si ? 0 : maxCoins_memo(nums , si , cut - 1 , dp); //lcost:leftcost 28 | int rcost = cut == ei ? 0 : maxCoins_memo(nums , cut + 1 , ei , dp); //rcost:rightcost 29 | 30 | maxCoin = Math.max(maxCoin , lcost + lele * nums[cut] * rele + rcost); // maxcoin means the maximum number of coins collect after balloon burst 31 | } 32 | 33 | return dp[si][ei] = maxCoin; 34 | } 35 | public int maxCoins(int[] nums) { 36 | int n = nums.length; 37 | int[][] dp = new int[n][n]; 38 | 39 | return maxCoins_memo(nums , 0 , n - 1 , dp); 40 | } 41 | 42 | 43 | 44 | 45 | 46 | /* 47 | Sample input: [3,1,5,8] 48 | 49 | Sample Output: 167 50 | 51 | 52 | */ 53 | -------------------------------------------------------------------------------- /LeetCode/PointInsideCircle.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. 3 | 4 | You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. 5 | 6 | For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. 7 | 8 | Return an array answer, where answer[j] is the answer to the jth query. 9 | 10 | Constraints: 11 | 12 | 1 <= points.length <= 500 13 | points[i].length == 2 14 | 0 <= x??????i, y??????i <= 500 15 | 1 <= queries.length <= 500 16 | queries[j].length == 3 17 | 0 <= xj, yj <= 500 18 | 1 <= rj <= 500 19 | All coordinates are integers. 20 | 21 | */ 22 | class PointInsideCircle { 23 | double equation(int arr[], int brr[]) //function taht take points and circle constants as input and return Decimal values. 24 | { 25 | return Math.pow((brr[0]-arr[0]),2) + Math.pow((brr[1]-arr[1]),2) - Math.pow(arr[2],2); //returning value after putting the points on circle 26 | } 27 | public int[] countPoints(int[][] points, int[][] queries) { //Given function 28 | int res[] = new int[queries.length]; //Array res of type integer 29 | for(int i = 0; i= 1) { 44 | ParagraphCount++; 45 | } 46 | System.out.println("Total word count = " 47 | + WordCount); 48 | System.out.println("Total number of sentences = " 49 | + SentenceCount); 50 | System.out.println("Total number of characters = " 51 | + CharacterCount); 52 | System.out.println("Number of paragraphs = " 53 | + ParagraphCount); 54 | System.out.println("Total number of whitespaces = " 55 | + WhiteSpaceCount); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Sorting/import java.util.Scanner;.java: -------------------------------------------------------------------------------- 1 | //Write a program to sort the array accordingly 2 | import java.util.Scanner; 3 | class Array_semi_sort{ 4 | public static void main(String args[]){ 5 | Scanner sc=new Scanner(System.in); 6 | System.out.println("Enter length of array : "); 7 | int l=sc.nextInt(); 8 | int ar[]=new int[l]; 9 | for(int x=0;xar[y+1]){ 52 | int t=ar[y]; 53 | ar[y]=ar[y+1]; 54 | ar[y+1]=t; 55 | } 56 | } 57 | } 58 | return ar; 59 | } 60 | 61 | public static int[] reverse(int ar[]){ 62 | int l=ar.length; 63 | int r[]=new int[l]; 64 | for(int x=0;x adjacencyList[]; // stores the connected vertices with vertex i 10 | 11 | 12 | // constructor to initialize instance variables 13 | undirectedGraph(int n) 14 | { 15 | size = n; 16 | adjacencyList = new LinkedList[n]; 17 | for (int i=0; i w 26 | adjacencyList[w].add(v); // adding edge w --> v 27 | } 28 | 29 | // method to print the graph 30 | void printGraph() 31 | { 32 | System.out.println("\nAdjacency list representation of graph"); 33 | 34 | // printing the vertices connected with vertex i 35 | for (int i = 0; i < adjacencyList.length; i++) 36 | System.out.println(i+" : "+adjacencyList[i]); 37 | 38 | } 39 | 40 | // driver code 41 | public static void main(String[] args) 42 | { 43 | // creating a graph of size 9 44 | int numberOfVertices = 9; 45 | 46 | // creating an instance of undirectedGraph 47 | undirectedGraph graph = new undirectedGraph(numberOfVertices); 48 | 49 | // adding different edges 50 | graph.addEdge(0, 3); 51 | graph.addEdge(1, 7); 52 | graph.addEdge(2, 5); 53 | graph.addEdge(3, 6); 54 | graph.addEdge(4, 1); 55 | graph.addEdge(5, 8); 56 | graph.addEdge(6, 0); 57 | graph.addEdge(7, 4); 58 | graph.addEdge(7, 5); 59 | graph.addEdge(8, 6); 60 | graph.addEdge(8, 2); 61 | 62 | // calling print method to print the graph 63 | graph.printGraph(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Data Structure/Linked List/Single Linked List/Remove_Nth_Node_from_the_end.java: -------------------------------------------------------------------------------- 1 | // Given the head of a linked list, remove the nth node from the end of the list and return its head. 2 | 3 | // Example 1: 4 | 5 | // Input: head = [1,2,3,4,5], n = 2 6 | // Output: [1,2,3,5] 7 | 8 | 9 | // Example 2: 10 | 11 | // Input: head = [1], n = 1 12 | // Output: [] 13 | 14 | public class Leetcode_19 { 15 | // Node class 16 | public class ListNode { 17 | int val; 18 | ListNode next; 19 | 20 | ListNode() { 21 | } 22 | 23 | ListNode(int val) { 24 | this.val = val; 25 | } 26 | 27 | ListNode(int val, ListNode next) { 28 | this.val = val; 29 | this.next = next; 30 | } 31 | } 32 | 33 | class Solution { 34 | public ListNode removeNthFromEnd(ListNode head, int n) { 35 | // Edge Case 36 | if (head == null || head.next == null) 37 | return null; 38 | 39 | // making 2 pointers slow and fast at the start of the LinkedList 40 | ListNode slow = head, fast = head; 41 | 42 | // Moving fast pointer n times 43 | while (n-- > 0) { 44 | fast = fast.next; 45 | } 46 | 47 | // Edge case- if fast is equal to null then return head.next; 48 | if (fast == null) 49 | return head.next; 50 | 51 | // Now, fast pointer is N distance away from slow. 52 | // now, moving fast and slow pointer one step at a time. 53 | while (fast.next != null) { 54 | slow = slow.next; 55 | fast = fast.next; 56 | } 57 | 58 | // slow reached n-1 position 59 | // so, now we are attaching slow to the slow.next.next, i.e removing nth node. 60 | slow.next = slow.next.next; 61 | 62 | return head; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /LeetCode/ThreeSum.java: -------------------------------------------------------------------------------- 1 | // Solution to https://leetcode.com/problems/3sum/ 2 | 3 | // Problem statement: 4 | // Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0 5 | 6 | // Apporach: We use 2 pointers in front and back of the given array. 7 | // We start with the first element and move the front pointer to the second element. 8 | // From back of the array we move to the second to last element. 9 | // Then from second element we move the front pointer to the third element. 10 | // From second last element we move the back pointer to the third last element and so on. 11 | // We keep moving the front pointer and the back pointer until we reach the end of the array. 12 | // The arrays are sorted to skip over duplicates and make the algorithm faster. 13 | 14 | class Solution { 15 | public List> threeSum(int[] nums) { 16 | Arrays.sort(nums); 17 | 18 | ArrayList> res = new ArrayList<>(); 19 | 20 | for (int i = 0; i < nums.length; i++) { 21 | int j = i + 1, k = nums.length - 1; 22 | 23 | if (i > 0 && nums[i] == nums[i - 1]) { 24 | continue; // skip duplicates 25 | } 26 | 27 | while (j < k) { 28 | if (k < nums.length - 1 && nums[k] == nums[k + 1]) { 29 | k--; 30 | continue; // skip duplicates 31 | } 32 | 33 | // sum of current triplet 34 | if (nums[i] + nums[j] + nums[k] > 0) { 35 | k--; 36 | } else if (nums[i] + nums[j] + nums[k] < 0) { 37 | j++; 38 | } else { 39 | // add triplet to result 40 | ArrayList list = new ArrayList( 41 | Arrays.asList(nums[i], nums[j], nums[k]) 42 | ); 43 | 44 | res.add(list); 45 | j++; 46 | k--; 47 | } 48 | } 49 | } 50 | 51 | return res; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort.java: -------------------------------------------------------------------------------- 1 | // Q : Sorting method ==> Bubble Sort 2 | import java.util.Arrays; // imported the Array class to print the output 3 | 4 | public class Bubble_Sort { 5 | public static void main(String[] args) { // main function 6 | int[] arr = {1, 2, 3, 6, 5, 4}; // input 7 | System.out.println(Arrays.toString(BubbleSort(arr))); // method to print the output 8 | } 9 | 10 | public static int[] BubbleSort(int[] arr) { // bubble sort ( the main code) 11 | boolean swapped; // added the boolean step to check whether the elements are swapped or not 12 | for (int i = 0; i < arr.length; i++) { // first loop 13 | swapped = false; // till here boolean is false because nothing is swapped 14 | for (int j = 1; j < arr.length - i; j++) { // second loop which will compare elements if the first element is greater then second 15 | if (arr[j] < arr[j - 1]) { // it will swap 16 | int temp = arr[j]; // method to swap two elements 17 | arr[j] = arr[j - 1]; 18 | arr[j - 1] = temp; 19 | swapped = true; // elements will be swapped and boolean will become true 20 | } 21 | } 22 | if (!swapped) { // if nothing will swap mean array is sorted so boolean will remain false anad the loop 23 | break; // will break 24 | } 25 | } 26 | return arr; // returning the array 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Pattern_Printing/C.java: -------------------------------------------------------------------------------- 1 | // Print C letter using pattern printing 2 | 3 | public class C { 4 | public static void main(String args[]){ 5 | 6 | for(int x=0;x<11;x++){ // to iterate from top to bottom 7 | for(int y=0;y<11;y++){ // to iterate from left to right in the same row 8 | 9 | if( (x>2 && x<8) ){ 10 | if(y==0 || y==1){ 11 | System.out.print("#"); // to print hash wherever necessary 12 | } 13 | else{ 14 | System.out.print(" "); // to print spaces wherever necessary 15 | } 16 | } 17 | else if((x==0 || x==10)&&(y>=4 && y<8)){ 18 | System.out.print("#"); // to print hash wherever necessary 19 | } 20 | else if(x!=0 && x!=10 && y!=0){ 21 | if(x+y==4 || x+y==3 || x-y==7 || x-y==6 || y-x==7 || y-x==8 || x+y==18 || x+y==17){ 22 | 23 | System.out.print("*"); // to print asterisks wherever necessary 24 | } 25 | // else if(){ 26 | // System.out.print("*"); // to print asterisks wherever necessary 27 | // } 28 | else{ 29 | System.out.print(" "); // to print spaces wherever necessary 30 | } 31 | } 32 | else{ 33 | System.out.print(" "); // to print spaces wherever necessary 34 | } 35 | 36 | } 37 | System.out.println(); 38 | } 39 | 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /GeeksForGeeks/minimum_Jumps.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers where each element represents the max number of steps that can be made forward from that element. 3 | Return the minimum number of jumps to reach the end of the array. If an element is 0, it cannot move through that element. If the end isn’t reachable, return -1. 4 | */ 5 | import java.util.*; 6 | 7 | public class minimum_Jumps { 8 | 9 | public static void main(String[] args){ 10 | 11 | Scanner sc = new Scanner(System.in); 12 | int n = sc.nextInt(); 13 | int[] arr = new int[n]; 14 | for(int i = 0; i < n; i++){ 15 | arr[i] = sc.nextInt(); 16 | } 17 | minJumps(arr, n); 18 | sc.close(); 19 | 20 | } 21 | static void minJumps(int[] arr, int n){ 22 | int[] jumps = new int[n]; 23 | int min; 24 | jumps[n-1] = 0; 25 | for(int i = n-2; i >= 0; i--){ 26 | // If arr[i] is 0 then arr[n-1] 27 | // can't be reached from here 28 | if(arr[i]==0){ 29 | jumps[i] = Integer.MAX_VALUE; 30 | // If we can directly reach to 31 | // the end point from here then 32 | // jumps[i] is 1 33 | }else if(arr[i] >= n-i-1){ 34 | jumps[i] = 1; 35 | }else{ 36 | min = Integer.MAX_VALUE; 37 | // following loop checks 38 | // with all reachable points 39 | // and takes the minimum 40 | for(int j = i+1; j < n && j <= arr[i]+i; j++){ 41 | if(min > jumps[i]){ 42 | min = jumps[j]; 43 | } 44 | } 45 | // Handle overflow 46 | if(min!=Integer.MAX_VALUE){ 47 | jumps[i] = min+1; 48 | }else{ 49 | jumps[i] = min; // or Integer.MAX_VALUE 50 | } 51 | } 52 | } 53 | System.out.println(jumps[0]); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /Java_abstract_class[Hackerrank].java: -------------------------------------------------------------------------------- 1 | /* 2 | A Java abstract class is a class that can't be instantiated. That means you cannot create new instances of an abstract class. It works as a base for subclasses. You should learn about Java Inheritance before attempting this challenge. 3 | 4 | Following is an example of abstract class: 5 | 6 | abstract class Book{ 7 | String title; 8 | abstract void setTitle(String s); 9 | String getTitle(){ 10 | return title; 11 | } 12 | } 13 | If you try to create an instance of this class like the following line you will get an error: 14 | 15 | Book new_novel=new Book(); 16 | You have to create another class that extends the abstract class. Then you can create an instance of the new class. 17 | 18 | Notice that setTitle method is abstract too and has no body. That means you must implement the body of that method in the child class. 19 | 20 | In the editor, we have provided the abstract Book class and a Main class. In the Main class, we created an instance of a class called MyBook. Your task is to write just the MyBook class. 21 | 22 | Your class mustn't be public. 23 | 24 | Sample Input 25 | 26 | A tale of two cities 27 | Sample Output 28 | 29 | The title is: A tale of two cities 30 | 31 | */ 32 | 33 | 34 | 35 | import java.util.*; 36 | abstract class Book{ 37 | String title; 38 | abstract void setTitle(String s); 39 | String getTitle(){ 40 | return title; 41 | } 42 | } 43 | 44 | class MyBook extends Book 45 | { 46 | 47 | void setTitle(String s){ 48 | title = s; 49 | } 50 | } 51 | 52 | 53 | 54 | 55 | public class Main{ 56 | 57 | public static void main(String []args){ 58 | //Book new_novel=new Book(); This line prHMain.java:25: error: Book is abstract; cannot be instantiated 59 | Scanner sc=new Scanner(System.in); 60 | String title=sc.nextLine(); 61 | MyBook new_novel=new MyBook(); 62 | new_novel.setTitle(title); 63 | System.out.println("The title is: "+new_novel.getTitle()); 64 | sc.close(); 65 | 66 | } 67 | } -------------------------------------------------------------------------------- /LeetCode/deletionOfNode.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class deletionOfNode { 3 | public static void main(String[] args) { 4 | 5 | /* Construct the following tree 6 | 1 7 | / \ 8 | / \ 9 | 2 3 10 | / / \ 11 | / / \ 12 | 4 5 6 13 | / \ 14 | / \ 15 | 7 8 16 | */ 17 | 18 | 19 | Node root=new Node(1); 20 | root.left=new Node(2); 21 | root.right=new Node(3); 22 | root.left.left=new Node(4); 23 | root.right.left=new Node(5); 24 | root.right.right=new Node(6); 25 | root.right.left.left=new Node(7); 26 | root.right.left.right=new Node(8); 27 | //Recursive 28 | deleteNode(root,6); 29 | PrintNodes(root); 30 | 31 | } 32 | static int findMin(Node root){ 33 | if(root.left!=null) return findMin(root.left); 34 | else return root.data; 35 | } 36 | public static Node deleteNode(Node root, int key) { 37 | if(root==null){ 38 | return null; 39 | } 40 | if(root.data>key){ 41 | root.left=deleteNode(root.left,key); 42 | } 43 | else if(root.data2->3->4->5->6 to 1->2->3->6->5->4 24 | 25 | Step 3: merge both the list by reordering them one by one in order 26 | 27 | reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4 28 | */ 29 | 30 | class Solution { 31 | 32 | public void reorderList(ListNode head) { 33 | if(head==null||head.next==null) return; 34 | 35 | //Find the middle of the list 36 | ListNode pt1=head; 37 | ListNode pt2=head; 38 | while(pt2.next!=null && pt2.next.next!=null){ 39 | pt1=pt1.next; 40 | pt2=pt2.next.next; 41 | } 42 | 43 | //Reverse the half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4 44 | ListNode preMid=pt1; 45 | ListNode preCurr=pt1.next; 46 | while(preCurr.next!=null){ 47 | ListNode curr=preCurr.next; 48 | preCurr.next=curr.next; 49 | curr.next=preMid.next; 50 | preMid.next=curr; 51 | } 52 | 53 | //Start reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4 54 | pt1=head; 55 | pt2=preMid.next; 56 | while(pt1!=preMid){ 57 | preMid.next=pt2.next; 58 | pt2.next=pt1.next; 59 | pt1.next=pt2; 60 | pt1=pt2.next; 61 | pt2=preMid.next; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /LeetCode/wordCount.java: -------------------------------------------------------------------------------- 1 | /*Given an m x n grid of characters board and a string word, return true if word exists in the grid. 2 | The word can be constructed from letters of sequentially adjacent cells, 3 | where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. 4 | */ 5 | 6 | class Solution { 7 | public boolean exist(char[][] board, String word) { 8 | 9 | int M=board.length, N=board[0].length; //Finding out no of rows and column in matrix 10 | 11 | for(int i=0;i= M || j < 0 || j >= N || board[i][j]!=word.charAt(pos) || board[i][j]=='#') //checking the necessary condition to find out whether word exists or not 32 | return false; 33 | 34 | char dup=board[i][j]; 35 | board[i][j]='#'; 36 | 37 | boolean ans = dfs(board, i + 1, j, word, pos + 1) || //traversing one letter right 38 | dfs(board, i - 1, j, word, pos + 1) || ////traversing one letter left 39 | dfs(board, i, j + 1, word, pos + 1) || //traversing one letter up 40 | dfs(board, i, j - 1, word, pos + 1); ////traversing one letter down 41 | 42 | board[i][j]=dup; //backtracking the string 43 | return ans; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Coding Application(Games and more)/DigitalClock.java: -------------------------------------------------------------------------------- 1 | public class DigitalClock { 2 | public static void main(String[] args) throws InterruptedException { 3 | 4 | //Variables 5 | int hours = 0; 6 | int minutes = 0; 7 | int seconds = 0; 8 | 9 | 10 | while (true) { 11 | //If 'hours' are less than 10, we write a '0' in front to get the desired structure 12 | if (hours < 10) { 13 | System.out.print("0"); 14 | } 15 | 16 | System.out.print(hours + ":"); 17 | 18 | //If 'minutes' are less than 10, we write a '0' in front to get the desired structure 19 | if (minutes < 10) { 20 | System.out.print("0"); 21 | } 22 | 23 | System.out.print(minutes + ":"); 24 | 25 | //If 'seconds' are less than 10, we write a '0' in front to get the desired structure 26 | if (seconds < 10) { 27 | System.out.print("0"); 28 | } 29 | 30 | //Line break 31 | System.out.println(seconds); 32 | 33 | //We increase 'seconds' 34 | seconds++; 35 | 36 | //We check the time 37 | if (seconds == 60) {//If 'seconds' = 60 38 | //We need to reset 'seconds' to '0' 39 | seconds = 0; 40 | //And increase 'minutes' 41 | minutes++; 42 | if (minutes == 60) {//If 'minutes' = 60 43 | //We need to reset 'minutes' to '0' 44 | minutes = 0; 45 | //And increase 'hours' 46 | hours++; 47 | if (hours == 24) {//If 'hours' = '24' 48 | //We need to reset 'hours' and it will be '00:00:00' again 49 | hours = 0; 50 | } 51 | } 52 | } 53 | 54 | //It interrupts the program's execution in 1 sec to give realism to the clock 55 | Thread.sleep(1000); 56 | System.out.print("\033[H\033[2J"); 57 | System.out.flush(); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /LeetCode/Letter_Combination_of_a_phone_number.java: -------------------------------------------------------------------------------- 1 | // Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. 2 | // A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 3 | // Example 1: 4 | // Input: digits = "23" 5 | // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 6 | // Example 2: 7 | // Input: digits = "" 8 | // Output: [] 9 | 10 | class Solution { 11 | public String [] key = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 12 | public List letterCombinations(String str) { 13 | // Edge Case - if string length is equal to zero then we have to return the empty ArrayList 14 | if(str.length() == 0){ 15 | return new ArrayList<>(); 16 | } 17 | 18 | List ans = letterCombinations1(str); 19 | return ans; 20 | } 21 | public List letterCombinations1(String str) { 22 | // Base Case 23 | // if String length is zero then we will make a new ArrayList, add empty string to it and return it. 24 | if(str.length() == 0){ 25 | List base = new ArrayList<>(); 26 | base.add(""); 27 | return base; 28 | } 29 | 30 | // For example if String = 23 31 | 32 | char ch = str.charAt(0); // Here, we are just taking out the 1st character of the string , i.e 2. 33 | String code = key[ch - '0']; // Here, we are taking out the String from key Array at index 2, i.e, abc. 34 | 35 | 36 | List recAns = letterCombinations1(str.substring(1)); // Recursive call // sending the remaining substring to the function again 37 | List ans = new ArrayList<>(); // Making our own Answer ArrayList 38 | 39 | for(int i=0;i0) //Loop for each test case 42 | { 43 | int n = in.nextInt(); //integer N, denoting the number of digits in X. 44 | if(n==1) //checking if n is 1 45 | { 46 | System.out.println(3); // then printing the value of 1. 47 | } 48 | else //if not 1 (else part) 49 | { 50 | int arr[] = new int[n]; // Array arr of int type. 51 | arr[0] = 3; // Setting the value of 1st index of Array to 3. 52 | arr[n-1] = 3; //Setting the value of last index of Array to 3. 53 | System.out.println(Arrays.toString(arr).replaceAll("[\\[\\], ]", "")); //Converting array to sting and then replcing all special characters and printing it. 54 | } 55 | t--; // decrementing the value of t. 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Arrays/2D Arrays/Spiraltraversal.java: -------------------------------------------------------------------------------- 1 | /*question - 2 | In this question will have to print element of matrix in spiral form . 3 | Basically you have to print character moving from outer most layer to inner most layer spirally 4 | 5 | Sample Case 6 | Input: 7 | 1 2 3 4 5 8 | 6 7 8 9 10 9 | 11 12 13 14 15 10 | 16 17 18 19 20 11 | 21 22 23 24 25 12 | 25 26 28 29 30 13 | Output: 14 | 1 6 11 16 21 26 27 28 29 30 25 20 15 10 5 4 3 2 7 12 17 22 23 24 19 14 9 8 13 18*/ 15 | 16 | package matrix; 17 | 18 | import java.util.Scanner; 19 | 20 | public class spira { 21 | 22 | public static void main(String[] args) { 23 | 24 | 25 | Scanner sc = new Scanner(System.in); 26 | //To enter no of rows 27 | int n = sc.nextInt(); 28 | //To enter no of columns 29 | int m = sc.nextInt(); 30 | int[][] mat = new int[n][m]; 31 | 32 | //To recieve elements of matrix as input from user 33 | for (int i = 0; i < mat.length; i++) { 34 | for (int j = 0; j < mat[0].length; j++) { 35 | mat[i][j] = sc.nextInt(); 36 | } 37 | } 38 | // total no of elements in matrix 39 | int total=m*n; 40 | int cnt=0; 41 | int minr=0,minc=0,maxr=mat.length-1,maxc=mat[0].length-1; 42 | 43 | //this while condition is used so that no element is printed twice or more 44 | while(cnt=minr&&cnt=minc&&cnt ans = majorityElement_II(nums); 39 | 40 | System.out.println("Majority Element is : " + ans); 41 | } 42 | 43 | public static List majorityElement_II(int[] nums) { 44 | 45 | // take variables 46 | int num1 = -1, num2 = -1, c1 = 0, c2 = 0, len = nums.length; 47 | // run foreach loop 48 | for (int el : nums) { 49 | // for first time check with the num1 if the numbers are same than increment in c1(count 1) 50 | // else if first time check with the num2 if the numbers are same than increment in c2(count 2) 51 | // if c1 is the first element so value of num1 is same as e1 and same for e2 52 | if (el == num1) 53 | c1++; 54 | else if (el == num2) 55 | c2++; 56 | else if (c1 == 0) { 57 | num1 = el; 58 | c1 = 1; 59 | } else if (c2 == 0) { 60 | num2 = el; 61 | c2 = 1; 62 | } else { 63 | c1--; 64 | c2--; 65 | } 66 | } 67 | // make list for the find all elements that appear more than ⌊ n/3⌋ times. 68 | List ans = new ArrayList(); 69 | c1 = 0; 70 | c2 = 0; 71 | for (int el : nums) { 72 | if (el == num1) 73 | c1++; 74 | else if (el == num2) 75 | c2++; 76 | } 77 | // checking the conditition 78 | if (c1 > len / 3) 79 | ans.add(num1); 80 | if (c2 > len / 3) 81 | ans.add(num2); 82 | 83 | return ans; 84 | 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /GeeksForGeeks/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Question :length of longest common subsequence of 2 string in java ? 3 | * input = s1 = "AGGTAB" s2 = "GXTXAYB"; 4 | * output =4 (GTAB) 5 | */ 6 | 7 | public class LongestCommonSubsequence { 8 | public static String lcs(String string1, String string2) { 9 | // Initialize variables 10 | int x = string1.length(); 11 | int y = string2.length(); 12 | int result = 0; 13 | 14 | // matrix 2 x 2 , plus one because the last one will be the result 15 | int arrPossibilities[][] = new int[x + 1][y + 1]; 16 | 17 | /* 18 | * Nested Loop , for a matrix 2 x 2 that will be define all the possibilities 19 | * from theory of permutation . 20 | */ 21 | for (int i = 0; i <= x; i++) { 22 | for (int j = 0; j <= y; j++) { 23 | if (i == 0 || j == 0) 24 | arrPossibilities[i][j] = 0; 25 | else if (string1.charAt(i - 1) == string2.charAt(j - 1)) 26 | arrPossibilities[i][j] = arrPossibilities[i - 1][j - 1] + 1; 27 | else 28 | arrPossibilities[i][j] = Math.max(arrPossibilities[i - 1][j], arrPossibilities[i][j - 1]); 29 | } 30 | } 31 | // Just a simple conversion, int for string. 32 | result = arrPossibilities[x][y]; 33 | String numberOfMatches = Integer.toString(result); 34 | 35 | // The next step will discovery the phrase that repeats more often. 36 | // So we need to walkthrough the array of Possibilities 37 | char[] stringMatch = new char[arrPossibilities.length + 1]; 38 | while (x > 0 && y > 0) { 39 | // If current character are same, so they are part of the Longest Possibilities 40 | if (string1.charAt(x - 1) == string2.charAt(y - 1)) { 41 | stringMatch[result - 1] = string1.charAt(x - 1); 42 | // condition for the while loop breaks. 43 | x--; 44 | y--; 45 | result--; 46 | } 47 | // If not same, then find the larger of two and go in the direction of larger value 48 | else if (arrPossibilities[x - 1][y] > arrPossibilities[x][y - 1]) 49 | x--; 50 | else 51 | y--; 52 | } 53 | 54 | String stringMatcher = new String(stringMatch); 55 | String formatedResult = String.format("The Longest Common Subsequens was : %s , %s times ", 56 | stringMatcher.strip().trim(), numberOfMatches); 57 | return formatedResult; 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /LeetCode/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Question :length of longest common subsequence of 2 string in java ? 3 | * input = s1 = "AGGTAB" s2 = "GXTXAYB"; 4 | * output =4 (GTAB) 5 | */ 6 | 7 | public class LongestCommonSubsequence { 8 | public static String lcs(String string1, String string2) { 9 | // Initialize variables 10 | int x = string1.length(); 11 | int y = string2.length(); 12 | int result = 0; 13 | 14 | // matrix 2 x 2 , plus one because the last one will be the result 15 | int arrPossibilities[][] = new int[x + 1][y + 1]; 16 | 17 | /* 18 | * Nested Loop , for a matrix 2 x 2 that will be define all the possibilities 19 | * from theory of permutation . 20 | */ 21 | for (int i = 0; i <= x; i++) { 22 | for (int j = 0; j <= y; j++) { 23 | if (i == 0 || j == 0) 24 | arrPossibilities[i][j] = 0; 25 | else if (string1.charAt(i - 1) == string2.charAt(j - 1)) 26 | arrPossibilities[i][j] = arrPossibilities[i - 1][j - 1] + 1; 27 | else 28 | arrPossibilities[i][j] = Math.max(arrPossibilities[i - 1][j], arrPossibilities[i][j - 1]); 29 | } 30 | } 31 | // Just a simple conversion, int for string. 32 | result = arrPossibilities[x][y]; 33 | String numberOfMatches = Integer.toString(result); 34 | 35 | // The next step will discovery the phrase that repeats more often. 36 | // So we need to walkthrough the array of Possibilities 37 | char[] stringMatch = new char[arrPossibilities.length + 1]; 38 | while (x > 0 && y > 0) { 39 | // If current character are same, so they are part of the Longest Possibilities 40 | if (string1.charAt(x - 1) == string2.charAt(y - 1)) { 41 | stringMatch[result - 1] = string1.charAt(x - 1); 42 | // condition for the while loop breaks. 43 | x--; 44 | y--; 45 | result--; 46 | } 47 | // If not same, then find the larger of two and go in the direction of larger value 48 | else if (arrPossibilities[x - 1][y] > arrPossibilities[x][y - 1]) 49 | x--; 50 | else 51 | y--; 52 | } 53 | 54 | String stringMatcher = new String(stringMatch); 55 | String formatedResult = String.format("The Longest Common Subsequens was : %s , %s times ", 56 | stringMatcher.strip().trim(), numberOfMatches); 57 | return formatedResult; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Sorting/merge-Sort.java: -------------------------------------------------------------------------------- 1 | // how to implement merge sort in java? 2 | 3 | class MergeSort 4 | { 5 | // Merges two subarrays of arr[]. 6 | // First subarray is arr[l..m] 7 | // Second subarray is arr[m+1..r] 8 | void merge(int arr[], int l, int m, int r) 9 | { 10 | // Find sizes of two subarrays to be merged 11 | int n1 = m - l + 1; 12 | int n2 = r - m; 13 | 14 | /* Create temp arrays */ 15 | int L[] = new int[n1]; 16 | int R[] = new int[n2]; 17 | 18 | /*Copy data to temp arrays*/ 19 | for (int i = 0; i < n1; ++i) 20 | L[i] = arr[l + i]; 21 | for (int j = 0; j < n2; ++j) 22 | R[j] = arr[m + 1 + j]; 23 | 24 | /* Merge the temp arrays */ 25 | 26 | // Initial indexes of first and second subarrays 27 | int i = 0, j = 0; 28 | 29 | // Initial index of merged subarray array 30 | int k = l; 31 | while (i < n1 && j < n2) { 32 | if (L[i] <= R[j]) { 33 | arr[k] = L[i]; 34 | i++; 35 | } 36 | else { 37 | arr[k] = R[j]; 38 | j++; 39 | } 40 | k++; 41 | } 42 | 43 | /* Copy remaining elements of L[] if any */ 44 | while (i < n1) { 45 | arr[k] = L[i]; 46 | i++; 47 | k++; 48 | } 49 | 50 | /* Copy remaining elements of R[] if any */ 51 | while (j < n2) { 52 | arr[k] = R[j]; 53 | j++; 54 | k++; 55 | } 56 | } 57 | 58 | // Main function that sorts arr[l..r] using 59 | // merge() 60 | void sort(int arr[], int l, int r) 61 | { 62 | if (l < r) { 63 | // Find the middle point 64 | int m =l+ (r-l)/2; 65 | 66 | // Sort first and second halves 67 | sort(arr, l, m); 68 | sort(arr, m + 1, r); 69 | 70 | // Merge the sorted halves 71 | merge(arr, l, m, r); 72 | } 73 | } 74 | 75 | /* A utility function to print array of size n */ 76 | static void printArray(int arr[]) 77 | { 78 | int n = arr.length; 79 | for (int i = 0; i < n; ++i) 80 | System.out.print(arr[i] + " "); 81 | System.out.println(); 82 | } 83 | 84 | // Driver code 85 | public static void main(String args[]) 86 | { 87 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 88 | 89 | System.out.println("Given Array"); 90 | printArray(arr); 91 | 92 | MergeSort ob = new MergeSort(); 93 | ob.sort(arr, 0, arr.length - 1); 94 | 95 | System.out.println("\nSorted array"); 96 | printArray(arr); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /LeetCode/Max_Chunks_To_Make_Sorted_II.java: -------------------------------------------------------------------------------- 1 | 2 | //768. Max Chunks To Make Sorted II 3 | 4 | //You are given an integer array arr. 5 | 6 | //We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. 7 | 8 | //Return the largest number of chunks we can make to sort the array. 9 | 10 | 11 | //Example 1: 12 | 13 | //Input: arr = [5,4,3,2,1] 14 | //Output: 1 15 | //Explanation: 16 | //Splitting into two or more chunks will not return the required result. 17 | //For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. 18 | 19 | //Example 2: 20 | 21 | //Input: arr = [2,1,3,4,4] 22 | //Output: 4 23 | //Explanation: 24 | //We can split into two chunks, such as [2, 1], [3, 4, 4]. 25 | //However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. 26 | 27 | 28 | //Constraints: 29 | 30 | //1 <= arr.length <= 2000 31 | //0 <= arr[i] <= 108 32 | 33 | import java.util.Scanner; 34 | 35 | public class Max_Chunks_To_Make_Sorted_II { 36 | 37 | public static void main(String[] args) { 38 | Scanner sc = new Scanner(System.in); 39 | 40 | System.out.println("Enter Number of element : "); 41 | int n = sc.nextInt(); 42 | 43 | int arr[] = new int[n]; 44 | System.out.println("Enter " + n + " values :"); 45 | for (int i = 0; i < n; i++) { 46 | arr[i] = sc.nextInt(); 47 | } 48 | int ans = maxChunksToSorted2(arr); 49 | 50 | System.out.println("Maximun chunk to sorts are : " + ans); 51 | } 52 | 53 | private static int maxChunksToSorted2(int[] arr) { 54 | // generate right minimum 55 | int[] rmin = new int[arr.length + 1]; 56 | 57 | rmin[arr.length] = Integer.MAX_VALUE; 58 | for (int i = arr.length - 1; i >= 0; i--) { 59 | rmin[i] = Math.min(rmin[i + 1], arr[i]); 60 | } 61 | 62 | // iterate on array and manage left maximum as well as count chunk 63 | int lmax = Integer.MIN_VALUE; 64 | int count = 0; 65 | for (int i = 0; i < arr.length; i++) { 66 | lmax = Math.max(lmax, arr[i]); 67 | // if the left max element is less than right minimum element than left partis one of the chunk so increment count 68 | if (lmax <= rmin[i + 1]) 69 | count++; 70 | } 71 | return count; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /Number Theory/nextpermutation.java: -------------------------------------------------------------------------------- 1 | //Implement next permutation, which rearranges numbers into the lexicographically 2 | //next greater permutation of numbers. 3 | 4 | import java.util.Scanner; 5 | 6 | public class nextpermutation { 7 | 8 | //This function is used to take input and store in array 9 | public static int[] input() { 10 | System.out.println("Enter the size array:"); 11 | Scanner sc = new Scanner(System.in); 12 | int n; 13 | n = sc.nextInt(); 14 | int a[] = new int[n]; 15 | System.out.println("Enter the array: "); 16 | for (int i = 0; i < n; i++) { 17 | a[i] = sc.nextInt(); 18 | } 19 | return a; 20 | 21 | } 22 | //This function is used to print the desired output 23 | public static void print(int a[]) { 24 | System.out.println("The array: "); 25 | int n = a.length; 26 | for (int i = 0; i < n; i++) { 27 | System.out.print(a[i] + " "); 28 | } 29 | System.out.println(); 30 | } 31 | public static int[] nextPermutation(int[] nums) { 32 | int i = nums.length - 2; 33 | while (i >= 0 && nums[i + 1] <= nums[i]) { 34 | i--; 35 | } 36 | // sort from i + 1 or reverse it as you will get decreasing order from i + 1 37 | if (i >= 0) { 38 | int j = nums.length - 1; 39 | while (nums[j] <= nums[i]) { 40 | j--; 41 | } 42 | swap(nums, i, j); 43 | } 44 | reverse(nums, i + 1); 45 | return nums; 46 | } 47 | 48 | private static void reverse(int[] nums, int start) { 49 | int i = start, j = nums.length - 1; 50 | while (i < j) { 51 | swap(nums, i, j); 52 | i++; 53 | j--; 54 | } 55 | } 56 | //Actual function to swapp 57 | private static void swap(int[] nums, int i, int j) { 58 | int temp = nums[i]; 59 | nums[i] = nums[j]; 60 | nums[j] = temp; 61 | } 62 | 63 | public static void main(String[] args) { 64 | Scanner sc = new Scanner(System.in); 65 | 66 | 67 | int a[] = input(); 68 | int b[]= nextPermutation(a); 69 | print(b); 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Arrays/2D Arrays/pattern387.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1 13 3 | 2 12 14 4 | 3 11 15 5 | 4 10 16 6 | 5 9 7 | 6 8 8 | 7 9 | Print the above mentioned pattern using Java Code */ 10 | import java.util.*; 11 | class pattern387 12 | { 13 | public static void main() 14 | { 15 | int sp=0;//variable to print required number of spaces while printing values 1 to 7 16 | int sp2=11;//variable to print required number of spaces while printing values 13 to 8 17 | int h=13;//variable to print the values from 13 to 8 18 | int k=14;//variable to print the values from 14 to 16 19 | int sp3=1;//variable to print required number of spaces while printing values 14 to 16 20 | for(int i=1;i<=7;i++)//outer loop 21 | { 22 | for(int j=1;j<=sp;j++)//first inner loop to print spaces while printing values until 7 23 | { 24 | System.out.print(" "); 25 | } 26 | sp++;//number of spaces increase while printing values from 1 to 7 27 | System.out.print(i); 28 | if(i!=7)//to prevent 7 from getting printed twice 29 | { 30 | for(int j=1;j<=sp2;j++)//second inner loop to print spaces ahead of values 13 to 8 from the corresponding values in front of them Ex-b/w 1 and 13, 11 spaces are there 31 | { 32 | System.out.print(" "); 33 | } 34 | sp2=sp2-2;//spaces decrease by 2 as from 1 to 13 spaces b/w values decrease by 2 35 | System.out.print(h); 36 | h--;//to print values from 13 to 8 37 | } 38 | if(i>=2 && i<=4)//for values 14 to 16 39 | { 40 | for(int j=1;j<=sp3;j++)//third inner loop to print spaces ahead of values 14 to 16 from the corresponding values in front of them Ex-b/w 11 and 15, 2 spaces are there 41 | { 42 | System.out.print(" "); 43 | } 44 | sp3=sp3+2;//spaces increase by 2 as from 10 to 16(excluding 13) spaces b/w values increase by 2 45 | System.out.print(k); 46 | k++;//to print values from 14 to 16 47 | } 48 | System.out.println(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Sorting/semisort1.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to sort half of the array in ascending and second half in descending or vice versa depending on users choice. 3 | AD - Ascending then descending 4 | DA - Descending then ascending 5 | */ 6 | import java.io.*; 7 | import java.util.Arrays; 8 | class semisort1 9 | { 10 | static void sort(int [] ar,int ln,String styl) //A method to sort array according to the style 11 | { 12 | int x; 13 | int [] tmparr =ar.clone(); //A method to clone an array 14 | if(ln%2==0) 15 | {x=(ln/2)-1; } 16 | else 17 | {x=(ln/2);} 18 | 19 | Arrays.sort(ar,0,(x+1)); //A method to sort array in ascending order from specified start index(inclusive) 20 | Arrays.sort(tmparr,(x+1),(ln)); // to end index(exclusive) . 21 | if(styl.equals("AD")) 22 | { 23 | int c=ln-1; 24 | for(int i=(x+1);i=0;i--) 36 | { 37 | tmparr[c]=ar[i]; 38 | c++; 39 | } 40 | System.out.println(Arrays.toString(tmparr)); 41 | } 42 | } 43 | public static void main(String[] args) throws IOException 44 | { 45 | 46 | InputStreamReader inp=new InputStreamReader(System.in); 47 | BufferedReader br=new BufferedReader(inp); 48 | System.out.print("Enter Sorting style :"); 49 | 50 | String styl=br.readLine(); //A string to store the style of sorting AD or DA 51 | 52 | System.out.print("Enter the length of the array(greater than 1) and elements of the array :"); 53 | int len=Integer.parseInt(br.readLine()); //A string to store length if the array 54 | 55 | System.out.println(); 56 | 57 | int []ar=new int[len]; 58 | for(int i=0;i res = partitionLabels(s); 36 | System.out.println("\nAns : "); 37 | for (int val : res) { 38 | System.out.print(val + " "); 39 | } 40 | } 41 | 42 | private static List partitionLabels(String s) { 43 | // make hashmap 44 | HashMap map = new HashMap<>(); 45 | 46 | // take the each character and its value according to the position 47 | for (int i = 0; i < s.length(); i++) { 48 | char ch = s.charAt(i); 49 | // here ch=key , i=value 50 | map.put(ch, i); 51 | } 52 | 53 | // make the result partition array 54 | List res = new ArrayList<>(); 55 | // take previous pointer for saparate two strings 56 | int prev = -1; 57 | // take the max variable for the know the last aperance of the character 58 | int max = Integer.MIN_VALUE; 59 | 60 | for (int i = 0; i < s.length(); i++) { 61 | char ch = s.charAt(i); 62 | // maximum from the last max value and the recently max value of the character 63 | max = Math.max(max, map.get(ch)); 64 | // if the maximum is the equle to the index so there is upto one string available 65 | if (max == i) { 66 | // for know the length of the string (Max - Prev) 67 | res.add(max - prev); 68 | // update value of prev 69 | prev = max; 70 | } 71 | } 72 | return res; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /String Handling/isomorphicString.java: -------------------------------------------------------------------------------- 1 | //Question you have given two strings you have to find out that , if they are isomorphic or not; 2 | 3 | // Java program to check if two strings are isomorphic 4 | import java.io.*; 5 | import java.util.*; 6 | class Isomorphic { 7 | static int size = 256; 8 | 9 | // Function returns true if str1 and str2 are ismorphic 10 | static boolean areIsomorphic(String str1, String str2) 11 | { 12 | int m = str1.length(); 13 | int n = str2.length(); 14 | 15 | // Length of both strings must be same for one to 16 | // one corresponance 17 | if (m != n) 18 | return false; 19 | 20 | // To mark visited characters in str2 21 | Boolean[] marked = new Boolean[size]; 22 | Arrays.fill(marked, Boolean.FALSE); 23 | 24 | // To store mapping of every character from str1 to 25 | // that of str2. Initialize all entries of map as 26 | // -1. 27 | int[] map = new int[size]; 28 | Arrays.fill(map, -1); 29 | 30 | // Process all characters one by on 31 | for (int i = 0; i < n; i++) { 32 | // If current character of str1 is seen first 33 | // time in it. 34 | if (map[str1.charAt(i)] == -1) { 35 | // If current character of str2 is already 36 | // seen, one to one mapping not possible 37 | if (marked[str2.charAt(i)] == true) 38 | return false; 39 | 40 | // Mark current character of str2 as visited 41 | marked[str2.charAt(i)] = true; 42 | 43 | // Store mapping of current characters 44 | map[str1.charAt(i)] = str2.charAt(i); 45 | } 46 | 47 | // If this is not first appearance of current 48 | // character in str1, then check if previous 49 | // appearance mapped to same character of str2 50 | else if (map[str1.charAt(i)] != str2.charAt(i)) 51 | return false; 52 | } 53 | 54 | return true; 55 | } 56 | // driver program 57 | public static void main(String[] args) 58 | { 59 | boolean res = areIsomorphic("aab", "xxy"); 60 | System.out.println(res); 61 | 62 | res = areIsomorphic("aab", "xyz"); 63 | System.out.println(res); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Data Structure/Trees/Binary Trees/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | // Question: 2 | // Write a Java program to identify the kth smallest element in the binary search tree where k =8. 3 | 4 | import java.util.*; 5 | import java.io.*; 6 | 7 | // initializing node class 8 | class Node { 9 | int data; 10 | Node left, right; 11 | Node(int x) // Node contructor 12 | { 13 | data = x; 14 | left = right = null; 15 | } 16 | } 17 | 18 | public class BinaryTree { 19 | 20 | static int count = 0; 21 | // insertion of element using recursion 22 | public static Node insert(Node root, int data) 23 | { 24 | if (root == null) 25 | return new Node(data); 26 | if (data < root.data) // if the data is less than node data go left 27 | root.left = insert(root.left, data); 28 | 29 | else if (data > root.data) // if data is greater than node data go right 30 | root.right = insert(root.right, data); 31 | 32 | return root; 33 | } 34 | 35 | public static Node kthSmallest(Node root, int k) 36 | { 37 | if (root == null) 38 | return null; 39 | Node left = kthSmallest(root.left, k); // at this line we go to leftmost node, so that we can start counting nth smallest from thatnode (leftmost) 40 | 41 | if (left != null) 42 | return left; 43 | count++; 44 | 45 | if (count == k) // if we find the element at k return k; 46 | return root; 47 | 48 | return kthSmallest(root.right, k); 49 | } 50 | 51 | public static void printKthSmallest(Node root, int k) 52 | { 53 | count = 0; 54 | Node res = kthSmallest(root, k); // get the smallest element 55 | 56 | if (res == null) 57 | System.out.println("can't print as k is greater than nodes"); 58 | else 59 | System.out.println(k+"-th Smallest Element is " + res.data); 60 | } 61 | 62 | public static void main (String[] args) { 63 | Scanner take = new Scanner(System.in); 64 | Node root = null; // initialising root node 65 | 66 | System.out.print("enter number of elements in the list: "); 67 | int size = take.nextInt(); 68 | 69 | while(size-- !=0) 70 | root = insert(root, take.nextInt()); // calling insert method to insert the element in the tree 71 | System.out.print("enter k: "); 72 | int k = take.nextInt(); 73 | printKthSmallest(root, k); //calling this function to find the kth smallest element 74 | 75 | 76 | } 77 | } 78 | --------------------------------------------------------------------------------