├── DP ├── test ├── Derangements.java ├── FriendsPairingProblem.java ├── CustomSorting.java ├── CountSquareSubmatricesWithAllOnes.java ├── MinimumPathSum.java ├── Knapsack.java ├── UnboundKnapsack.java ├── PartitionEqualSubsetSum.java ├── TargetSum.java ├── BishalClimbingStairs.java ├── CoinChangeMinCoins.java ├── RussianDollEnvelopes.java ├── PrintLongestCommonSubstring.java ├── FibonacciDP.java ├── LongestPalindromicSubsequence.java ├── LargestDivisibleSubset.java ├── MinimumInsertionsToMakePalindrome.java └── LongestBitonicArray.java ├── Graphs ├── test ├── KeysAndRooms.java ├── NumberOfProvinces.java └── TopologicalSort.java ├── Heaps ├── test ├── NearlySortedArray.java ├── KthSmallestElement.java ├── PriorityQueueSTL.java ├── BSTToSpecialMaxHeap.java ├── CustomComparator.java ├── IsBinaryTreeMaxHeap.java ├── KClosestPointsToOrigin.java ├── MedianInDataStream.java └── TopKFrequentElements.java ├── Stacks ├── sample ├── NextGreaterElement2.java ├── VisiblePeopleInQueue.java ├── RemoveNodesFromLinkedList.java ├── NextGreaterElement.java ├── BaseBallGame.java ├── BasicSTLOfStacks.java ├── BalancedBrackets.java ├── PushAtBottom.java ├── CelebrityProblem.java └── LargestRectangleInHistogram.java ├── 2D_Arrays ├── hi ├── sum2D.java ├── Transpose.java ├── SearchInRowColSortedMatrix.java ├── MatrixMultiplication.java ├── SnakePrint.java ├── Representation.java ├── InstantInitialise.java ├── RotateMatrix.java ├── ArrayListMulti.java ├── PascalTriangle.java └── SpiralMatrix.java ├── Arrays ├── Nothing ├── WaveArray.java ├── MissingInArray.java ├── TwoSumGFG.java ├── PassingArrayToMethods.java ├── ForEach.java ├── SegregateZerosAndOnes.java ├── ArrayOfOtherDataTypes.java ├── TwoSum.java ├── SortArrayBuiltIn.java ├── ArrayBasics.java ├── RotateArray.java ├── SumAndMax.java ├── ProductOfArray.java ├── PrintNegative.java ├── SecondMax.java ├── LinearSearch.java ├── AddOne.java ├── ReverseArray.java ├── ShallowCopyDeepCopy.java ├── MergeTwoSortedArrays.java └── OutputInputArray.java ├── Backtracking ├── test ├── RatInAMaze.java └── RatInAMazeObstacles.java ├── LinkedList ├── test ├── DeleteNodeInALinkedList.java ├── CircularLLTraversal.java ├── RemoveDuplicatesFromASortedLinkedList.java ├── KthFromEndOfList.java ├── OddEvenLinkedListLeetcode.java ├── SwappingNodesInALinkedList.java ├── MergeTwoSortedLists.java ├── PartitionListLeetcode.java ├── MiddleOfLinkedList.java ├── NodeOfLinkedList.java ├── FlattenADoublyLL.java ├── RemoveDuplicatesFromSortedList2.java ├── DetectLoopInLinkedList.java ├── ReverseDLL.java ├── MergeKSortedLL.java ├── RotateList.java ├── IntersectionOfTwoLinkedLists.java ├── SortList.java ├── ReverseLinkedList.java └── CritialPointsDistance.java ├── Maps&Sets ├── testFile ├── CountDistinctElements.java ├── TwoSum.java ├── CountEqualPairs.java ├── PairsWithDifferenceK.java ├── Anagram.java ├── Maps_STL.java ├── LongestNonRepeatingSubstring.java ├── MostFrequentChar.java ├── MissingElementsInRange.java ├── Sets_STL.java ├── CopyListWithRandomPointer.java ├── CountPairsWithSumDivisibleByK.java └── ArraySubset.java ├── OOPS ├── test.java ├── RevisionOOPS.java ├── Inheritance2.java ├── Marks.java ├── FinalAndStatic.java ├── PassingClassesToMethods.java ├── Inheritance.java ├── PrivateKeyword.java ├── Constructors.java ├── ComplexNumberClass.java ├── PolyMorphism.java └── UserDefinedDataType.java ├── Queues ├── testfile ├── LLImplementationOfQueue.java ├── BasicSTLOfQueues.java ├── ReverseQueue.java ├── WinnerOfCircularGame.java ├── FirstNegetiveInEveryWindow.java ├── RearrangeQueue.java ├── MyQueue.java └── StackFromQueue.java ├── SpecialAlgos ├── test ├── MaximumSubarraySum.java ├── MajorityElement.java ├── MaximumProductSubarray.java └── SortZerosOnesTwos.java ├── Bit_Manipulation ├── test ├── CheckKthBit.java ├── SetKthBit.java ├── NumberOfSetBits.java ├── TwoKiPower.java ├── DataTypes.java ├── PowerOfFour.java ├── SingleNumber.java ├── BitwiseAndOrXor.java ├── Subsets.java ├── TwoSingleNumbers.java ├── PowerOfTwo.java └── ScoreAfterFlippingMatrix.java ├── Methods ├── MaxOfTwo.java ├── ReturnIsMandatory.java ├── PassByValueAndReference.java ├── Arguments.java ├── ReturnType.java ├── MaxOfThreeBuiltIn.java ├── Syntax.java ├── Swap.java ├── BuiltIn.java └── PermutationAndCombination.java ├── Recursion ├── GCD.java ├── SumUptoN.java ├── Factorial.java ├── nThStair.java ├── Fibonacci.java ├── PowerOfNumbers.java ├── Reverse.java ├── GlobalVariables.java ├── PreInPost.java ├── BinarySearchRecursive.java ├── PowerSet.java ├── UniquePaths.java ├── PrintSubsets.java ├── RecursionOnArrays.java ├── Power.java ├── TowerOfHanoi.java ├── StringsBasicsMore.java ├── InversionCount.java └── OneToN.java ├── Pattern_Printing ├── Test.java ├── StarSquare.java ├── FloydTriangle.java ├── OddTriangle.java ├── StarTriangle.java ├── StarRectangle.java ├── StarTriangleHorFlipped.java ├── Zoom.java ├── AlphabetSmallCapitalSquare.java ├── HollowRectangle.java ├── Pyramid.java ├── Bridge.java ├── TriangleFlippedVertically.java ├── NumberStarVertical.java └── Diamond.java ├── Loops ├── LimitsOfInt.java ├── asciiiiii.java ├── Continue.java ├── basicLoop.java ├── FactorialLoop.java ├── AP.java ├── ReverseNumber.java ├── CountDigits.java ├── SumOfDigits.java ├── PowerLoop.java ├── WhileLoop.java ├── CompositeNumber.java └── evenHundred.java ├── Basic_Cheeze ├── DivisionOfDataTypes.java ├── IncrementDecrement.java ├── PrintingNumbers.java ├── HelloYashikaaaa.java ├── VariableNaming.java ├── SI.java ├── arithmeticOperationsOnInt.java ├── AreaOfCircle.java ├── SumofTwo.java ├── VariablesBasics.java └── CharDataType.java ├── If_Else ├── RelationalOperators.java ├── AbsoluteValue.java ├── ternaryInVariable.java ├── Oddeven.java ├── IsInteger.java ├── ternaryBasic.java ├── StudentsCode.java ├── SidesOfATriangle.java ├── FourDigitNumber.java ├── ProfitLoss.java └── GreatestOfThree.java ├── BST ├── SearchInBST.java ├── LCAinBST.java ├── NodesInARange.java ├── MinMaxInBST.java ├── InsertInBST.java ├── kThSmallestInBST.java ├── SortedArrayToBalancedBST.java ├── FlattenABTToLLMorris.java ├── IsBST.java ├── DeleteNodeInBST.java ├── MorrisInorder.java ├── BST_To_GST.java └── LargestBSTInBT.java ├── Basic Sorting ├── CheckIfArrayIsSorted.java ├── TwoSumSorted.java ├── SelectionSort.java ├── PushZerosToEnd.java ├── BubbleSort.java └── kthSmallest.java ├── Strings ├── PalindromeString.java ├── CountDigits.java ├── PassingStringToMethod.java ├── StringBasics.java ├── StringToCharArray.java ├── IntToString.java ├── SubStringsOfString.java ├── Anagram.java ├── CompareToStringMethod.java ├── NumberOfVowels.java ├── BuiltInMethods.java ├── Plus.java ├── ReverseSb.java ├── InterningNew.java └── StringBuilders.java ├── BinaryTrees ├── LCA.java ├── SameTree.java ├── PathSum.java ├── PreorderIterative.java ├── Diameter.java ├── RightView.java ├── PostorderIterative.java ├── BalancedTree.java ├── InvertTree.java ├── SymmetricTree.java ├── RootToLeafPaths.java ├── InorderIterative.java ├── PathSum3.java ├── MinDistanceBw2Nodes.java ├── ConstructTreeFromPreAndIn.java └── FlattenTreeToLL.java ├── BinarySearch ├── sqrt.java ├── Binary_Search.java ├── FloorInSortedArray.java ├── KthMissingPositiveNumber.java ├── PeakInMountainArray.java ├── FirstOccurence.java ├── SearchInASortedMatrix.java ├── RotatedSortedArray.java ├── SingleAmongDoubles.java ├── KokoEatingBananas.java ├── FirstAndLastOccurences.java ├── ArrangeCoins.java └── CapacityToShipPackagesWithinDDays.java └── Cyclic_Sort ├── MissingInArray.java ├── ArrayDuplicates.java └── FirstMissingPositive.java /DP/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Graphs/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Heaps/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Stacks/sample: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /2D_Arrays/hi: -------------------------------------------------------------------------------- 1 | hi 2 | -------------------------------------------------------------------------------- /Arrays/Nothing: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Backtracking/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LinkedList/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Maps&Sets/testFile: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /OOPS/test.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Queues/testfile: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SpecialAlgos/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Bit_Manipulation/test: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Methods/MaxOfTwo.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | 3 | public class MaxOfTwo { 4 | public static void main(String[] args) { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Bit_Manipulation/CheckKthBit.java: -------------------------------------------------------------------------------- 1 | class CheckBit { 2 | static boolean checkKthBit(int n, int k) { 3 | return ((n>>k) % 2 == 1); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Recursion/GCD.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int gcd(int a, int b) { 3 | if(a==0) return b; 4 | return gcd(b%a,a); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Bit_Manipulation/SetKthBit.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int setKthBit(int n, int k) { 3 | int mask = (1<3); 6 | System.out.println(x); 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Loops/asciiiiii.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | 3 | public class asciiiiii { 4 | public static void main(String[] args) { 5 | for(int i=65;i<=90;i++){ 6 | System.out.println((char)i + " " + i); 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Basic_Cheeze/IncrementDecrement.java: -------------------------------------------------------------------------------- 1 | package Basic_Cheeze; 2 | 3 | public class IncrementDecrement { 4 | public static void main(String[] args) { 5 | int x = 10; 6 | int y = ++x; 7 | System.out.println(x+" "+y); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Basic_Cheeze/PrintingNumbers.java: -------------------------------------------------------------------------------- 1 | package Basic_Cheeze; 2 | 3 | public class PrintingNumbers { 4 | public static void main(String[] args) { 5 | System.out.println(69+1); // ye number hai 6 | System.out.println("69+1"); // ye text hai 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Bit_Manipulation/NumberOfSetBits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int setBits(int n) { 3 | int count = 0; 4 | for(int i=0;i<31;i++){ // O(31) 5 | if((n>>i)%2 != 0) count++; 6 | } 7 | return count; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Arrays/WaveArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static void convertToWave(int[] arr) { 3 | for(int i=1;i x) return search(root.left,x); 6 | else return search(root.right,x); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Basic Sorting/CheckIfArrayIsSorted.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean arraySortedOrNot(int[] arr) { 3 | // code here 4 | for(int i=0;iarr[i+1]) return false; 6 | } 7 | return true; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LinkedList/CircularLLTraversal.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void printList(Node head) { 3 | Node temp = head; 4 | while(temp.next!=head){ 5 | System.out.print(temp.data+" "); 6 | temp = temp.next; 7 | } 8 | System.out.print(temp.data+" "); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Loops/Continue.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | 3 | public class Continue { 4 | public static void main(String[] args) { 5 | for(int i=1;i<=20;i++){ 6 | System.out.println(i); 7 | if(i==13) continue; 8 | System.out.println("Good Morning"); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Loops/basicLoop.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | 3 | public class basicLoop { 4 | public static void main(String[] args) { 5 | int i; 6 | for(i=1;i<=8;i++){ 7 | System.out.print(i+" "); 8 | } 9 | System.out.println(); 10 | System.out.println(i); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Strings/PalindromeString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean isPalindrome(String s) { 3 | int i = 0, j = s.length()-1; 4 | while(i<=j){ 5 | if(s.charAt(i)!=s.charAt(j)) return false; 6 | i++; 7 | j--; 8 | } 9 | return true; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Bit_Manipulation/TwoKiPower.java: -------------------------------------------------------------------------------- 1 | package BitManipulation; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TwoKiPower { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | System.out.println(1< , . / ? 7 | int xy = 3; 8 | int raghav = 5; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /2D_Arrays/sum2D.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int sumOfMatrix(int n, int m, int[][] arr) { 3 | // code here 4 | int sum = 0; 5 | for(int i=0;i set = new HashSet<>(); 8 | for(int ele : arr) set.add(ele); 9 | return set.size(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /2D_Arrays/Transpose.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void transpose(int n, int arr[][]) { 3 | for(int i=0;i p.data && root.data > q.data) 4 | return LCA(root.left,p,q); 5 | else if(root.data < p.data && root.data < q.data) 6 | return LCA(root.right,p,q); 7 | else return root; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Bit_Manipulation/DataTypes.java: -------------------------------------------------------------------------------- 1 | package BitManipulation; 2 | 3 | public class DataTypes { 4 | public static void main(String[] args) { 5 | byte x = 127; 6 | x += 3; 7 | System.out.println(x); 8 | 9 | int y = Integer.MAX_VALUE; 10 | y += 10; 11 | System.out.println(y); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Strings/CountDigits.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CountDigits { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | double n = sc.nextDouble(); 9 | String s = "" + n; 10 | System.out.println(s.length()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Basic_Cheeze/SI.java: -------------------------------------------------------------------------------- 1 | package Basic_Cheeze; 2 | 3 | import java.util.Scanner; 4 | 5 | public class SI { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | 9 | int p = 69, r = 5, t = 8; 10 | double si = p*r*t/100.0; // 27.6 11 | System.out.println(si); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Methods/ReturnIsMandatory.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | 3 | public class ReturnIsMandatory { 4 | public static void main(String[] args) { 5 | System.out.println(ananya(3)); 6 | } 7 | public static int ananya(int a) { 8 | if(a < 5) { 9 | return a; 10 | } 11 | return -9; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Arrays/MissingInArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int missingNum(int arr[]) { 3 | long n = arr.length + 1; // 1 to n tak numbers honge arr me 4 | long sum = n*(n+1)/2; 5 | long arraySum = 0; 6 | for(int ele : arr){ 7 | arraySum += ele; 8 | } 9 | return (int)(sum - arraySum); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Arrays/TwoSumGFG.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean twoSum(int arr[], int target) { 3 | int n = arr.length; 4 | for(int i=0;i=b && a>=c) return a; 6 | else if(b>=a && b>=c) return b; 7 | else return c; 8 | } 9 | public static void main(String[] args) { 10 | System.out.println(max(4,2,9)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Recursion/PowerOfNumbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int pow(int a, int b) { 3 | if(b==0) return 1; 4 | int call = pow(a,b/2); 5 | if(b%2 == 0) return call*call; 6 | else return call*call*a; 7 | } 8 | public int reverseExponentiation(int n) { 9 | if(n==10) return 10; 10 | return pow(n,n); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Strings/PassingStringToMethod.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class PassingStringToMethod { 4 | public static void change(String x){ 5 | x = "Utkarsh"; 6 | } 7 | public static void main(String[] args) { 8 | String x = "raghav"; 9 | System.out.println(x); 10 | change(x); 11 | System.out.println(x); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Strings/StringBasics.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StringBasics { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | String s = sc.nextLine(); 9 | System.out.println(s); 10 | String t = sc.next(); 11 | System.out.println(t); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Arrays/PassingArrayToMethods.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | public class PassingArrayToMethods { 4 | public static void main(String[] args) { 5 | int x[] = {10,3,29,38}; 6 | System.out.println(x[2]); 7 | change(x); 8 | System.out.println(x[2]); 9 | } 10 | public static void change(int[] y) { 11 | y[2] = 99; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /BinaryTrees/LCA.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node lca(Node root, int p, int q) { // TC = O(n) 3 | if(root==null) return null; 4 | if(root.data==p || root.data==q) return root; 5 | Node l = lca(root.left,p,q); 6 | Node r = lca(root.right,p,q); 7 | if(l!=null && r!=null) return root; 8 | return (l==null) ? r : l; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Basic_Cheeze/arithmeticOperationsOnInt.java: -------------------------------------------------------------------------------- 1 | package Basic_Cheeze; 2 | 3 | public class arithmeticOperationsOnInt { 4 | public static void main(String[] args) { 5 | double x = 50; 6 | double y = 8; 7 | System.out.println(x+y); 8 | System.out.println(x-y); 9 | System.out.println(x*y); 10 | System.out.println(x/y); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Bit_Manipulation/PowerOfFour.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean isPowerofTwo(long n) { 3 | return ((n & (n-1))==0); 4 | } 5 | boolean isSquare(long n) { 6 | long root = (long)(Math.sqrt(n)); 7 | return (root*root == n); 8 | } 9 | int isPowerOfFour(long n) { 10 | return (isPowerofTwo(n) && isSquare(n)) ? 1 : 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Bit_Manipulation/SingleNumber.java: -------------------------------------------------------------------------------- 1 | package BitManipulation; 2 | 3 | public class SingleNumber { 4 | class Solution { 5 | int getSingle(int arr[]) { 6 | // 1 1 1 1 2 2 3 3 3 7 | int xor = 0; 8 | for(int ele : arr){ 9 | xor = xor ^ ele; 10 | } 11 | return xor; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /If_Else/AbsoluteValue.java: -------------------------------------------------------------------------------- 1 | package If_Else; 2 | import java.util.Scanner; 3 | public class AbsoluteValue { 4 | public static void main(String[] args) { 5 | Scanner sb = new Scanner(System.in); 6 | System.out.print("Enter Number: "); 7 | int n = sb.nextInt(); 8 | if(n < 0) n = -n; 9 | System.out.println(n); 10 | 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /BST/NodesInARange.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int getCount(Node root, int l, int h) { 3 | if(root==null) return 0; 4 | if(root.data < l) return getCount(root.right,l,h); 5 | else if(root.data > h) return getCount(root.left,l,h); 6 | else // l <= root.data <= h 7 | return 1 + getCount(root.left,l,h) + getCount(root.right,l,h); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /BinarySearch/sqrt.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int n) { 3 | if(n==0) return 0; 4 | int lo = 1, hi = n; 5 | while(lo<=hi){ 6 | int mid = lo + (hi-lo)/2; 7 | if(mid == n/mid) return mid; 8 | else if(mid > n/mid) hi = mid - 1; 9 | else lo = mid + 1; 10 | } 11 | return hi; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Loops/FactorialLoop.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | import java.util.Scanner; 3 | public class FactorialLoop { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | int fact = 1; 8 | for(int i=1;i<=n;i++){ 9 | fact *= i; 10 | } 11 | System.out.println(fact); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /2D_Arrays/SearchInRowColSortedMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static boolean matSearch(int arr[][], int x) { 3 | int m = arr.length, n = arr[0].length; 4 | int i=0, j=n-1; 5 | while(i=0){ 6 | if(arr[i][j]==x) return true; 7 | else if(arr[i][j]tar) hi = mid - 1; 7 | else if(arr[mid]=0) ? 100 : 0; 10 | 11 | System.out.println(prasun); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Strings/StringToCharArray.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class StringToCharArray { 4 | public static void main(String[] args) { 5 | String s = "Ruhan"; 6 | char[] arr = s.toCharArray(); 7 | for(char ch : arr){ 8 | System.out.println(ch); 9 | } 10 | // isTareekeKoHumCamelCaseKehteHai 11 | // IsWayKoPascalCaseKehteHai 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Maps&Sets/TwoSum.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | import java.util.HashSet; 3 | public class TwoSum { 4 | boolean twoSum(int arr[], int target) { 5 | HashSet set = new HashSet<>(); 6 | for(int ele : arr){ 7 | int rem = target - ele; 8 | if(set.contains(rem)) return true; 9 | set.add(ele); 10 | } 11 | return false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Strings/IntToString.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | import java.util.Scanner; 4 | 5 | public class IntToString { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | // String s = ""; // empty string 10 | // s += n; 11 | String s = Integer.toString(n); 12 | System.out.println(s); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BinaryTrees/SameTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // 0 0 Not Same 3 | // / \ 4 | // 0 0 5 | boolean isIdentical(Node p, Node q) { 6 | if(p==null && q==null) return true; 7 | if(p==null || q==null) return false; 8 | if(p.data != q.data) return false; 9 | return isIdentical(p.left,q.left) && isIdentical(p.right,q.right); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /If_Else/Oddeven.java: -------------------------------------------------------------------------------- 1 | package If_Else; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Oddeven { 6 | public static void main(String[] args) { 7 | Scanner sb = new Scanner(System.in); 8 | System.out.print("Enter Number: "); 9 | int n = sb.nextInt(); 10 | if(n%2 == 0) System.out.println("Even Number"); 11 | if(n%2 == 1) System.out.println("Odd Number"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Loops/AP.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | 3 | import java.util.Scanner; 4 | 5 | public class AP { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | // 4,10,16,22,28... 10 | int a = 4, d = 6; 11 | for(int i=1;i<=n;i++){ 12 | System.out.print(a+" "); 13 | a += d; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2D_Arrays/MatrixMultiplication.java: -------------------------------------------------------------------------------- 1 | class GfG { 2 | public static void multiply(int a[][], int b[][], int c[][], int n) { 3 | for(int i=0;i0) return 5; // khatam 7 | else return 10; 8 | } 9 | public static void main(String[] args) { 10 | int x = prasun(7); 11 | System.out.println(3+x); 12 | //prasun(); // stand alone call lagayi bas 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Strings/SubStringsOfString.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class SubStringsOfString { 4 | public static void main(String[] args) { 5 | String s = "bhakti"; 6 | for(int i=0;i key){ // LST me attach karke aao 8 | root.left = insert(root.left,key); 9 | } 10 | return root; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LinkedList/RemoveDuplicatesFromASortedLinkedList.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node removeDuplicates(Node head) { 3 | Node i = head; 4 | Node j = head; 5 | while(j != null){ 6 | if(i.data == j.data) j = j.next; 7 | else{ 8 | i.next = j; 9 | i = j; 10 | } 11 | } 12 | i.next = j; 13 | return head; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Loops/ReverseNumber.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | import java.util.Scanner; 3 | public class ReverseNumber { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | int r = 0; 8 | while(n != 0){ 9 | r *= 10; 10 | r += (n%10); 11 | n /= 10; 12 | } 13 | System.out.println(r); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Loops/CountDigits.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | import java.util.Scanner; 3 | public class CountDigits { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | if(n==0) n = 9; 8 | int count = 0; 9 | while(n != 0){ 10 | n /= 10; 11 | count++; 12 | } 13 | System.out.println(count); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Loops/SumOfDigits.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | import java.util.Scanner; 3 | public class SumOfDigits { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | if(n<0) n = -n; 8 | int sum = 0; 9 | while(n != 0){ 10 | sum += (n%10); 11 | n /= 10; 12 | } 13 | System.out.println(sum); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /SpecialAlgos/MaximumSubarraySum.java: -------------------------------------------------------------------------------- 1 | package SpecialAlgos; 2 | 3 | public class MaximumSubarraySum { 4 | int maxSubarraySum(int[] arr) { 5 | // [2, 3, -8, 7, -1, 2, 3] 6 | int sum = 0, maxSum = Integer.MIN_VALUE; 7 | for(int ele : arr){ 8 | sum += ele; 9 | maxSum = Math.max(maxSum,sum); 10 | if(sum<0) sum = 0; 11 | } 12 | return maxSum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Basic Sorting/TwoSumSorted.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean twoSum(int arr[], int target) { 3 | Arrays.sort(arr); // time = nlogn , space = n 4 | int i=0,j=arr.length-1; 5 | while(itarget) j--; 8 | else if(arr[i]+arr[j]tar) hi = mid - 1; 7 | else{ // arr[mid] <= x 8 | idx = mid; 9 | lo = mid + 1; 10 | } 11 | } 12 | return idx; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BinaryTrees/PathSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean hasPathSum(TreeNode root, int targetSum) { 3 | if(root==null) return false; 4 | if(root.left==null && root.right==null){ // finish the path at leaf 5 | if(targetSum==root.val) return true; 6 | else return false; 7 | } 8 | return hasPathSum(root.left,targetSum-root.val) || hasPathSum(root.right,targetSum-root.val); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Loops/PowerLoop.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | import java.util.Scanner; 3 | public class PowerLoop { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int a = sc.nextInt(); 7 | int b = sc.nextInt(); 8 | int pow = 1; 9 | for(int i=1;i<=b;i++){ 10 | pow *= a; 11 | } 12 | System.out.println(a+" raised to the power "+b+" is "+pow); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Basic Sorting/PushZerosToEnd.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void pushZerosToEnd(int[] arr) { 3 | int n=arr.length; 4 | int j=0; 5 | for(int i=0;i=k) hi = mid - 1; 9 | else lo = mid + 1; 10 | } 11 | return hi + 1 + k; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Methods/MaxOfThreeBuiltIn.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class MaxOfThreeBuiltIn { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.print("Enter the numbers : "); 9 | int a = sc.nextInt(); 10 | int b = sc.nextInt(); 11 | int c = sc.nextInt(); 12 | System.out.println(Math.max(Math.max(a,b),c)); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Recursion/Reverse.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | public class Reverse { 4 | public static int reverse(int n, int r){ 5 | if(n==0) return r; 6 | return reverse(n/10,r*10+n%10); 7 | } 8 | public static void main(String[] args) { 9 | int n = 6587597; 10 | // while(n!=0){ 11 | // r = r*10 + (n%10); 12 | // n = n/10; 13 | // } 14 | System.out.println(reverse(n,0)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Strings/Anagram.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static boolean areAnagrams(String s1, String s2) { 3 | if(s1.length()!=s2.length()) return false; 4 | char[] arr1 = s1.toCharArray(); 5 | char[] arr2 = s2.toCharArray(); 6 | Arrays.sort(arr1); 7 | Arrays.sort(arr2); 8 | for(int i=0;iarr[j+1]){ 6 | int temp = arr[j]; 7 | arr[j] = arr[j+1]; 8 | arr[j+1] = temp; 9 | swaps++; 10 | } 11 | } 12 | if(swaps==0) break; 13 | } 14 | -------------------------------------------------------------------------------- /Pattern_Printing/StarSquare.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StarSquare { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | for(int i=1;i<=n;i++){ 10 | for(int j=1;j<=n;j++){ 11 | System.out.print("*"+" "); 12 | } 13 | System.out.println(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Strings/CompareToStringMethod.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class CompareToStringMethod { 4 | public static int compareTo(String a, String b){ 5 | 6 | return -1; 7 | } 8 | public static void main(String[] args) { 9 | String a = "gitanjali"; 10 | String b = "priya"; 11 | // a = a.concat(b); 12 | a = a + b; 13 | System.out.println(a); 14 | //System.out.println(compareTo(a,b)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Strings/NumberOfVowels.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class NumberOfVowels { 4 | public static void main(String[] args) { 5 | String s = "rtyoytoreyoruytopayrropuopiaesaefxnlfn"; 6 | int count = 0; 7 | for(int i=0;ihi) return null; 8 | int mid = (lo+hi)/2; 9 | Node root = new Node(arr[mid]); 10 | root.left = convert(arr,lo,mid-1); 11 | root.right = convert(arr,mid+1,hi); 12 | return root; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Bit_Manipulation/BitwiseAndOrXor.java: -------------------------------------------------------------------------------- 1 | package BitManipulation; 2 | 3 | public class BitwiseAndOrXor { 4 | public static void main(String[] args) { 5 | System.out.println(51&42); 6 | System.out.println(51|42); 7 | 8 | int x = 5; 9 | System.out.println(~x); // 1s complement 10 | System.out.println(-x-1); // 1s complement 11 | System.out.println(~x+1); // 2s complement 12 | System.out.println(-x); // 2s complement 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LinkedList/KthFromEndOfList.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int getKthFromLast(Node head, int k) { 3 | Node slow = head; 4 | Node fast = head; 5 | // fast ko k steps aage le jaao 6 | for(int i=1;i<=k;i++){ 7 | if(fast==null) return -1; 8 | fast = fast.next; 9 | } 10 | while(fast!=null){ 11 | slow = slow.next; 12 | fast = fast.next; 13 | } 14 | return slow.data; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Methods/Syntax.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | public class Syntax { 3 | 4 | public static void main(String[] args) { 5 | rishika(); 6 | } 7 | public static void rishika(){ 8 | System.out.println("archit"); 9 | ishan(); 10 | } 11 | public static void ishan(){ 12 | System.out.println("lakshay"); 13 | varad(); 14 | } 15 | public static void varad(){ 16 | System.out.println("malini"); 17 | rishika(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Arrays/TwoSum.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | public class TwoSum { 4 | public static void main(String[] args) { 5 | System.out.println("Two Sum"); 6 | } 7 | public static boolean twoSum(int arr[], int target) { 8 | int n = arr.length; 9 | for(int i=0;iarr[mid-1] && arr[mid]>arr[mid+1]) return mid; 7 | else if(arr[mid]>arr[mid-1] && arr[mid] preorder(Node root) { 3 | ArrayList ans = new ArrayList<>(); 4 | Stack st = new Stack<>(); 5 | st.push(root); 6 | while(st.size()>0){ 7 | Node top = st.pop(); 8 | ans.add(top.data); 9 | if(top.right!=null) st.push(top.right); 10 | if(top.left!=null) st.push(top.left); 11 | } 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Pattern_Printing/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class FloydTriangle { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | int a = 1; 10 | for(int i=1;i<=n;i++){ 11 | for(int j=1;j<=i;j++){ 12 | System.out.print(a++ +" "); 13 | } 14 | System.out.println(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /BinaryTrees/Diameter.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int max; 3 | int diameter(Node root) { 4 | max = 0; 5 | levels(root); 6 | return max; 7 | } 8 | int levels(Node root) { // kaam ki cheez 9 | if(root==null) return 0; 10 | int leftLevels = levels(root.left); 11 | int rightLevels = levels(root.right); 12 | max = Math.max(max,leftLevels + rightLevels); // extra 13 | return 1 + Math.max(leftLevels,rightLevels); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Pattern_Printing/OddTriangle.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | import java.util.Scanner; 3 | public class OddTriangle { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | for(int i=1;i<=n;i++){ 8 | int a = 1; 9 | for(int j=1;j<=i;j++){ 10 | System.out.print(a+" "); 11 | a += 2; 12 | } 13 | System.out.println(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Heaps/NearlySortedArray.java: -------------------------------------------------------------------------------- 1 | package Heaps; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class NearlySortedArray { 6 | public void nearlySorted(int[] arr, int k) { 7 | // TC = O(nlogk) AS = O(k) 8 | int idx = 0; 9 | PriorityQueue pq = new PriorityQueue<>(); 10 | for(int ele : arr){ 11 | pq.add(ele); 12 | if(pq.size()>k) arr[idx++] = pq.remove(); 13 | } 14 | while(pq.size()>0) arr[idx++] = pq.remove(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /If_Else/ternaryBasic.java: -------------------------------------------------------------------------------- 1 | package If_Else; 2 | import java.util.Scanner; 3 | public class ternaryBasic { 4 | public static void main(String[] args) { 5 | Scanner sb = new Scanner(System.in); 6 | System.out.print("Enter Number: "); 7 | int n = sb.nextInt(); 8 | 9 | // if(n%2 == 0) System.out.println("Even"); 10 | // else System.out.println("Odd"); 11 | // condition ? sach : jhoot 12 | System.out.println((n%2==0) ? "Even" : "Odd"); 13 | 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /BinaryTrees/RightView.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList rightView(Node root) { 3 | ArrayList ans = new ArrayList<>(); 4 | view(root,0,ans); 5 | return ans; 6 | } 7 | 8 | private void view(Node root, int level, ArrayList ans) { 9 | if(root==null) return; 10 | if(level>=ans.size()) ans.add(root.data); 11 | else ans.set(level,root.data); 12 | view(root.left,level+1,ans); 13 | view(root.right,level+1,ans); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Methods/Swap.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Swap { 6 | public static void swap(int a, int b){ 7 | int temp = a; 8 | a = b; 9 | b = temp; 10 | } 11 | public static void main(String[] args) { 12 | Scanner sc = new Scanner(System.in); 13 | int a = sc.nextInt(); 14 | int b = sc.nextInt(); 15 | 16 | System.out.println(a+" "+b); 17 | swap(a,b); 18 | System.out.println(a+" "+b); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Recursion/PreInPost.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | public class PreInPost { 4 | public static void main(String[] args) { 5 | pip(3); 6 | } 7 | public static void pip(int n){ 8 | if(n==0) return; 9 | System.out.print("Pre "+n+" "); // Pre 10 | pip(n-1); 11 | System.out.print("In "+n+" "); // In 12 | pip(n-1); 13 | System.out.print("Post "+n+" "); // Post 14 | } 15 | // 2 1 1 1 2 1 1 1 2 16 | // 3 2 1 1 1 2 1 1 1 2 3 2 1 1 1 2 1 1 1 2 3 17 | } 18 | -------------------------------------------------------------------------------- /Arrays/SortArrayBuiltIn.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | import java.util.Arrays; 3 | public class SortArrayBuiltIn { 4 | public static void main(String[] args) { 5 | // sort - ascending order 6 | int[] arr = {4,1,7,5,-3,10,2}; 7 | print(arr); 8 | Arrays.sort(arr); 9 | print(arr); 10 | } 11 | public static void print(int[] arr) { 12 | for(int i=0;itar) hi = mid - 1; 8 | else if(arr[mid]hi) return -1; 4 | int mid = lo + (hi-lo)/2; 5 | if(nums[mid]==target) return mid; 6 | else if(nums[mid]>target) return helper(nums,target,lo,mid-1); 7 | else return helper(nums,target,mid+1,hi); 8 | } 9 | 10 | public int search(int[] nums, int target) { 11 | int n = nums.length; 12 | return helper(nums,target,0,n-1); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DP/CustomSorting.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | import java.util.Arrays; 4 | 5 | public class CustomSorting { 6 | public static void main(String[] args) { 7 | Integer[] arr = {3,-1,5,2,-7,4,9}; 8 | // Arrays.sort(arr); 9 | Arrays.sort(arr, (a, b) -> Math.abs(a)-Math.abs(b)); 10 | print(arr); 11 | } 12 | 13 | private static void print(Integer[] arr) { 14 | for(int ele : arr){ 15 | System.out.print(ele+" "); 16 | } 17 | System.out.println(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Queues/BasicSTLOfQueues.java: -------------------------------------------------------------------------------- 1 | package Queues; 2 | import java.util.ArrayDeque; 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | public class BasicSTLOfQueues { 6 | public static void main(String[] args) { 7 | Queue q = new LinkedList<>(); 8 | q.add(10); q.add(20); q.add(30); q.add(40); 9 | System.out.println(q+" "+q.peek()); // nakli printing 10 | q.remove(); 11 | System.out.println(q+" "+q.size()); 12 | System.out.println(q.remove()+" "+q); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BinaryTrees/PostorderIterative.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList postOrder(Node root) { 3 | ArrayList ans = new ArrayList<>(); 4 | Stack st = new Stack<>(); 5 | st.push(root); 6 | while(st.size()>0){ 7 | Node top = st.pop(); 8 | ans.add(top.data); 9 | if(top.left!=null) st.push(top.left); 10 | if(top.right!=null) st.push(top.right); 11 | } 12 | Collections.reverse(ans); 13 | return ans; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /OOPS/RevisionOOPS.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | 3 | public class RevisionOOPS { 4 | 5 | public static void main(String[] args) { 6 | Pokemon pikachu = new Pokemon("Electric",70); 7 | pikachu.type = "Fire"; 8 | // pikachu.power = 34; 9 | // Pokemon jigglypuff = new Pokemon(50,"Fairy"); 10 | // System.out.println(pikachu.getPower()); 11 | // pikachu.print(); jigglypuff.print(); 12 | Pokemon gengar = new Pokemon(); 13 | final int x = 89; // x cant be changed 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Pattern_Printing/StarTriangle.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StarTriangle { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | for(int i=1;i<=n;i++){ 10 | for(int j=1;j<=i;j++){ 11 | if((i+j)%2 == 0) System.out.print(1+" "); 12 | else System.out.print(0+" "); 13 | } 14 | System.out.println(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Arrays/ArrayBasics.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | public class ArrayBasics { 4 | public static void main(String[] args) { 5 | // int[] x = {6,19,7,69,9,171,5}; 6 | // // indexing 7 | // System.out.println(x[5]); // access 8 | // // updating elements - mutability 9 | // x[3] = 89; 10 | // System.out.println(x[3]); 11 | int[] arr = new int[4]; // 4 size ka array | 0 to 3 12 | arr[0] = 10; 13 | arr[1] = 20; 14 | arr[2] = 150; 15 | arr[3] = -8; 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Queues/ReverseQueue.java: -------------------------------------------------------------------------------- 1 | package Queues; 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | import java.util.Stack; 5 | 6 | public class ReverseQueue { 7 | public static void main(String[] args) { 8 | 9 | } 10 | public Queue reverseQueue(Queue q) { 11 | Stack st = new Stack<>(); 12 | while(q.size()>0){ 13 | st.push(q.remove()); 14 | } 15 | while(st.size()>0){ 16 | q.add(st.pop()); 17 | } 18 | return q; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Bit_Manipulation/Subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] arr) { 3 | int n = arr.length; 4 | int m = (1<> ans = new ArrayList<>(); 6 | for(int i=0;i a = new ArrayList<>(); 8 | for(int j=0;j>j)%2 == 1) a.add(arr[j]); 10 | } 11 | ans.add(a); 12 | } 13 | return ans; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Heaps/KthSmallestElement.java: -------------------------------------------------------------------------------- 1 | package Heaps; 2 | import java.util.Collections; 3 | import java.util.PriorityQueue; 4 | public class KthSmallestElement { 5 | public static int kthSmallest(int[] arr, int k) { 6 | // maxheap 7 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 8 | for(int ele : arr){ // nlogk 9 | pq.add(ele); // logk 10 | if(pq.size()>k) pq.remove(); // logk 11 | } 12 | return pq.peek(); 13 | // TC = O(nlogk) AS = O(k) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Strings/BuiltInMethods.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class BuiltInMethods { 4 | public static void main(String[] args) { 5 | String s = "harshita"; 6 | s.toUpperCase(); 7 | System.out.println(s); 8 | // System.out.println(s.contains("harsha")); 9 | // if(s.contains("arsh")) 10 | // System.out.println("happy"); 11 | // System.out.println(s.startsWith("ha")); 12 | String str = "7567854"; 13 | int n = Integer.parseInt(str); 14 | System.out.println(n+1); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Strings/Plus.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | public class Plus { 4 | public static void main(String[] args) { 5 | String s = "bhakti"; 6 | s = 10 + s; 7 | // s += " hi shakti hai"; 8 | // s += 10; 9 | // s += '\n'; 10 | // s += 'n'; 11 | System.out.println(s); 12 | System.out.println("krutika"+10+20); 13 | System.out.println(10+"vikas"+20); 14 | System.out.println(10+20+"gopi"); 15 | System.out.println('A'+"guddu"); 16 | System.out.println('A'+2+"Isha"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Pattern_Printing/StarRectangle.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StarRectangle { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int row = sc.nextInt(); 9 | int col = sc.nextInt(); 10 | for(int i=1;i<=row;i++){ // kitni lines hogi 11 | for(int j=1;j<=col;j++){ // har line me kitna print hoga 12 | System.out.print("* "); 13 | } 14 | System.out.println(); 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Methods/BuiltIn.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | 3 | public class BuiltIn { 4 | public static void main(String[] args) { 5 | // Math. wale 6 | //System.out.println(Math.sqrt(100)); 7 | //System.out.println(Math.cbrt(100)); 8 | //System.out.println(Math.floor(-7.8)); 9 | //System.out.println(Math.ceil(3.0001)); 10 | //System.out.println(Math.min(3.78,9)); 11 | //System.out.println(Math.max(2.4,2.41)); 12 | 13 | System.out.println(Math.pow(0,0)); 14 | // SAWAAL - 3 number ka maximum kaise nikale 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Pattern_Printing/StarTriangleHorFlipped.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class StarTriangleHorFlipped { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | int a = n; // no of stars to be printed in each line 10 | for(int i=1;i<=n;i++){ 11 | for(int j=1;j<=a;j++){ 12 | System.out.print("*"+" "); 13 | } 14 | a--; 15 | System.out.println(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Arrays/RotateArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to rotate an array by d elements in counter-clockwise direction. 3 | static void rotateArr(int arr[], int d) { 4 | int n = arr.length; 5 | d %= n; 6 | reverse(arr,0,d-1); 7 | reverse(arr,d,n-1); 8 | reverse(arr,0,n-1); 9 | } 10 | static void reverse(int[] arr, int i, int j){ 11 | while(i max) max = arr[i]; 16 | } 17 | System.out.println(max); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /BST/FlattenABTToLLMorris.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static void flatten(Node root) { // Morris 3 | Node curr = root; 4 | while(curr!=null){ 5 | if(curr.left!=null){ // pred nikal sakta hai 6 | Node pred = curr.left; 7 | while(pred.right!=null) pred = pred.right; 8 | pred.right = curr.right; 9 | curr.right = curr.left; 10 | curr.left = null; 11 | curr = curr.right; 12 | } 13 | else curr = curr.right; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /BinaryTrees/BalancedTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static boolean flag; 3 | public boolean isBalanced(Node root) { 4 | if(root==null) return true; 5 | flag = true; 6 | levels(root); 7 | return flag; 8 | } 9 | 10 | private int levels(Node root) { // kaam ki cheez 11 | if(root==null) return 0; 12 | int leftLevels = levels(root.left); 13 | int rightLevels = levels(root.right); 14 | if(Math.abs(leftLevels-rightLevels) > 1) flag = false; 15 | return 1 + Math.max(leftLevels,rightLevels); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Arrays/ProductOfArray.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | 4 | public class ProductOfArray { 5 | public static void main(String[] args) { 6 | // min of array 7 | int[] arr = {3,7,3,-7,8}; 8 | print(arr); 9 | for(int i=0;in) a = 2*n - i; 13 | if(j>n) b = 2*n - j; 14 | System.out.print(Math.min(a,b)+" "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Stacks/NextGreaterElement2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] nextGreaterElements(int[] arr) { 3 | int n = arr.length; 4 | int[] nge = new int[n]; 5 | Stack st = new Stack<>(); 6 | for(int i=n-1;i>=0;i--){ 7 | st.push(arr[i]); 8 | } 9 | for(int i=n-1;i>=0;i--){ 10 | while(st.size()>0 && arr[i]>=st.peek()) st.pop(); 11 | if(st.size()==0) nge[i] = -1; 12 | else nge[i] = st.peek(); 13 | st.push(arr[i]); 14 | } 15 | 16 | return nge; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Bit_Manipulation/TwoSingleNumbers.java: -------------------------------------------------------------------------------- 1 | package BitManipulation; 2 | import java.util.*; 3 | public class TwoSingleNumbers { 4 | public int[] singleNum(int[] arr) { 5 | int xor = 0; 6 | for(int ele : arr){ 7 | xor ^= ele; 8 | } 9 | int mask = (xor&(xor-1))^xor; // rightmost setbit mask of xor 10 | int b1 = 0, b2 = 0; 11 | for(int ele : arr){ 12 | if((ele&mask)!=0) b1 ^= ele; 13 | else b2 ^= ele; 14 | } 15 | int[] ans = {b1,b2}; 16 | Arrays.sort(ans); 17 | return ans; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Arrays/PrintNegative.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | import java.util.Scanner; 3 | public class PrintNegative { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter array size: "); 7 | int n = sc.nextInt(); 8 | int[] arr = new int[n]; 9 | System.out.print("Enter Array Elements: "); 10 | for(int i=0;i list) { 3 | if(idx==s.length()){ 4 | if(ans.length()!=0) list.add(ans); 5 | return; 6 | } 7 | char ch = s.charAt(idx); 8 | subsets(ans+ch,s,idx+1,list); // pick 9 | subsets(ans,s,idx+1,list); // skip 10 | } 11 | public List AllPossibleStrings(String s) { 12 | List list = new ArrayList<>(); 13 | subsets("",s,0,list); 14 | Collections.sort(list); 15 | return list; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Pattern_Printing/HollowRectangle.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class HollowRectangle { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int m = sc.nextInt(); 9 | int n = sc.nextInt(); 10 | for(int i=1;i<=m;i++){ 11 | for(int j=1;j<=n;j++){ 12 | if(i==1 || i==m || j==1 || j==n) 13 | System.out.print("* "); 14 | else System.out.print(" "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /BinarySearch/SearchInASortedMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to search a given number in row-column sorted matrix. 3 | public boolean searchMatrix(int[][] arr, int tar) { 4 | int rows = arr.length, cols = arr[0].length; 5 | int lo = 0, hi = rows*cols-1; 6 | while(lo<=hi){ 7 | int mid = (lo+hi)/2; 8 | int midRow = mid/cols, midCol = mid%cols; 9 | if(arr[midRow][midCol]==tar) return true; 10 | else if(arr[midRow][midCol]>tar) hi = mid - 1; 11 | else lo = mid + 1; 12 | } 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Maps&Sets/CountEqualPairs.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | 3 | import java.util.HashMap; 4 | 5 | public class CountEqualPairs { 6 | long equalPairs(String s) { 7 | // ananyaa = 4+4+4+4+2+2+1 8 | HashMap map = new HashMap<>(); 9 | for(int i=0;i q = new LinkedList<>(); 9 | for(int i=1;i<=n;i++){ 10 | q.add(i); 11 | } 12 | while(q.size()>1){ 13 | // k-1 elements remove and add 14 | for(int i=1;i<=k-1;i++){ 15 | q.add(q.remove()); 16 | } 17 | q.remove(); // kth will be removed 18 | } 19 | return q.peek(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Recursion/UniquePaths.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int uniquePaths(int m, int n) { 3 | if(m==1 || n==1) return 1; 4 | return uniquePaths(m-1,n) + uniquePaths(m,n-1); 5 | } 6 | 7 | // public int paths(int cr, int cc, int lr, int lc) { 8 | // if(cr==lr && cc==lc) return 1; 9 | // if(cr>lr || cc>lc) return 0; // IMPORTANT 10 | // int right = paths(cr,cc+1,lr,lc); 11 | // int down = paths(cr+1,cc,lr,lc); 12 | // return right + down; 13 | // } 14 | // public int uniquePaths(int m, int n) { 15 | // return paths(0,0,m-1,n-1); 16 | // } 17 | } 18 | -------------------------------------------------------------------------------- /Basic Sorting/kthSmallest.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int kthSmallest(int[] arr, int k) { 3 | int n = arr.length; 4 | // TC = O(n*k) 5 | for(int i=0;i1){ 8 | // if(n%2 == 1) return false; 9 | // n /= 2; 10 | // } 11 | // return true; 12 | // } 13 | // public static boolean isPowerofTwo(int n) { 14 | // if(n==0) return false; 15 | // if(n==1) return true; 16 | // if(n%2 == 1) return false; 17 | // return isPowerofTwo(n/2); 18 | // } 19 | } 20 | -------------------------------------------------------------------------------- /DP/CountSquareSubmatricesWithAllOnes.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class CountSquareSubmatricesWithAllOnes { 4 | public int countSquares(int N, int M, int arr[][]) { 5 | int count = 0; 6 | for(int i=0;ic && b+c>a && c+a>b) 14 | System.out.println("Valid Triangle"); 15 | else System.out.println("Invalid Triangle"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LinkedList/SwappingNodesInALinkedList.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode swapNodes(ListNode head, int k) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | for(int i=1;i<=k;i++){ 6 | fast = fast.next; 7 | } 8 | while(fast != null){ 9 | slow = slow.next; 10 | fast = fast.next; 11 | } 12 | fast = head; 13 | for(int i=1;i<=k-1;i++){ 14 | fast = fast.next; 15 | } 16 | int temp = fast.val; 17 | fast.val = slow.val; 18 | slow.val = temp; 19 | return head; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Methods/PermutationAndCombination.java: -------------------------------------------------------------------------------- 1 | package Methods; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PermutationAndCombination { 6 | public static int fact(int x){ 7 | int f = 1; 8 | for(int i=1;i<=x;i++){ 9 | f *= i; 10 | } 11 | return f; 12 | } 13 | public static void main(String[] args) { 14 | Scanner sc = new Scanner(System.in); 15 | int n = sc.nextInt(); 16 | int r = sc.nextInt(); 17 | 18 | int ncr = fact(n)/(fact(r)*fact(n-r)); 19 | int npr = fact(n)/fact(n-r); 20 | System.out.println(ncr+" "+npr); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Queues/FirstNegetiveInEveryWindow.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static List firstNegInt(int arr[], int k) { 3 | List ans = new ArrayList<>(); 4 | int n = arr.length; 5 | Queue q = new LinkedList<>(); 6 | for(int i=0;i0 && q.peek()0 && q.peek()<=i+k-1) ans.add(arr[q.peek()]); 13 | else ans.add(0); 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Arrays/SecondMax.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | import java.util.Arrays; 3 | public class SecondMax { 4 | public static void main(String[] args) { 5 | int[] arr = {4,10,10,8,3,8}; 6 | int max = Integer.MIN_VALUE; 7 | int smax = Integer.MIN_VALUE; 8 | // calculate max 9 | for(int i=0;imax) max = arr[i]; 11 | } 12 | // calculate second max 13 | for(int i=0;ismax && arr[i]!=max) smax = arr[i]; 15 | } 16 | System.out.println(max); 17 | System.out.println(smax); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DP/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class MinimumPathSum { 4 | public int minPathSum(int[][] grid) { 5 | int m = grid.length, n = grid[0].length; 6 | int[][] dp = new int[m][n]; 7 | for(int i=0;i999 && n<10000) 12 | // System.out.println("4 Digit Number"); 13 | // else System.out.println("Not a 4 digit no."); 14 | 15 | if(n%5 == 0 || n%3 == 0) 16 | System.out.println("Divisible by 5 or 3"); 17 | else 18 | System.out.println("Not divisible by 5 or 3"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Arrays/LinearSearch.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | public class LinearSearch { 4 | public static void main(String[] args) { 5 | int[] arr = {12,3,27,53,18,62,88,6,53}; 6 | int target = -1; 7 | int found = -789; // -789 means target array me nahi hai 8 | for(int i=0;i st = new Stack<>(); 6 | st.push(arr[n-1]); 7 | ans[n-1] = 0; 8 | for(int i=n-2;i>=0;i--){ 9 | int count = 0; 10 | while(st.size()>0 && st.peek()<=arr[i]){ 11 | count++; 12 | st.pop(); 13 | } 14 | if(st.size()>0) count++; // Very Very IMPORTANT 15 | ans[i] = count; 16 | st.push(arr[i]); 17 | } 18 | return ans; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /OOPS/Marks.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | import java.util.Arrays; 3 | public class Marks { 4 | public static class StudentData{ 5 | String name; 6 | int rno; 7 | int[] marks; 8 | StudentData(int[] s){ 9 | marks = Arrays.copyOf(s,s.length); 10 | } 11 | StudentData(int s){ 12 | marks = new int[s]; 13 | } 14 | } 15 | public static void main(String[] args) { 16 | int[] arr = {4,7,1,4,8}; 17 | StudentData s1 = new StudentData(arr); 18 | s1.marks[0] = 40; 19 | System.out.println(arr[0]); 20 | StudentData s2 = new StudentData(2); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /BinarySearch/RotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int Search(int arr[], int tar) { 3 | int lo = 0, hi = arr.length - 1; 4 | while(lo<=hi){ 5 | int mid = lo + (hi-lo)/2; 6 | if(arr[mid]==tar) return mid; 7 | else if(arr[lo]<=arr[mid]){ // lo to mid is sorted 8 | if(arr[lo]<=tar && tar addOne(int[] arr) { 4 | Vector ans = new Vector<>(); 5 | int n = arr.length; 6 | int carry = 1; 7 | for(int i=n-1;i>=0;i--){ 8 | if(arr[i]+carry <= 9){ 9 | ans.add(arr[i]+carry); 10 | carry = 0; 11 | } 12 | else{ // arr[i]+carry = 10 13 | ans.add(0); 14 | carry = 1; 15 | } 16 | } 17 | if(carry==1) ans.add(1); 18 | Collections.reverse(ans); 19 | return ans; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /2D_Arrays/SnakePrint.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to return list of integers visited in snake pattern in matrix. 3 | static ArrayList snakePattern(int arr[][]) { 4 | ArrayList ans = new ArrayList<>(); 5 | int m = arr.length, n = arr[0].length; 6 | for(int i=0;i=0;j--){ 14 | ans.add(arr[i][j]); 15 | } 16 | } 17 | } 18 | return ans; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Maps&Sets/PairsWithDifferenceK.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int countPairs(int[] arr, int k) { 3 | HashMap map = new HashMap<>(); 4 | for(int ele : arr){ 5 | map.put(ele,map.getOrDefault(ele,0)+1); 6 | } 7 | int pairs = 0; // 1 1 1 1 1 4 4 4 1 -2 -2 k=3 (1,6) (4,3) (-2,2) 8 | for(int ele : map.keySet()){ 9 | int rem1 = ele-k; 10 | int rem2 = ele+k; 11 | if(map.containsKey(rem1)) pairs += (map.get(ele))*(map.get(rem1)); 12 | if(map.containsKey(rem2)) pairs += (map.get(ele))*(map.get(rem2)); 13 | } 14 | pairs /= 2; 15 | return pairs; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Recursion/PrintSubsets.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | import java.util.*; 4 | 5 | public class PrintSubsets { 6 | public static void main(String[] args) { 7 | String s = "abc"; 8 | List list = new ArrayList<>(); 9 | subsets("",s,0,list); 10 | System.out.println(list); 11 | } 12 | 13 | private static void subsets(String ans, String s, int idx, List list) { 14 | if(idx==s.length()){ 15 | if(ans.length()!=0) list.add(ans); 16 | return; 17 | } 18 | char ch = s.charAt(idx); 19 | subsets(ans+ch,s,idx+1,list); // pick 20 | subsets(ans,s,idx+1,list); // skip 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2D_Arrays/Representation.java: -------------------------------------------------------------------------------- 1 | package MultiDimensionalArrays; 2 | 3 | public class Representation { 4 | public static void main(String[] args) { 5 | int[][] arr = new int[4][5]; // total ele - 20 6 | // rows - 0 to 3 and cols - 0 to 4 7 | arr[2][3] = 2; 8 | arr[0][0] = 7; arr[0][1] = 2; arr[0][2] = 9; arr[0][3] = 5; arr[0][4] = 4; 9 | for(int i=0;i<=3;i++){ 10 | for(int j=0;j<=4;j++){ 11 | System.out.print(arr[i][j]+" "); 12 | } 13 | System.out.println(); 14 | } 15 | System.out.println(); 16 | for(int ele : arr[2]){ 17 | System.out.print(ele+" "); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Arrays/ReverseArray.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | public class ReverseArray { 4 | public static void main(String[] args) { 5 | int[] arr = {3,19,56,9,83,18,24,85,14}; 6 | int n = arr.length; 7 | // for(int i=0;i findDuplicates(int[] arr) { 3 | ArrayList ans = new ArrayList<>(); 4 | int n = arr.length; // 1 to n 5 | int i=0; 6 | while(in) i++; 12 | else if(arr[i]==i+1) i++; // already at correct place 13 | else if(arr[i]==arr[arr[i]-1]) i++; // +ve duplicate 14 | else swap(arr,i,arr[i]-1); 15 | } 16 | for(i=0;i20->30->40->50 6 | Node a = new Node(10); // head node 7 | Node b = new Node(20); 8 | Node c = new Node(30); 9 | Node d = new Node(40); 10 | Node e = new Node(50); 11 | // Connect karenge (Link karenge) 12 | a.next = b; 13 | b.next = c; 14 | c.next = d; 15 | d.next = e; 16 | 17 | System.out.println(e.val); 18 | System.out.println(a.next.next.next.val); 19 | System.out.println(c); 20 | System.out.println(b.next); 21 | System.out.println(a.next.next); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Recursion/RecursionOnArrays.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | public class RecursionOnArrays { 4 | public static void main(String[] args) { 5 | int[] arr = {5,3,7,12,76,9,34,5}; 6 | // recPrint(arr,0); 7 | int target = 76; 8 | System.out.println(exists(arr,target,0)); 9 | } 10 | 11 | public static boolean exists(int[] arr, int target, int idx) { 12 | if(idx == arr.length) return false; 13 | if(arr[idx] == target) return true; 14 | return exists(arr,target,idx+1); 15 | } 16 | 17 | 18 | public static void recPrint(int[] arr, int idx){ 19 | if(idx == arr.length) return; 20 | recPrint(arr,idx+1); 21 | System.out.print(arr[idx]+" "); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Maps&Sets/Anagram.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | import java.util.HashMap; 3 | public class Anagram { 4 | public static boolean areAnagrams(String s1, String s2) { 5 | if(s1.length()!=s2.length()) return false; 6 | HashMap map = new HashMap<>(); 7 | for(int i=0;i st = new Stack<>(); 13 | ListNode temp = head; 14 | while(temp!=null){ 15 | while(st.size()>0 && st.peek().val < temp.val) 16 | st.pop(); 17 | st.push(temp); 18 | } 19 | while(st.size()>0){ 20 | ListNode top = st.pop(); 21 | top.next = temp; 22 | temp = top; 23 | } 24 | return temp; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LinkedList/FlattenADoublyLL.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public Node flatten(Node head) { 3 | if(head==null) return head; 4 | Node curr = head; 5 | while(curr!=null){ 6 | if(curr.child==null) curr = curr.next; 7 | else{ 8 | Node fwd = curr.next; 9 | Node c = flatten(curr.child); 10 | curr.child = null; 11 | curr.next = c; 12 | c.prev = curr; 13 | Node temp = c; 14 | while(temp.next!=null) temp = temp.next; 15 | temp.next = fwd; 16 | if(fwd!=null) fwd.prev = temp; 17 | curr = fwd; 18 | } 19 | } 20 | return head; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DP/Knapsack.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class Knapsack { 4 | static int knapsack(int capacity, int val[], int wt[]) { 5 | int n = val.length; 6 | int[][] dp = new int[n][capacity+1]; 7 | return helper(0,capacity,val,wt,dp); 8 | } 9 | // i->0 to n-1 capacity -> capacity to 0 10 | static int helper(int i, int capacity, int[] val, int[] wt, int[][] dp) { 11 | if(i==val.length) return 0; 12 | if(dp[i][capacity]!=0) return dp[i][capacity]; 13 | int skip = helper(i+1,capacity,val,wt,dp); 14 | if(capacity0 to n-1 capacity -> capacity to 0 10 | static int helper(int i, int capacity, int[] val, int[] wt, int[][] dp) { 11 | if(i==val.length) return 0; 12 | if(dp[i][capacity]!=0) return dp[i][capacity]; 13 | int skip = helper(i+1,capacity,val,wt,dp); 14 | if(capacity pq = new PriorityQueue<>(); 7 | pq.add(10); pq.add(20); pq.add(-30); 8 | System.out.println(pq.peek()); 9 | pq.add(35); 10 | System.out.println(pq.peek()); 11 | System.out.println(pq.size()); 12 | System.out.println(pq.remove()); 13 | System.out.println(pq.peek()); 14 | System.out.println(pq); 15 | 16 | pq.add(5); pq.add(8); pq.add(2); pq.add(0); 17 | pq.add(3); pq.add(1); pq.add(7); pq.add(6); 18 | 19 | for(int ele : pq){ 20 | System.out.print(ele+" "); 21 | } 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2D_Arrays/RotateMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to rotate matrix anticlockwise by 90 degrees. 3 | static void rotateby90(int arr[][]) { 4 | int n = arr.length; 5 | // transpose 6 | for(int i=0;i cp) System.out.println("Profit is "+(sp-cp)); 12 | // if(cp > sp) System.out.println("Loss is "+(cp-sp)); 13 | // if(sp == cp) System.out.println("No Profit No Loss"); 14 | 15 | if(sp > cp) System.out.println("Profit is "+(sp-cp)); 16 | else if(cp > sp) System.out.println("Loss is "+(cp-sp)); 17 | else System.out.println("No Profit No Loss"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Stacks/NextGreaterElement.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.ArrayList; 3 | import java.util.Stack; 4 | 5 | public class NextGreaterElement { 6 | public ArrayList nextLargerElement(int[] arr) { 7 | int n = arr.length; 8 | int[] nge = new int[n]; 9 | nge[n-1] = -1; 10 | Stack st = new Stack<>(); 11 | st.push(arr[n-1]); 12 | for(int i=n-2;i>=0;i--){ 13 | while(st.size()>0 && arr[i]>st.peek()) st.pop(); 14 | if(st.size()==0) nge[i] = -1; 15 | else nge[i] = st.peek(); 16 | st.push(arr[i]); 17 | } 18 | ArrayList ans = new ArrayList<>(n); 19 | for(int i=0;i=b){ 16 | if(a>=c) System.out.println(a); 17 | else // c > a 18 | System.out.println(c); 19 | } 20 | else{ // b > a 21 | if(b>=c) System.out.println(b); 22 | else // c > b 23 | System.out.println(c); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BinaryTrees/RootToLeafPaths.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static ArrayList> Paths(Node root) { 3 | ArrayList> ans = new ArrayList<>(); 4 | ArrayList arr = new ArrayList<>(); 5 | dfs(root,arr,ans); 6 | return ans; 7 | } 8 | private static void dfs(Node root, ArrayList arr, ArrayList> ans) { 9 | if(root==null) return; 10 | arr.add(root.data); 11 | if(root.left==null && root.right==null){ 12 | ArrayList list = new ArrayList<>(); 13 | list.addAll(arr); 14 | ans.add(list); 15 | } 16 | dfs(root.left,arr,ans); 17 | dfs(root.right,arr,ans); 18 | arr.remove(arr.size()-1); // backtracking 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SpecialAlgos/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package SpecialAlgos; 2 | 3 | public class MajorityElement { 4 | int majorityElement(int arr[]) { 5 | // 1 1 1 1 2 2 2 3 no majority 6 | int winner = arr[0], count = 1, n = arr.length; 7 | for(int i=1;in/2) return winner; 17 | } 18 | count = 0; // this count will store winner's count 19 | for(int ele : arr){ 20 | if(ele==winner) count++; 21 | } 22 | return (count>n/2) ? winner : -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /OOPS/FinalAndStatic.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | import java.util.*; 3 | class Cricketer{ 4 | static String country = "NZ"; 5 | int runs; 6 | String name; 7 | double avg; 8 | void print(){ 9 | System.out.println(runs+" "+name+" "+avg); 10 | } 11 | static void greet(){ 12 | System.out.println("I only believe in Jassi bhai"); 13 | } 14 | } 15 | public class FinalAndStatic { 16 | public static void main(String[] args) { 17 | Cricketer.greet(); 18 | System.out.println(Cricketer.country); 19 | // Cricketer c1 = new Cricketer(); 20 | // // c1.country = "England"; Error 21 | // Cricketer c2 = new Cricketer(); 22 | // c1.country = "India"; 23 | // System.out.println(c2.country); 24 | // c2.greet(); 25 | 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2D_Arrays/ArrayListMulti.java: -------------------------------------------------------------------------------- 1 | package MultiDimensionalArrays; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class ArrayListMulti { 6 | public static void main(String[] args) { 7 | ArrayList> arr = new ArrayList<>(); 8 | ArrayList a1 = new ArrayList<>(); 9 | a1.add(100); a1.add(210); a1.add(130); 10 | ArrayList a2 = new ArrayList<>(); 11 | a2.add(5); a2.add(63); 12 | ArrayList a3 = new ArrayList<>(); 13 | a3.add(1000); 14 | arr.add(a1); arr.add(a2); arr.add(a1); arr.add(a3); 15 | System.out.println(arr); 16 | a1.remove(a1.size()-1); 17 | a2.add(90); 18 | System.out.println(arr); 19 | 20 | arr.get(0).set(1,910); 21 | System.out.println(arr); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /OOPS/PassingClassesToMethods.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | 3 | public class PassingClassesToMethods { 4 | public static class Car{ 5 | int seats; 6 | String name; 7 | double length; 8 | String type; 9 | int torque; 10 | void print(){ 11 | System.out.println(seats+" "+name+" "+length+"m "+type+" "+torque+"nm "); 12 | } 13 | } 14 | public static void main(String[] args) { 15 | Car c = new Car(); 16 | c.length = 3.99; 17 | c.name = "Kia Sonet"; 18 | c.seats = 5; 19 | c.torque = 178; 20 | c.type = "SUV"; 21 | 22 | change(c); 23 | 24 | System.out.println(c.seats); 25 | c.print(); 26 | 27 | } 28 | 29 | private static void change(Car x) { 30 | x.seats = 4; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Arrays/MergeTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | public class MergeTwoSortedArrays { 4 | public static void main(String[] args) { 5 | int[] a = {2,5,6,9,20}; 6 | int[] b = {1,3,4,5,7,8,90}; 7 | 8 | int[] c = new int[a.length+b.length]; 9 | for(int ele : c) System.out.print(ele+" "); 10 | System.out.println(); 11 | merge(c,a,b); 12 | for(int ele : c) System.out.print(ele+" "); 13 | System.out.println(); 14 | } 15 | 16 | public static void merge(int[] c, int[] a, int[] b) { 17 | int i=0,j=0,k=0; 18 | while(i rearrangeQueue(Queue q) { 3 | Stack st = new Stack<>(); 4 | int n = q.size(); 5 | for(int i=1;i<=n/2;i++){ 6 | st.push(q.remove()); 7 | } 8 | while(st.size()>0){ 9 | q.add(st.pop()); 10 | } 11 | for(int i=1;i<=n/2;i++){ 12 | st.push(q.remove()); 13 | } 14 | 15 | // re arrangement 16 | while(st.size()>0){ 17 | q.add(st.pop()); 18 | q.add(q.remove()); 19 | } 20 | 21 | // reverse the q 22 | while(q.size()>0){ 23 | st.push(q.pop()); 24 | } 25 | while(st.size()>0){ 26 | q.add(st.pop()); 27 | } 28 | return q; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Arrays/OutputInputArray.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | 3 | import java.util.Scanner; 4 | 5 | public class OutputInputArray { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | // int[] arr = {5,-8,2,67,43,-97,6,23,89}; 9 | // int n = arr.length; // index - 0 to n-1 10 | // for(int i=0;i inOrder(Node root) { // Iterative 3 | ArrayList ans = new ArrayList<>(); 4 | Stack st = new Stack<>(); 5 | Node curr = root; 6 | while(st.size()>0 || curr!=null){ 7 | if(curr!=null){ 8 | if(curr.left!=null){ 9 | st.push(curr); 10 | curr = curr.left; 11 | } 12 | else{ 13 | ans.add(curr.data); 14 | curr = curr.right; 15 | } 16 | } 17 | else{ // curr == null 18 | Node top = st.pop(); 19 | ans.add(top.data); 20 | curr = top.right; 21 | } 22 | } 23 | return ans; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Heaps/BSTToSpecialMaxHeap.java: -------------------------------------------------------------------------------- 1 | package Heaps; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | public class BSTToSpecialMaxHeap { 5 | static int idx; 6 | public static void convertToMaxHeapUtil(Node root) { 7 | idx = 0; 8 | ArrayList in = new ArrayList<>(); 9 | inorder(root,in); 10 | postorder(root,in); 11 | } 12 | 13 | private static void postorder(Node root, ArrayList in) { 14 | if(root==null) return; 15 | postorder(root.left,in); 16 | postorder(root.right,in); 17 | root.data = in.get(idx++); 18 | } 19 | 20 | private static void inorder(Node root, ArrayList in) { 21 | if(root==null) return; 22 | inorder(root.left,in); 23 | in.add(root.data); 24 | inorder(root.right,in); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Recursion/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | public class TowerOfHanoi { 4 | public static void main(String[] args) { 5 | hanoi(5,'A','B','C'); 6 | } 7 | 8 | private static void hanoi(int n, char a, char b, char c) { 9 | if(n==0) return; 10 | hanoi(n-1,a,c,b); // n-1 disks from A to B via C 11 | System.out.println(a+"->"+c); // largest from A to C 12 | hanoi(n-1,b,a,c); // n-1 disks from B to C via A 13 | } 14 | 15 | public static void merge(int[] a, int[] b, int[] c){ 16 | int i=0,j=0,k=0; 17 | while(i al = new ArrayList<>(); 15 | al.add("Shravani"); 16 | al.add("Umang"); 17 | al.add("Ayan"); 18 | al.add("Shelly"); 19 | al.add("Riya"); 20 | System.out.println(al); 21 | change2(al); 22 | System.out.println(al); 23 | } 24 | 25 | private static void change2(List al) { 26 | al.add("Biplab"); 27 | } 28 | 29 | private static void change(String s) { 30 | s = "lavish"; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /BST/IsBST.java: -------------------------------------------------------------------------------- 1 | class Triplet{ 2 | int max; 3 | int min; 4 | boolean isBST; 5 | Triplet(int max, int min, boolean isBST){ 6 | this.max = max; 7 | this.min = min; 8 | this.isBST = isBST; 9 | } 10 | } 11 | class Solution { 12 | boolean isBST(Node root) { 13 | return maxMin(root).isBST; 14 | } 15 | Triplet maxMin(Node root){ 16 | if(root==null) return new Triplet(Integer.MIN_VALUE,Integer.MAX_VALUE,true); 17 | Triplet lst = maxMin(root.left); 18 | Triplet rst = maxMin(root.right); 19 | int max = Math.max(root.data,Math.max(lst.max,rst.max)); 20 | int min = Math.min(root.data,Math.min(lst.min,rst.min)); 21 | boolean isBST = lst.isBST && rst.isBST && (lst.max < root.data) && (rst.min > root.data); 22 | return new Triplet(max,min,isBST); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Stacks/BaseBallGame.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.Stack; 3 | public class BaseBallGame { 4 | public int calPoints(String[] arr) { 5 | int n = arr.length; 6 | Stack st = new Stack<>(); 7 | for(int i=0;i0){ 22 | sum += st.pop(); 23 | } 24 | return sum; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BinarySearch/KokoEatingBananas.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | public class KokoEatingBananas { 4 | public int kokoEat(int[] arr, int k) { 5 | int max = Integer.MIN_VALUE; 6 | for(int ele : arr){ 7 | max = Math.max(max,ele); 8 | } 9 | int lo = 1, hi = max, speed = max; 10 | while(lo<=hi){ // O(n*log(max)) 11 | int mid = lo + (hi-lo)/2; 12 | if(hours(mid,arr) <= k){ 13 | hi = mid - 1; 14 | speed = mid; 15 | } 16 | else lo = mid + 1; 17 | } 18 | return speed; 19 | } 20 | 21 | private int hours(int speed, int[] arr) { 22 | int h = 0; 23 | for(int ele : arr){ 24 | if(ele%speed == 0) h += ele/speed; 25 | else h += (ele/speed + 1); 26 | } 27 | return h; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Stacks/BasicSTLOfStacks.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.Stack; 3 | public class BasicSTLOfStacks { 4 | public static void main(String[] args) { 5 | Stack st = new Stack<>(); 6 | System.out.println(st.isEmpty()); 7 | System.out.println(st.size()==0); 8 | // System.out.println(st.peek()); 9 | // st.pop(); // Underflow 10 | st.push("Khushi"); 11 | st.push("Preet"); 12 | st.push("Rishika"); 13 | st.push("Isha"); 14 | st.push("Prayas"); 15 | System.out.println(st.size()); 16 | System.out.println(st); // A.S. = O(n) 17 | st.pop(); 18 | System.out.println(st+" "+st.size()); 19 | System.out.println(st.peek()); 20 | System.out.println(st.pop()); // it returns the topmost element and then removes it 21 | String s = st.pop(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Strings/StringBuilders.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class StringBuilders { 6 | public static void main(String[] args) { 7 | StringBuilder s = new StringBuilder(); 8 | System.out.println(s.length()+" "+s.capacity()); 9 | s.append("Raghav"); 10 | System.out.println(s.length()+" "+s.capacity()); 11 | System.out.println(s); 12 | s.setCharAt(1,'o'); 13 | System.out.println(s); 14 | String t = s.toString(); 15 | System.out.println(t); 16 | s.append("aDKLHJvlkbjlkdbvlkjdbfjklrbf.jkrbgjklrbkljVR"); 17 | System.out.println(s.length()+" "+s.capacity()); 18 | s.append("t"); 19 | System.out.println(s.length()+" "+s.capacity()); 20 | s.append("khaefbkeabfk"); 21 | System.out.println(s.length()+" "+s.capacity()); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /BinaryTrees/PathSum3.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public static ArrayList> printPaths(Node root, int sum) { 4 | ArrayList> ans = new ArrayList<>(); 5 | ArrayList arr = new ArrayList<>(); 6 | dfs(root,arr,ans,sum); 7 | return ans; 8 | } 9 | 10 | private static void dfs(Node root, ArrayList arr, ArrayList> ans, int sum) { 11 | arr.add(root.data); 12 | // ✅ If current path sum matches, add it 13 | if (sum == root.data) { 14 | ans.add(new ArrayList<>(arr)); 15 | } 16 | // Continue searching children 17 | if (root.left != null) dfs(root.left, arr, ans, sum - root.data); 18 | if (root.right != null) dfs(root.right, arr, ans, sum - root.data); 19 | arr.remove(arr.size() - 1); // backtrack 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Graphs/KeysAndRooms.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | import java.util.LinkedList; 3 | import java.util.List; 4 | import java.util.Queue; 5 | public class KeysAndRooms { 6 | public boolean canVisitAllRooms(List> rooms) { 7 | // single BFS lagana hai 0 pe 8 | int n = rooms.size(); 9 | boolean[] visited = new boolean[n]; 10 | visited[0] = true; 11 | Queue q = new LinkedList<>(); 12 | q.add(0); 13 | while(q.size()>0){ 14 | int front = q.remove(); 15 | for(int ele : rooms.get(front)){ 16 | if(!visited[ele]){ 17 | q.add(ele); 18 | visited[ele] = true; 19 | } 20 | } 21 | } 22 | for(boolean flag : visited){ 23 | if(!flag) return false; 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Maps&Sets/Maps_STL.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | import java.util.HashMap; 3 | public class Maps_STL { 4 | public static void main(String[] args) { 5 | HashMap map = new HashMap<>(); 6 | map.put("Raghav",25); map.put("Abhinav Sir",35); // add 7 | map.put("Vivek",17); map.put("Deepika",19); 8 | for(String key : map.keySet()){ 9 | System.out.println(key+" "+map.get(key)); 10 | } 11 | // System.out.println(map+" "+map.size()); 12 | // System.out.println(map.containsKey("Vivek")); 13 | // System.out.println(map.remove("Vivek")); 14 | // System.out.println(map+" "+map.size()); 15 | // System.out.println(map.get("Raghav")); 16 | // map.put("Deepika",20); 17 | // System.out.println(map+" "+map.size()); 18 | // System.out.println(map.containsKey("Vivek")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Pattern_Printing/Bridge.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Bridge { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | for(int i=1;i<=2*n-1;i++){ 10 | System.out.print("* "); 11 | } 12 | System.out.println(); 13 | int nsp = 1; 14 | for(int i=1;i<=n-1;i++){ // lines 15 | for(int j=1;j<=n-i;j++){ // stars 16 | System.out.print("*"+" "); 17 | } 18 | for(int j=1;j<=nsp;j++){ // spaces 19 | System.out.print(" "+" "); 20 | } 21 | for(int j=1;j<=n-i;j++){ // stars 22 | System.out.print("*"+" "); 23 | } 24 | nsp += 2; 25 | System.out.println(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Pattern_Printing/TriangleFlippedVertically.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TriangleFlippedVertically { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | // for(int i=1;i<=n;i++){ 10 | // for(int j=1;j<=n;j++){ 11 | // if(i+j > n) System.out.print(j+" "); 12 | // else System.out.print(" "); 13 | // } 14 | // System.out.println(); 15 | // } 16 | for(int i=1;i<=n;i++){ // lines 17 | for(int j=1;j<=n-i;j++){ // spaces 18 | System.out.print(" "); 19 | } 20 | for(int j=1;j<=i;j++){ // stars 21 | System.out.print("*"+" "); 22 | } 23 | System.out.println(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BinaryTrees/MinDistanceBw2Nodes.java: -------------------------------------------------------------------------------- 1 | class GfG { 2 | int findDist(Node root, int a, int b) { 3 | Node LCA = lca(root,a,b); 4 | int[] dis = {0,0}; 5 | dfs(LCA,a,b,0,dis); 6 | return dis[0] + dis[1]; 7 | } 8 | 9 | private void dfs(Node root, int a, int b, int depth, int[] dis) { 10 | if(root==null) return; 11 | if(root.data == a) dis[0] = depth; 12 | if(root.data == b) dis[1] = depth; 13 | dfs(root.left,a,b,depth+1,dis); 14 | dfs(root.right,a,b,depth+1,dis); 15 | } 16 | 17 | Node lca(Node root, int p, int q) { // TC = O(n) 18 | if(root==null) return null; 19 | if(root.data==p || root.data==q) return root; 20 | Node l = lca(root.left,p,q); 21 | Node r = lca(root.right,p,q); 22 | if(l!=null && r!=null) return root; 23 | return (l==null) ? r : l; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OOPS/Inheritance.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | class Pokemon{ 3 | int power; 4 | String type; 5 | Pokemon(String type, int power){ 6 | this.power = power; 7 | this.type = type; 8 | } 9 | Pokemon(){ 10 | 11 | } 12 | void print(){ // getter 13 | System.out.println(this.power+" "+this.type); 14 | } 15 | } 16 | class StrongPokemon extends Pokemon{ // child class 17 | int speed; 18 | } 19 | class LegendaryPokemon extends Pokemon{ // child class 20 | String ability; 21 | } 22 | class GodPokemon extends LegendaryPokemon{ 23 | char tag; 24 | } 25 | public class Inheritance { 26 | public static void main(String[] args) { 27 | LegendaryPokemon mewtwo = new LegendaryPokemon(); 28 | mewtwo.ability = "Pressure"; 29 | Pokemon pikachu = new Pokemon(); 30 | GodPokemon dialga = new GodPokemon(); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LinkedList/ReverseDLL.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public DLLNode reverseDLL(DLLNode head) { 3 | if(head.next==null) return head; 4 | DLLNode temp = null; 5 | DLLNode curr = head; 6 | while(curr!=null){ 7 | temp = curr.prev; 8 | curr.prev = curr.next; 9 | curr.next = temp; 10 | curr = curr.prev; // aage leke jaa rahe hai 11 | } 12 | return temp.prev; 13 | } 14 | // public DLLNode reverseDLL(DLLNode head) { 15 | // DLLNode pre = null; 16 | // DLLNode curr = head; 17 | // DLLNode fwd = null; 18 | // while(curr!=null){ 19 | // fwd = curr.next; 20 | // curr.next = pre; 21 | // curr.prev = fwd; // added line 22 | // pre = curr; 23 | // curr = fwd; 24 | // } 25 | // return pre; 26 | // } 27 | } 28 | -------------------------------------------------------------------------------- /Loops/evenHundred.java: -------------------------------------------------------------------------------- 1 | package Loops; 2 | 3 | public class evenHundred { 4 | public static void main(String[] args) { 5 | // // 154 iterations hai loop ke 6 | // for (int i = 17; i <= 170 ; i=i+1) { 7 | // if(i%17 == 0) System.out.print(i+" "); 8 | // } 9 | // // 10 iterations hai loop ke 10 | // for (int i = 17; i <= 170 ; i=i+17) { 11 | // System.out.print(i+" "); 12 | // } 13 | // // 10 iterations hai loop ke 14 | // for (int i = 1; i <= 10 ; i=i+1) { 15 | // System.out.print(i*18+" "); 16 | // } 17 | // // 50 baar chalega 18 | // for (int i = 2; i <= 100 ; i=i+2) { 19 | // System.out.print(i+" "); 20 | // } 21 | // 100 baar chalega 22 | for (int i = 1; i <= 100 ; i=i++) { 23 | if(i%2==0) System.out.print(i+" "); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DP/PartitionEqualSubsetSum.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class PartitionEqualSubsetSum { 4 | static boolean equalPartition(int arr[]) { 5 | int arraySum = 0; 6 | for(int ele : arr) arraySum += ele; 7 | if(arraySum%2 == 1) return false; 8 | int sum = arraySum/2; 9 | Boolean[][] dp = new Boolean[arr.length][sum+1]; 10 | return partition(0,sum,arr,dp); 11 | } 12 | 13 | static boolean partition(int i, int sum, int[] arr, Boolean[][] dp) { 14 | if(i==arr.length){ 15 | if(sum==0) return true; 16 | else return false; 17 | } 18 | if(dp[i][sum]!=null) return dp[i][sum]; 19 | boolean skip = partition(i+1,sum,arr,dp); 20 | if(sum < arr[i]) return dp[i][sum] = skip; 21 | boolean pick = partition(i+1,sum-arr[i],arr,dp); 22 | return dp[i][sum] = (pick || skip); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /SpecialAlgos/MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | package SpecialAlgos; 2 | 3 | public class MaximumProductSubarray { 4 | int maxProduct(int[] arr) { 5 | int pro = 1, maxPro = Integer.MIN_VALUE; 6 | for(int i=0;i=0;i--){ // right to left 18 | if(arr[i]==0){ 19 | pro = 1; 20 | if(maxPro<0) maxPro = 0; 21 | } 22 | else{ 23 | pro *= arr[i]; 24 | maxPro = Math.max(maxPro,pro); 25 | } 26 | } 27 | return maxPro; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /OOPS/PrivateKeyword.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | 3 | import java.util.Scanner; 4 | 5 | class Students{ 6 | String name; // null 7 | private int rno; // 0 8 | double cgpa; // 0.0 9 | void print(){ // getter 10 | System.out.println(name+" "+cgpa+" "+rno); 11 | } 12 | int getRno(){ // getter 13 | return rno; 14 | } 15 | void setRno(int x){ // setter 16 | rno = x; 17 | } 18 | } 19 | public class PrivateKeyword { 20 | public static void main(String[] args) { 21 | Scanner sc = new Scanner(System.in); 22 | Students s1 = new Students(); 23 | // s1.print(); 24 | s1.cgpa = 8.9; 25 | s1.name = "Hemant"; 26 | // s1.rno = 45; error 27 | s1.setRno(45); 28 | System.out.println(s1.getRno()); 29 | 30 | // StringBuilder sb = new StringBuilder(sc.nextLine()); 31 | // System.out.println(sb); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Maps&Sets/LongestNonRepeatingSubstring.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | import java.util.HashSet; 3 | public class LongestNonRepeatingSubstring { 4 | int longestUniqueSubstring(String s) { 5 | // ulangwar 6 | HashSet set = new HashSet<>(); 7 | int i = 0, j = 0, maxLen = 1; 8 | while(j preHi || inLo > inHi) return null; 8 | int val = preorder[preLo]; 9 | Node root = new Node(val); 10 | int r = 0; 11 | for(int i=inLo;i<=inHi;i++){ // locating root in inorder array 12 | if(inorder[i]==val){ 13 | r = i; 14 | break; 15 | } 16 | } 17 | int cnt = r - inLo; // Number of elements in LST 18 | root.left = build(preLo+1,preLo+cnt,inLo,r-1,inorder,preorder); 19 | root.right = build(preLo+cnt+1,preHi,r+1,inHi,inorder,preorder); 20 | return root; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DP/TargetSum.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class TargetSum { 4 | static int absSum; 5 | static int findTargetSumWays(int n, int[] arr, int target) { 6 | // 140000006 140000002 target = 4 7 | absSum = 0; 8 | for(int ele : arr) absSum += Math.abs(ele); 9 | int[][] dp = new int[arr.length][2*absSum+1]; 10 | return helper(0,0,target,arr,dp); 11 | } 12 | // i -> 0 to n-1 sum -> -arrayAbs to arrayAbs => 0 to 2*arrayAbs 13 | static int helper(int i, int sum, int target, int[] arr, int[][] dp) { 14 | if(i==arr.length){ 15 | if(sum==target) return 1; // 1 valid way 16 | else return 0; 17 | } 18 | if(dp[i][sum+absSum]!=0) return dp[i][sum+absSum]; 19 | int add = helper(i+1,sum+arr[i],target,arr,dp); 20 | int subtract = helper(i+1,sum-arr[i],target,arr,dp); 21 | return dp[i][sum+absSum] = add + subtract; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Maps&Sets/MostFrequentChar.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | import java.util.HashMap; 3 | public class MostFrequentChar { 4 | public char getMaxOccuringChar(String s) { 5 | HashMap map = new HashMap(); 6 | for(int i=0;imaxFreq) maxFreq = freq; 18 | } 19 | char ans = s.charAt(0); 20 | for(char ch : map.keySet()){ 21 | int freq = map.get(ch); 22 | if(freq==maxFreq && ch nthRowOfPascalTriangle(int n) { 3 | ArrayList> arr = new ArrayList<>(); 4 | // create triangle like 2D arraylist 5 | for(int i=0;i a = new ArrayList<>(); // khali 7 | for(int j=0;j<=i;j++){ 8 | a.add(0); 9 | } 10 | arr.add(a); 11 | } 12 | 13 | // fill the values of pascal triangle 14 | for(int i=0;i arr = new ArrayList<>(); 12 | int max = 0; 13 | while(n2!=0){ 14 | max = Math.max(max,n2%10); 15 | arr.add(n2%10); 16 | n2 = n2/10; 17 | count++; 18 | } 19 | Collections.reverse(arr); 20 | for(int i=1;i<=max;i++){ 21 | for(int j=0;j=i) System.out.print("* "); 23 | else System.out.print(" "); 24 | } 25 | System.out.println(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stacks/BalancedBrackets.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | 3 | import java.util.Stack; 4 | 5 | public class BalancedBrackets { 6 | static boolean isBalanced(String s) { 7 | int n = s.length(); 8 | if(n%2 == 1) return false; 9 | Stack st = new Stack<>(); 10 | for(int i=0;i missingRange(int[] arr, int low, int high) { 7 | // ArrayList ans = new ArrayList<>(); 8 | // int[] a = new int[high-low+1]; // 0-low 9 | // for(int ele : arr){ 10 | // if(ele>=low && ele<=high) a[ele-low] = 1; 11 | // } 12 | // for(int i=low;i<=high;i++){ 13 | // if(a[i-low]==0) ans.add(i); 14 | // } 15 | // return ans; 16 | // } 17 | public ArrayList missingRange(int[] arr, int low, int high) { 18 | ArrayList ans = new ArrayList<>(arr.length); 19 | HashSet set = new HashSet<>(); 20 | for(int ele : arr) set.add(ele); 21 | for(int i=low;i<=high;i++){ 22 | if(!set.contains(i)) ans.add(i); 23 | } 24 | return ans; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DP/BishalClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BishalClimbingStairs { 6 | static int minCostClimbingStairs(int[] cost) { 7 | int n = cost.length; 8 | int[] dp = new int[n]; // 0 to n-1 9 | dp[0] = cost[0]; dp[1] = cost[1]; 10 | for(int i=2;i 0 n-1 24 | // if(i>=cost.length) return 0; 25 | // if(dp[i]!=-1) return dp[i]; 26 | // return dp[i] = cost[i] + Math.min(minCost(i+1,cost),minCost(i+2,cost)); 27 | // } 28 | } 29 | -------------------------------------------------------------------------------- /BST/DeleteNodeInBST.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node deleteNode(Node root, int target) { 3 | if(root==null) return null; 4 | if(root.data > target) // go left 5 | root.left = deleteNode(root.left,target); 6 | else if(root.data < target) // go right 7 | root.right = deleteNode(root.right,target); 8 | else{ // root.data == target 9 | // Case 1 (Leaf Node) 10 | if(root.left==null && root.right==null) return null; 11 | // Case 2 (1 child node) 12 | if(root.left==null) return root.right; 13 | if(root.right==null) return root.left; 14 | // Case 3 (2 Child Nodes) 15 | Node succ = root.right; 16 | while(succ.left!=null) succ = succ.left; 17 | root.right = deleteNode(root.right,succ.data); 18 | succ.left = root.left; 19 | succ.right = root.right; 20 | return succ; 21 | } 22 | return root; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DP/CoinChangeMinCoins.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class CoinChangeMinCoins { 4 | public int minCoins(int coins[], int sum) { 5 | if(sum==0) return 0; 6 | // 2 20 10 5 1 sum = 14 10+2+2 = 3 coins 7 | int[][] dp = new int[coins.length][sum+1]; 8 | int ans = helper(0,sum,coins,dp); 9 | return (ans!=Integer.MAX_VALUE) ? ans : -1; 10 | } 11 | // i -> 0 to n-1 sum -> sum to 0 12 | private int helper(int i, int sum, int[] coins, int[][] dp) { 13 | if(i==coins.length){ 14 | if(sum==0) return 0; // valid ans 15 | else return Integer.MAX_VALUE; // invalid ans 16 | } 17 | if(dp[i][sum]!=0) return dp[i][sum]; 18 | int skip = helper(i+1,sum,coins,dp); 19 | if(sum < coins[i]) return dp[i][sum] = skip; 20 | int take = helper(i,sum-coins[i],coins,dp); 21 | int pick = (take==Integer.MAX_VALUE) ? take : take + 1; 22 | return dp[i][sum] = Math.min(skip,pick); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DP/RussianDollEnvelopes.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | import java.util.*; 3 | public class RussianDollEnvelopes { 4 | public int maxEnvelopes(int[][] envelopes) { 5 | Arrays.sort(envelopes, (a,b) -> (a[0]!=b[0]) ? Integer.compare(a[0],b[0]) : Integer.compare(b[1],a[1])); 6 | ArrayList ans = new ArrayList<>(); 7 | for(int[] a : envelopes){ 8 | int ele = a[1]; 9 | if(ans.size()==0 || ele>ans.get(ans.size()-1)) ans.add(ele); 10 | else replace(ele,ans); 11 | } 12 | return ans.size(); 13 | } 14 | 15 | public void replace(int ele, ArrayList ans) { 16 | // find the lower bound 17 | int lo = 0, hi = ans.size()-1, lb = -1; 18 | while(lo<=hi){ 19 | int mid = lo + (hi-lo)/2; 20 | if(ans.get(mid)>=ele){ 21 | lb = mid; 22 | hi = mid - 1; 23 | } 24 | else lo = mid + 1; 25 | } 26 | ans.set(lb,ele); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LinkedList/MergeKSortedLL.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node mergeKLists(List arr) { 3 | while(arr.size()>1){ 4 | Node a = arr.get(arr.size()-1); 5 | arr.remove(arr.size()-1); 6 | Node b = arr.get(arr.size()-1); 7 | arr.remove(arr.size()-1); 8 | Node c = merge(a,b); 9 | arr.add(c); 10 | } 11 | return arr.get(0); 12 | } 13 | Node merge(Node head1, Node head2) { 14 | Node i = head1; 15 | Node j = head2; 16 | Node dummy = new Node(-1); 17 | Node k = dummy; 18 | while(i!=null && j!=null){ 19 | if(i.data <= j.data){ 20 | k.next = i; 21 | i = i.next; 22 | } 23 | else{ 24 | k.next = j; 25 | j = j.next; 26 | } 27 | k = k.next; 28 | } 29 | if(i==null) k.next = j; 30 | else k.next = i; 31 | return dummy.next; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Stacks/PushAtBottom.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.Stack; 3 | public class PushAtBottom { 4 | public static void main(String[] args) { 5 | Stack st = new Stack<>(); 6 | st.push(10); // bottom 7 | st.push(20); 8 | st.push(30); 9 | st.push(40); // top 10 | int ele = 50; 11 | System.out.println(st); 12 | pushAtBottom(st,ele); 13 | System.out.println(st); 14 | reverse(st); 15 | System.out.println(st); 16 | } 17 | 18 | private static void reverse(Stack st) { 19 | if(st.size()<=1) return; 20 | int top = st.pop(); 21 | reverse(st); // magic 22 | pushAtBottom(st,top); 23 | } 24 | 25 | private static void pushAtBottom(Stack st, int ele) { 26 | if(st.size()==0){ 27 | st.push(ele); 28 | return; 29 | } 30 | int top = st.pop(); 31 | pushAtBottom(st,ele); 32 | st.push(top); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Backtracking/RatInAMaze.java: -------------------------------------------------------------------------------- 1 | package Backtracking; 2 | 3 | public class RatInAMaze { 4 | public static void main(String[] args) { 5 | int m = 3, n = 3; 6 | boolean[][] visited = new boolean[m][n]; // false 7 | System.out.println(paths(0,0,m-1,n-1,visited,"")); 8 | } 9 | 10 | private static int paths(int r, int c, int er, int ec, boolean[][] visited, String s) { 11 | if(r>er || c>ec || r<0 || c<0 || visited[r][c]) return 0; 12 | visited[r][c] = true; 13 | if(r==er && c==ec){ 14 | System.out.println(s); 15 | visited[r][c] = false; // backtracking 16 | return 1; // valid path 17 | } 18 | int left = paths(r,c-1,er,ec,visited,s+'L'); 19 | int up = paths(r-1,c,er,ec,visited,s+'U'); 20 | int right = paths(r,c+1,er,ec,visited,s+'R'); 21 | int down = paths(r+1,c,er,ec,visited,s+'D'); 22 | visited[r][c] = false; // backtracking 23 | return right + down + left + up; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LinkedList/RotateList.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int length(ListNode head){ 3 | int len = 0; 4 | ListNode temp = head; 5 | while(temp != null){ 6 | temp = temp.next; 7 | len++; 8 | } 9 | return len; 10 | } 11 | public ListNode rotateRight(ListNode head, int k) { 12 | if(head == null || head.next == null) return head; 13 | int n = length(head); 14 | k %= n; 15 | if(k == 0) return head; 16 | ListNode slow = head; 17 | ListNode fast = head; 18 | for(int i=1;i<=k+1;i++){ 19 | fast = fast.next; 20 | } 21 | while(fast != null){ 22 | slow = slow.next; 23 | fast = fast.next; 24 | } 25 | ListNode a = slow.next; 26 | slow.next = null; 27 | ListNode tail = a; 28 | while(tail.next != null){ 29 | tail = tail.next; 30 | } 31 | tail.next = head; 32 | return a; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /BST/MorrisInorder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList inOrder(Node root) { // Morris 3 | ArrayList ans = new ArrayList<>(); 4 | Node curr = root; 5 | while(curr != null){ 6 | if(curr.left != null){ 7 | // find pred and do work 8 | Node pred = curr.left; 9 | while(pred.right != null && pred.right != curr) 10 | pred = pred.right; 11 | if(pred.right == null){ // link 12 | pred.right = curr; 13 | curr = curr.left; 14 | } 15 | else{ // pred.right = curr // Unlink & Print 16 | pred.right = null; 17 | ans.add(curr.data); 18 | curr = curr.right; 19 | } 20 | } 21 | else{ 22 | ans.add(curr.data); 23 | curr = curr.right; 24 | } 25 | } 26 | return ans; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2D_Arrays/SpiralMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList spirallyTraverse(int[][] arr) { 3 | ArrayList ans = new ArrayList<>(); 4 | int m = arr.length, n = arr[0].length; 5 | int minr=0, maxr=m-1,minc=0,maxc=n-1; 6 | while(minr<=maxr && minc<=maxc){ 7 | for(int j=minc;j<=maxc;j++){ 8 | ans.add(arr[minr][j]); 9 | } 10 | minr++; 11 | if(minr>maxr || minc>maxc) break; 12 | for(int i=minr;i<=maxr;i++){ 13 | ans.add(arr[i][maxc]); 14 | } 15 | maxc--; 16 | if(minr>maxr || minc>maxc) break; 17 | for(int j=maxc;j>=minc;j--){ 18 | ans.add(arr[maxr][j]); 19 | } 20 | maxr--; 21 | if(minr>maxr || minc>maxc) break; 22 | for(int i=maxr;i>=minr;i--){ 23 | ans.add(arr[i][minc]); 24 | } 25 | minc++; 26 | } 27 | return ans; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /DP/PrintLongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class PrintLongestCommonSubstring { 4 | public String getLongestPal(String s) { 5 | int n = s.length(); 6 | int[][] dp = new int[n][n]; 7 | int maxLen = 1; 8 | for(int i=0;i len2){ // temp1 ko aage bhejenge 18 | for(int i=1;i<=len1-len2;i++){ 19 | temp1 = temp1.next; 20 | } 21 | } 22 | else{ // temp2 ko aage bhejenge 23 | for(int i=1;i<=len2-len1;i++){ 24 | temp2 = temp2.next; 25 | } 26 | } 27 | while(temp1 != temp2){ 28 | temp1 = temp1.next; 29 | temp2 = temp2.next; 30 | } 31 | return temp1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /BinarySearch/FirstAndLastOccurences.java: -------------------------------------------------------------------------------- 1 | class GFG { 2 | ArrayList find(int arr[], int tar) { 3 | ArrayList ans = new ArrayList<>(); 4 | // first occurence 5 | int lo = 0, hi = arr.length - 1, idx = -1; 6 | while(lo<=hi){ 7 | int mid = (lo+hi)/2; 8 | if(arr[mid]tar) hi = mid - 1; 10 | else{ // arr[mid] = tar 11 | idx = mid; 12 | hi = mid - 1; 13 | } 14 | } 15 | ans.add(idx); 16 | // last occurence 17 | lo = 0; 18 | hi = arr.length - 1; 19 | idx = -1; 20 | while(lo<=hi){ 21 | int mid = (lo+hi)/2; 22 | if(arr[mid]tar) hi = mid - 1; 24 | else{ // arr[mid] = tar 25 | idx = mid; 26 | lo = mid + 1; 27 | } 28 | } 29 | ans.add(idx); 30 | return ans; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /OOPS/ComplexNumberClass.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | class ComplexNumber{ 3 | double x; 4 | double y; 5 | ComplexNumber(double x, double y){ 6 | this.x = x; 7 | this.y = y; 8 | } 9 | ComplexNumber(){ 10 | 11 | } 12 | void print(){ 13 | if(y>=0) System.out.println(x+" + "+y+"i"); 14 | else System.out.println(x+" - "+(-y)+"i"); 15 | } 16 | 17 | void add(ComplexNumber z) { 18 | x += z.x; 19 | y += z.y; 20 | } 21 | 22 | void multiply(ComplexNumber z) { 23 | x = x*z.x - y*z.y; 24 | y = x*z.y + y*z.x; 25 | } 26 | 27 | void divide(ComplexNumber z) { 28 | 29 | } 30 | } 31 | public class ComplexNumberClass { 32 | public static void main(String[] args) { 33 | ComplexNumber z1 = new ComplexNumber(2,-5); 34 | ComplexNumber z2 = new ComplexNumber(3,4); 35 | z1.print(); z2.print(); 36 | z1.add(z2); 37 | z1.print(); z2.print(); 38 | z2.multiply(z1); 39 | z1.print(); z2.print(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Pattern_Printing/Diamond.java: -------------------------------------------------------------------------------- 1 | package Pattern_Printing; 2 | import java.util.Scanner; 3 | public class Diamond { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | int nsp = n-1, nst = 1; 8 | for(int i=1;i<=n;i++){ // lines 9 | for(int j=1;j<=nsp;j++){ // spaces 10 | System.out.print(" "+" "); 11 | } 12 | for(int j=1;j<=nst;j++){ // stars 13 | System.out.print("*"+" "); 14 | } 15 | nsp--; nst += 2; 16 | System.out.println(); 17 | } 18 | nsp = 1; nst = 2*n-3; 19 | for(int i=1;i<=n-1;i++){ // lines 20 | for(int j=1;j<=nsp;j++){ // spaces 21 | System.out.print(" "+" "); 22 | } 23 | for(int j=1;j<=nst;j++){ // stars 24 | System.out.print("*"+" "); 25 | } 26 | nsp++; nst -= 2; 27 | System.out.println(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /BinarySearch/ArrangeCoins.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sqrt(long n) { 3 | if(n==0) return 0; 4 | long lo = 1, hi = n; 5 | while(lo<=hi){ 6 | long mid = lo + (hi-lo)/2; 7 | if(mid == n/mid) return (int)mid; 8 | else if(mid > n/mid) hi = mid - 1; 9 | else lo = mid + 1; 10 | } 11 | return (int)hi; 12 | } 13 | public int arrangeCoins(int n) { 14 | long m = (long)n; 15 | return (sqrt(8*m+1) - 1)/2; 16 | } 17 | } 18 | 19 | class Solution { 20 | public int arrangeCoins(int n) { 21 | long lo = 0, hi = n, ans = 0; 22 | while(lo<=hi){ 23 | long k = lo + (hi-lo)/2; 24 | long m = k*(k+1)/2; 25 | if(m==n) return (int)k; 26 | else if(m>n){ 27 | 28 | hi = k - 1; 29 | } 30 | else { 31 | ans = k; 32 | lo = k + 1; 33 | } 34 | } 35 | return (int)(ans); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /DP/FibonacciDP.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class FibonacciDP { 4 | public int nthFibonacci(int n) { 5 | if(n<=1) return n; 6 | int[] dp = new int[3]; 7 | dp[1] = 1; 8 | for(int i=2;i<=n;i++){ 9 | dp[2] = dp[1] + dp[0]; 10 | dp[0] = dp[1]; 11 | dp[1] = dp[2]; 12 | } 13 | return dp[2]; 14 | } 15 | // public int nthFibonacci(int n) { 16 | // int[] dp = new int[n+1]; // idx from 0 to n 17 | // dp[1] = 1; 18 | // for(int i=2;i<=n;i++){ 19 | // dp[i] = dp[i-1] + dp[i-2]; 20 | // } 21 | // return dp[n]; 22 | // } 23 | // static int[] dp; 24 | // public int fibo(int n) { 25 | // if(n<=1) return n; 26 | // if(dp[n]!=0) return dp[n]; // extra 27 | // int ans = fibo(n-1) + fibo(n-2); 28 | // dp[n] = ans; // extra 29 | // return ans; 30 | // } 31 | // public int nthFibonacci(int n) { 32 | // dp = new int[n+1]; // idx from 0 to n 33 | // return fibo(n); 34 | // } 35 | } 36 | -------------------------------------------------------------------------------- /DP/LongestPalindromicSubsequence.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | public class LongestPalindromicSubsequence { 4 | public int longestPalinSubseq(String s) { 5 | StringBuilder a = new StringBuilder(s); 6 | StringBuilder b = new StringBuilder(s); 7 | b.reverse(); 8 | return lcs(a,b); 9 | } 10 | public int lcs(StringBuilder a, StringBuilder b) { 11 | int m = a.length(), n = b.length(); 12 | int[][] dp = new int[m][n]; 13 | for(int i=0;i m-1 to 0 j -> n-1 to 0 19 | public int LCS(int i, int j, StringBuilder a, StringBuilder b, int[][] dp) { 20 | if(i<0 || j<0) return 0; // there is nothing in common 21 | if(dp[i][j]!=-1) return dp[i][j]; 22 | if(a.charAt(i)==b.charAt(j)) return dp[i][j] = 1 + LCS(i-1,j-1,a,b,dp); 23 | else return dp[i][j] = Math.max(LCS(i-1,j,a,b,dp),LCS(i,j-1,a,b,dp)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OOPS/PolyMorphism.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | 3 | public class PolyMorphism { 4 | public static class Dog{ 5 | void speak(){ 6 | System.out.println("Bhau Bhau"); 7 | } 8 | } 9 | public static class Cat{ 10 | void speak(){ 11 | System.out.println("Meow Meow"); 12 | } 13 | } 14 | public static class Lion{ 15 | void speak(){ 16 | System.out.println("GRRRRRR"); 17 | } 18 | } 19 | public static class Pikachu{ 20 | void speak(){ 21 | System.out.println("Pika Pika"); 22 | } 23 | } 24 | public static class Human{ 25 | void speak(){ 26 | System.out.println("Hello"); 27 | } 28 | } 29 | public static void main(String[] args) { 30 | Dog tommy = new Dog(); 31 | Cat c = new Cat(); 32 | Human bishal = new Human(); 33 | Pikachu p = new Pikachu(); 34 | 35 | tommy.speak(); 36 | c.speak(); 37 | p.speak(); 38 | bishal.speak(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Recursion/InversionCount.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int count; 3 | static int inversionCount(int arr[]) { 4 | count = 0; 5 | mergeSort(arr); 6 | return count; 7 | } 8 | private static void mergeSort(int[] arr) { 9 | int n = arr.length; 10 | if(n==1) return; 11 | int[] a = new int[n/2]; 12 | int[] b = new int[n-n/2]; 13 | int idx = 0; 14 | for(int i=0;i b[j] 25 | c[k++] = b[j++]; 26 | count += (a.length - i); 27 | } 28 | } 29 | while(i{ 4 | String name; 5 | int rno; 6 | double cgpa; 7 | Student(String name, int rno, double cgpa){ 8 | this.name = name; 9 | this.rno = rno; 10 | this.cgpa = cgpa; 11 | } 12 | 13 | public int compareTo(Student s){ 14 | if(this.cgpa == s.cgpa) 15 | return this.rno - s.rno; 16 | return Double.compare(this.cgpa,s.cgpa); 17 | } 18 | } 19 | public class CustomComparator { 20 | public static void main(String[] args) { 21 | Student s1 = new Student("Gopi",200,8.3); 22 | Student s2 = new Student("Shahid",49,8.9); 23 | Student s3 = new Student("Anuj",90,8.5); 24 | Student s4 = new Student("Isha",8,8.3); 25 | Student s5 = new Student("Aditya",31,9.7); 26 | Student[] arr = {s1,s2,s3,s4,s5}; 27 | Arrays.sort(arr); 28 | for(Student s : arr){ 29 | System.out.println(s.name+" "+s.rno+" "+s.cgpa); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Maps&Sets/Sets_STL.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | import java.util.HashSet; 3 | import java.util.TreeSet; 4 | 5 | public class Sets_STL { 6 | public static void main(String[] args) { 7 | // TreeSet set = new TreeSet<>(); // Balanced BST 8 | HashSet set = new HashSet<>(); 9 | set.add(77); set.add(65); set.add(2); set.add(2); 10 | set.add(11); set.add(45); set.add(3); set.add(77); 11 | // for(int ele : set){ // ERROR 12 | // set.remove(ele); 13 | // } 14 | for(int ele : set){ 15 | System.out.print(ele+" "); 16 | } 17 | set.clear(); 18 | System.out.println(); 19 | for(int ele : set){ 20 | System.out.print(ele+" "); 21 | } 22 | 23 | // System.out.println(set.size()); 24 | // System.out.println(set); 25 | // System.out.println(set.contains(21)+" "+set.contains(18)); 26 | // set.remove(21); 27 | // System.out.println(set.contains(21)); 28 | // System.out.println(set.size()); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /DP/LargestDivisibleSubset.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | import java.util.*; 4 | 5 | public class LargestDivisibleSubset { 6 | public ArrayList largestSubset(int[] arr) { 7 | int n = arr.length; 8 | Arrays.sort(arr); 9 | int[] dp = new int[n]; // LIS right to left 10 | Arrays.fill(dp,1); 11 | int maxLen = 1; 12 | for(int i=n-2;i>=0;i--){ 13 | int max = 0; 14 | for(int j=i+1;j ans = new ArrayList<>(); 29 | ans.add(arr[idx]); 30 | maxLen--; 31 | idx++; 32 | // while(idx map = new HashMap<>(); // 18 | Node tempA = a; 19 | Node tempB = b; 20 | map.put(null,null); 21 | while(tempA!=null){ 22 | map.put(tempA,tempB); 23 | tempA = tempA.next; 24 | tempB = tempB.next; 25 | } 26 | tempA = a; 27 | while(tempA!=null){ 28 | tempB = map.get(tempA); 29 | tempB.random = map.get(tempA.random); 30 | tempA = tempA.next; 31 | } 32 | return b; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Maps&Sets/CountPairsWithSumDivisibleByK.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | 3 | import java.util.HashMap; 4 | 5 | public class CountPairsWithSumDivisibleByK { 6 | public static long countKdivPairs(int arr[], int n, int k) { 7 | HashMap map = new HashMap<>(); 8 | for(int ele : arr){ 9 | int x = ele%k; 10 | map.put(x,map.getOrDefault(x,0)+1); 11 | } 12 | long pairs = 0; 13 | // check for zero remainders 14 | long zeroCount = map.get(0); 15 | pairs += zeroCount*(zeroCount-1)/2; 16 | map.remove(0); 17 | // check for k/2 remainders 18 | if(k%2 == 0){ 19 | long halfCount = map.get(k/2); 20 | pairs += halfCount*(halfCount-1)/2; 21 | map.remove(k/2); 22 | } 23 | pairs *= 2; 24 | 25 | for(int key : map.keySet()){ 26 | int rem = k - key; 27 | if(map.containsKey(rem)) 28 | pairs += (map.get(key))*(map.get(rem)); 29 | } 30 | pairs /= 2; 31 | return pairs; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /BST/BST_To_GST.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int sum; 3 | public static void revInorder(Node root) { 4 | if(root==null) return; 5 | revInorder(root.right); 6 | int val = root.data; 7 | root.data = sum; 8 | sum += val; 9 | revInorder(root.left); 10 | } // 7 6 3 2 1 -> 0 7 13 16 18 11 | public static void transformTree(Node root) { 12 | sum = 0; 13 | revInorder(root); 14 | } 15 | // public static void revInorder(Node root, ArrayList arr) { 16 | // if(root==null) return; 17 | // revInorder(root.right,arr); 18 | // arr.add(root); 19 | // revInorder(root.left,arr); 20 | // } // 7 6 3 2 1 -> 0 7 13 16 18 21 | // public static void transformTree(Node root) { 22 | // ArrayList arr = new ArrayList<>(); 23 | // revInorder(root,arr); 24 | // int sum = 0; 25 | // for(int i=0;i root.data); 28 | if(isBST) maxSize = Math.max(size,maxSize); 29 | return new Quad(max,min,size,isBST); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Backtracking/RatInAMazeObstacles.java: -------------------------------------------------------------------------------- 1 | package Backtracking; 2 | import java.util.ArrayList; 3 | public class RatInAMazeObstacles { 4 | public ArrayList ratInMaze(int[][] maze) { 5 | ArrayList ans = new ArrayList<>(); 6 | int n = maze.length; 7 | boolean[][] visited = new boolean[n][n]; // false 8 | paths(0,0,n-1,n-1,visited,"",maze,ans); 9 | return ans; 10 | } 11 | private static void paths(int r, int c, int er, int ec, boolean[][] visited, String s, int[][] maze, ArrayList ans) { 12 | if(r>er || c>ec || r<0 || c<0 || maze[r][c]==0 || visited[r][c]) return; 13 | visited[r][c] = true; 14 | if(r==er && c==ec){ 15 | ans.add(s); 16 | visited[r][c] = false; // backtracking 17 | return; 18 | } 19 | paths(r,c-1,er,ec,visited,s+'L',maze,ans); 20 | paths(r-1,c,er,ec,visited,s+'U',maze,ans); 21 | paths(r,c+1,er,ec,visited,s+'R',maze,ans); 22 | paths(r+1,c,er,ec,visited,s+'D',maze,ans); 23 | visited[r][c] = false; // backtracking 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /BinarySearch/CapacityToShipPackagesWithinDDays.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | public class CapacityToShipPackagesWithinDDays { 4 | static int leastWeightCapacity(int[] arr, int n, int d) { 5 | int max = Integer.MIN_VALUE, sum = 0; 6 | for(int ele : arr){ 7 | max = Math.max(max,ele); 8 | sum += ele; 9 | } 10 | int lo = max, hi = sum, ans = -1; 11 | while(lo<=hi){ // O(n*log(sum-max)) 12 | int mid = lo + (hi-lo)/2; 13 | if(days(mid,arr) <= d){ 14 | hi = mid - 1; 15 | ans = mid; 16 | } 17 | else lo = mid + 1; 18 | } 19 | return ans; 20 | } 21 | // 1 2 3 4 5 6 7 8 9 10 12 22 | static int days(int capacity, int[] arr) { 23 | int days = 0; 24 | int c = capacity; 25 | for(int ele : arr){ 26 | if(c >= ele) c -= ele; 27 | else{ 28 | days++; 29 | c = capacity - ele; 30 | } 31 | } 32 | days++; 33 | return days; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Graphs/NumberOfProvinces.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | import java.util.ArrayList; 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | public class NumberOfProvinces { 6 | static int numProvinces(ArrayList> adj, int n) { 7 | // 0 to n-1 nodes 8 | int count = 0; 9 | boolean[] visited = new boolean[n]; // false 10 | for(int i=0;i> adj) { 20 | int n = adj.size(); 21 | Queue q = new LinkedList<>(); 22 | q.add(i); 23 | visited[i] = true; 24 | while(q.size()>0){ 25 | int front = q.remove(); 26 | for(int j=0;j m-1 to 0 j -> n-1 to 0 22 | int LCS(int i, int j, StringBuilder a, StringBuilder b, int[][] dp) { 23 | if(i<0 || j<0) return 0; // there is nothing in common 24 | if(dp[i][j]!=-1) return dp[i][j]; 25 | if(a.charAt(i)==b.charAt(j)) return dp[i][j] = 1 + LCS(i-1,j-1,a,b,dp); 26 | else return dp[i][j] = Math.max(LCS(i-1,j,a,b,dp),LCS(i,j-1,a,b,dp)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Maps&Sets/ArraySubset.java: -------------------------------------------------------------------------------- 1 | package Maps_And_Sets; 2 | 3 | import java.util.HashMap; 4 | 5 | public class ArraySubset { 6 | public boolean isSubset(int a[], int b[]) { 7 | // a[] = [11, 1, 13, 21, 3, 7, 3], b[] = [11, 3, 7, 1, 7] 8 | // no 9 | HashMap aMap = new HashMap<>(); 10 | for(int ele : a){ 11 | if(aMap.containsKey(ele)){ 12 | int freq = aMap.get(ele); 13 | aMap.put(ele,freq+1); 14 | } 15 | else aMap.put(ele,1); 16 | } 17 | HashMap bMap = new HashMap<>(); 18 | for(int ele : b){ 19 | if(!aMap.containsKey(ele)) return false; 20 | if(bMap.containsKey(ele)){ 21 | int freq = bMap.get(ele); 22 | bMap.put(ele,freq+1); 23 | } 24 | else bMap.put(ele,1); 25 | } 26 | for(int ele : bMap.keySet()){ 27 | int freq = bMap.get(ele); 28 | int aFreq = aMap.get(ele); 29 | if(aFreqn) return; 30 | System.out.print(x+" "); 31 | print1toNGlobal(x+1); 32 | } 33 | public static void ParameterisedPrint1toN(int x, int n){ 34 | if(x>n) return; 35 | System.out.println(x); 36 | ParameterisedPrint1toN(x+1,n); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /DP/LongestBitonicArray.java: -------------------------------------------------------------------------------- 1 | package DP; 2 | 3 | import java.util.Arrays; 4 | 5 | public class LongestBitonicArray { 6 | public static int LongestBitonicSequence(int n, int[] arr) { 7 | int[] dp = new int[n]; // LIS left to right 8 | Arrays.fill(dp,1); 9 | for(int i=1;i=0;i--){ 22 | int max = 0; 23 | for(int j=i+1;j arr = new ArrayList<>(); 25 | // while(temp!=null){ 26 | // arr.add(temp); 27 | // temp = temp.next; 28 | // } 29 | // int n = arr.size(); 30 | // for(int i=n-1;i>=1;i--){ 31 | // arr.get(i).next = arr.get(i-1); 32 | // } 33 | // arr.get(0).next = null; 34 | // return arr.get(n-1); 35 | // } 36 | } 37 | -------------------------------------------------------------------------------- /Queues/MyQueue.java: -------------------------------------------------------------------------------- 1 | package Queues; 2 | class Node{ 3 | int val; 4 | Node next; 5 | Node(int val){ 6 | this.val = val; 7 | } 8 | } 9 | public class MyQueue { 10 | Node head; 11 | Node tail; 12 | int size; 13 | int peek(){ 14 | if(size==0){ 15 | System.out.println("Queue is Empty!"); 16 | return -1; 17 | } 18 | return head.val; 19 | } 20 | int remove(){ 21 | if(size==0){ 22 | System.out.println("Queue is Empty!"); 23 | return -1; 24 | } 25 | int front = head.val; 26 | head = head.next; 27 | size--; 28 | return front; 29 | } 30 | void add(int val){ 31 | Node temp = new Node(val); 32 | if(size==0) head = tail = temp; 33 | else{ 34 | tail.next = temp; 35 | tail = temp; 36 | } 37 | size++; 38 | } 39 | void display(){ 40 | Node temp = head; 41 | while(temp!=null){ 42 | System.out.print(temp.val+" "); 43 | temp = temp.next; 44 | } 45 | System.out.println(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Heaps/IsBinaryTreeMaxHeap.java: -------------------------------------------------------------------------------- 1 | package Heaps; 2 | class Node{ 3 | int data; 4 | Node left,right; 5 | Node(int d){ 6 | data=d; 7 | left=right=null; 8 | } 9 | } 10 | public class IsBinaryTreeMaxHeap { 11 | static int s; 12 | boolean isHeap(Node root) { 13 | s = size(root); 14 | return isMaxHeap(root) && isCBT(root,1); 15 | } 16 | 17 | private int size(Node root) { 18 | if(root==null) return 0; 19 | return 1 + size(root.left) + size(root.right); 20 | } 21 | 22 | private boolean isCBT(Node root, int idx) { 23 | if(root==null) return true; 24 | if(idx>s) return false; 25 | return isCBT(root.left,2*idx) && isCBT(root.right,2*idx+1); 26 | } 27 | 28 | private boolean isMaxHeap(Node root) { 29 | if(root==null) return true; 30 | int leftVal = (root.left != null) ? root.left.data : Integer.MIN_VALUE; 31 | int rightVal = (root.right != null) ? root.right.data : Integer.MIN_VALUE; 32 | if(root.data <= leftVal || root.data <= rightVal) return false; 33 | return isMaxHeap(root.left) && isMaxHeap(root.right); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Heaps/KClosestPointsToOrigin.java: -------------------------------------------------------------------------------- 1 | package Heaps; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | class Triplet implements Comparable{ 6 | int dist; 7 | int x; 8 | int y; 9 | Triplet(int dist, int x, int y){ 10 | this.dist = dist; 11 | this.x = x; 12 | this.y = y; 13 | } 14 | 15 | public int compareTo(Triplet t) { 16 | return this.dist - t.dist; 17 | } 18 | } 19 | public class KClosestPointsToOrigin { 20 | public int[][] kClosest(int[][] points, int k) { 21 | // k smallest distances -> maxheap 22 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 23 | for(int[] point : points){ 24 | int x = point[0], y = point[1]; 25 | int dist = x*x + y*y; 26 | pq.add(new Triplet(dist,x,y)); 27 | if(pq.size()>k) pq.remove(); 28 | } 29 | int[][] ans = new int[k][2]; 30 | for(int i=0;i a.val && b.val > c.val) || (b.val < a.val && b.val < c.val)){ 13 | if(firstIdx==-1) firstIdx = idx; 14 | if(lastIdx!=-1){ 15 | int dist = idx - lastIdx; 16 | minDist = Math.min(dist,minDist); 17 | } 18 | lastIdx = idx; 19 | } 20 | idx++; 21 | a = a.next; 22 | b = b.next; 23 | c = c.next; 24 | } 25 | int maxDist = lastIdx - firstIdx; 26 | if(maxDist==0) maxDist = -1; 27 | if(minDist==Integer.MAX_VALUE) minDist = -1; 28 | ans[0] = minDist; 29 | ans[1] = maxDist; 30 | return ans; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Graphs/TopologicalSort.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | public class TopologicalSort { 8 | public ArrayList topoSort(int n, int[][] edges) { 9 | ArrayList> adj = new ArrayList<>(); 10 | for(int i=0;i()); 12 | } 13 | int[] indegree = new int[n]; 14 | for(int i=0;i q = new LinkedList<>(); 22 | for(int i=0;i ans = new ArrayList<>(); 26 | while(q.size()>0){ 27 | int vertex = q.remove(); 28 | ans.add(vertex); 29 | for(int ele : adj.get(vertex)){ 30 | indegree[ele]--; 31 | if(indegree[ele]==0) q.add(ele); 32 | } 33 | } 34 | return ans; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Stacks/CelebrityProblem.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int celebrity(int arr[][]) { 3 | int n = arr.length; 4 | Stack st = new Stack<>(); 5 | for(int i=0;i1){ 7 | int a = st.pop(); 8 | int b = st.pop(); 9 | boolean aFlag = true, bFlag = true; 10 | if(arr[a][b]==1) // a to celeb nahi hua 11 | aFlag = false; 12 | else // arr[a][b]==0 -> b celeb nahi hua 13 | bFlag = false; 14 | if(arr[b][a]==1) // b to celeb nahi hua 15 | bFlag = false; 16 | else // arr[b][a]==0 -> a celeb nahi hua 17 | aFlag = false; 18 | if(aFlag) st.push(a); 19 | if(bFlag) st.push(b); 20 | } 21 | if(st.size()==0) return -1; 22 | int celeb = st.pop(); 23 | for(int j=0;j st = new Stack<>(); 6 | 7 | int[] nse = new int[n]; 8 | nse[n-1] = n; // PLS SAMAJ JAO (-1) 9 | st.push(n-1); 10 | for(int i=n-2;i>=0;i--){ 11 | while(st.size()>0 && arr[st.peek()] >= arr[i]) st.pop(); 12 | if(st.size()==0) nse[i] = n; 13 | else nse[i] = st.peek(); 14 | st.push(i); 15 | } 16 | 17 | while(st.size()>0) st.pop(); 18 | 19 | int[] pse = new int[n]; 20 | pse[0] = -1; 21 | st.push(0); 22 | for(int i=1;i0 && arr[st.peek()] >= arr[i]) st.pop(); 24 | if(st.size()==0) pse[i] = -1; 25 | else pse[i] = st.peek(); 26 | st.push(i); 27 | } 28 | 29 | int maxArea = 0; 30 | for(int i=0;i arr = new ArrayList<>(); 18 | // dfs(root,arr); 19 | // for(int i=0;i arr) { 31 | // if(root==null) return; 32 | // arr.add(root); 33 | // dfs(root.left,arr); 34 | // dfs(root.right,arr); 35 | // } 36 | } 37 | -------------------------------------------------------------------------------- /OOPS/UserDefinedDataType.java: -------------------------------------------------------------------------------- 1 | package OOPS; 2 | 3 | import java.util.Scanner; 4 | class Student{ // khudka ek data type bana liya hai 5 | String name; 6 | int rno; 7 | double cgpa; 8 | void print(){ 9 | System.out.println(name+" "+rno+" "+cgpa); 10 | } 11 | } 12 | public class UserDefinedDataType { 13 | 14 | public static void main(String[] args) { 15 | Scanner sc = new Scanner(System.in); 16 | 17 | Student s1 = new Student(); // declaration 18 | s1.name = "Khushi"; 19 | s1.rno = 23; 20 | s1.cgpa = 8.5; 21 | 22 | Student s2 = new Student(); // declaration 23 | s2.name = "Lavish"; 24 | s2.rno = 33; 25 | s2.cgpa = 2.2; 26 | 27 | Student s3 = new Student(); // declaration 28 | s3.name = "Anagha"; 29 | s3.rno = sc.nextInt(); 30 | s3.cgpa = 9.37; 31 | 32 | System.out.println(s1.name+" "+s1.cgpa+" "+s1.rno); 33 | s2.cgpa = 9.8; 34 | System.out.println(s3.rno); 35 | 36 | s1.print(); s2.print(); s3.print(); 37 | 38 | // print(s1); print(s1); print(s1); 39 | 40 | } 41 | private static void print(Student s){ 42 | System.out.println(s.name+" "+s.rno+" "+s.cgpa); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Queues/StackFromQueue.java: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | Queue q = new LinkedList<>(); 3 | public MyStack() { 4 | 5 | } 6 | 7 | public void push(int x) { // O(n) 8 | // q ke front pe add karna 9 | q.add(x); 10 | int n = q.size(); 11 | for(int i=1;i<=n-1;i++){ 12 | q.add(q.remove()); 13 | } 14 | } 15 | 16 | public int pop() { // O(1) 17 | return q.remove(); 18 | } 19 | 20 | public int top() { // O(1) 21 | return q.peek(); 22 | } 23 | 24 | // public void push(int x) { // O(1) 25 | // q.add(x); 26 | // } 27 | 28 | // public int pop() { // O(n) 29 | // int n = q.size(); 30 | // for(int i=1;i<=n-1;i++){ 31 | // q.add(q.remove()); 32 | // } 33 | // return q.remove(); 34 | // } 35 | 36 | // public int top() { // O(n) 37 | // int n = q.size(); 38 | // for(int i=1;i<=n-1;i++){ 39 | // q.add(q.remove()); 40 | // } 41 | // int p = q.peek(); 42 | // q.add(q.remove()); // imp 43 | // return p; 44 | // } 45 | 46 | public boolean empty() { 47 | return (q.size()==0); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Heaps/MedianInDataStream.java: -------------------------------------------------------------------------------- 1 | package Heaps; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.PriorityQueue; 6 | 7 | class MedianFinder { // we are creating a DS 8 | PriorityQueue minHeap = new PriorityQueue<>(); 9 | PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 10 | public MedianFinder() { 11 | 12 | } 13 | 14 | public void addNum(int num) { 15 | if(maxHeap.size()==0) maxHeap.add(num); 16 | else{ 17 | if(num no of 1 15 | for(int j=0;jones){ // flip that col 22 | for(int i=0;i=0;j--){ 30 | int ones = 0; 31 | for(int i=0;i{ 8 | int ele; 9 | int freq; 10 | Pair(int ele, int freq){ 11 | this.ele = ele; 12 | this.freq = freq; 13 | } 14 | public int compareTo(Pair p){ 15 | if(this.freq == p.freq) return this.ele - p.ele; 16 | return this.freq - p.freq; 17 | } 18 | } 19 | public class TopKFrequentElements { 20 | public ArrayList topKFrequent(int[] arr, int k) { 21 | HashMap map = new HashMap<>(); 22 | for(int ele : arr){ 23 | map.put(ele,map.getOrDefault(ele,0)+1); 24 | } 25 | PriorityQueue pq = new PriorityQueue<>(); // minheap 26 | for(int ele : map.keySet()){ 27 | int freq = map.get(ele); 28 | pq.add(new Pair(ele,freq)); 29 | if(pq.size()>k) pq.remove(); 30 | } 31 | ArrayList ans = new ArrayList<>(); 32 | while(pq.size()>0){ 33 | Pair top = pq.remove(); 34 | ans.add(top.ele); 35 | } 36 | Collections.reverse(ans); 37 | return ans; 38 | } 39 | } 40 | --------------------------------------------------------------------------------