├── Josephus.java ├── AllAnagram.java ├── README.md ├── First.class ├── RecursionDemo.class ├── FindDuplicateInArray.java ├── LeetCode_RemoveDuplicate ├── Sum.java ├── Loop.java ├── RemoveDup.java ├── TreeRecursion2.java ├── StrongestNeighbour.java ├── ArrayListAndArray.java ├── LT-867 ├── PowerOfTwo.java ├── LeetCode-766 ├── TowerOfHanoi.java ├── HashCode.java ├── Fibo.java ├── DecimalToBinary.java ├── GFG-LeaderElement ├── Suffix.java ├── TriesDefinition.java ├── Pattern2.java ├── BinaryToDecimal.java ├── ReverseAnArray.java ├── RunningLengthEncoding.java ├── LC-74 ├── RLE.java ├── PrintMatrixSnake ├── ArrayWithFunction.java ├── TreeRecursion.java ├── Space.java ├── DP ├── FibSeriesTabulation.java ├── notes.txt ├── DiceCountRec.java ├── DiceCountMemo.java └── FibSeries.java ├── RichestCustomerWealth.java ├── WindowSliding.java ├── PrintPatternInSingleMethod.java ├── MCP.java ├── LIS.java ├── SubSetSumProblem-GFG ├── LC-48 ├── PatternAnotherApproach.java ├── MinCoinChangeDP.java ├── LeetCode- TargetSum-494 ├── RecursionDemo.java ├── Anagram.java ├── ArraySearch.java ├── UniqueChar.java ├── Pattern.java ├── Factorial.java ├── StockSpan.java ├── LeetCode-134 ├── BinaryNums.java ├── Sort0And1.java ├── SumOfUpperAndBoundary ├── CheckArrayIsSortedOrNot.java ├── SortedArray.java ├── LastStoneWeight.java ├── FindInWindowSlide.java ├── BarChart.java ├── RopeCutting.java ├── NextSmallerElement.java ├── CoinChangeProblem.java ├── BinarySearchAlgo.java ├── CoinChange.java ├── PalindromeSubstring.java ├── SecondLargest.java ├── CoinChangeProblem2.java ├── NthNumber.java ├── PreviousSmallerElements.java ├── EvenOddPosSum.java ├── MinDifference.java ├── PrintSubsequences.java ├── ReverseAnString.java ├── SortColor ├── PreComputationTech.java ├── LeetCode-TwoSum ├── Substring.java ├── ZigZagArray.java ├── SubSequence.java ├── ConvertTo2D.java ├── SortStack.java ├── IsBinaryMaxHeap.java ├── IsBinaryMinHeap.java ├── SecondLargestElement.java ├── SortByFrequency.java ├── Dijkstra.java ├── NaivePatternMatching.java ├── ArrayVsArrayList.java ├── Perm.java ├── LargestArea.java ├── RotateAnArray.java ├── RabinKarp.java ├── ComputeWeightArray.java ├── InsertionInTries.java ├── EditDistanceProblem.java ├── GraphDemo.java ├── SumOfDigit.java ├── ReverseQueue.java ├── MCPTabulation.java ├── LeetCode-GenerateParenthsis-22 ├── LCP.java ├── NearestLowestAndGreatest.java ├── PascalTriangle.java ├── CountIntegers.java ├── GraphDFS.java ├── TwoDArray.java ├── ValidParanthesis.java ├── DiceGameProblem.java ├── LC-1380 ├── Stack.java ├── StringHalvesAreAlike.java ├── GenerateParentheses.java ├── First.java ├── LeetCode_987 - Vertical Order Traversal of a Binary Tree ├── EditDistanceTabulation.java ├── AtoI.java ├── Prims.java ├── SuffixInTries.java ├── PrefixInTries.java ├── LeetCode-Problem-17 ├── LC-1365 ├── MazePathProblem.java ├── FirstAndLastIndex.java ├── StackWithArray.java ├── FenWickTreeExample.java ├── LCSubsequence.java ├── StackWithLL.java ├── RomanToInteger.java ├── LeetCodeWordSearchProblem ├── LC-42 ├── KMP.java ├── ShortestPathUnweighted.java ├── MazePathProblem2.java ├── SearchInTries.java ├── BITS.java ├── RatInAMaze.java ├── DetectCycle.java ├── GraphBFS.java ├── NQueen.java ├── WordSearch.java ├── TwoSum.java ├── FindDuplicateNumberLeetCode ├── GraphBFS_Disconnected.java ├── MaxHeap.java ├── MinHeap.java ├── KthLargestInHeap.java ├── KthSmallestInHeap.java ├── MyTwoStack.java ├── LeetCode-NQueen-ProblemNo-51 ├── LCSRecursionSolution.java ├── LeetCode-SudkouSolve-ProblemNumber-37r- ├── SegmentTreeExample.java ├── BSTExample.java ├── ArrayCRUDOperation.java ├── LinkedListOperations.java └── BinaryTreeExample.java /Josephus.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /AllAnagram.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DIT_BATCH_DSA_CODES -------------------------------------------------------------------------------- /First.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brainmentorspvtltd/DIT_BATCH_DSA_CODES/HEAD/First.class -------------------------------------------------------------------------------- /RecursionDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brainmentorspvtltd/DIT_BATCH_DSA_CODES/HEAD/RecursionDemo.class -------------------------------------------------------------------------------- /FindDuplicateInArray.java: -------------------------------------------------------------------------------- 1 | public class FindDuplicateInArray { 2 | public static void main(String[] args) { 3 | 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /LeetCode_RemoveDuplicate: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int j =0; 4 | for(int i = 1; i l = new ArrayList<>(); 6 | // l.add(""); 7 | System.out.println(l.size()); 8 | for(String e : l){ 9 | System.out.println("E is "+e); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /RemoveDup.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class RemoveDup { 4 | public static void main(String[] args) { 5 | HashSet set = new HashSet<>(); 6 | int nums [] = {1,1,2}; 7 | for(int element : nums){ 8 | set.add(element); 9 | } 10 | System.out.println(set); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /TreeRecursion2.java: -------------------------------------------------------------------------------- 1 | public class TreeRecursion2 { 2 | 3 | static void print(int n){ 4 | if(n>0){ 5 | System.out.println(n); 6 | print(n-1); // Inner Call 7 | print(n-2); // Outer Call 8 | } 9 | } 10 | public static void main(String[] args) { 11 | print(3); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /StrongestNeighbour.java: -------------------------------------------------------------------------------- 1 | public class StrongestNeighbour { 2 | public static void main(String[] args) { 3 | int arr[] = {1,2,2,3,4,5}; 4 | for(int i = 1; i list = Arrays.asList(10,20,30,40,50); 8 | Integer x[] = new Integer[list.size()]; 9 | Integer a[] = list.toArray(x); 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LT-867: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] transpose(int[][] matrix) { 3 | int result[][] = new int[matrix[0].length][matrix.length]; 4 | for(int i = 0; i " + C); 6 | return; 7 | } 8 | toh(n-1, A, C, B); 9 | toh(1,A,B,C); 10 | toh(n-1, B, A, C); 11 | } 12 | public static void main(String[] args) { 13 | toh(3, 'A', 'B', 'C'); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /HashCode.java: -------------------------------------------------------------------------------- 1 | public class HashCode { 2 | static long HashValue(String pattern){ 3 | long hashvalue =0; 4 | for(int i=0;i0){ 6 | int bit = n&1; 7 | ans.append(bit); 8 | n = n>>1; 9 | } 10 | return ans.reverse().toString(); 11 | } 12 | public static void main(String[] args) { 13 | int n=12; 14 | System.out.println(DecToBinary(n)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /GFG-LeaderElement: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | //Function to find the leaders in the array. 3 | static ArrayList leaders(int arr[], int n){ 4 | int max = 0; 5 | ArrayList list= new ArrayList<>(); 6 | for(int i = arr.length-1; i>=0; i--){ 7 | if(arr[i]>=max){ 8 | max = arr[i]; 9 | list.add(max); 10 | } 11 | } 12 | Collections.reverse(list); 13 | return list; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Suffix.java: -------------------------------------------------------------------------------- 1 | public class Suffix { 2 | 3 | static void findSuffix(String str){ 4 | int n = str.length(); 5 | String []arr = new String[n]; 6 | for(int i=0;i=0;i--){ 7 | int bit = str.charAt(i) - '0'; 8 | ans+= (bit << mask); 9 | mask++; 10 | } 11 | return ans; 12 | } 13 | public static void main(String[] args) { 14 | String str = "1001"; 15 | System.out.println("NUMBER IS : " + binaryToDec(str)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ReverseAnArray.java: -------------------------------------------------------------------------------- 1 | public class ReverseAnArray { 2 | public static void main(String[] args) { 3 | int arr[] = {10,20,30,40,50}; 4 | int low = 0; 5 | int high = arr.length-1; 6 | int temp = 0; 7 | while(low=0 ){ 6 | if(matrix[low][high]== target){ 7 | return true; 8 | } 9 | else if(matrix[low][high]>target){ 10 | high --; 11 | } 12 | else if(matrix[low][high]=0 ){ 6 | if(matrix[low][high]== target){ 7 | return true; 8 | } 9 | else if(matrix[low][high]>target){ 10 | high --; 11 | } 12 | else if(matrix[low][high]=5){ 9 | return ; 10 | } 11 | System.out.println(x); 12 | branch(x+1); // Inner Call 13 | branch(x+2); // Outer Call 14 | branch(x+3); 15 | } 16 | 17 | /* 18 | * 0 19 | 1 20 | 2 21 | 2 22 | */ 23 | 24 | public static void main(String[] args) { 25 | branch(0); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Space.java: -------------------------------------------------------------------------------- 1 | public class Space { 2 | static int computeSum(int arr[], int sum ){ 3 | for(int i = 0 ; ielements[j]){ 13 | dp[i]= Math.max(dp[i], 1 + dp[j]); 14 | len = Math.max(len, dp[i]); 15 | } 16 | } 17 | } 18 | System.out.println(len); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SubSetSumProblem-GFG: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | 4 | static Boolean isSubsetSum(int N, int arr[], int sum){ 5 | // Termination Case 6 | if(sum ==0){ 7 | return true; 8 | } 9 | if(N==0){ 10 | return false; 11 | } 12 | // Array Element it must be less than equal to sum 13 | if(arr[N-1]<=sum){ 14 | // Include the Sum 15 | return isSubsetSum(N-1, arr, sum - arr[N-1]) || isSubsetSum(N-1, arr, sum); 16 | 17 | // Not Include the Sum 18 | 19 | } 20 | else{ 21 | return isSubsetSum(N-1, arr, sum); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LC-48: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | // Transpose the Matrix 4 | for(int i = 0; i=0 && dp[i-coin]!=Integer.MAX_VALUE){ 11 | dp[i] = Math.min(dp[i], dp[i-coin]+1) ; 12 | } 13 | } 14 | } 15 | System.out.println(dp[moneyValue]==Integer.MAX_VALUE?"No Solution ":dp[moneyValue]); 16 | 17 | 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode- TargetSum-494: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int count = 0; 3 | public int findTargetSumWays(int[] nums, int target) { 4 | compute(nums, 0,0, target); 5 | return count; 6 | } 7 | private void compute(int[] nums , int sum , int index, int target ){ 8 | // Termination Case 9 | if(index == nums.length){ 10 | if(sum == target){ 11 | count++; 12 | } 13 | } 14 | else{ 15 | // Include 16 | compute(nums, sum + nums[index], index + 1, target); 17 | // Not Include 18 | compute(nums, sum - nums[index], index + 1, target); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /RecursionDemo.java: -------------------------------------------------------------------------------- 1 | public class RecursionDemo { 2 | // n is a local variable 3 | static void show(int n){ 4 | if(n==0){ // Termination Case (Brake) 5 | return ; // exit from the function 6 | } 7 | System.out.println("Hello Amit "+n); // Logic During Stack Build 8 | // Making a Cycle 9 | show(n-1); // Stack Build 10 | System.out.println("Hi Amit "+n); // Logic During Stack Fall 11 | } 12 | 13 | static void disp(int n){ 14 | for(int i = 1;i<=n;i++){ 15 | System.out.println("Hi Amit"); 16 | } 17 | } 18 | public static void main(String[] args) { 19 | show(5); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Anagram.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class Anagram { 5 | 6 | static boolean areAnagram(String s1, String s2){ 7 | if(s1.length() != s2.length()){ 8 | return false; 9 | } 10 | 11 | char []a = s1.toCharArray(); 12 | Arrays.sort(a); 13 | s1 = new String(a); 14 | 15 | char[] b = s2.toCharArray(); 16 | Arrays.sort(b); 17 | s2 = new String(b); 18 | 19 | return s1.equals(s2); 20 | } 21 | public static void main(String[] args) { 22 | String s1 = "cod"; 23 | String s2 = "code"; 24 | System.out.println(areAnagram(s1, s2)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ArraySearch.java: -------------------------------------------------------------------------------- 1 | public class ArraySearch { 2 | 3 | static int search(int arr[], int index, int searchValue){ 4 | 5 | // Termination Case 6 | if(arr.length==index){ 7 | return -1; 8 | } 9 | if(arr[index] == searchValue){ // Element Found... 10 | return index; 11 | } 12 | // Small Problem 13 | return search(arr, index+1, searchValue); 14 | } 15 | public static void main(String[] args) { 16 | int arr[] = {10,90,100,20,40,88}; 17 | int searchValue = 1120; 18 | 19 | System.out.println(search(arr, 0, searchValue)>=0?"Element Found":"Not Found"); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /UniqueChar.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class UniqueChar { 4 | 5 | static int firstUnique(String s){ 6 | HashMap count = new HashMap<>(); 7 | int n = s.length(); 8 | for(int i=0;i target) { 11 | return 0; 12 | } 13 | int count = 0; 14 | for(int dice = 1; dice <= 6; dice++) { 15 | count = count + countWays(current+dice, target); 16 | } 17 | return count; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int res = countWays(0, 10); 22 | System.out.println(res); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial { 2 | 3 | static int fact(int num){ 4 | // Termination Case 5 | if(num ==1 || num ==0){ 6 | return 1; 7 | } 8 | int result = fact(num-1); // Small Problem 9 | return result * num; 10 | } 11 | 12 | static void fact(int num, int result){ 13 | // Termination case 14 | if(num ==1 || num ==0){ 15 | System.out.println(result); 16 | return; // exit from the function 17 | } 18 | fact(num-1, num * result); // Small Problem 19 | } 20 | public static void main(String[] args) { 21 | //fact(0,1); 22 | System.out.println(fact(5)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /StockSpan.java: -------------------------------------------------------------------------------- 1 | public class StockSpan { 2 | 3 | static int[] func(int []prices){ 4 | int n = prices.length; 5 | int []ans = new int[n]; 6 | for(int i=0;i=0 && prices[j]<=prices[i]){ 10 | c++; 11 | j--; 12 | } 13 | ans[i] = c; 14 | } 15 | return ans; 16 | } 17 | public static void main(String[] args) { 18 | int prices[] = {60,50,40,30,85,90,60}; 19 | int []ans = func(prices); 20 | for(int i:ans){ 21 | System.out.print(i + " "); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode-134: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | int startingPoint = 0; 4 | int surplus = 0; 5 | int deficit = 0; 6 | for(int i = 0; i=0){ 16 | return startingPoint; 17 | } 18 | else { 19 | return -1; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /BinaryNums.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | public class BinaryNums { 5 | 6 | static void printBinary(int n){ 7 | Queue queue = new LinkedList<>(); 8 | queue.offer("1"); 9 | 10 | for(int i=0;iarr[j]){ 7 | // System.out.println("Not Sorted..."); 8 | // return ; 9 | // } 10 | // } 11 | // } 12 | for(int i = 1; iarr[i]){ 14 | System.out.println("Not Sorted..."); 15 | return ; 16 | } 17 | } 18 | System.out.println("Sorted..."); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SortedArray.java: -------------------------------------------------------------------------------- 1 | public class SortedArray { 2 | 3 | static boolean isSortedArray(int []arr, int index){ 4 | // Termination Case 5 | if(arr.length-1 == index){ 6 | return true; // Array is Sorted 7 | } 8 | if(arr[index]>arr[index+1]){ 9 | return false; // Array is not sorted 10 | } 11 | // 0 , 1, 2 , 3 , 4 (Index will keep moving) 12 | // Small Problem (Moving Index) (recursion (cycle)) 13 | return isSortedArray(arr, index+1); 14 | } 15 | public static void main(String[] args) { 16 | int arr[] = {10,20,30,90,50}; 17 | System.out.println(isSortedArray(arr, 0)?"Array is Sorted ":"Array is Not Sorted"); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LastStoneWeight.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | public class LastStoneWeight { 4 | 5 | static int lastStone(int []arr){ 6 | PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> b-a); 7 | for(int i:arr){ 8 | maxHeap.add(i); 9 | } 10 | 11 | while(maxHeap.size()>1){ 12 | int x1 = maxHeap.poll(); 13 | int x2 = maxHeap.poll(); 14 | 15 | int difference = x1 - x2; 16 | maxHeap.add(difference); 17 | } 18 | return maxHeap.poll(); 19 | } 20 | public static void main(String[] args) { 21 | int arr[] = {4,2,6,4}; 22 | int ans = lastStone(arr); 23 | System.out.println(ans); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /FindInWindowSlide.java: -------------------------------------------------------------------------------- 1 | public class FindInWindowSlide { 2 | public static void main(String[] args) { 3 | int arr[] = {1,2,3,2,1,2,3,1}; 4 | int k = 3; 5 | int x = 2; 6 | int f = 0; 7 | for(int i = 0; imax){ 8 | max = element; 9 | } 10 | } 11 | int min = 1; 12 | for(int i = max; i>=min; i--){ 13 | for(int j = 0; j=0;i--){ 8 | while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]){ 9 | stack.pop(); 10 | } 11 | 12 | ns[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; 13 | 14 | stack.push(i); 15 | } 16 | return ns; 17 | } 18 | public static void main(String[] args) { 19 | int arr[] = {50,60,50,40,95,80}; 20 | int ans[] = findNs(arr); 21 | 22 | for(int i : ans){ 23 | System.out.print(i + " "); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CoinChangeProblem.java: -------------------------------------------------------------------------------- 1 | public class CoinChangeProblem { 2 | 3 | static int count(int coins[], int coinsLen, int moneyValue){ 4 | if(moneyValue==0){ 5 | return 1; 6 | } 7 | if(moneyValue<=0) 8 | { 9 | return 0; 10 | } 11 | if(coinsLen<=0){ 12 | return 0; 13 | } 14 | // include coin 15 | // exclude coin 16 | return count(coins, coinsLen-1, moneyValue) + 17 | count(coins, coinsLen, moneyValue - coins[coinsLen-1]); 18 | } 19 | 20 | public static void main(String[] args) { 21 | int coins[] = {1,3,7,10}; 22 | int moneyValue = 15; 23 | int countCoins = count(coins, coins.length, moneyValue); 24 | System.out.println(countCoins); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BinarySearchAlgo.java: -------------------------------------------------------------------------------- 1 | public class BinarySearchAlgo { 2 | public static void main(String[] args) { 3 | int arr [] = {10,20,30,40,50,60,70,80,90}; 4 | int search = 2000; 5 | int low = 0; 6 | int high = arr.length-1; 7 | int mid =0; 8 | while(lowarr[mid]){ 15 | low = mid + 1; // Search in Upper Side 16 | } 17 | else if (search 0 && index== coins.length){ 15 | return 0; } 16 | 17 | return helper(coins, amount - coins[index], index) + helper(coins, amount , index + 1); 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] coins = {1,2}; 22 | int amount = 3; 23 | System.out.println(coinChange(coins, amount)); // Output: 5 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /PalindromeSubstring.java: -------------------------------------------------------------------------------- 1 | public class PalindromeSubstring { 2 | 3 | static boolean isPalindrome(String str){ 4 | int i=0; 5 | int j = str.length()-1; 6 | while(i<=j){ 7 | if(str.charAt(i)!= str.charAt(j)){ 8 | return false; 9 | } 10 | i++; 11 | j--; 12 | } 13 | return true; 14 | } 15 | public static void main(String[] args) { 16 | String str = "abccbc"; 17 | for(int i=0;ifirstLargest){ 13 | secondLargest = firstLargest; 14 | firstLargest = arr[i]; 15 | } 16 | else if(arr[i]>secondLargest && arr[i]!=firstLargest){ 17 | secondLargest = arr[i]; 18 | } 19 | } 20 | System.out.println(firstLargest+ " "+secondLargest); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CoinChangeProblem2.java: -------------------------------------------------------------------------------- 1 | class CoinChangeProblem2{ 2 | static int count (int coins[], int len , int moneyValue){ 3 | if(moneyValue==0){ 4 | return 0; 5 | } 6 | // maintain initalize result 7 | int res = Integer.MAX_VALUE; 8 | for(int i = 0; i minHeap = new PriorityQueue<>(); 10 | minHeap.add(1); 11 | for(int i=1;i stack = new Stack<>(); 8 | 9 | for(int i=0;i= prices[i]){ 11 | stack.pop(); 12 | } 13 | 14 | ans[i] = stack.isEmpty() ? -1 : stack.peek(); 15 | stack.push(prices[i]); 16 | } 17 | return ans; 18 | } 19 | public static void main(String[] args) { 20 | int prices[] = {60,50,40,85,90,60}; 21 | int [] ans= func2(prices); 22 | for(int i:ans){ 23 | System.out.print(i + " "); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /EvenOddPosSum.java: -------------------------------------------------------------------------------- 1 | public class EvenOddPosSum { 2 | 3 | static int[] sumEvenOddPos(int num, int pos){ 4 | // Termination Case 5 | if(num ==0){ // Init Once 6 | int result [] = new int[2]; // {0,0} 7 | return result; 8 | } 9 | 10 | 11 | // Small Problem 12 | int arr[] = sumEvenOddPos(num/10, pos + 1); // Make a number small 13 | int digit = num % 10; 14 | if(pos%2!=0){ 15 | arr[0] = arr[0] + digit; // Every time fill 16 | } 17 | else{ 18 | arr[1] = arr[1] + digit; // Every time fill 19 | } 20 | return arr; 21 | } 22 | public static void main(String[] args) { 23 | int arr[] = sumEvenOddPos(2789, 0); 24 | System.out.println("Odd Sum "+arr[0]); 25 | System.out.println("Even Sum "+arr[1]); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /MinDifference.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | public class MinDifference { 4 | static int minDiff(int arr[]){ 5 | if(arr.length == 1 || arr.length == 0){ 6 | return 0; 7 | } 8 | PriorityQueue minHeap = new PriorityQueue<>(); 9 | for(int i :arr){ 10 | minHeap.offer(i); 11 | } 12 | 13 | int min = Integer.MAX_VALUE; 14 | 15 | int top = minHeap.poll(); 16 | while(!minHeap.isEmpty()){ 17 | int current =minHeap.poll(); 18 | int diff = current - top; 19 | min = Math.min(min, diff); 20 | top= current; 21 | } 22 | return min; 23 | } 24 | p 25 | public static void main(String[] args) { 26 | int arr[] = {}; 27 | int ans = minDiff(arr); 28 | System.out.println(ans); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PrintSubsequences.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class PrintSubsequences { 4 | public static void main(String[] args) { 5 | String str = "abcd"; 6 | ArrayList subSeqList = new ArrayList<>(); 7 | 8 | int n = str.length(); 9 | for(int i=0;i hash = new HashMap<>(); 6 | 7 | 8 | for(int i = 0; iarr[i+1]){ 9 | temp = arr[i]; 10 | arr[i] = arr[i+1]; 11 | arr[i+1] = temp; 12 | } 13 | } 14 | else{ // flag is false 15 | if(arr[i] target) { 11 | return 0; 12 | } 13 | if(cache[current] != 0) { 14 | return cache[current]; 15 | } 16 | int count = 0; 17 | for(int dice = 1; dice <= 6; dice++) { 18 | count = count + countWays(current+dice, target, cache); 19 | } 20 | cache[current] = count; 21 | return count; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int target = 5; 26 | int cache[] = new int[target+1]; 27 | int res = countWays(0, target, cache); 28 | System.out.println(res); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /SubSequence.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class SubSequence { 4 | 5 | static ArrayList getAllSubSequence(String str){ 6 | // Termination Case 7 | if(str.length() ==0){ 8 | ArrayList list = new ArrayList<>(); 9 | list.add(""); 10 | return list; 11 | } 12 | // Small Problem (Make a String small) 13 | char firstChar = str.charAt(0); 14 | ArrayList result = new ArrayList<>(); 15 | ArrayList list = getAllSubSequence(str.substring(1)); 16 | for(String s : list){ 17 | // Not Include it 18 | result.add(s); 19 | // Include it 20 | result.add(firstChar + s); 21 | } 22 | return result; 23 | } 24 | 25 | public static void main(String[] args) { 26 | ArrayList result = getAllSubSequence("amit"); 27 | System.out.println(result); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ConvertTo2D.java: -------------------------------------------------------------------------------- 1 | public class ConvertTo2D { 2 | 3 | static int[][] convert2D(int []arr, int n, int m){ 4 | int [][]result = new int[n][m]; 5 | 6 | if((m*n) != arr.length){ 7 | return new int[0][0]; 8 | } 9 | int row =0; 10 | int col =0; 11 | for(int i=0;i sortStack(Stack original){ 5 | Stack temp = new Stack(); 6 | 7 | while(!original.isEmpty()){ 8 | int current = original.pop(); 9 | 10 | while(!temp.isEmpty() && current > temp.peek()){ 11 | original.push(temp.pop()); 12 | } 13 | temp.push(current); 14 | } 15 | return temp; 16 | } 17 | public static void main(String[] args) { 18 | Stack original = new Stack(); 19 | original.push(95); 20 | original.push(46); 21 | original.push(50); 22 | original.push(74); 23 | original.push(39); 24 | Stack ans = sortStack(original); 25 | 26 | while(!ans.isEmpty()){ 27 | System.out.print(ans.pop() + " "); 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /IsBinaryMaxHeap.java: -------------------------------------------------------------------------------- 1 | class TreeNode{ 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | public TreeNode(int val){ 7 | this.val = val; 8 | } 9 | } 10 | public class IsBinaryMaxHeap { 11 | 12 | public static boolean isMinHeap(TreeNode root){ 13 | return helper(root, Integer.MAX_VALUE); 14 | } 15 | 16 | static boolean helper(TreeNode node, int parentValue){ 17 | if(node == null){ 18 | return true; 19 | } 20 | if(node.val > parentValue){ 21 | return false; 22 | } 23 | return helper(node.left, node.val) && helper(node.right, node.val); 24 | } 25 | public static void main(String[] args) { 26 | TreeNode root =new TreeNode(10); 27 | root.left = new TreeNode(30); 28 | root.right = new TreeNode(5); 29 | root.left.left = new TreeNode(40); 30 | root.left.right = new TreeNode(15); 31 | System.out.println(isMinHeap(root)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /IsBinaryMinHeap.java: -------------------------------------------------------------------------------- 1 | class TreeNode{ 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | public TreeNode(int val){ 7 | this.val = val; 8 | } 9 | } 10 | public class IsBinaryMinHeap { 11 | 12 | public static boolean isMinHeap(TreeNode root){ 13 | return helper(root, Integer.MIN_VALUE); 14 | } 15 | 16 | static boolean helper(TreeNode node, int parentValue){ 17 | if(node == null){ 18 | return true; 19 | } 20 | if(node.val < parentValue){ 21 | return false; 22 | } 23 | return helper(node.left, node.val) && helper(node.right, node.val); 24 | } 25 | public static void main(String[] args) { 26 | TreeNode root =new TreeNode(10); 27 | root.left = new TreeNode(20); 28 | root.right = new TreeNode(30); 29 | root.left.left = new TreeNode(40); 30 | root.left.right = new TreeNode(50); 31 | System.out.println(isMinHeap(root)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /SecondLargestElement.java: -------------------------------------------------------------------------------- 1 | public class SecondLargestElement { 2 | public static void main(String[] args) { 3 | int arr[] = {10,20,90,100,1,44}; 4 | // First Largest 5 | int firstLargest = 0; // 0th index 6 | int secondLargest = -1; 7 | // get the first largest 8 | for(int i= 1; iarr[firstLargest]){ 10 | firstLargest = i; 11 | } 12 | } 13 | // now get the second largest 14 | for(int i = 0; iarr[secondLargest]){ 20 | secondLargest = i; 21 | } 22 | } 23 | } 24 | System.out.println("First Largest "+arr[firstLargest]); 25 | System.out.println("Second Largest "+arr[secondLargest]); 26 | 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /SortByFrequency.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.PriorityQueue; 3 | import java.util.HashMap; 4 | 5 | public class SortByFrequency { 6 | static String frequencySort(String str){ 7 | Map map = new HashMap<>(); 8 | for(char c : str.toCharArray()){ 9 | map.put(c,map.getOrDefault(c, 0)+1); 10 | } 11 | 12 | PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a)); 13 | maxHeap.addAll(map.keySet()); 14 | StringBuilder res = new StringBuilder(); 15 | while(!maxHeap.isEmpty()){ 16 | char c = maxHeap.poll(); 17 | int freq = map.get(c); 18 | for(int i=0;i list = new ArrayList<>(); 11 | Object o = 10; 12 | list.add(10); 13 | list.add(20); 14 | list.add(30); 15 | list.add(10); 16 | list.add(10); 17 | list.add(0,99); 18 | list.removeIf((Integer element)->element==10); 19 | //System.out.println(list); 20 | // list.remove(o); 21 | System.out.println(list); 22 | //list.remove(100); 23 | 24 | list.set(0, 11111); 25 | System.out.println(list); 26 | 27 | ArrayList names = new ArrayList<>(); 28 | names.add("amit"); 29 | names.add("ram"); 30 | names.add("shyam"); 31 | names.remove("ram"); 32 | System.out.println(names); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Perm.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Perm { 4 | 5 | static ArrayList getPerm(String str){ 6 | // TERMINATION CASE 7 | if(str.length()==0){ 8 | ArrayList l = new ArrayList<>(); 9 | l.add(""); 10 | return l; 11 | } 12 | // get the first char 13 | char firstChar = str.charAt(0); 14 | ArrayList finalList = new ArrayList<>(); 15 | // Make the String small so it is easy to compute Perm of Small 16 | ArrayList result = getPerm(str.substring(1)); 17 | // Traverse the Result 18 | for(String t : result){ 19 | for(int i = 0; i<=t.length(); i++){ 20 | StringBuilder sb = new StringBuilder(t); 21 | sb.insert(i,firstChar); 22 | finalList.add(sb.toString()); 23 | } 24 | } 25 | return finalList; 26 | } 27 | public static void main(String[] args) { 28 | System.out.println(getPerm("abc")); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /LargestArea.java: -------------------------------------------------------------------------------- 1 | public class LargestArea { 2 | 3 | static int getMaxArea(int arr[]){ 4 | int ans =0; 5 | int n = arr.length; 6 | for(int i=0;i=0;j--){ 11 | if(arr[j] >= arr[i]){ 12 | current += arr[i]; 13 | } 14 | else{ 15 | break; 16 | } 17 | } 18 | //next area 19 | for(int j=i+1;j= arr[i]){ 21 | current += arr[i]; 22 | } 23 | else{ 24 | break; 25 | } 26 | } 27 | ans = Math.max(ans,current); 28 | } 29 | return ans; 30 | } 31 | public static void main(String[] args) { 32 | int arr[] = {6,2,5,4,5,6}; 33 | System.out.println("Max Area Is :" + getMaxArea(arr)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /RotateAnArray.java: -------------------------------------------------------------------------------- 1 | public class RotateAnArray { 2 | 3 | static void reverse(int arr[], int low, int high){ 4 | while(low> adj, int u, int v) { 6 | // for undirected graph connect u and v and then v and u 7 | adj.get(u).add(v); 8 | adj.get(v).add(u); 9 | } 10 | 11 | static void printGraph(ArrayList> adj) { 12 | for(int i = 0; i < adj.size(); i++) { 13 | System.out.print(i + " : "); 14 | for(int j = 0; j < adj.get(i).size(); j++) { 15 | System.out.print(adj.get(i).get(j) + ","); 16 | } 17 | System.out.println(); 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | int V = 4; 23 | ArrayList> adj = new ArrayList<>(); 24 | for(int i = 0; i < V; i++) { 25 | adj.add(new ArrayList<>()); 26 | } 27 | addEdge(adj, 0, 1); 28 | addEdge(adj, 0, 2); 29 | addEdge(adj, 1, 2); 30 | addEdge(adj, 1, 3); 31 | addEdge(adj, 2, 3); 32 | printGraph(adj); 33 | } 34 | } -------------------------------------------------------------------------------- /SumOfDigit.java: -------------------------------------------------------------------------------- 1 | public class SumOfDigit { 2 | 3 | static int sod(int num){ 4 | // Termination Case 5 | if(num ==0){ 6 | return 0; // It is a sum initial value 7 | } 8 | int singleDigit = num % 10; 9 | int sum =sod(num/10); // Make a Number Small (Small Problem) 10 | // Stack Fall 11 | 12 | sum = sum + singleDigit; 13 | return sum; 14 | } 15 | 16 | static void sod(int num, int sum ){ 17 | 18 | // Termination Case 19 | if(num==0){ 20 | System.out.println("Sum "+sum); 21 | return ; 22 | } 23 | 24 | // get the reminder (Single digit) 25 | // Local Variable 26 | int singleDigit = num % 10; // Business Logic 27 | sum = sum + singleDigit; 28 | // Small Problem 29 | // num/10 make the number small and pass the sum for the next call 30 | sod(num/10, sum); // Tail Recursion 31 | 32 | } 33 | public static void main(String[] args) { 34 | int num = 123; 35 | //sod(num, 0); 36 | System.out.println(sod(123)); 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ReverseQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | import java.util.Stack; 4 | 5 | public class ReverseQueue { 6 | 7 | static void reverseQueue(Queue queue){ 8 | Stack stack = new Stack<>(); 9 | 10 | while(!queue.isEmpty()){ 11 | stack.push(queue.poll()); 12 | } 13 | 14 | while(!stack.isEmpty()){ 15 | queue.offer(stack.pop()); 16 | } 17 | } 18 | 19 | //Without using extra space 20 | static void reverseQueue2(Queue queue ){ 21 | if(queue.isEmpty()){ 22 | return; 23 | } 24 | int front = queue.poll(); 25 | reverseQueue2(queue); 26 | queue.offer(front); 27 | } 28 | public static void main(String[] args) { 29 | Queue queue = new LinkedList<>(); 30 | queue.add(10); 31 | queue.add(20); 32 | queue.add(30); 33 | queue.add(40); 34 | System.out.println("Original Queue : " + queue); 35 | reverseQueue2(queue); 36 | System.out.println("Reversed Queue : " + queue); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MCPTabulation.java: -------------------------------------------------------------------------------- 1 | public class MCPTabulation { 2 | public static void main(String[] args) { 3 | int cost [][] = {{2,0,6},{3,1,7},{4,5,9}}; 4 | int result [][] = new int[cost.length][cost.length]; 5 | // fill the first cell 6 | result [0][0] = cost[0][0]; 7 | // now we know the first cell value, based on first cell , fill the rest of the columns 8 | // fill the first column 9 | for(int i = 1; i generateParenthesis(int n) { 3 | List result = new ArrayList<>(); 4 | StringBuilder sb = new StringBuilder(); 5 | generateBrackets(result, n, 0, 0, sb); 6 | return result; 7 | } 8 | 9 | private void generateBrackets(List result, int n , int opening, int closing, StringBuilder output){ 10 | // Termination Case 11 | if(output.length() == n*2){ 12 | result.add(output.toString()); 13 | return ; 14 | } 15 | // Can i Place Opening 16 | if(openingarr[mid]){ 13 | nearestLowestElement = arr[mid]; 14 | low = mid + 1; 15 | } 16 | else if(searchElement> generate(int numRows) { 6 | List> trows = new ArrayList<>(); 7 | 8 | 9 | for(int i = 0; i < numRows; i++){ 10 | List col = new ArrayList<>(); 11 | 12 | for(int j = 0; j <= i; j++){ 13 | if (j==0 || j==i){ 14 | // Every Column's First and Last Element are filled with 1 15 | col.add(1); 16 | } else { 17 | // Addition of previous Row's First two elements then second two elements , and so on 18 | col.add(j, trows.get(i-1).get(j-1)+trows.get(i-1).get(j)); 19 | } 20 | } 21 | 22 | trows.add(col); 23 | } 24 | return trows; 25 | 26 | } 27 | 28 | public static void main(String[] args) { 29 | int numRows = 5; 30 | List> triangle = generate(numRows); 31 | System.out.println(triangle); 32 | System.out.println(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /CountIntegers.java: -------------------------------------------------------------------------------- 1 | public class CountIntegers { 2 | 3 | //PROBLEM COUNT INTEGERS 4 | public static int countIntegers(int n) { 5 | int count = 0; 6 | 7 | for (int x = 0; x <= n; x++) { 8 | if ((n & x) == x) { 9 | count++; 10 | } 11 | } 12 | 13 | return count; 14 | } 15 | 16 | 17 | 18 | // PROBLEM findMaximumBitwiseAnd 19 | 20 | public static int findMaximumBitwiseAnd(int[] array) { 21 | int maxAnd = 0; 22 | 23 | for (int i = 0; i < array.length - 1; i++) { 24 | for (int j = i + 1; j < array.length; j++) { 25 | int bitwiseAnd = array[i] & array[j]; 26 | if (bitwiseAnd > maxAnd) { 27 | maxAnd = bitwiseAnd; 28 | } 29 | } 30 | } 31 | 32 | return maxAnd; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int n = 5; 37 | int output = countIntegers(n); 38 | System.out.println(output); // Output: 4 39 | 40 | int []arr = {3, 5, 8, 10, 12}; 41 | System.out.println(findMaximumBitwiseAnd(arr)); 42 | } 43 | } -------------------------------------------------------------------------------- /GraphDFS.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class GraphDFS { 4 | 5 | static void addEdge(ArrayList> adj, int u, int v) { 6 | // for undirected graph connect u and v and then v and u 7 | adj.get(u).add(v); 8 | adj.get(v).add(u); 9 | } 10 | 11 | static void dfsRec(ArrayList> adj, int s, boolean[] visited) { 12 | visited[s] = true; 13 | System.out.print(s + ","); 14 | for(int u : adj.get(s)) { 15 | if(visited[u] == false) { 16 | dfsRec(adj, u, visited); 17 | } 18 | } 19 | } 20 | 21 | static void dfs(ArrayList> adj, int V, int s) { 22 | boolean[] visited = new boolean[V]; 23 | for(int i = 0; i < V; i++) { 24 | visited[i] = false; 25 | } 26 | // dfsRec(adj, s, visited); 27 | // for disconnected 28 | for(int i = 0; i < V; i++) { 29 | if(visited[i] == false) { 30 | dfsRec(adj, i, visited); 31 | } 32 | } 33 | } 34 | 35 | public static void main(String[] args) { 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /TwoDArray.java: -------------------------------------------------------------------------------- 1 | public class TwoDArray { 2 | public static void main(String[] args) { 3 | //int a[] = new int[10]; 4 | int x[][] = new int[3][3]; 5 | int [][]y = new int[3][3]; 6 | int []z[] = new int[3][3]; 7 | int a[][] = {{1,2,3}, {10,20,30},{1,1,2}}; 8 | int b[][] = new int[3][]; 9 | b[0] = new int[5]; 10 | b[1] = new int[6]; 11 | b[2] = new int[7]; 12 | // Row Major Access 13 | for(int i = 0; i stack = new Stack<>(); 5 | for(int i=0;i diceGame(int currentValue, int endValue){ 6 | if(currentValue == endValue){ 7 | // Part of the result (10 Reach) 8 | ArrayList result = new ArrayList<>(); 9 | result.add(""); 10 | return result; 11 | } 12 | 13 | if(currentValue>endValue){ 14 | // Exceed 10 (Not Part of the result) 15 | ArrayList result = new ArrayList<>(); 16 | return result; 17 | } 18 | 19 | 20 | // 1 to 6 Calls? 21 | // Roll the Dice (Can be 1 to 6) 22 | ArrayList finalResult = new ArrayList<>(); 23 | for(int dice = 1; dice<=6; dice++){ 24 | int newValue = currentValue + dice; 25 | ArrayList list = diceGame(newValue, endValue); 26 | for(String s : list){ 27 | finalResult.add(dice + s); 28 | } 29 | } 30 | return finalResult; 31 | } 32 | 33 | public static void main(String[] args) { 34 | ArrayList result = diceGame(0,10); 35 | System.out.println(result); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LC-1380: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List luckyNumbers (int[][] matrix) { 3 | List minValues = new ArrayList<>(); 4 | // Min Value in a Row 5 | int minRow = Integer.MAX_VALUE; 6 | for(int i = 0; i maxValues = new ArrayList<>(); 15 | int maxCol = Integer.MIN_VALUE; 16 | for(int i = 0; i result = new ArrayList<>(); 26 | for(int minElement : minValues){ 27 | if(maxValues.contains(minElement)){ 28 | result.add(minElement); 29 | } 30 | } 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Stack.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | public class Stack { 5 | Queue queue1; 6 | Queue queue2; 7 | 8 | public Stack(){ 9 | queue1 = new LinkedList<>(); 10 | queue2 = new LinkedList<>(); 11 | } 12 | 13 | public void push(int x){ 14 | queue2.add(x); 15 | while(!queue1.isEmpty()){ 16 | queue2.add(queue1.remove()); 17 | } 18 | Queue temp = queue1; 19 | queue1 = queue2; 20 | queue2 = temp; 21 | } 22 | 23 | public int pop(){ 24 | if(isEmpty()){ 25 | throw new RuntimeException("Stack is empty"); 26 | } 27 | return queue1.remove(); 28 | } 29 | 30 | public boolean isEmpty(){ 31 | return queue1.isEmpty(); 32 | } 33 | 34 | public int size(){ 35 | return queue1.size(); 36 | } 37 | 38 | public static void main(String[] args) { 39 | Stack stack = new Stack(); 40 | 41 | stack.push(10); 42 | stack.push(20); 43 | stack.push(30); 44 | 45 | System.out.println(stack.size()); 46 | stack.pop(); 47 | System.out.println(stack.size()); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /StringHalvesAreAlike.java: -------------------------------------------------------------------------------- 1 | public class StringHalvesAreAlike { 2 | 3 | static boolean halvesAreAlike(String s) { 4 | int c1 =0; 5 | int c2=0; 6 | int n = s.length(); 7 | String a = s.substring(0, n/2); 8 | String b = s.substring(n/2); 9 | 10 | if(n%2 !=0){ 11 | return false; 12 | } 13 | 14 | for(int i=0;i generate(int n) { 9 | List ans = new ArrayList<>(); 10 | helper(ans, "", 0, 0, n); 11 | return ans; 12 | } 13 | 14 | static void helper(List ans, String currentBracket, int open, int close, int max) { 15 | 16 | // Base Case 17 | if(currentBracket.length() == max * 2) { 18 | ans.add(currentBracket); 19 | return; 20 | } 21 | 22 | if(open < max) { 23 | // we can open bracket when open is less than n 24 | // if n=3, then we can only open 3 brackets 25 | helper(ans, currentBracket + "(", open + 1, close, max); 26 | } 27 | 28 | if(close < open) { 29 | // closing number of brackets cannot be greater then opening brackets 30 | helper(ans, currentBracket + ")", open, close + 1, max); 31 | } 32 | return; 33 | } 34 | 35 | 36 | public static void main(String[] args) { 37 | List ans = generate(3); 38 | System.out.println(ans); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /First.java: -------------------------------------------------------------------------------- 1 | class First{ 2 | public static void main(String[] args) { 3 | int mul[][] = {{10,20},{30,40,50}, {60,70,80,90}}; 4 | // Traditional Loop 5 | // for(int i = 0; i> verticalTraversal(TreeNode root) { 2 | TreeMap>> map = new TreeMap<>(); 3 | List> li = new ArrayList<>(); 4 | verticalOrder(map, root, 0, 0); 5 | for(int key : map.keySet()){ 6 | List> temp = map.get(key); 7 | temp.sort((a,b) -> a.getKey().compareTo(b.getKey())== 0? a. getValue().compareTo(b.getValue()) : a.getKey().compareTo(b.getKey())); 8 | List list = new ArrayList<>(); 9 | for(Pair pair : temp){ 10 | list.add(pair.getValue()); 11 | } 12 | li.add(list); 13 | } 14 | 15 | return li; 16 | } 17 | private void verticalOrder(TreeMap>> map, 18 | TreeNode root, int level, int distance){ 19 | if(root == null) return; 20 | if(map.get(distance)==null){ 21 | map.put(distance, new ArrayList<>()); 22 | } 23 | map.get(distance).add(new Pair(level, root.val)); 24 | verticalOrder(map, root.left, level + 1, distance - 1); 25 | verticalOrder(map, root.right, level + 1, distance + 1); 26 | } 27 | -------------------------------------------------------------------------------- /EditDistanceTabulation.java: -------------------------------------------------------------------------------- 1 | public class EditDistanceTabulation { 2 | public static void main(String[] args) { 3 | String first = "sunday"; 4 | String second = "saturday"; 5 | int m = first.length(); 6 | int n = second.length(); 7 | int matrix [][] = new int[m+1][n+1]; 8 | for(int i = 0; i<=m; i++){ 9 | for(int j = 0; j<=n;j++){ 10 | if(i == 0){ 11 | matrix[i][j] = j; 12 | 13 | } 14 | else if (j==0){ 15 | matrix[i][j] = i; 16 | } 17 | else 18 | // char same 19 | if(first.charAt(i-1) == second.charAt(j-1)){ 20 | matrix[i][j] = matrix[i-1][j-1]; 21 | } 22 | else{ 23 | // char not same 24 | int replace = matrix[i-1][j-1]; 25 | int insert = matrix[i][j-1]; 26 | int delete = matrix[i-1][j]; 27 | int result = Math.min(insert, delete); 28 | matrix[i][j] = 1 + Math.min(result, replace); 29 | } 30 | } 31 | } 32 | System.out.println("Min Operation "+matrix[m][n]); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /AtoI.java: -------------------------------------------------------------------------------- 1 | public class AtoI { 2 | 3 | static int ConvertAtoI(String s){ 4 | int n = s.length(); 5 | int sign = 1; 6 | int index = 0; 7 | int r =0; 8 | 9 | //Spaces 10 | while(index=Integer.MAX_VALUE/10 || (r==Integer.MAX_VALUE/10 && digit>Integer.MAX_VALUE%10)){ 29 | return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE; 30 | } 31 | else 32 | if (r <= (Integer.MIN_VALUE/10)){ 33 | return Integer.MIN_VALUE; 34 | } 35 | r = 10 * r +digit; 36 | index++; 37 | } 38 | return r * sign; 39 | } 40 | public static void main(String[] args) { 41 | String s ="-249"; 42 | System.out.println(ConvertAtoI(s)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Prims.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Prims { 4 | 5 | static int prims(int graph[][], int v) { 6 | int key[] = new int[v]; 7 | Arrays.fill(key, Integer.MAX_VALUE); 8 | key[0] = 0; 9 | boolean set[] = new boolean[v]; 10 | int result = 0; 11 | for(int i = 0; i < v; i++) { 12 | int source = -1; 13 | for(int j = 0; j < v; j++) { 14 | // source must not be visited 15 | if(!set[j] && (source == -1 || key[j] < key[source])) { 16 | source = j; 17 | } 18 | } 19 | set[source] = true; 20 | result += key[source]; 21 | for(int vertex = 0; vertex < v; vertex++) { 22 | if(graph[source][vertex] != 0 && set[vertex] == false) { 23 | key[vertex] = Math.min(key[vertex], graph[source][vertex]); 24 | } 25 | } 26 | } 27 | return result; 28 | } 29 | 30 | public static void main(String[] args) { 31 | int V = 4; 32 | int graph[][] = { 33 | {0,5,8,0}, 34 | {5,0,10,15}, 35 | {8,10,0,20}, 36 | {0,15,20,0} 37 | }; 38 | int res = prims(graph, V); 39 | System.out.println(res); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SuffixInTries.java: -------------------------------------------------------------------------------- 1 | public class SuffixInTries { 2 | static class Node{ 3 | Node[] children; 4 | boolean isTerminal; 5 | 6 | public Node(){ 7 | children = new Node[26]; 8 | for(int i=0;i<26;i++){ 9 | children[i] = null; 10 | } 11 | isTerminal = false; 12 | } 13 | } 14 | static Node root = new Node(); 15 | 16 | static void insert(String word){ 17 | Node current = root; 18 | for(int i=0;i letterCombinations(String digits) { 5 | if(digits.length() ==0){ 6 | List list = new ArrayList<>(); 7 | return list; 8 | } 9 | return letterCombinationsHelper(digits); 10 | } 11 | public List letterCombinationsHelper(String digits) { 12 | // Termination Case 13 | if(digits.length() ==0){ 14 | List list = new ArrayList<>(); 15 | list.add(""); 16 | return list; 17 | } 18 | // Get the first character from the String (e.g digits) 19 | char firstChar = digits.charAt(0); 20 | // get the index so convert character into int 21 | int index = firstChar - '0'; 22 | String phoneKey = phoneKeys[index]; // get the phone key 23 | String remString = digits.substring(1); 24 | List finalList = new ArrayList<>(); 25 | for(int i = 0 ; i result = letterCombinationsHelper(remString); 27 | for(String s : result){ 28 | finalList.add(phoneKey.charAt(i) + s); 29 | } 30 | } 31 | return finalList; 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LC-1365: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] smallerNumbersThanCurrent(int[] nums) { 3 | // Approach-2 4 | /*int org[] = nums.clone(); 5 | Arrays.sort(nums); 6 | HashMap map = new HashMap<>(); 7 | for(int i = 0; i getMazePos(int currentRow , int currentCol, int endRow, int endCol){ 6 | 7 | // Termination Case (Positive Case and Negative Case) 8 | // Positive Case 9 | if(currentCol == endCol && currentRow == endRow){ 10 | ArrayList result = new ArrayList<>(); 11 | result.add(""); 12 | return result; 13 | } 14 | // Negative Case 15 | if(currentCol>endCol || currentRow>endRow){ 16 | ArrayList result = new ArrayList<>(); 17 | return result; 18 | } 19 | 20 | // All the Right and Down Result Store in Final Result 21 | ArrayList finalResult = new ArrayList<>(); 22 | // Move to the Right 23 | ArrayList rightResult = getMazePos(currentRow, currentCol+1, endRow, endCol); 24 | for(String t : rightResult){ 25 | finalResult.add("R"+ t); 26 | } 27 | // On BackTrack so we have another choice (Makes Branch) 28 | // Move to the Down 29 | ArrayList downResult = getMazePos(currentRow+1, currentCol, endRow, endCol); 30 | for(String t : downResult){ 31 | finalResult.add("D"+ t); 32 | } 33 | return finalResult; 34 | } 35 | public static void main(String[] args) { 36 | ArrayList result = getMazePos(0, 0, 2, 2); 37 | System.out.println(result); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /FirstAndLastIndex.java: -------------------------------------------------------------------------------- 1 | public class FirstAndLastIndex { 2 | public static void main(String[] args) { 3 | int arr[] = {10,20,30,40,40,40,40,50,60}; 4 | int search = 40; 5 | int firstIndex = -1; 6 | int lastIndex = -1; 7 | int low = 0; 8 | int high = arr.length-1; 9 | // First Index 10 | while(low<=high){ 11 | int mid = (low + high)/2; 12 | if(arr[mid]== search){ 13 | firstIndex = mid; 14 | // narrow the search From Left Side 15 | high = mid - 1; 16 | } 17 | else if (search>arr[mid]){ 18 | low = mid + 1; 19 | } 20 | else if (searcharr[mid]){ 36 | low = mid + 1; 37 | } 38 | else if (search list ; 5 | int n; // size 6 | FenwickTree(int n){ 7 | this.n = n + 1; // Consider start with 1 index 8 | Integer a[] = new Integer[this.n]; 9 | Arrays.fill(a, 0); // Fill All values with 0 10 | list = Arrays.asList(a); // fill with 0 11 | 12 | } 13 | 14 | void add(int index, int value){ 15 | index++; 16 | while(index0){ 27 | result+=list.get(index); 28 | index -=(index & (-index)); 29 | } 30 | return result; 31 | } 32 | 33 | int rangeQuery(int left, int right){ 34 | return rangeQueryHelper(right) - rangeQueryHelper(left-1); 35 | } 36 | 37 | } 38 | class FenwickTreeExample{ 39 | public static void main(String[] args) { 40 | List list = Arrays.asList(1,2,3,4,5,6,7); 41 | FenwickTree obj = new FenwickTree(list.size()); 42 | for(int i = 0; i generateSubsequence(String str){ 7 | ArrayList subSeqList = new ArrayList<>(); 8 | 9 | int n = str.length(); 10 | for(int i=0;i subsequenceslist1 = generateSubsequence(str1); 28 | List subsequenceslist2 = generateSubsequence(str2); 29 | 30 | String lcs = ""; 31 | for(String word1 : subsequenceslist1){ 32 | for(String word2 : subsequenceslist2){ 33 | if(word1.equals(word2) && word1.length()>lcs.length()){ 34 | lcs = word1; 35 | } 36 | } 37 | } 38 | return lcs; 39 | 40 | } 41 | public static void main(String[] args) { 42 | String str1 = "abcd"; 43 | String str2 = "aebyc"; 44 | String ans = lcs(str1, str2); 45 | System.out.println("LCS IS : " + ans); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /StackWithLL.java: -------------------------------------------------------------------------------- 1 | import java.util.EmptyStackException; 2 | 3 | public class StackWithLL { 4 | 5 | private Node top; 6 | private int size; 7 | 8 | private class Node{ 9 | int data; 10 | Node next; 11 | 12 | public Node(int data){ 13 | this.data = data; 14 | next = null; 15 | } 16 | } 17 | public StackWithLL(){ 18 | top =null; 19 | size = 0; 20 | } 21 | 22 | public void push(int value){ 23 | Node newNode = new Node(value); 24 | newNode.next = top; 25 | top = newNode; 26 | size++; 27 | } 28 | 29 | public int pop(){ 30 | if(isEmpty()){ 31 | throw new EmptyStackException(); 32 | } 33 | int poppedValue = top.data; 34 | top = top.next; 35 | size--; 36 | return poppedValue; 37 | } 38 | 39 | public boolean isEmpty(){ 40 | return size ==0; 41 | } 42 | 43 | public int size(){ 44 | return size; 45 | } 46 | 47 | public int peek(){ 48 | if(isEmpty()){ 49 | throw new EmptyStackException(); 50 | } 51 | return top.data; 52 | } 53 | public static void main(String[] args) { 54 | StackWithLL stack = new StackWithLL(); 55 | stack.push(10); 56 | stack.push(20); 57 | stack.push(30); 58 | stack.pop(); 59 | System.out.println(stack.size()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /RomanToInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class RomanToInteger { 4 | 5 | static int romanToInt(String s){ 6 | HashMap map = new HashMap<>(); 7 | 8 | map.put("I", 1); 9 | map.put("V", 5); 10 | map.put("X", 10); 11 | map.put("L", 50); 12 | map.put("C", 100); 13 | map.put("D", 500); 14 | map.put("M", 1000); 15 | 16 | int sum =0; 17 | int i=0; 18 | int count = 1; 19 | while(i= nextValue){ 31 | if(currentValue == nextValue){ 32 | count+= 1; 33 | } 34 | sum += currentValue; 35 | i+=1; 36 | } 37 | 38 | else{ 39 | sum += (nextValue - currentValue); 40 | i+=2; 41 | } 42 | } 43 | 44 | if(count ==4){ 45 | System.out.println("INCORRECT STRING"); 46 | } 47 | return sum; 48 | } 49 | public static void main(String[] args) { 50 | String s ="LXIIII"; 51 | System.out.println(romanToInt(s)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /LeetCodeWordSearchProblem: -------------------------------------------------------------------------------- 1 | class Solution { 2 | char[][] board; 3 | public boolean exist(char[][] board, String word){ 4 | this.board = board; 5 | //exist(0,0, word); 6 | for(int i = 0; i=0; i--){ 23 | rightPillarMax[i] = Math.max(rightPillarMax[i+1], pillars[i]); 24 | } 25 | // System.out.println("Right Pillar Max"); 26 | // for(int i : rightPillarMax){ 27 | // System.out.print(i+" "); 28 | // } 29 | // System.out.println(); 30 | int amountOfWater = 0; 31 | for(int i = 0; icurrentPillar){ 35 | amountOfWater += decideHeight-currentPillar; 36 | } 37 | 38 | } 39 | return amountOfWater; 40 | //System.out.println(amountOfWater); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /KMP.java: -------------------------------------------------------------------------------- 1 | public class KMP { 2 | 3 | static int[] computeWeight(String pattern){ 4 | int []weightArray = new int[pattern.length()]; 5 | int length =0; 6 | int j=1; 7 | 8 | weightArray[0] = 0; 9 | while(j> adj, int u, int v) { 8 | // for undirected graph connect u and v and then v and u 9 | adj.get(u).add(v); 10 | adj.get(v).add(u); 11 | } 12 | 13 | static void bfs(ArrayList> adj, int V, int s, int []dist) { 14 | boolean[] visited = new boolean[V]; 15 | for(int i = 0; i < V; i++) { 16 | visited[i] = false; 17 | } 18 | Queue q = new LinkedList<>(); 19 | visited[s] = true; 20 | q.add(s); 21 | while(!q.isEmpty()) { 22 | int u = q.poll(); 23 | for(int v : adj.get(u)) { 24 | if(visited[v] == false) { 25 | dist[v] = dist[u] + 1; 26 | visited[v] = true; 27 | q.add(v); 28 | } 29 | } 30 | } 31 | } 32 | public static void main(String[] args) { 33 | int V = 4; 34 | ArrayList> adj = new ArrayList<>(); 35 | for(int i = 0; i < V+1; i++) { 36 | adj.add(new ArrayList<>()); 37 | } 38 | addEdge(adj, 0, 1); 39 | addEdge(adj, 1, 2); 40 | addEdge(adj, 2, 3); 41 | addEdge(adj, 0, 2); 42 | addEdge(adj, 1, 3); 43 | int []dist = new int[V]; 44 | for(int i = 0; i < V; i++) { 45 | dist[i] = Integer.MAX_VALUE; 46 | } 47 | dist[0] = 0; 48 | bfs(adj, V, 0, dist); 49 | for(int i = 0; i < V; i++) { 50 | System.out.println(dist[i]); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /MazePathProblem2.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class MazePathProblem2 { 4 | 5 | static ArrayList getMazePos(int currentRow , int currentCol, int endRow, int endCol){ 6 | 7 | // Termination Case (Positive Case and Negative Case) 8 | // Positive Case 9 | if(currentCol == endCol && currentRow == endRow){ 10 | ArrayList result = new ArrayList<>(); 11 | result.add(""); 12 | return result; 13 | } 14 | // Negative Case 15 | if(currentCol>endCol || currentRow>endRow){ 16 | ArrayList result = new ArrayList<>(); 17 | return result; 18 | } 19 | 20 | // All the Right and Down Result Store in Final Result 21 | ArrayList finalResult = new ArrayList<>(); 22 | // Move to the Right 23 | ArrayList rightResult = getMazePos(currentRow, currentCol+1, endRow, endCol); 24 | for(String t : rightResult){ 25 | finalResult.add("R"+ t); 26 | } 27 | // On BackTrack so we have another choice (Makes Branch) 28 | // Move to the Down 29 | ArrayList downResult = getMazePos(currentRow+1, currentCol, endRow, endCol); 30 | for(String t : downResult){ 31 | finalResult.add("D"+ t); 32 | } 33 | // On BackTrack so we have another choice (Makes Branch) 34 | // Move to the Diagonal 35 | ArrayList diagonalResult = getMazePos(currentRow+1, currentCol+1, endRow, endCol); 36 | for(String t : diagonalResult){ 37 | finalResult.add("I"+ t); 38 | } 39 | return finalResult; 40 | } 41 | public static void main(String[] args) { 42 | ArrayList result = getMazePos(0, 0, 2, 2); 43 | System.out.println(result); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /SearchInTries.java: -------------------------------------------------------------------------------- 1 | public class SearchInTries { 2 | static class Node{ 3 | Node[] children; 4 | boolean IsTerminal; 5 | 6 | public Node(){ 7 | children = new Node[26]; 8 | for(int i=0;i<26;i++){ 9 | children[i] = null; 10 | } 11 | IsTerminal = false; 12 | 13 | } 14 | } 15 | 16 | static Node root = new Node(); 17 | 18 | static void insert(String word){ 19 | Node current = root; 20 | for(int i=0;i>1)); 39 | 40 | 41 | // PROBLEM 6 : POWER OF 2 42 | 43 | int s = 16; 44 | int copy =s; 45 | int count = 0; 46 | while(s>0){ 47 | count += s&1; 48 | s =s>>1; 49 | } 50 | 51 | if(count==1){ 52 | System.out.println(copy + " : IS POWER OF 2"); 53 | } 54 | 55 | // Approach 2: 56 | 57 | System.out.println((n&n-1) > 0 ? "Yes" : "No"); 58 | 59 | 60 | // PROBLEM 7 : XOR WITHOUT XOR 61 | 62 | int b1 = 10; 63 | int b2 = 20; 64 | int b3 = b1 ^ b2; 65 | 66 | int b4 = (b1 & (~b2)) | (b2 & (~b1)); 67 | 68 | System.out.println("WITH XOR : " + b3 + " WITHOUT XOR IS : "+ b4); 69 | 70 | } 71 | } -------------------------------------------------------------------------------- /RatInAMaze.java: -------------------------------------------------------------------------------- 1 | class RatInAMaze{ 2 | 3 | 4 | // Need to Check Block Area 5 | static boolean isNotBlocked(int board[][], int row, int col){ 6 | if(row< board.length && col> adj, int u, int v) { 6 | // for undirected graph connect u and v and then v and u 7 | adj.get(u).add(v); 8 | adj.get(v).add(u); 9 | } 10 | 11 | static boolean dfsRec(ArrayList> adj, int s, boolean[] visited, int parent) { 12 | visited[s] = true; 13 | 14 | for(int u : adj.get(s)) { 15 | if(visited[u] == false) { 16 | if (dfsRec(adj, u, visited, s) == true) { 17 | return true; 18 | } 19 | } 20 | else if(u != parent) { 21 | return true; 22 | } 23 | } 24 | return false; 25 | } 26 | 27 | static boolean dfs(ArrayList> adj, int V) { 28 | boolean[] visited = new boolean[V]; 29 | for(int i = 0; i < V; i++) { 30 | visited[i] = false; 31 | } 32 | // dfsRec(adj, s, visited); 33 | // for disconnected 34 | for(int i = 0; i < V; i++) { 35 | if(visited[i] == false) { 36 | if(dfsRec(adj, i, visited, -1) == true) { 37 | return true; 38 | } 39 | } 40 | } 41 | return false; 42 | } 43 | public static void main(String[] args) { 44 | int V = 7; 45 | ArrayList> adj = new ArrayList<>(); 46 | for(int i = 0; i < V; i++) { 47 | adj.add(new ArrayList<>()); 48 | } 49 | addEdge(adj, 0, 1); 50 | addEdge(adj, 1, 2); 51 | addEdge(adj, 2, 3); 52 | addEdge(adj, 3, 4); 53 | addEdge(adj, 4, 5); 54 | addEdge(adj, 5, 6); 55 | boolean res = dfs(adj, V); 56 | System.out.println(res); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /GraphBFS.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | public class GraphBFS { 5 | static void addEdge(ArrayList> adj, int u, int v) { 6 | // for undirected graph connect u and v and then v and u 7 | adj.get(u).add(v); 8 | adj.get(v).add(u); 9 | } 10 | 11 | static void bfs(ArrayList> adj, int v) { 12 | boolean []visited = new boolean[v+1]; 13 | for(int i = 0; i < v+1; i++) { 14 | visited[i] = false; 15 | } 16 | int source = 1; 17 | visited[source] = true; 18 | LinkedList queue = new LinkedList<>(); 19 | queue.add(source); 20 | while(queue.size() != 0) { 21 | // pop and retrieve first element of queue 22 | source = queue.poll(); 23 | System.out.print(source + ","); 24 | // get number of adjacent vertices of current source 25 | int size = adj.get(source).size(); 26 | for(int i = 0; i < size; i++) { 27 | // get adjacent node 28 | int adjNode = adj.get(source).get(i); 29 | if(visited[adjNode] == false) { 30 | visited[adjNode] = true; 31 | queue.add(adjNode); 32 | } 33 | } 34 | } 35 | 36 | } 37 | 38 | public static void main(String[] args) { 39 | int V = 6; 40 | ArrayList> adj = new ArrayList<>(); 41 | for(int i = 0; i < V+1; i++) { 42 | adj.add(new ArrayList<>()); 43 | } 44 | addEdge(adj, 1, 2); 45 | addEdge(adj, 1, 3); 46 | addEdge(adj, 2, 4); 47 | addEdge(adj, 2, 5); 48 | addEdge(adj, 3, 5); 49 | addEdge(adj, 4, 5); 50 | addEdge(adj, 4, 6); 51 | addEdge(adj, 5, 6); 52 | // printGraph(adj); 53 | bfs(adj, V); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /NQueen.java: -------------------------------------------------------------------------------- 1 | public class NQueen { 2 | static boolean isQueenPlaceOnSafeArea(boolean [][]board, int row, int col){ 3 | // Check - 1 Checking on Above Row 4 | for(int i = row; i>=0; i--){ 5 | if(board[i][col]){ // There is a Queen 6 | return false; 7 | } 8 | } 9 | // check -2 Left Diagonal Check 10 | for(int i = row, j = col; i>=0&& j>=0 ; i--, j--){ 11 | if(board[i][j]){ 12 | return false; 13 | } 14 | } 15 | // Check -3 Right Diagonal Check 16 | for(int i = row, j=col; i>=0 && j target){ 31 | // high--; 32 | // } 33 | 34 | // Approach-3 35 | int max = 0; 36 | for(int element : arr){ 37 | if(element>max){ 38 | max = element; 39 | } 40 | } 41 | int hash[] = new int[max+1]; // fill 0 42 | // all 5 fills with 0 43 | for(int i = 0; i map = new HashMap<>(); 22 | // for(int element : nums){ 23 | // if(map.get(element)==null){ 24 | // map.put(element , 1); 25 | // } 26 | // else{ 27 | // return element; 28 | // } 29 | // } 30 | // return -1; 31 | 32 | // Approach -3 33 | // int n = 0; 34 | // int total = 0; 35 | // for(int element : nums){ 36 | // total = total + element; 37 | // if(element>n){ 38 | // n = element; 39 | // } 40 | // } 41 | // int sum = n * (n+1)/2; 42 | // return total - sum; 43 | 44 | 45 | // Approach - 2 46 | // Arrays.sort(nums); 47 | // for(int i= 0; i> adj, int u, int v) { 6 | // for undirected graph connect u and v and then v and u 7 | adj.get(u).add(v); 8 | adj.get(v).add(u); 9 | } 10 | 11 | static void bfs(ArrayList> adj, int source, boolean[] visited) { 12 | visited[source] = true; 13 | LinkedList queue = new LinkedList<>(); 14 | queue.add(source); 15 | while(queue.size() != 0) { 16 | // pop and retrieve first element of queue 17 | source = queue.poll(); 18 | System.out.print(source + ","); 19 | // get number of adjacent vertices of current source 20 | int size = adj.get(source).size(); 21 | for(int i = 0; i < size; i++) { 22 | // get adjacent node 23 | int adjNode = adj.get(source).get(i); 24 | if(visited[adjNode] == false) { 25 | visited[adjNode] = true; 26 | queue.add(adjNode); 27 | } 28 | } 29 | } 30 | } 31 | 32 | static void bfs_dis(ArrayList> adj, int v) { 33 | boolean []visited = new boolean[v]; 34 | int count = 0; 35 | for(int i = 0; i < v; i++) { 36 | visited[i] = false; 37 | } 38 | for(int i = 0; i < v; i++) { 39 | if(visited[i] == false) { 40 | bfs(adj, i, visited); 41 | count++; 42 | } 43 | } 44 | System.out.println(count); 45 | } 46 | 47 | public static void main(String[] args) { 48 | int V = 6; 49 | ArrayList> adj = new ArrayList<>(); 50 | for(int i = 0; i < V+1; i++) { 51 | adj.add(new ArrayList<>()); 52 | } 53 | addEdge(adj, 0, 1); 54 | addEdge(adj, 0, 2); 55 | addEdge(adj, 2, 3); 56 | addEdge(adj, 1, 3); 57 | addEdge(adj, 4, 5); 58 | addEdge(adj, 4, 6); 59 | addEdge(adj, 5, 6); 60 | // printGraph(adj); 61 | bfs_dis(adj, V); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /MaxHeap.java: -------------------------------------------------------------------------------- 1 | public class MaxHeap { 2 | private int []heap; 3 | private int size; 4 | private int capacity; 5 | 6 | public MaxHeap(int capacity){ 7 | this.capacity = capacity; 8 | this.size =0; 9 | this.heap = new int[capacity]; 10 | } 11 | 12 | public int parent(int index){ 13 | return (index-1)/2; 14 | } 15 | 16 | public int leftChild(int index){ 17 | return 2*index+1; 18 | } 19 | 20 | public int rightChild(int index){ 21 | return 2*index+2; 22 | } 23 | 24 | public void swap(int index1,int index2){ 25 | int temp = heap[index1]; 26 | heap[index1] = heap[index2]; 27 | heap[index2] = temp; 28 | } 29 | 30 | public void insert(int value){ 31 | //OUT OF RANGE --> OVERFLOW 32 | if(size==capacity){ 33 | System.out.println("HEAP IS FULL...."); 34 | return; 35 | } 36 | 37 | int current = size; 38 | heap[size++] = value; 39 | 40 | while(current>0 && heap[current] > heap[parent(current)]){ 41 | swap(current,parent(current)); 42 | current = parent(current); 43 | } 44 | } 45 | 46 | public int delete(){ 47 | //UNDERFLOW 48 | if(size ==0){ 49 | System.out.println("HEAP IS EMPTY....."); 50 | } 51 | int x = heap[0]; 52 | heap[0] = heap[--size]; 53 | maxHeapify(0); 54 | return x; 55 | } 56 | 57 | public void maxHeapify(int index){ 58 | int par = index; 59 | int lci = leftChild(index); 60 | int rci = rightChild(index); 61 | 62 | if(lci < size && heap[lci] > heap[par]){ 63 | par = lci; 64 | } 65 | 66 | if(rci < size && heap[rci] > heap[par]){ 67 | par=rci; 68 | } 69 | 70 | if(par != index){ 71 | swap(index, par); 72 | maxHeapify(par); 73 | } 74 | } 75 | 76 | public static void main(String[] args) { 77 | MaxHeap maxHeap = new MaxHeap(10); 78 | maxHeap.insert(10); 79 | maxHeap.insert(20); 80 | maxHeap.insert(30); 81 | maxHeap.insert(40); 82 | maxHeap.insert(50); 83 | 84 | System.out.println(maxHeap.delete()); 85 | System.out.println(maxHeap.delete()); 86 | System.out.println(maxHeap.delete()); 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /MinHeap.java: -------------------------------------------------------------------------------- 1 | public class MinHeap { 2 | private int []heap; 3 | private int size; 4 | private int capacity; 5 | 6 | public MinHeap(int capacity){ 7 | this.capacity = capacity; 8 | this.size =0; 9 | this.heap = new int[capacity]; 10 | } 11 | 12 | public int parent(int index){ 13 | return (index-1)/2; 14 | } 15 | 16 | public int leftChild(int index){ 17 | return 2*index+1; 18 | } 19 | 20 | public int rightChild(int index){ 21 | return 2*index+2; 22 | } 23 | 24 | public void swap(int index1,int index2){ 25 | int temp = heap[index1]; 26 | heap[index1] = heap[index2]; 27 | heap[index2] = temp; 28 | } 29 | 30 | public void insert(int value){ 31 | //OUT OF RANGE --> OVERFLOW 32 | if(size==capacity){ 33 | System.out.println("HEAP IS FULL...."); 34 | return; 35 | } 36 | 37 | int current = size; 38 | heap[size++] = value; 39 | 40 | while(current>0 && heap[current] < heap[parent(current)]){ 41 | swap(current,parent(current)); 42 | current = parent(current); 43 | } 44 | } 45 | 46 | public int delete(){ 47 | //UNDERFLOW 48 | if(size ==0){ 49 | System.out.println("HEAP IS EMPTY....."); 50 | } 51 | int x = heap[0]; 52 | heap[0] = heap[--size]; 53 | minHeapify(0); 54 | return x; 55 | } 56 | 57 | public void minHeapify(int index){ 58 | int par = index; 59 | int lci = leftChild(index); 60 | int rci = rightChild(index); 61 | 62 | if(lci < size && heap[lci] < heap[par]){ 63 | par = lci; 64 | } 65 | 66 | if(rci < size && heap[rci] < heap[par]){ 67 | par=rci; 68 | } 69 | 70 | if(par != index){ 71 | swap(index, par); 72 | minHeapify(par); 73 | } 74 | } 75 | 76 | public static void main(String[] args) { 77 | MinHeap minHeap = new MinHeap(10); 78 | minHeap.insert(10); 79 | minHeap.insert(40); 80 | minHeap.insert(50); 81 | minHeap.insert(20); 82 | minHeap.insert(30); 83 | 84 | System.out.println(minHeap.delete()); 85 | System.out.println(minHeap.delete()); 86 | System.out.println(minHeap.delete()); 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /KthLargestInHeap.java: -------------------------------------------------------------------------------- 1 | public class KthLargestInHeap { 2 | private int []heap; 3 | private int size; 4 | private int capacity; 5 | 6 | public KthLargestInHeap(int capacity){ 7 | this.capacity = capacity; 8 | this.size =0; 9 | this.heap = new int[capacity]; 10 | } 11 | 12 | public int parent(int index){ 13 | return (index-1)/2; 14 | } 15 | 16 | public int leftChild(int index){ 17 | return 2*index+1; 18 | } 19 | 20 | public int rightChild(int index){ 21 | return 2*index+2; 22 | } 23 | 24 | public void swap(int index1,int index2){ 25 | int temp = heap[index1]; 26 | heap[index1] = heap[index2]; 27 | heap[index2] = temp; 28 | } 29 | 30 | public void insert(int value){ 31 | //OUT OF RANGE --> OVERFLOW 32 | if(size==capacity){ 33 | System.out.println("HEAP IS FULL...."); 34 | return; 35 | } 36 | 37 | int current = size; 38 | heap[size++] = value; 39 | 40 | while(current>0 && heap[current] > heap[parent(current)]){ 41 | swap(current,parent(current)); 42 | current = parent(current); 43 | } 44 | } 45 | 46 | public int delete(){ 47 | //UNDERFLOW 48 | if(size ==0){ 49 | System.out.println("HEAP IS EMPTY....."); 50 | } 51 | int x = heap[0]; 52 | heap[0] = heap[--size]; 53 | maxHeapify(0); 54 | return x; 55 | } 56 | 57 | public void maxHeapify(int index){ 58 | int par = index; 59 | int lci = leftChild(index); 60 | int rci = rightChild(index); 61 | 62 | if(lci < size && heap[lci] > heap[par]){ 63 | par = lci; 64 | } 65 | 66 | if(rci < size && heap[rci] > heap[par]){ 67 | par=rci; 68 | } 69 | 70 | if(par != index){ 71 | swap(index, par); 72 | maxHeapify(par); 73 | } 74 | } 75 | 76 | public static void main(String[] args) { 77 | KthLargestInHeap maxHeap = new KthLargestInHeap(10); 78 | maxHeap.insert(13); 79 | maxHeap.insert(20); 80 | maxHeap.insert(18); 81 | maxHeap.insert(45); 82 | maxHeap.insert(5); 83 | 84 | int k=3; 85 | for(int i=0;i OVERFLOW 32 | if(size==capacity){ 33 | System.out.println("HEAP IS FULL...."); 34 | return; 35 | } 36 | 37 | int current = size; 38 | heap[size++] = value; 39 | 40 | while(current>0 && heap[current] < heap[parent(current)]){ 41 | swap(current,parent(current)); 42 | current = parent(current); 43 | } 44 | } 45 | 46 | public int delete(){ 47 | //UNDERFLOW 48 | if(size ==0){ 49 | System.out.println("HEAP IS EMPTY....."); 50 | } 51 | int x = heap[0]; 52 | heap[0] = heap[--size]; 53 | minHeapify(0); 54 | return x; 55 | } 56 | 57 | public void minHeapify(int index){ 58 | int par = index; 59 | int lci = leftChild(index); 60 | int rci = rightChild(index); 61 | 62 | if(lci < size && heap[lci] < heap[par]){ 63 | par = lci; 64 | } 65 | 66 | if(rci < size && heap[rci] < heap[par]){ 67 | par=rci; 68 | } 69 | 70 | if(par != index){ 71 | swap(index, par); 72 | minHeapify(par); 73 | } 74 | } 75 | 76 | public static void main(String[] args) { 77 | KthSmallestInHeap minHeap = new KthSmallestInHeap(10); 78 | minHeap.insert(10); 79 | minHeap.insert(40); 80 | minHeap.insert(50); 81 | minHeap.insert(20); 82 | minHeap.insert(30); 83 | int k=3; 84 | for(int i=0;i=0){ 39 | int x = arr[top1]; 40 | top1--; 41 | return x; 42 | } 43 | else{ 44 | throw new RuntimeException("Stack1 is empty"); 45 | } 46 | } 47 | 48 | int pop2(){ 49 | if(top2=0){ 61 | int x = arr[top1]; 62 | return x; 63 | } 64 | else{ 65 | throw new RuntimeException("Stack1 is empty"); 66 | } 67 | } 68 | 69 | int peek2(){ 70 | if(top2> finalList = new ArrayList>(); 4 | boolean isQueenPlaceOnSafeArea( int row, int col){ 5 | // Check - 1 Checking on Above Row 6 | for(int i = row; i>=0; i--){ 7 | if(board[i][col]){ // There is a Queen 8 | return false; 9 | } 10 | } 11 | // check -2 Left Diagonal Check 12 | for(int i = row, j = col; i>=0&& j>=0 ; i--, j--){ 13 | if(board[i][j]){ 14 | return false; 15 | } 16 | } 17 | // Check -3 Right Diagonal Check 18 | for(int i = row, j=col; i>=0 && j l = fillSolutionResult(); 30 | finalList.add(l); 31 | return 1; // 1 Possiblity 32 | } 33 | // From the Row ( Need to Traverse Each Column) 34 | for(int column = 0 ; column fillSolutionResult(){ 49 | List list = new ArrayList<>(); 50 | String dots = ""; 51 | for(int i = 0 ; i> solveNQueens(int n) { 72 | MySolution solution = new MySolution(); 73 | solution.board = new boolean [n][n]; 74 | 75 | if(n==1){ 76 | List list = new ArrayList(); 77 | list.add("Q"); 78 | solution.finalList.add(list); 79 | return solution.finalList; 80 | } 81 | 82 | solution.countNumberOfWays(0); 83 | return solution.finalList; 84 | 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /LCSRecursionSolution.java: -------------------------------------------------------------------------------- 1 | class LCSRecursionSolution{ 2 | static int lcsTabulation(String first, String second, int m , int n){ 3 | int matrix [][] = new int[m+1][n+1]; 4 | for(int i = 0; i<=m ; i++){ 5 | for(int j = 0; j<=n; j++){ 6 | if(i==0 || j==0){ 7 | matrix[i][j] =0; 8 | } 9 | else 10 | // char match 11 | if(first.charAt(i-1) == second.charAt(j-1)){ 12 | matrix[i][j] = matrix[i-1][j-1] + 1; 13 | } 14 | // if char not match 15 | else{ 16 | matrix[i][j] = Math.max(matrix[i-1][j], matrix[i][j-1]); 17 | } 18 | } 19 | } 20 | return matrix[m][n]; 21 | } 22 | // Memoization 23 | static int lcs(String first, String second, int m, int n, int[][] cache ){ 24 | // Termination Case 25 | if (m==0 || n==0){ 26 | return 0; 27 | } 28 | // Check Before Store in Cache, the Value is Already Present in Cache 29 | if(cache[m-1][n-1]!=0){ 30 | return cache[m-1][n-1]; 31 | } 32 | // the character will be match 33 | if(first.charAt(m-1) == second.charAt(n-1)){ 34 | // Store the result in cache 35 | cache[m-1][n-1] = 1 + lcs(first, second, m-1, n-1, cache); 36 | return cache[m-1][n-1]; 37 | } 38 | else{ 39 | // Not Match 40 | int result1 = lcs(first, second, m, n-1, cache); 41 | int result2 = lcs(first, second, m-1, n, cache); 42 | cache[m-1][n-1] = Math.max(result1, result2); 43 | return cache[m-1][n-1]; 44 | } 45 | } 46 | 47 | static int lcs(String first, String second){ 48 | // Termination Case - If String Exhaust 49 | if(first.length()==0 || second.length()==0){ 50 | return 0; 51 | } 52 | 53 | int count = 0; // Maintain a Count 54 | 55 | // The Character will be matched 56 | if(first.charAt(0) == second.charAt(0)){ 57 | count = 1 + lcs(first.substring(1), second.substring(1)); 58 | } 59 | else{ 60 | // No Character Match 61 | int result1 = lcs(first.substring(1), second); 62 | int result2 = lcs(first, second.substring(1)); 63 | count = Math.max(result1, result2); 64 | } 65 | return count; 66 | } 67 | 68 | public static void main(String[] args) { 69 | //int len = lcs("abbg", "agbg"); 70 | //System.out.println(len); 71 | String first = "abbg"; 72 | String second = "agbg"; 73 | //int cache [][] = new int[first.length()][second.length()]; 74 | //int len = lcs(first, second, first.length(), second.length(),cache ); 75 | //System.out.println("LCS "+len); 76 | int len = lcsTabulation(first, second, first.length(),second.length()); 77 | System.out.println(len); 78 | } 79 | } -------------------------------------------------------------------------------- /LeetCode-SudkouSolve-ProblemNumber-37r-: -------------------------------------------------------------------------------- 1 | class Solution { 2 | final int MAX_SIZE = 9; 3 | private boolean isPresentInRow(int row, char value){ 4 | // IN a Row Traverse in Each Col 5 | for(int col = 0; col segments; 5 | int n; 6 | SegmentTree(int n){ 7 | this.n = n; 8 | Integer arr[] = new Integer[4*n]; // null 9 | Arrays.fill(arr, 0); 10 | segments = Arrays.asList(arr); // All Segments are fill with 0 value 11 | 12 | 13 | } 14 | 15 | void createSegmentTreeHelper(int startIndex, int endIndex, int node, List list){ 16 | // Termination Case 17 | if(startIndex == endIndex){ 18 | // Reach to Leaf node 19 | segments.set(node, list.get(startIndex)); 20 | return ; 21 | } 22 | // compute mid point 23 | int mid = (startIndex + endIndex)/2; 24 | // Create Left Sub Tree 25 | createSegmentTreeHelper(startIndex, mid, 2 * node + 1, list); 26 | // Create Right Sub Tree 27 | createSegmentTreeHelper(mid + 1, endIndex, 2 * node + 2, list); 28 | 29 | // BackTrack 30 | // Fill the Ancestor 31 | int leftChildValue = segments.get(2 * node + 1); 32 | int rightChildValue = segments.get(2 * node + 2); 33 | int ancestor = leftChildValue + rightChildValue; 34 | segments.set(node, ancestor); 35 | } 36 | 37 | void createSegmentTree(List list){ 38 | createSegmentTreeHelper(0, n-1,0, list); 39 | 40 | } 41 | int rangeQueryHelper(int startIndex, int endIndex, int left, int right, int node){ 42 | // No Overlapping case 43 | if(startIndex>right || endIndex< left){ 44 | return 0 ; // No Answer Found... 45 | } 46 | // Complete Overlapping Case 47 | if(startIndex>=left && endIndex<=right){ 48 | return segments.get(node); 49 | } 50 | // Parital Overlapping Case 51 | int mid = (startIndex + endIndex)/2; 52 | int leftNodeValue = rangeQueryHelper(startIndex, mid, left, right, 2* node + 1); 53 | int rightNodeValue = rangeQueryHelper(mid + 1, endIndex, left, right, 2* node + 2); 54 | return leftNodeValue + rightNodeValue; 55 | 56 | 57 | } 58 | int rangeQuery(int left , int right){ 59 | return rangeQueryHelper(0, n-1, left, right, 0); 60 | } 61 | 62 | void updateHelper(int startIndex, int endIndex,int node, int index, int value){ 63 | // Termination Case 64 | if(startIndex == endIndex){ 65 | segments.set(node, value); 66 | return ; 67 | } 68 | 69 | int mid = (startIndex + endIndex )/2; 70 | // either Lookup the Value on Left SubTree or Right SubTree 71 | if(index<=mid){ 72 | // Go to Left Sub Tree 73 | updateHelper(startIndex, mid, 2*node+1, index, value); 74 | } 75 | else{ 76 | // Go to Right Sub Tree 77 | updateHelper(mid+1, endIndex, 2*node+2, index, value); 78 | } 79 | // Back Track 80 | // Update Ancestor Update 81 | int leftChildValue = segments.get(2 * node + 1); 82 | int rightChildValue = segments.get(2 * node + 2); 83 | int ancestor = leftChildValue + rightChildValue; 84 | segments.set(node, ancestor); 85 | 86 | } 87 | 88 | void update(int index, int value){ 89 | updateHelper(0, n-1, 0, index, value); 90 | } 91 | 92 | } 93 | class SegmentTreeExample{ 94 | public static void main(String[] args) { 95 | List list = Arrays.asList(1,2,3,4,5,6,7,8); 96 | SegmentTree obj = new SegmentTree(list.size()); 97 | obj.createSegmentTree(list); 98 | System.out.println("Range (0,3) " +obj.rangeQuery(0, 3)); 99 | System.out.println("Range (2,5) " +obj.rangeQuery(2, 5)); 100 | System.out.println("Range (4,4) " +obj.rangeQuery(4, 4)); 101 | obj.update(4, 100); 102 | System.out.println("*********** After Update"); 103 | System.out.println("Range (0,3) " +obj.rangeQuery(0, 3)); 104 | System.out.println("Range (2,5) " +obj.rangeQuery(2, 5)); 105 | System.out.println("Range (4,4) " +obj.rangeQuery(4, 4)); 106 | 107 | } 108 | } -------------------------------------------------------------------------------- /BSTExample.java: -------------------------------------------------------------------------------- 1 | class BSTNode{ 2 | T data; 3 | BSTNode left; 4 | BSTNode right; 5 | BSTNode(T data){ 6 | this.data = data; 7 | } 8 | 9 | } 10 | class BSTOperations{ 11 | BSTNode root; // root is null 12 | void takeTreeValues(){ 13 | root = insert(root, 10); 14 | BSTNode t = insert(root, 20); 15 | t = insert(root, 5); 16 | t = insert(root, 7); 17 | print(root); 18 | BSTNode node = search(root, 45); 19 | System.out.println( node==null?"No Data Found":"Data Found "+node.data); 20 | System.out.println("Min Value "+minValue(root)); 21 | System.out.println("Max Value "+maxValue(root)); 22 | } 23 | BSTNode insert(BSTNode currentNode, int data){ 24 | // Check Root is Not Present 25 | if(currentNode == null){ 26 | currentNode = new BSTNode(data); 27 | return currentNode; 28 | } 29 | // Root is Present 30 | if(datacurrentNode.data){ 34 | currentNode.right = insert(currentNode.right, data); 35 | } 36 | return currentNode; 37 | } 38 | 39 | 40 | void print(BSTNode currentNode){ 41 | if(currentNode!=null){ 42 | print(currentNode.left); 43 | System.out.println(currentNode.data); 44 | print(currentNode.right); 45 | } 46 | } 47 | 48 | BSTNode search(BSTNode currentNode, int dataToSearch){ 49 | if(currentNode == null || currentNode.data == dataToSearch){ 50 | return currentNode; 51 | } 52 | if(currentNode.data>dataToSearch){ 53 | return search(currentNode.left, dataToSearch); 54 | } 55 | else{ 56 | return search(currentNode.right, dataToSearch); 57 | } 58 | } 59 | 60 | 61 | 62 | 63 | int minValue(BSTNode currentNode){ 64 | if(currentNode==null){ 65 | return Integer.MIN_VALUE; 66 | } 67 | int min = currentNode.data; 68 | while(currentNode.left!=null){ 69 | min = (Integer) currentNode.left.data; 70 | currentNode = currentNode.left; 71 | 72 | } 73 | return min; 74 | } 75 | 76 | int maxValue(BSTNode currentNode){ 77 | if(currentNode==null){ 78 | return Integer.MAX_VALUE; 79 | } 80 | int max = currentNode.data; 81 | while(currentNode.right!=null){ 82 | max = (Integer) currentNode.right.data; 83 | currentNode = currentNode.right; 84 | 85 | } 86 | return max; 87 | } 88 | 89 | void remove(BSTNode currentNode, BSTNode parent,boolean isLeft, int data){ 90 | if(data>currentNode.data){ 91 | // lookup in right 92 | remove(currentNode.right, currentNode, false, data); 93 | } 94 | else if(datacurrentSize){ 14 | throw new RuntimeException("Position Can't be Greater than Current Size"); 15 | } 16 | if(currentSize == arr.length){ 17 | throw new RuntimeException("Array is Full...."); 18 | 19 | } 20 | for(int i = currentSize-1; i>=index; i--){ 21 | arr[i+1] = arr[i]; 22 | } 23 | arr[index] = value; // Element Inserted... 24 | currentSize++; 25 | System.out.println("Element Added...."); 26 | print(); 27 | 28 | } 29 | void print(){ 30 | for(int i = 0 ; imax){ 85 | max = arr[i]; 86 | } 87 | } 88 | System.out.println("Max Element "+max); 89 | } 90 | void minElement(){ 91 | int min = arr[0]; 92 | for(int i = 1 ; i{ 4 | T data; 5 | Node next; // Reference Variable 6 | Node(T data){ 7 | this.data = data; 8 | this.next = null; 9 | } 10 | } 11 | class LinkedListOperations{ 12 | Scanner scanner = new Scanner(System.in); 13 | Node head; 14 | Node tail; 15 | void add(T data){ 16 | Node newNode = new Node<>(data); 17 | if(head==null){ 18 | head = newNode; 19 | tail = newNode; 20 | } 21 | else{ 22 | tail.next = newNode; 23 | tail = newNode; 24 | } 25 | 26 | } 27 | void addPositionWise(int position, T data){ 28 | Node newNode = new Node<>(data); 29 | // Put the New Node on Head 30 | if(position ==0){ 31 | newNode.next = head; 32 | head = newNode; 33 | return ; 34 | } 35 | int i = 1; 36 | Node temp = head; 37 | while(i start){ 45 | Node temp = start; 46 | while(temp!=null){ 47 | System.out.println(temp.data); 48 | temp = temp.next; 49 | } 50 | } 51 | void midElement(){ 52 | Node slow = head; 53 | Node fast = head; 54 | while(fast!=null && fast.next!=null){ 55 | fast = fast.next.next; 56 | slow = slow.next; 57 | } 58 | System.out.println(slow.data); // Mid Element 59 | } 60 | 61 | void findKthElementFromLast(int kth){ 62 | Node p = head; 63 | Node q = head; 64 | // move q till kth 65 | for(int i = 1; i<=kth; i++){ 66 | q = q.next; 67 | } 68 | // now q move till end 69 | while(q!=null){ 70 | p = p.next; 71 | q = q.next; 72 | } 73 | System.out.println("Kth Element "+p.data); 74 | } 75 | 76 | void detectCycleAndRemoveCycle(){ 77 | Node slow = head; 78 | Node fast = head; 79 | while(fast!=null && fast.next!=null){ 80 | slow = slow.next; 81 | fast = fast.next.next; 82 | if(slow == fast){ // Detect the Cycle 83 | System.out.println("Yes Cycle..."); 84 | break; 85 | } 86 | } 87 | if(slow!=fast){ 88 | System.out.println("No Cycle..."); 89 | return ; 90 | } 91 | slow = head; 92 | while(slow.next!=fast.next){ 93 | slow = slow.next; 94 | fast = fast.next.next; 95 | } 96 | fast.next = null; // Break the Cycle 97 | 98 | } 99 | void deletePositionWise(int position){ 100 | if(head == null){ 101 | System.out.println("Linked List is Empty !"); 102 | return ; 103 | } 104 | Node temp = head; 105 | Node temp2 = null; 106 | // Delete Head 107 | if(position ==0){ 108 | Node temp3 = head; 109 | temp = head.next; 110 | head = temp; 111 | temp3.next = null; 112 | temp3 = null; 113 | 114 | return ; 115 | } 116 | int i =1; 117 | temp = head; 118 | while(i opr = new LinkedListOperations<>(); 130 | int choice =0; 131 | Scanner scanner = new Scanner(System.in); 132 | while(true){ 133 | System.out.println("1. Add"); 134 | System.out.println("2. Print"); 135 | System.out.println("3. Add Position Wise..."); 136 | System.out.println("4. Delete Position Wise..."); 137 | System.out.println("Enter the Choice..."); 138 | choice = scanner.nextInt(); 139 | switch(choice){ 140 | case 1: 141 | opr.add(10); 142 | opr.add(20); 143 | opr.add(30); 144 | opr.add(40); 145 | break; 146 | case 2: 147 | opr.print(opr.head); 148 | break; 149 | case 3: 150 | opr.addPositionWise(2, 1000); 151 | break; 152 | case 4: 153 | opr.deletePositionWise(2); 154 | break; 155 | default: 156 | System.out.println("Wrong Choice...."); 157 | return ; 158 | } 159 | } 160 | // opr.add(100); 161 | // opr.add(200); 162 | // opr.add(300); 163 | // opr.print(opr.head); 164 | // // Create a node 165 | // Node node = new Node<>(100); 166 | // // Connect the Nodes 167 | // Node node2 = new Node<>(200); 168 | // node.next = node2; 169 | // LinkedListOperations l = new LinkedListOperations<>(); 170 | // l.print(node); 171 | } 172 | } -------------------------------------------------------------------------------- /BinaryTreeExample.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | import java.util.Queue; 6 | import java.util.TreeMap; 7 | import java.util.ArrayList; 8 | 9 | class BinaryTreeNode{ 10 | T data; 11 | // Left Child Reference 12 | BinaryTreeNode left; 13 | // Right Child Reference 14 | BinaryTreeNode right; 15 | BinaryTreeNode(T data){ 16 | this.data = data; 17 | // left and right default value is null 18 | } 19 | } 20 | class BinaryTreeOperations{ 21 | String nodeName = "root"; 22 | Scanner scanner = new Scanner(System.in); 23 | BinaryTreeNode insert(){ 24 | System.out.println("Enter the "+nodeName+" Data or enter -1 to exit"); 25 | int data = scanner.nextInt(); 26 | if(data == -1){ 27 | return null; 28 | } 29 | // if data coming correct 30 | // Prepare a Node 31 | BinaryTreeNode node = new BinaryTreeNode<>(data); 32 | // Prepare a Left Node (DFT) 33 | nodeName = "left"; 34 | node.left = insert(); 35 | // BackTrack 36 | nodeName = "right"; 37 | node.right = insert(); 38 | // BackTrack 39 | nodeName = "root"; 40 | return node; 41 | 42 | 43 | } 44 | 45 | void print(BinaryTreeNode root){ 46 | //System.out.println("Print Call..."); 47 | if(root == null){ 48 | return ; 49 | } 50 | // Branch Recursion 51 | // DFT 52 | String result = ""; 53 | result += root.data+" -> "; 54 | // checking current node left exist 55 | if(root.left!=null){ 56 | result += " Left "+root.left.data; 57 | } 58 | if(root.right!=null){ 59 | result +=" Right "+root.right.data; 60 | } 61 | System.out.println(result); 62 | print(root.left); 63 | print(root.right); 64 | 65 | } 66 | 67 | 68 | 69 | void inOrder(BinaryTreeNode root){ 70 | if(root == null){ 71 | return ; 72 | } 73 | inOrder(root.left); 74 | System.out.println(root.data); 75 | inOrder(root.right); 76 | } 77 | 78 | 79 | 80 | 81 | // DFT 82 | // Pre Order (PLR) 83 | void preOrder(BinaryTreeNode root){ 84 | if(root == null){ 85 | return ; 86 | } 87 | System.out.println(root.data); // Parent 88 | preOrder(root.left); // Left 89 | preOrder(root.right); // Right 90 | } 91 | 92 | // Iterative Way of Preorder 93 | void iterativeWayOfPreOrder(BinaryTreeNode root){ 94 | if(root == null){ 95 | return ; 96 | } 97 | // Prepare a Stack 98 | Stack> stack = new Stack<>(); 99 | stack.push(root); 100 | while(!stack.isEmpty()){ 101 | BinaryTreeNode currentNode = stack.pop(); 102 | System.out.print(currentNode.data+" "); 103 | // Now Push Right and then Left 104 | if(currentNode.right!=null){ 105 | stack.push(currentNode.right); 106 | } 107 | if(currentNode.left!=null){ 108 | stack.push(currentNode.left); 109 | } 110 | } 111 | System.out.println(); 112 | } 113 | void iterativeWayOfPreOrder2(BinaryTreeNode root){ 114 | if(root == null){ 115 | return ; 116 | } 117 | // Prepare a Stack 118 | Stack> stack = new Stack<>(); 119 | //stack.push(root); 120 | BinaryTreeNode currentNode = root; 121 | while(currentNode!=null || !stack.isEmpty()){ 122 | while(currentNode!=null){ 123 | System.out.print(currentNode.data+" "); 124 | if(currentNode.right!=null){ 125 | stack.push(currentNode.right); 126 | } 127 | currentNode = currentNode.left; 128 | } 129 | if(!stack.isEmpty()){ 130 | // get the right node 131 | currentNode = stack.pop(); 132 | } 133 | } 134 | System.out.println(); 135 | } 136 | 137 | void iterativeInorder(BinaryTreeNode root){ 138 | Stack> stack = new Stack<>(); 139 | BinaryTreeNode currentNode = root; 140 | while(currentNode!=null || !stack.isEmpty()){ 141 | while(currentNode!=null){ 142 | stack.push(currentNode); 143 | currentNode = currentNode.left; 144 | } 145 | currentNode = stack.pop(); 146 | System.out.print(currentNode.data+" "); 147 | currentNode = currentNode.right; 148 | } 149 | } 150 | 151 | // PostOrder (LRP) 152 | void postOrder(BinaryTreeNode root){ 153 | if(root == null){ 154 | return ; 155 | } 156 | 157 | postOrder(root.left); 158 | postOrder(root.right); 159 | System.out.println(root.data); 160 | } 161 | 162 | void levelOrder(BinaryTreeNode root){ 163 | LinkedList> queue = new LinkedList<>(); 164 | queue.add(root); 165 | while(!queue.isEmpty()){ 166 | // Remove the first element from the queue 167 | BinaryTreeNode node = queue.removeFirst(); 168 | System.out.print(node.data+" "); 169 | // Put parent Left and Right in a Queue 170 | if(node.left!=null){ 171 | queue.addLast(node.left); 172 | } 173 | if(node.right!=null){ 174 | queue.addLast(node.right); 175 | } 176 | } 177 | } 178 | int height (BinaryTreeNode root){ 179 | if(root == null){ 180 | return 0; // Empty Tree Height is 0 181 | } 182 | int leftHeight = height(root.left); 183 | int rightHeight = height(root.right); 184 | int value = Math.max(leftHeight, rightHeight); 185 | return value + 1; 186 | } 187 | int maxLevel = 0; 188 | void printLeftView(BinaryTreeNode root, int currentLevel){ 189 | // Termination Case 190 | if(root == null){ 191 | return ; 192 | } 193 | if(maxLevel root, int currentLevel){ 203 | // Termination Case 204 | if(root == null){ 205 | return ; 206 | } 207 | if(maxLevel root){ 217 | if(root == null){ 218 | return ; 219 | } 220 | Queue> queue = new LinkedList<>(); 221 | queue.add(root); 222 | while(!queue.isEmpty()){ 223 | int queueSize = queue.size(); 224 | for(int i = 0; i currentNode = queue.poll(); 226 | if(i==0){ 227 | System.out.println(currentNode.data); 228 | } 229 | if(currentNode.left!=null){ 230 | queue.add(currentNode.left); 231 | } 232 | if(currentNode.right!=null){ 233 | queue.add(currentNode.right); 234 | } 235 | } 236 | 237 | } 238 | } 239 | 240 | public void printVerticalOrder(BinaryTreeNode root){ 241 | TreeMap> map = new TreeMap<>(); 242 | verticalOrder(root, 0, map); 243 | for(Map.Entry> m: map.entrySet()){ 244 | System.out.println(m.getKey()+" "+m.getValue()); 245 | } 246 | } 247 | 248 | public void verticalOrder(BinaryTreeNode root, int distance, TreeMap> map ){ 249 | // Termination Case 250 | if(root == null){ 251 | return ; 252 | } 253 | if(map.get(distance)==null){ // No Distance Exist 254 | // Create Fresh ArrayList 255 | ArrayList list = new ArrayList<>(); 256 | list.add(root.data); 257 | map.put(distance,list); 258 | } 259 | else { // Distance Exist 260 | // get the old list 261 | // and add new element 262 | ArrayList l = map.get(distance); 263 | l.add(root.data); 264 | map.put(distance, l); 265 | } 266 | verticalOrder(root.left, distance -1 , map); 267 | verticalOrder(root.right, distance +1 , map); 268 | } 269 | 270 | public void printTopView(BinaryTreeNode root){ 271 | TreeMap> map = new TreeMap<>(); 272 | topView(root, 0, map); 273 | for(Map.Entry> m: map.entrySet() ){ 274 | System.out.println(m.getValue()); 275 | } 276 | 277 | } 278 | 279 | public void topView(BinaryTreeNode root, int distance, TreeMap> map ){ 280 | // Termination Case 281 | if(root == null){ 282 | return ; 283 | } 284 | if(map.get(distance)==null){ // No Distance Exist 285 | // Create Fresh ArrayList 286 | ArrayList list = new ArrayList<>(); 287 | list.add(root.data); 288 | map.put(distance,list); 289 | } 290 | // else { // Distance Exist 291 | // // get the old list 292 | // // and add new element 293 | // ArrayList l = map.get(distance); 294 | // l.add(root.data); 295 | // map.put(distance, l); 296 | // } 297 | topView(root.left, distance -1 , map); 298 | topView(root.right, distance +1 , map); 299 | } 300 | 301 | public void printBottomView(BinaryTreeNode root){ 302 | TreeMap> map = new TreeMap<>(); 303 | verticalOrder(root, 0, map); 304 | for(Map.Entry> m: map.entrySet() ){ 305 | ArrayList l = m.getValue(); 306 | System.out.println(l.get(l.size()-1)); 307 | } 308 | 309 | } 310 | 311 | 312 | 313 | 314 | void printRightViewIterative(BinaryTreeNode root){ 315 | if(root == null){ 316 | return ; 317 | } 318 | Queue> queue = new LinkedList<>(); 319 | queue.add(root); 320 | while(!queue.isEmpty()){ 321 | int queueSize = queue.size(); 322 | for(int i = 0; i currentNode = queue.poll(); 324 | if(i==0){ 325 | System.out.println(currentNode.data); 326 | } 327 | if(currentNode.right!=null){ 328 | queue.add(currentNode.right); 329 | } 330 | if(currentNode.left!=null){ 331 | queue.add(currentNode.left); 332 | } 333 | 334 | } 335 | 336 | } 337 | } 338 | 339 | int sizeOfBinaryTree(BinaryTreeNode root){ 340 | if(root == null){ 341 | return 0; 342 | } 343 | int counter = 1; 344 | // Visit to the Node (1) 345 | counter+=sizeOfBinaryTree(root.left); 346 | counter+=sizeOfBinaryTree(root.right); 347 | return counter; 348 | } 349 | 350 | void levelOrder2(BinaryTreeNode root){ 351 | LinkedList> queue = new LinkedList<>(); 352 | queue.add(root); 353 | while(!queue.isEmpty()){ 354 | // Remove the first element from the queue 355 | int countQueue = queue.size(); 356 | for(int i = 0; i currentNode = queue.poll(); 358 | System.out.print(currentNode.data+" "); 359 | if(currentNode.left!=null){ 360 | queue.addLast(currentNode.left); 361 | } 362 | if(currentNode.right!=null){ 363 | queue.addLast(currentNode.right); 364 | } 365 | 366 | } 367 | System.out.println(); 368 | } 369 | } 370 | 371 | boolean isChildrenSum(BinaryTreeNode root){ 372 | if(root == null){ 373 | return true; 374 | } 375 | if(root.left==null && root.right==null){ 376 | return true; 377 | } 378 | int sum = 0; 379 | if(root.left!=null){ 380 | sum = sum + root.left.data; 381 | } 382 | if(root.right!=null){ 383 | sum = sum + root.right.data; 384 | } 385 | return (root.data == sum 386 | && isChildrenSum(root.left) 387 | && isChildrenSum(root.right)); 388 | } 389 | 390 | boolean search(BinaryTreeNode root, int searchElement, ArrayList> path){ 391 | if(root == null){ 392 | return false; 393 | } 394 | path.add(root); 395 | if(root.data == searchElement){ 396 | return true; 397 | } 398 | if(search(root.left, searchElement,path ) || search(root.right, searchElement,path ) ){ 399 | return true; 400 | } 401 | return false; 402 | } 403 | 404 | 405 | BinaryTreeNode lca(BinaryTreeNode root, int n1 , int n2){ 406 | ArrayList> path1 = new ArrayList<>(); 407 | ArrayList> path2 = new ArrayList<>(); 408 | if(!search(root, n1, path1) || !search(root, n2, path2)){ 409 | return null; 410 | } 411 | 412 | 413 | for(int i = path1.size()-1;i>=0; i--){ 414 | for(int j = path2.size()-1; j>=0; j--){ 415 | if(path1.get(i).data == path2.get(j).data){ 416 | System.out.println("LCA "+path1.get(i).data); 417 | return path1.get(i); 418 | } 419 | } 420 | } 421 | return null; 422 | } 423 | 424 | class BinaryTreeExample{ 425 | public static void main(String[] args) { 426 | // BinaryTreeNode b = new BinaryTreeNode<>(); 427 | // BinaryTreeNode e = new BinaryTreeNode<>(); 428 | BinaryTreeOperations opr = new BinaryTreeOperations(); 429 | Scanner scanner = new Scanner(System.in); 430 | BinaryTreeNode root = null; 431 | while(true){ 432 | System.out.println("Binary Tree Operations "); 433 | System.out.println("1. Insert"); 434 | System.out.println("2. Print"); 435 | System.out.println("3. Exit"); 436 | System.out.println("Enter the Choice"); 437 | int choice = scanner.nextInt(); 438 | 439 | switch(choice){ 440 | case 1: 441 | root =opr.insert(); 442 | break; 443 | case 2: 444 | //opr.iterativeWayOfPreOrder(root); 445 | // opr.iterativeInorder(root); 446 | //opr.levelOrder2(root); 447 | // opr.printLeftView(root, 1); 448 | //opr.printLeftViewIterative(root); 449 | //opr.printRightView(root, 1); 450 | //opr.printVerticalOrder(root); 451 | System.out.println(opr.isChildrenSum(root)?"Yes":"No"); 452 | 453 | //opr.printBottomView(root); 454 | // opr.printTopView(root); 455 | //opr.topView(root); 456 | //opr.print(root); 457 | break; 458 | case 3: 459 | return ; 460 | } 461 | 462 | } 463 | //scanner.close(); 464 | 465 | } 466 | } --------------------------------------------------------------------------------