├── .gitignore └── src └── com └── dsalgo ├── AllUniqueSubstring.java ├── AnagramSort.java ├── AnyNumberSumUptoK.java ├── AnyNumberSumUptoKRecursive.java ├── BalanceWeight.java ├── BalloonCoinProduct.java ├── BinaryTreeDistanceBetweenNodes.java ├── BinaryTreeInsertionOrder.java ├── BinaryTreeLevelWithMaxNodes.java ├── BinaryTreeNicePrint.java ├── BinaryTreeSumChildNodes.java ├── BinaryTreeSumOfValuesAtOddHeight.java ├── BinaryTreeToLinkedList.java ├── BinaryTreeZigzag.java ├── CalculatePower.java ├── CheckForBST.java ├── ClosestKpoints.java ├── CompactBinaryTree.java ├── CreateTreeFromInPre.java ├── DistributedCircularListSum.java ├── DistributedDoublyLinkedListSum.java ├── DistributedSystemSum.java ├── EqualSumPartition.java ├── ExpandArray.java ├── FindDeepestNodes.java ├── FindMinMax.java ├── FindMinMax2.java ├── FindOrderOfLetter.java ├── FindPathFromRoot.java ├── FindPermutations.java ├── FindRepetitionWithoutExtraSpace.java ├── FoldLinkedList.java ├── FrogJump.java ├── IncreasingArraySubsequence.java ├── IncreasingDecreasingTuple.java ├── InorderSuccessor.java ├── InterviewHierarchy.java ├── IsAveragePossible.java ├── KthLargestOnline.java ├── KthLargestSortedMatrix.java ├── LargestPalindromeIterative.java ├── LargestPalindromeRecursive.java ├── LargestSumSubArray.java ├── LargestSumSubMatrix.java ├── LeastCommonAncestorWithoutRoot.java ├── LeastDifference.java ├── LevelOrderWithoutQueue.java ├── LinkedListKthElementFromEnd.java ├── LinkedListRandomPointer.java ├── LinkedListRemoveDuplicate.java ├── LinkedListWithLoop.java ├── LinkedListYShape.java ├── LongestCommonSubsequence.java ├── LongestPathInMaze.java ├── LowestCommonAncestor.java ├── MaxAlternatingSequence.java ├── MaxArithmeticSequence.java ├── MaxHeapAndBinarySearchTree.java ├── MaxKUsingMinHeap.java ├── MaxProductSubArray.java ├── MaxSubarrayEqualOnesZeros.java ├── MaxSumTreePathNegative.java ├── MaxSumTreePathPositive.java ├── MaximumSumUptoKRecursive.java ├── MergeInSingleArray.java ├── MergeNSortedArrays.java ├── NextLargerNumber.java ├── NextPalindrome.java ├── NextPowerOfTwo.java ├── NextSmallInteger.java ├── NumberOfOnes.java ├── OneWordPermutationOfOther.java ├── PathInMaze.java ├── PermutationSubstring.java ├── PostorderSuccessor.java ├── PotsOfGoldGame.java ├── PreorderSuccessor.java ├── PrintBinartyTreeBottomToTop.java ├── PrintBinartyTreeBottomToTopContinuous.java ├── PrintMatrixSpiral.java ├── PrintNodeOfSameLevel.java ├── PythagoreanTriplet.java ├── QueueMinUsingStack.java ├── QueueUsingStack.java ├── README.md ├── RemoveDuplicateBST.java ├── ReverseKNodes.java ├── ReverseLinkedListIterative.java ├── ReverseLinkedListRecursive.java ├── ReverseWordsInSentence.java ├── RotateKTimes.java ├── RotateString.java ├── RunningMedian.java ├── SameAverageSubset.java ├── SearchInSortedMatrix.java ├── SeparateWordsInSentence.java ├── ShortestPathInMaze.java ├── SnakesAndLadders.java ├── SortStack.java ├── StackMinimum.java ├── SumPossibleAlongPathBinaryTree.java ├── SuperImposeBinaryTree.java ├── SwapWithoutTemp.java ├── TelephoneDirectory.java ├── TowersOfHanoi.java ├── TwoSumToK.java └── UnsortedTwoSumToK.java /.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | bin/ 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /src/com/dsalgo/AllUniqueSubstring.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | For problem and solution description please visit the link below 4 | http://www.dsalgo.com/2013/02/AllUniqueSubstring.php.html 5 | */ 6 | 7 | package com.dsalgo; 8 | 9 | import java.util.HashSet; 10 | 11 | public class AllUniqueSubstring 12 | { 13 | public static void main(String[] args) 14 | { 15 | String input = "abacbdadbc"; 16 | printAllUniqueSubstring(input); 17 | } 18 | 19 | public static void printAllUniqueSubstring(String input) 20 | { 21 | HashSet set = new HashSet(); 22 | int startIndex = 0; 23 | int endIndex = 0; 24 | int maxLength = 0; 25 | int startMax = 0; 26 | int endMax = 0; 27 | 28 | while (endIndex < input.length()) 29 | { 30 | char addChar = input.charAt(endIndex); 31 | if (!set.contains(addChar)) 32 | { 33 | set.add(addChar); 34 | int currentLength = endIndex - startIndex + 1; 35 | if (currentLength > maxLength) 36 | { 37 | maxLength = currentLength; 38 | startMax = startIndex; 39 | endMax = endIndex; 40 | } 41 | endIndex++; 42 | } else 43 | { 44 | char removeChar = input.charAt(startIndex); 45 | set.remove(removeChar); 46 | startIndex++; 47 | if (removeChar == addChar) 48 | { 49 | int currentLength = endIndex - startIndex + 1; 50 | if (currentLength > maxLength) 51 | { 52 | maxLength = currentLength; 53 | startMax = startIndex; 54 | endMax = endIndex; 55 | } 56 | endIndex++; 57 | } 58 | } 59 | } 60 | System.out.println(startMax + "," + endMax); 61 | System.out.println(input.substring(startMax, endMax)); 62 | } 63 | 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/com/dsalgo/AnagramSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/sort-to-bring-anagrams-closer.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Arrays; 10 | import java.util.Collections; 11 | import java.util.List; 12 | 13 | public class AnagramSort 14 | { 15 | public static void main(String[] args) 16 | { 17 | String[]arr={"dog","listen","tip","enlist","pit","god","man","top","pot"}; 18 | sort(arr); 19 | for(String str:arr) 20 | { 21 | System.out.println(str); 22 | } 23 | } 24 | 25 | private static void sort(String[] arr) 26 | { 27 | List list=new ArrayList(); 28 | for(String str:arr) 29 | { 30 | list.add(new Anagram(str)); 31 | } 32 | Collections.sort(list); 33 | for(int i=0;i 39 | { 40 | String str; 41 | public Anagram(String str) 42 | { 43 | this.str=str; 44 | } 45 | public String getSortedString() 46 | { 47 | char[]arr=str.toCharArray(); 48 | Arrays.sort(arr); 49 | return new String(arr); 50 | } 51 | @Override 52 | public int compareTo(Anagram o) 53 | { 54 | return getSortedString().compareTo(o.getSortedString()); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/com/dsalgo/AnyNumberSumUptoK.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/AnyNumberSumUptoK.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class AnyNumberSumUptoK 9 | { 10 | 11 | public static void main(String[] args) 12 | { 13 | int[]arr={4,6,2,8}; 14 | System.out.println(isSumPossible(arr,22)); 15 | } 16 | 17 | public static boolean isSumPossible(int[] arr, int k) 18 | { 19 | boolean[][] memo=new boolean[arr.length+1][k+1]; 20 | for(int i=1;i<=arr.length;++i) 21 | { 22 | for(int w=1;w<=k;++w) 23 | { 24 | if(w==arr[i-1]) 25 | memo[i][w]=true; 26 | else if(w>arr[i-1]) 27 | memo[i][w]=memo[i-1][w]||memo[i-1][w-arr[i-1]]; 28 | else 29 | memo[i][w]=memo[i-1][w]; 30 | } 31 | } 32 | return memo[arr.length][k]; 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /src/com/dsalgo/AnyNumberSumUptoKRecursive.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/AnyNumberSumUptoKRecursive.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class AnyNumberSumUptoKRecursive 9 | { 10 | public static void main(String[] args) 11 | { 12 | int [] arr={3,5,6,2}; 13 | System.out.println(isSumPossible(arr, 13)); 14 | } 15 | 16 | public static boolean isSumPossible(int[]arr, int k) 17 | { 18 | Boolean [][]memo=new Boolean[arr.length+1][k+1]; 19 | return isSumPossible(memo,arr,0,k); 20 | } 21 | 22 | private static boolean isSumPossible(Boolean[][]memo, int[]arr,int i,int k) 23 | { 24 | if(memo[i][k]!=null) 25 | return memo[i][k]; 26 | if(i==arr.length-1) 27 | { 28 | if(arr[i]==k||k==0) 29 | return true; 30 | else 31 | return false; 32 | } 33 | if(arr[i]>k) 34 | { 35 | memo[i][k]=isSumPossible(memo,arr,i+1,k); 36 | return memo[i][k]; 37 | } 38 | memo[i][k]=isSumPossible(memo,arr,i+1,k-arr[i])||isSumPossible(memo,arr, i+1, k); 39 | return memo[i][k]; 40 | } 41 | 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/com/dsalgo/BalanceWeight.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/BalanceTheBalance.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class BalanceWeight 9 | { 10 | final static int weightOfBalanceBeam = 10; 11 | 12 | public static void main(String[] args) 13 | { 14 | Balance a = new Balance(1, 4, 6); 15 | Balance b = new Balance(2, 3, 8); 16 | Balance c = new Balance(3, 5, 9); 17 | Balance d = new Balance(4, 3, 2); 18 | 19 | a.left = b; 20 | a.right = c; 21 | b.left = d; 22 | 23 | doBalance(a); 24 | } 25 | 26 | public static double doBalance(Balance balance) 27 | { 28 | if (balance == null) 29 | return 0; 30 | if (balance.left == null && balance.right == null) 31 | { 32 | return printBalance(balance.id, balance.leftWeight, balance.rightWeight); 33 | } 34 | else 35 | { 36 | return printBalance(balance.id, balance.leftWeight 37 | + doBalance(balance.left), balance.rightWeight 38 | + doBalance(balance.right)); 39 | } 40 | } 41 | 42 | public static double printBalance(int id, double leftWeight, 43 | double rightWeight) 44 | { 45 | if (leftWeight > rightWeight) 46 | { 47 | System.out.println("Add " + (leftWeight - rightWeight) + " to the right of Balance#" + id); 48 | return leftWeight * 2 + weightOfBalanceBeam; 49 | } 50 | else if (leftWeight < rightWeight) 51 | { 52 | System.out.println("Add " + (rightWeight - leftWeight) + " to the left of Balance#" + id); 53 | return rightWeight * 2 + 10; 54 | } 55 | else 56 | { 57 | return rightWeight * 2 + 10; 58 | } 59 | } 60 | 61 | } 62 | class Balance 63 | { 64 | public int id; 65 | public Balance left; 66 | public Balance right; 67 | public double leftWeight; 68 | public double rightWeight; 69 | 70 | public Balance(int id, double leftWeight, double rightWeight) 71 | { 72 | this.id = id; 73 | this.leftWeight = leftWeight; 74 | this.rightWeight = rightWeight; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/com/dsalgo/BalloonCoinProduct.java: -------------------------------------------------------------------------------- 1 | package com.dsalgo; 2 | 3 | public class BalloonCoinProduct { 4 | 5 | public static void main(String[] args) { 6 | int[] coins = { 1, 3, 4, 5, 4, 5, 3, 6, 7 }; 7 | int maxProduct = getMaxCoins(coins); 8 | System.out.println("Max product: " + maxProduct); 9 | } 10 | 11 | public static int getMaxCoins(int[] coins) { 12 | int n = coins.length; 13 | Integer[][] memo = new Integer[n][n]; 14 | return getMaxCoins(coins, 0, n - 1, memo); 15 | } 16 | 17 | public static int getMaxCoins(int[] coins, int start, int end, 18 | Integer[][] memo) { 19 | if (start == end){ 20 | memo[start][end]=coins[start]; 21 | return coins[start]; 22 | } 23 | if(start>end) 24 | return 0; 25 | if (memo[start][end] == null) { 26 | int max=0; 27 | for (int i = start + 1; i < end - 1; ++i) { 28 | max = Math.max(max, 29 | getMaxCoins(coins, start + 1, i - 1, memo) 30 | + coins[start] * coins[i] * coins[end] 31 | + getMaxCoins(coins, i + 1, end - 1, memo)); 32 | } 33 | memo[start][end]=max; 34 | } 35 | return memo[start][end]; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeDistanceBetweenNodes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-distance-between-two-nodes-in.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class BinaryTreeDistanceBetweenNodes 12 | { 13 | 14 | /** 15 | * @param args 16 | */ 17 | public static void main(String[] args) 18 | { 19 | Node a = new Node(1); 20 | Node b = new Node(2); 21 | Node c = new Node(3); 22 | Node d = new Node(4); 23 | Node e = new Node(5); 24 | Node f = new Node(6); 25 | Node g = new Node(7); 26 | Node h = new Node(8); 27 | a.left = b; 28 | a.right = c; 29 | b.left = d; 30 | c.left = e; 31 | c.right = f; 32 | f.left = g; 33 | f.right = h; 34 | 35 | int distance = findDistance(a, 2, 7); 36 | System.out.println(distance); 37 | 38 | } 39 | 40 | private static int findDistance(Node root, int val1, int val2) 41 | { 42 | List path1 = new ArrayList(); 43 | List path2 = new ArrayList(); 44 | findPath(root, val1, path1); 45 | findPath(root, val2, path2); 46 | if (path1.size() == 0 || path2.size() == 0) 47 | return -1; 48 | int index = 0; 49 | for (; index < path1.size(); ++index) 50 | { 51 | if (path1.get(index) != path2.get(index)) 52 | break; 53 | } 54 | return path1.size() + path2.size() - 2 * index; 55 | } 56 | 57 | private static boolean findPath(Node root, int value, List path) 58 | { 59 | if (root == null) 60 | return false; 61 | path.add(root); 62 | if (root.value == value) 63 | { 64 | return true; 65 | } 66 | if (findPath(root.left, value, path) 67 | || findPath(root.right, value, path)) 68 | return true; 69 | path.remove(root); 70 | return false; 71 | } 72 | 73 | static class Node 74 | { 75 | Node left; 76 | Node right; 77 | int value; 78 | 79 | public Node(int value) 80 | { 81 | this.value = value; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeInsertionOrder.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | For problem and solution description please visit the link below 4 | http://www.dsalgo.com/2013/03/binary-search-tree-with-insertion-order.html 5 | */ 6 | 7 | package com.dsalgo; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public class BinaryTreeInsertionOrder 13 | { 14 | public static void main(String[] args) 15 | { 16 | BinaryTree bt = new BinaryTree(); 17 | bt.add(4).add(5).add(2).add(9).add(14).add(6).add(3); 18 | List list = bt.getSortedOrder(); 19 | for (Integer num : list) 20 | System.out.print(num + ", "); 21 | System.out.println(); 22 | list = bt.getInsertionOrder(); 23 | for (Integer num : list) 24 | System.out.print(num + ", "); 25 | System.out.println(); 26 | } 27 | 28 | private static class BinaryTree 29 | { 30 | Node root; 31 | Node head; 32 | Node last; 33 | 34 | public BinaryTree add(int num) 35 | { 36 | if (root == null) 37 | { 38 | root = new Node(num); 39 | head = root; 40 | last = root; 41 | } else 42 | { 43 | Node node = new Node(num); 44 | add(root, node); 45 | last.next = node; 46 | last = node; 47 | } 48 | return this; 49 | } 50 | 51 | private void add(Node root, Node node) 52 | { 53 | if (node.value < root.value) 54 | { 55 | if (root.left == null) 56 | root.left = node; 57 | else 58 | add(root.left, node); 59 | } else 60 | { 61 | if (root.right == null) 62 | root.right = node; 63 | else 64 | add(root.right, node); 65 | } 66 | 67 | } 68 | 69 | public List getInsertionOrder() 70 | { 71 | Node current = head; 72 | List list = new ArrayList(); 73 | while (current != null) 74 | { 75 | list.add(current.value); 76 | current = current.next; 77 | } 78 | return list; 79 | } 80 | 81 | public List getSortedOrder() 82 | { 83 | List list = new ArrayList(); 84 | inorder(root, list); 85 | return list; 86 | } 87 | 88 | private void inorder(Node root, List list) 89 | { 90 | if (root == null) 91 | return; 92 | inorder(root.left, list); 93 | list.add(root.value); 94 | inorder(root.right, list); 95 | } 96 | 97 | } 98 | 99 | private static class Node 100 | { 101 | int value; 102 | Node left; 103 | Node right; 104 | Node next; 105 | 106 | public Node(int value) 107 | { 108 | this.value = value; 109 | } 110 | 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeLevelWithMaxNodes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/binary-tree-level-with-maximum-number.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | 11 | public class BinaryTreeLevelWithMaxNodes 12 | { 13 | public static void main(String[] args) 14 | { 15 | Node a = new Node(1); 16 | Node b = new Node(2); 17 | Node c = new Node(3); 18 | Node d = new Node(4); 19 | Node e = new Node(5); 20 | Node f = new Node(8); 21 | Node g = new Node(6); 22 | Node h = new Node(7); 23 | a.left = b; 24 | a.right = c; 25 | b.left = d; 26 | b.right = e; 27 | c.right = f; 28 | f.left = g; 29 | f.right = h; 30 | printMaxLevel(a); 31 | } 32 | 33 | private static void printMaxLevel(Node a) 34 | { 35 | HashMap < Integer, List < Integer > > levelMap = new HashMap < Integer, List < Integer > >(); 36 | printLevelOrder(a, 1, levelMap); 37 | int level = 1; 38 | int maxNodes = 0; 39 | List < Integer > values = null; 40 | while (true) 41 | { 42 | List < Integer > list = levelMap.get(level); 43 | if (list == null) 44 | break; 45 | if (list.size() > maxNodes) 46 | { 47 | maxNodes = list.size(); 48 | values = list; 49 | } 50 | level++; 51 | } 52 | System.out.println(values); 53 | } 54 | 55 | private static void printLevelOrder(Node a, int level, 56 | HashMap < Integer, List < Integer > > levelMap) 57 | { 58 | if (a == null) 59 | return; 60 | List < Integer > list = levelMap.get(level); 61 | if (list == null) 62 | { 63 | list = new ArrayList < Integer > (); 64 | list.add(a.value); 65 | levelMap.put(level, list); 66 | } else 67 | { 68 | list.add(a.value); 69 | } 70 | printLevelOrder(a.left, level + 1, levelMap); 71 | printLevelOrder(a.right, level + 1, levelMap); 72 | } 73 | 74 | static class Node 75 | { 76 | Node left; 77 | Node right; 78 | int value; 79 | 80 | public Node(int value) 81 | { 82 | this.value = value; 83 | } 84 | } 85 | 86 | } 87 | 88 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeNicePrint.java: -------------------------------------------------------------------------------- 1 | package com.dsalgo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.TreeMap; 6 | 7 | public class BinaryTreeNicePrint { 8 | 9 | public static void main(String[] args) { 10 | Node a = new Node(1); 11 | Node b = new Node(2); 12 | Node c = new Node(3); 13 | Node d = new Node(4); 14 | Node e = new Node(5); 15 | Node f = new Node(8); 16 | Node g = new Node(6); 17 | Node h = new Node(7); 18 | Node i = new Node(9); 19 | a.left = b; 20 | a.right = c; 21 | b.left = d; 22 | b.right = e; 23 | c.left = i; 24 | c.right = f; 25 | f.left = g; 26 | f.right = h; 27 | nicePrint(a); 28 | } 29 | 30 | public static void nicePrint(Node root) { 31 | List< StringPoint > result = getStrings((getWidth(root) + 1) / 2, 0, root); 32 | TreeMap< Integer, List< StringPoint > > lines = new TreeMap< >(); 33 | for (StringPoint s : result) { 34 | if (lines.get(s.y) != null) { 35 | lines.get(s.y).add(s); 36 | } else { 37 | List< StringPoint > l = new ArrayList< >(); 38 | l.add(s); 39 | lines.put(s.y, l); 40 | } 41 | } 42 | for (List< StringPoint > l : lines.values()) { 43 | System.out.println(flatten(l)); 44 | } 45 | } 46 | 47 | private static String flatten(List< StringPoint > l) { 48 | int x = 0; 49 | StringBuilder sb = new StringBuilder(); 50 | for (StringPoint s : l) { 51 | sb.append(new String(new char[s.x - x]).replace('\0', ' ')); 52 | sb.append(s.value); 53 | x = sb.length(); 54 | } 55 | return sb.toString(); 56 | } 57 | 58 | private static int getWidth(Node root) { 59 | int width = 0; 60 | if (root.left != null) { 61 | width += getWidth(root.left); 62 | } 63 | if (root.right != null) { 64 | width += getWidth(root.right); 65 | } 66 | width += ("" + root.value).length(); 67 | return width; 68 | } 69 | 70 | private static List< StringPoint > getStrings(int x, int y, Node root) { 71 | List< StringPoint > result = new ArrayList< StringPoint >(); 72 | result.add(new StringPoint(x - ("" + root.value).length() / 2, y, "" 73 | + root.value)); 74 | if (root.left != null) { 75 | int width = getWidth(root.left); 76 | int i = 0; 77 | for (; i < (width + 1) / 2; ++i) 78 | result.add(new StringPoint(x - i - 1, y + i + 1, "/")); 79 | result.addAll(getStrings(x - i - 1, y + i + 1, root.left)); 80 | } 81 | if (root.right != null) { 82 | int width = getWidth(root.right); 83 | int i = 0; 84 | for (; i < (width + 1) / 2; ++i) 85 | result.add(new StringPoint(x + i + 1, y + i + 1, "\\")); 86 | result.addAll(getStrings(x + i + 1, y + i + 1, root.right)); 87 | } 88 | return result; 89 | } 90 | 91 | static class StringPoint { 92 | Integer x; 93 | Integer y; 94 | String value; 95 | 96 | StringPoint(int x, int y, String value) { 97 | this.x = x; 98 | this.y = y; 99 | this.value = value; 100 | } 101 | 102 | @Override 103 | public String toString() { 104 | return "(" + x + "," + y + "," + value + ")"; 105 | } 106 | } 107 | 108 | static class Node { 109 | Node left; 110 | Node right; 111 | int value; 112 | 113 | public Node(int value) { 114 | this.value = value; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeSumChildNodes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/BinaryTreeSumChildNodes.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | /* 10 | * In a binary tree change each node's value(except leaf node) as the sum of left and right subtree's value. 11 | * 12 | * 13 | Constructed binary tree is: 14 | 1 15 | / \ 16 | 2 3 17 | / \ \ 18 | 4 5 8 19 | / \ 20 | 6 7 21 | 22 | 23 | After sum stored is in each node, binary tree is: 24 | 35 25 | / \ 26 | 9 21 27 | / \ \ 28 | 4 5 13 29 | / \ 30 | 6 7 31 | 32 | */ 33 | public class BinaryTreeSumChildNodes 34 | { 35 | 36 | /** 37 | * @param args 38 | */ 39 | public static void main(String[] args) 40 | { 41 | 42 | Node a = new Node(1); 43 | Node b = new Node(2); 44 | Node c = new Node(3); 45 | Node d = new Node(4); 46 | Node e = new Node(5); 47 | Node f = new Node(8); 48 | Node g = new Node(6); 49 | Node h = new Node(7); 50 | a.left = b; 51 | a.right = c; 52 | b.left = d; 53 | b.right = e; 54 | c.right = f; 55 | f.left = g; 56 | f.right = h; 57 | printNice(a); 58 | System.out.println(); 59 | makeSum(a); 60 | printNice(a); 61 | } 62 | 63 | public static int makeSum(Node root) 64 | { 65 | if (root == null) 66 | return 0; 67 | int temp = root.value; 68 | int sum = makeSum(root.left) + makeSum(root.right); 69 | if (root.left != null || root.right != null) 70 | root.value = sum; 71 | return temp + sum; 72 | } 73 | 74 | public static void printNice(Node root) 75 | { 76 | if (root == null) 77 | return; 78 | else 79 | { 80 | System.out.print(root.value); 81 | if (root.left != null) 82 | { 83 | System.out.print("L->["); 84 | printNice(root.left); 85 | System.out.print("]"); 86 | } 87 | if (root.right != null) 88 | { 89 | System.out.print("R->["); 90 | printNice(root.right); 91 | System.out.print("]"); 92 | } 93 | } 94 | } 95 | static class Node 96 | { 97 | public Node left; 98 | public Node right; 99 | public int value; 100 | public Node(int value) 101 | { 102 | this.value=value; 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeSumOfValuesAtOddHeight.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/binary-tree-sum-of-nodes-at-odd-levels.html 4 | */ 5 | 6 | package com.dsalgo; 7 | public class BinaryTreeSumOfValuesAtOddHeight 8 | { 9 | public static void main(String[] args) 10 | { 11 | Node a = new Node(1); 12 | Node b = new Node(2); 13 | Node c = new Node(3); 14 | Node d = new Node(4); 15 | Node e = new Node(5); 16 | Node f = new Node(8); 17 | Node g = new Node(6); 18 | Node h = new Node(9); 19 | a.left = b; 20 | a.right = c; 21 | b.left = d; 22 | b.right = e; 23 | c.right = f; 24 | f.left = g; 25 | f.right = h; 26 | int sum = findOddLevelSum(a); 27 | System.out.println(sum); 28 | } 29 | 30 | private static int findOddLevelSum(Node a) 31 | { 32 | return findOddLevelSum(a, true); 33 | } 34 | 35 | private static int findOddLevelSum(Node a, boolean oddLevel) 36 | { 37 | if (a == null) 38 | return 0; 39 | int childSum=findOddLevelSum(a.left, !oddLevel) 40 | + findOddLevelSum(a.right, !oddLevel); 41 | if (oddLevel) 42 | return a.value + childSum; 43 | else 44 | return childSum; 45 | } 46 | 47 | static class Node 48 | { 49 | Node left; 50 | Node right; 51 | int value; 52 | 53 | public Node(int value) 54 | { 55 | this.value = value; 56 | } 57 | } 58 | 59 | } 60 | 61 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeToLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/BinaryTreeToLinkedList.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | 12 | 13 | public class BinaryTreeToLinkedList 14 | { 15 | 16 | public static void main(String[] args) 17 | { 18 | BinaryTreeNode a=new BinaryTreeNode(1); 19 | BinaryTreeNode b=new BinaryTreeNode(2); 20 | BinaryTreeNode c=new BinaryTreeNode(3); 21 | BinaryTreeNode d=new BinaryTreeNode(4); 22 | BinaryTreeNode e=new BinaryTreeNode(5); 23 | BinaryTreeNode f=new BinaryTreeNode(6); 24 | BinaryTreeNode g=new BinaryTreeNode(7); 25 | BinaryTreeNode h=new BinaryTreeNode(8); 26 | BinaryTreeNode i=new BinaryTreeNode(9); 27 | a.left=b; 28 | a.right=c; 29 | b.right=d; 30 | c.left=e; 31 | c.right=f; 32 | d.left=g; 33 | d.right=h; 34 | g.right=i; 35 | 36 | List result=getLinkedListFromEachLevel(a); 37 | for(LinkedNode head:result) 38 | printLinkedList(head); 39 | 40 | } 41 | 42 | static List getLinkedListFromEachLevel(BinaryTreeNode root) 43 | { 44 | List result=new ArrayList(); 45 | if(root==null) 46 | return result; 47 | LinkedList queue=new LinkedList(); 48 | queue.add(root); 49 | BinaryTreeNode marker=new BinaryTreeNode(-1); 50 | queue.add(marker); 51 | LinkedNode head=null; 52 | LinkedNode prev=null; 53 | while(!queue.isEmpty()) 54 | { 55 | BinaryTreeNode btNode=queue.poll(); 56 | if(btNode==marker) 57 | { 58 | result.add(head); 59 | head=null; 60 | 61 | if(!queue.isEmpty()) 62 | { 63 | queue.add(marker); 64 | } 65 | continue; 66 | } 67 | if(head==null) 68 | { 69 | head=new LinkedNode(btNode.value); 70 | prev=head; 71 | } 72 | else 73 | { 74 | prev.next=new LinkedNode(btNode.value); 75 | prev=prev.next; 76 | } 77 | if(btNode.left!=null) 78 | queue.add(btNode.left); 79 | if(btNode.right!=null) 80 | queue.add(btNode.right); 81 | 82 | } 83 | return result; 84 | } 85 | static class BinaryTreeNode 86 | { 87 | public BinaryTreeNode left; 88 | public BinaryTreeNode right; 89 | public int value; 90 | public BinaryTreeNode(int value) 91 | { 92 | this.value=value; 93 | } 94 | } 95 | 96 | static class LinkedNode 97 | { 98 | public LinkedNode next; 99 | public int value; 100 | public LinkedNode(int value) 101 | { 102 | this.value=value; 103 | } 104 | } 105 | 106 | static void printLinkedList(LinkedNode head) 107 | { 108 | while(head!=null) 109 | { 110 | System.out.print(head.value); 111 | System.out.print("->"); 112 | head=head.next; 113 | } 114 | System.out.println(); 115 | } 116 | 117 | } 118 | 119 | -------------------------------------------------------------------------------- /src/com/dsalgo/BinaryTreeZigzag.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/BinaryTreeZigzag.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.LinkedList; 9 | import java.util.Stack; 10 | 11 | public class BinaryTreeZigzag { 12 | public static void main(String[] args) { 13 | Node a = new Node(1); 14 | Node b = new Node(2); 15 | Node c = new Node(3); 16 | Node d = new Node(4); 17 | Node e = new Node(5); 18 | Node f = new Node(6); 19 | Node g = new Node(7); 20 | Node h = new Node(8); 21 | Node i = new Node(9); 22 | 23 | a.left = b; 24 | a.right = c; 25 | b.right = d; 26 | c.left = e; 27 | c.right = f; 28 | d.left = g; 29 | d.right = h; 30 | g.right = i; 31 | 32 | printZigzag(a); 33 | 34 | } 35 | 36 | public static void printZigzag(Node root) { 37 | LinkedList queue = new LinkedList(); 38 | Stack stack = new Stack(); 39 | if (root == null) 40 | return; 41 | Node marker = new Node(-1); 42 | boolean printOrder = true; 43 | queue.add(root); 44 | queue.add(marker); 45 | while (!queue.isEmpty()) { 46 | Node node = queue.poll(); 47 | if (node == marker) { 48 | if (!printOrder) { 49 | while (stack.size() > 0) { 50 | Node printNode = stack.pop(); 51 | System.out.println(printNode.value); 52 | 53 | } 54 | 55 | } 56 | printOrder = !printOrder; 57 | if (!queue.isEmpty()) 58 | queue.add(marker); 59 | continue; 60 | } 61 | if (printOrder) { 62 | System.out.println(node.value); 63 | } else { 64 | stack.push(node); 65 | } 66 | if (node.left != null) 67 | queue.add(node.left); 68 | if (node.right != null) 69 | queue.add(node.right); 70 | 71 | } 72 | 73 | } 74 | 75 | static class Node { 76 | public Node left; 77 | public Node right; 78 | public int value; 79 | 80 | public Node(int value) { 81 | this.value = value; 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/com/dsalgo/CalculatePower.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/CalculatePower.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class CalculatePower 9 | { 10 | public static void main(String[] args) 11 | { 12 | int x = 4; 13 | int y = 10; 14 | long power = x; 15 | long answer = 1; 16 | while (y != 0) 17 | { 18 | if ((y & 1) == 1) 19 | { 20 | answer *= power; 21 | } 22 | y >>= 1; 23 | power *= power; 24 | } 25 | System.out.println(answer); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/com/dsalgo/CheckForBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/CheckForBST.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class CheckForBST 9 | { 10 | 11 | /** 12 | * @param args 13 | */ 14 | public static void main(String[] args) 15 | { 16 | Node a=new Node(12); 17 | Node b=new Node(3); 18 | Node c=new Node(15); 19 | Node d=new Node(10); 20 | Node e=new Node(14); 21 | Node f=new Node(17); 22 | Node g=new Node(4); 23 | Node h=new Node(11); 24 | Node i=new Node(5); 25 | a.left=b; 26 | a.right=c; 27 | b.right=d; 28 | c.left=e; 29 | c.right=f; 30 | d.left=g; 31 | d.right=h; 32 | g.right=i; 33 | System.out.println(isBST(a)); 34 | 35 | } 36 | 37 | public static boolean isBST(Node root) 38 | { 39 | return checkBooleanAndReturn(root, Integer.MAX_VALUE, Integer.MIN_VALUE); 40 | } 41 | 42 | private static boolean checkBooleanAndReturn(Node root, int max,int min) 43 | { 44 | if(root==null)return true; 45 | boolean leftOk=true; 46 | boolean rightOk=true; 47 | boolean centerOk=true; 48 | if(root.left!=null) 49 | leftOk=checkBooleanAndReturn(root.left,root.value,min); 50 | if(root.value>=min &&root.value<=max) 51 | centerOk=true; 52 | else 53 | centerOk=false; 54 | if(root.right!=null) 55 | rightOk=checkBooleanAndReturn(root.right,max,root.value); 56 | return leftOk&¢erOk&&rightOk; 57 | } 58 | 59 | 60 | static class Node 61 | { 62 | public Node left; 63 | public Node right; 64 | public int value; 65 | public Node(int value) 66 | { 67 | this.value=value; 68 | } 69 | } 70 | } 71 | 72 | -------------------------------------------------------------------------------- /src/com/dsalgo/ClosestKpoints.java: -------------------------------------------------------------------------------- 1 | package com.dsalgo; 2 | 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | 6 | public class ClosestKpoints { 7 | 8 | public static void main(String[] args) { 9 | /*double[][] coordinates = { { 1.2, 4 }, { 4.5, 3 }, { 1.2, 5 }, 10 | { 4.3, 6 }, { 0.2, 4 }, { 4.3, 3.4 }, { 5.6, 3 }, { 6.5, 2.3 }, 11 | { 4, 5.4 }, };*/ 12 | double[][] coordinates = { { 1,1 }, { 4, 4 }, { 2,2 }, 13 | { 3,3 }, {5,5 }}; 14 | 15 | Point[] points = new Point[coordinates.length]; 16 | for (int i = 0; i < coordinates.length; ++i) { 17 | points[i] = new Point(coordinates[i][0], coordinates[i][1]); 18 | } 19 | Point fromPoint = new Point(3,3); 20 | Point[] nearPoints = findNearPoints(points, fromPoint, 4); 21 | for (Point p:nearPoints) 22 | { 23 | System.out.print(p); 24 | System.out.print(","); 25 | } 26 | System.out.println(); 27 | } 28 | 29 | private static Point[] findNearPoints(Point[] points, Point fromPoint, int k) { 30 | DistanceComparator comparator = new DistanceComparator(fromPoint); 31 | PriorityQueue maxHeap = new PriorityQueue(k, comparator); 32 | for (Point p : points) { 33 | if (maxHeap.size() < k) 34 | maxHeap.add(p); 35 | else { 36 | if (comparator.compare(maxHeap.peek(), p) < 0) { 37 | maxHeap.poll(); 38 | maxHeap.add(p); 39 | } 40 | } 41 | } 42 | Point[] result = new Point[k]; 43 | int index = 0; 44 | while (!maxHeap.isEmpty()) { 45 | result[index++] = maxHeap.poll(); 46 | } 47 | return result; 48 | } 49 | 50 | public static class Point { 51 | public double x; 52 | public double y; 53 | 54 | public Point(double x, double y) { 55 | this.x = x; 56 | this.y = y; 57 | } 58 | public String toString() 59 | { 60 | return "("+this.x+","+this.y+")"; 61 | } 62 | } 63 | 64 | public static class DistanceComparator implements Comparator { 65 | Point p; 66 | 67 | public DistanceComparator(Point p) { 68 | this.p = p; 69 | } 70 | 71 | @Override 72 | public int compare(Point o1, Point o2) { 73 | double distance1 = (o1.x - p.x) * (o1.x - p.x) + (o1.y - p.y) 74 | * (o1.y - p.y); 75 | double distance2 = (o2.x - p.x) * (o2.x - p.x) + (o2.y - p.y) 76 | * (o2.y - p.y); 77 | return -1*new Double(distance1).compareTo(new Double(distance2)); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/com/dsalgo/CompactBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.dsalgo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public class CompactBinaryTree { 9 | 10 | public static void main(String[] args) { 11 | 12 | Node a = new Node(1); 13 | Node b = new Node(2); 14 | Node bb = new Node(2); 15 | Node c = new Node(3); 16 | Node d = new Node(4); 17 | Node e = new Node(5); 18 | Node ee = new Node(5); 19 | Node eee = new Node(5); 20 | Node f = new Node(6); 21 | Node ff = new Node(6); 22 | Node g = new Node(7); 23 | Node h = new Node(8); 24 | Node i = new Node(9); 25 | a.left = b; 26 | b.left = e; 27 | b.right = f; 28 | a.right = c; 29 | c.left = d; 30 | c.right = bb; 31 | bb.left = ee; 32 | bb.right = ff; 33 | d.left = g; 34 | g.left = h; 35 | g.right = i; 36 | h.right = eee; 37 | compactTree(a); 38 | System.out.println("Let's see if it worked..."); 39 | System.out.println("left child of a: " 40 | + System.identityHashCode(a.left)); 41 | System.out.println("right child of c: " 42 | + System.identityHashCode(c.right)); 43 | System.out.println("right child of h: " 44 | + System.identityHashCode(h.right)); 45 | System.out.println("left child of b: " 46 | + System.identityHashCode(b.left)); 47 | } 48 | 49 | static void compactTree(Node root) { 50 | Map< NodeHash, Node > map = new HashMap< >(); 51 | compactTree(root, map); 52 | } 53 | 54 | static void compactTree(Node root, Map< NodeHash, Node > map) { 55 | NodeHash nodeHash = new NodeHash(root); 56 | map.put(nodeHash, root); 57 | if (root.left != null) { 58 | NodeHash leftHash = new NodeHash(root.left); 59 | if (map.containsKey(leftHash)) { 60 | root.left = (Node) map.get(leftHash); 61 | } else { 62 | compactTree(root.left, map); 63 | } 64 | } 65 | if (root.right != null) { 66 | NodeHash rightHash = new NodeHash(root.right); 67 | if (map.containsKey(rightHash)) { 68 | root.right = (Node) map.get(rightHash); 69 | } else { 70 | compactTree(root.right, map); 71 | } 72 | } 73 | } 74 | 75 | static class Node { 76 | private Node left; 77 | private Node right; 78 | private int value; 79 | 80 | public Node(int value) { 81 | this.value = value; 82 | } 83 | 84 | @Override 85 | public int hashCode() { 86 | return value; 87 | } 88 | 89 | @Override 90 | public boolean equals(Object obj) { 91 | return value == ((Node) obj).value; 92 | } 93 | 94 | @Override 95 | public String toString() { 96 | return "" + value; 97 | } 98 | } 99 | 100 | static class NodeHash { 101 | List< Node > preOrderList; 102 | List< Node > inOrderList; 103 | 104 | NodeHash(Node root) { 105 | preOrderList = preOrder(root); 106 | inOrderList = inOrder(root); 107 | } 108 | 109 | @Override 110 | public boolean equals(Object obj) { 111 | NodeHash n = (NodeHash) obj; 112 | return preOrderList.equals(n.preOrderList) 113 | && inOrderList.equals(n.inOrderList); 114 | } 115 | 116 | @Override 117 | public int hashCode() { 118 | return 31 * preOrderList.hashCode() + inOrderList.hashCode(); 119 | } 120 | 121 | List< Node > preOrder(Node root) { 122 | List< Node > result = new ArrayList< >(); 123 | if (root == null) 124 | return result; 125 | result.add(root); 126 | result.addAll(preOrder(root.left)); 127 | result.addAll(preOrder(root.right)); 128 | return result; 129 | } 130 | 131 | List< Node > inOrder(Node root) { 132 | List< Node > result = new ArrayList< >(); 133 | if (root == null) 134 | return result; 135 | result.addAll(inOrder(root.left)); 136 | result.add(root); 137 | result.addAll(inOrder(root.right)); 138 | return result; 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/com/dsalgo/CreateTreeFromInPre.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/CreateTreeFromInPre.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class CreateTreeFromInPre 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[] inorder = 13 | { 4, 2, 5, 1, 6, 3 }; 14 | int[] preorder = 15 | { 1, 2, 4, 5, 3, 6 }; 16 | Node root = buildBinaryTree(inorder, preorder); 17 | printNice(root); 18 | } 19 | 20 | public static Node buildBinaryTree(int[] inorder, int[] preorder) 21 | { 22 | return buildBinaryTree(inorder, 0, inorder.length, preorder, new int[] 23 | { 0 }); 24 | } 25 | 26 | private static Node buildBinaryTree(int[] inorder, int inStartIndex, 27 | int inEndIndex, int[] preorder, int[] preIndex) 28 | { 29 | if (preIndex[0] == preorder.length) 30 | return null; 31 | Node root = new Node(preorder[preIndex[0]]); 32 | int findIndex = -1; 33 | for (int i = inStartIndex; i < inEndIndex; ++i) 34 | { 35 | if (preorder[preIndex[0]] == inorder[i]) 36 | { 37 | findIndex = i; 38 | } 39 | } 40 | if (findIndex == -1) 41 | return null; 42 | preIndex[0]++; 43 | root.left = buildBinaryTree(inorder, inStartIndex, findIndex, preorder, 44 | preIndex); 45 | root.right = buildBinaryTree(inorder, findIndex + 1, inEndIndex, 46 | preorder, preIndex); 47 | return root; 48 | } 49 | 50 | static class Node 51 | { 52 | Node left; 53 | Node right; 54 | int value; 55 | 56 | public Node(int value) 57 | { 58 | this.value = value; 59 | } 60 | } 61 | 62 | public static void printNice(Node root) 63 | { 64 | if (root == null) 65 | return; 66 | else 67 | { 68 | System.out.print(root.value); 69 | if (root.left != null) 70 | { 71 | System.out.print("L->["); 72 | printNice(root.left); 73 | System.out.print("]"); 74 | } 75 | if (root.right != null) 76 | { 77 | System.out.print("R->["); 78 | printNice(root.right); 79 | System.out.print("]"); 80 | } 81 | } 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /src/com/dsalgo/DistributedCircularListSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/distributed-circular-linked-list-sum.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | class DistributedCircularListSum 9 | { 10 | public static volatile boolean startFlag = false; 11 | private static Boolean flag = false; 12 | 13 | public static void main(String[] args) 14 | { 15 | Node a = new Node(1); 16 | Node b = new Node(2); 17 | Node c = new Node(3); 18 | Node d = new Node(4); 19 | Node e = new Node(5); 20 | a.next = b; 21 | b.next = c; 22 | c.next = d; 23 | d.next = e; 24 | e.next = a; 25 | startFlag = true; 26 | } 27 | 28 | private static class Node 29 | { 30 | Node next; 31 | int value; 32 | Integer data; 33 | 34 | public Node(int value) 35 | { 36 | this.value = value; 37 | new Thread(new NodeRunner(this, value)).start(); 38 | } 39 | 40 | public synchronized void send(int data) 41 | { 42 | this.data = data; 43 | } 44 | 45 | } 46 | 47 | private static class NodeRunner implements Runnable 48 | { 49 | Node node; 50 | int id; 51 | 52 | public NodeRunner(Node node, int id) 53 | { 54 | this.node = node; 55 | this.id = id; 56 | } 57 | 58 | @Override 59 | public void run() 60 | { 61 | while (!startFlag) 62 | { 63 | } 64 | 65 | boolean isFirst = false; 66 | synchronized (flag) 67 | { 68 | if (flag == false) 69 | { 70 | flag = true; 71 | isFirst = true; 72 | } 73 | } 74 | if (isFirst) 75 | node.next.send(node.value); 76 | else 77 | { 78 | while (node.data == null) 79 | { 80 | try 81 | { 82 | Thread.sleep(10); 83 | } catch (InterruptedException e) 84 | { 85 | 86 | } 87 | } 88 | int sum = node.value + node.data; 89 | node.data = null; 90 | node.next.send(sum); 91 | } 92 | while (node.data == null) 93 | { 94 | try 95 | { 96 | Thread.sleep(10); 97 | } catch (InterruptedException e) 98 | { 99 | 100 | } 101 | } 102 | System.out.println("id:" + id + "sum:" + node.data); 103 | node.next.send(node.data); 104 | } 105 | } 106 | } 107 | 108 | -------------------------------------------------------------------------------- /src/com/dsalgo/DistributedDoublyLinkedListSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/distributed-doubly-linked-list-sum.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class DistributedDoublyLinkedListSum 9 | { 10 | public static volatile boolean startFlag = false; 11 | 12 | public static void main(String[] args) 13 | { 14 | Node a = new Node(1); 15 | Node b = new Node(2); 16 | Node c = new Node(3); 17 | Node d = new Node(4); 18 | Node e = new Node(5); 19 | a.next = b; 20 | b.next = c; 21 | c.next = d; 22 | d.next = e; 23 | e.prev = d; 24 | d.prev = c; 25 | c.prev = b; 26 | b.prev = a; 27 | startFlag = true; 28 | } 29 | 30 | private static class Node 31 | { 32 | Node next; 33 | Node prev; 34 | int value; 35 | Integer data; 36 | 37 | public Node(int value) 38 | { 39 | this.value = value; 40 | new Thread(new NodeRunner(this, value)).start(); 41 | } 42 | 43 | public synchronized void send(int data) 44 | { 45 | this.data = data; 46 | } 47 | 48 | } 49 | 50 | private static class NodeRunner implements Runnable 51 | { 52 | Node node; 53 | int id; 54 | 55 | public NodeRunner(Node node, int id) 56 | { 57 | this.node = node; 58 | this.id = id; 59 | } 60 | 61 | @Override 62 | public void run() 63 | { 64 | while (!startFlag) 65 | { 66 | } 67 | if (node.next == null) 68 | { 69 | node.prev.send(node.value); 70 | } else 71 | { 72 | while (node.data == null) 73 | { 74 | try 75 | { 76 | Thread.sleep(10); 77 | } catch (InterruptedException e) 78 | { 79 | } 80 | } 81 | int sum = node.data + node.value; 82 | if (node.prev != null) 83 | { 84 | node.data = null; 85 | node.prev.send(sum); 86 | } 87 | } 88 | while (node.data == null) 89 | { 90 | try 91 | { 92 | Thread.sleep(10); 93 | } catch (InterruptedException e) 94 | { 95 | } 96 | } 97 | System.out.println("id:" + id + " sum:" + node.data); 98 | if (node.next != null) 99 | { 100 | node.next.send(node.data); 101 | } 102 | 103 | } 104 | } 105 | } 106 | 107 | -------------------------------------------------------------------------------- /src/com/dsalgo/DistributedSystemSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/distributed-binary-tree-sum.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class DistributedSystemSum 9 | { 10 | public static volatile boolean startFlag = false; 11 | 12 | public static void main(String[] args) 13 | { 14 | Node a = new Node(1); 15 | Node b = new Node(2); 16 | Node c = new Node(3); 17 | Node d = new Node(4); 18 | Node e = new Node(5); 19 | Node f = new Node(6); 20 | Node g = new Node(7); 21 | Node h = new Node(8); 22 | a.left = b; 23 | b.parent = a; 24 | a.right = c; 25 | c.parent = a; 26 | b.left = d; 27 | d.parent = b; 28 | c.left = e; 29 | e.parent = c; 30 | c.right = f; 31 | f.parent = c; 32 | f.left = g; 33 | g.parent = f; 34 | f.right = h; 35 | h.parent = f; 36 | startFlag = true; 37 | } 38 | 39 | private static class Node 40 | { 41 | Node parent; 42 | Node left; 43 | Node right; 44 | int value; 45 | int sum = 0; 46 | int receiveCount = 0; 47 | 48 | public Node(int value) 49 | { 50 | this.value = value; 51 | NodeRunner nodeRunner = new NodeRunner(this, value); 52 | new Thread(nodeRunner).start(); 53 | } 54 | 55 | public synchronized void send(Integer data) 56 | { 57 | sum += data; 58 | receiveCount++; 59 | } 60 | 61 | public synchronized int getReceivedCount() 62 | { 63 | return receiveCount; 64 | } 65 | } 66 | 67 | private static class NodeRunner implements Runnable 68 | { 69 | Node node; 70 | int id; 71 | 72 | NodeRunner(Node node, int id) 73 | { 74 | this.node = node; 75 | this.id = id; 76 | } 77 | 78 | @Override 79 | public void run() 80 | { 81 | while (!DistributedSystemSum.startFlag) 82 | { 83 | } 84 | int childCount = 0; 85 | if (node.left != null) 86 | childCount++; 87 | if (node.right != null) 88 | childCount++; 89 | while (node.getReceivedCount() != childCount) 90 | { 91 | } 92 | int sum = node.sum + node.value; 93 | node.sum = 0; 94 | if (node.parent != null) 95 | { 96 | node.parent.send(sum); 97 | while (node.getReceivedCount() != childCount + 1) 98 | { 99 | } 100 | } else 101 | { 102 | node.sum = sum; 103 | } 104 | if (node.left != null) 105 | node.left.send(node.sum); 106 | if (node.right != null) 107 | node.right.send(node.sum); 108 | System.out.println("Thread id=" + id + " sum=" + node.sum); 109 | 110 | } 111 | 112 | } 113 | } 114 | 115 | -------------------------------------------------------------------------------- /src/com/dsalgo/EqualSumPartition.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/back-to-content-array-equal-sum.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class EqualSumPartition 12 | { 13 | public static void main(String[] args) 14 | { 15 | Integer[] arr ={ 1, 2, 3, 6, 4, 5, 7 }; 16 | System.out.println("Original Array"); 17 | for (Integer num : arr) 18 | { 19 | System.out.print(num + ", "); 20 | } 21 | System.out.println(); 22 | 23 | Integer[][] parts = partition(arr); 24 | if (parts == null) 25 | { 26 | System.out.println("partition not possible"); 27 | return; 28 | } 29 | System.out.println("partition"); 30 | for (Integer num : parts[0]) 31 | System.out.print(num + ", "); 32 | System.out.println(); 33 | for (Integer num : parts[1]) 34 | System.out.print(num + ", "); 35 | } 36 | 37 | private static Integer[][] partition(Integer[] arr) 38 | { 39 | List list = new ArrayList(); 40 | List part = new ArrayList(); 41 | 42 | int sum = 0; 43 | for (Integer num : arr) 44 | { 45 | list.add(num); 46 | sum += num; 47 | } 48 | if (sum % 2 == 1) 49 | return null; 50 | sum /= 2; 51 | int[][] memo = new int[arr.length + 1][sum + 1]; 52 | for (int i = 1; i <= arr.length; ++i) 53 | { 54 | for (int s = 1; s <= sum; ++s) 55 | { 56 | if (arr[i - 1] > s 57 | || memo[i - 1][s] > arr[i - 1] 58 | + memo[i - 1][s - arr[i - 1]]) 59 | memo[i][s] = memo[i - 1][s]; 60 | else 61 | { 62 | memo[i][s] = arr[i - 1] + memo[i - 1][s - arr[i - 1]]; 63 | } 64 | } 65 | } 66 | if (memo[arr.length][sum] != sum) 67 | return null; 68 | int i = arr.length; 69 | int s = sum; 70 | while (s > 0 && i > 0) 71 | { 72 | if (arr[i - 1] <= s 73 | && memo[i][s] == arr[i - 1] + memo[i - 1][s - arr[i - 1]]) 74 | { 75 | part.add(arr[i - 1]); 76 | s = s - arr[i - 1]; 77 | } 78 | i--; 79 | } 80 | for (Integer num : part) 81 | list.remove(num); 82 | Integer[][] result = new Integer[2][]; 83 | result[0] = part.toArray(new Integer[] {}); 84 | result[1] = list.toArray(new Integer[] {}); 85 | return result; 86 | } 87 | 88 | } 89 | 90 | -------------------------------------------------------------------------------- /src/com/dsalgo/ExpandArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/expand-array.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class ExpandArray 9 | { 10 | public static void main(String[] args) 11 | { 12 | char[] arr = "a2b1c1d1e4f0g11 ".toCharArray(); 13 | expand(arr); 14 | for (char ch : arr) 15 | System.out.print(ch); 16 | } 17 | 18 | private static void expand(char[] arr) 19 | { 20 | expand(arr, 0, 0); 21 | } 22 | 23 | private static void expand(char[] arr, int startReading, int startWriting) 24 | { 25 | char ch = arr[startReading++]; 26 | if (ch == ' ') 27 | return; 28 | int count = 0; 29 | while (Character.isDigit(arr[startReading])) 30 | { 31 | count = count * 10 + arr[startReading] - 48; 32 | startReading++; 33 | } 34 | expand(arr, startReading, startWriting + count); 35 | for (int i = 0; i < count; ++i) 36 | arr[startWriting + i] = ch; 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/com/dsalgo/FindDeepestNodes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/find-deepest-nodes-of-binary-tree.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class FindDeepestNodes 11 | { 12 | public static void main(String[] args) 13 | { 14 | Node a = new Node(1); 15 | Node b = new Node(2); 16 | Node c = new Node(3); 17 | Node d = new Node(4); 18 | Node e = new Node(5); 19 | Node f = new Node(8); 20 | Node g = new Node(6); 21 | Node h = new Node(7); 22 | a.left = b; 23 | a.right = c; 24 | b.left = d; 25 | b.right = e; 26 | c.right = f; 27 | f.left = g; 28 | f.right = h; 29 | 30 | List nodes = findDeepestNodes(a); 31 | for (Node node : nodes) 32 | { 33 | System.out.print(node.value + ", "); 34 | } 35 | } 36 | 37 | @SuppressWarnings("unchecked") 38 | private static List findDeepestNodes(Node root) 39 | { 40 | Object[] levelNodes = new Object[2]; 41 | levelNodes[0] = 0; 42 | levelNodes[1] = new ArrayList(); 43 | findDeepestNodes(root, 1, levelNodes); 44 | return (List) levelNodes[1]; 45 | } 46 | 47 | @SuppressWarnings("unchecked") 48 | private static void findDeepestNodes(Node root, int level, 49 | Object[] levelNodes) 50 | { 51 | if (root == null) 52 | return; 53 | if((Integer)levelNodes[0]<=level) 54 | { 55 | if((Integer)levelNodes[0])levelNodes[1]).clear(); 57 | levelNodes[0]=level; 58 | ((List)levelNodes[1]).add(root); 59 | } 60 | findDeepestNodes(root.left, level+1, levelNodes); 61 | findDeepestNodes(root.right, level+1, levelNodes); 62 | } 63 | 64 | static class Node 65 | { 66 | Node left; 67 | Node right; 68 | int value; 69 | 70 | public Node(int value) 71 | { 72 | this.value = value; 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/com/dsalgo/FindMinMax.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/FindMinMax.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class FindMinMax 9 | { 10 | 11 | public static void main(String[] args) 12 | { 13 | int[] arr = {4, 3, 5, 1, 2, 6, 9, 2, 10, 11}; 14 | int max = arr[0]; 15 | int min = arr[0]; 16 | int i = 0; 17 | for (; i < arr.length / 2; i++) 18 | { 19 | int num1 = arr[i * 2]; 20 | int num2 = arr[i * 2 + 1]; 21 | if (num1 >= num2) 22 | { 23 | if (num1 > max) 24 | max = num1; 25 | if (num2 < min) 26 | min = num2; 27 | } 28 | else 29 | { 30 | if (num2 > max) 31 | max = num2; 32 | if (num1 < min) 33 | min = num1; 34 | } 35 | } 36 | if (i * 2 < arr.length) 37 | { 38 | int num = arr[i * 2]; 39 | if (num > max) 40 | max = num; 41 | if (num < min) 42 | min = num; 43 | } 44 | System.out.println("maximum= " + max); 45 | System.out.println("minimum= " + min); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/com/dsalgo/FindMinMax2.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/FindMinMax.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class FindMinMax2 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[] arr = {4, 3, 5, 1, 2, 6, 9, 2, 10, 11, 12}; 13 | MinMax result = findMinMaxRecursive(arr, 0, arr.length - 1); 14 | System.out.println("maximum= " + result.max); 15 | System.out.println("minimum= " + result.min); 16 | } 17 | 18 | private static MinMax findMinMaxRecursive(int[] arr, int i, int j) 19 | { 20 | if (i > j) 21 | return null; 22 | if (i == j) 23 | return new MinMax(arr[i], arr[i]); 24 | else 25 | { 26 | MinMax left; 27 | MinMax right; 28 | left = findMinMaxRecursive(arr, i, (i + j) / 2); 29 | right = findMinMaxRecursive(arr, (i + j) / 2 + 1, j); 30 | if (left == null) 31 | return right; 32 | else if (right == null) 33 | return left; 34 | else 35 | { 36 | return new MinMax(Math.min(left.min, right.min), Math.max( 37 | left.max, right.max)); 38 | } 39 | } 40 | } 41 | } 42 | 43 | class MinMax 44 | { 45 | public int min; 46 | public int max; 47 | 48 | public MinMax(int min, int max) 49 | { 50 | this.min = min; 51 | this.max = max; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/com/dsalgo/FindOrderOfLetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/FindOrderOfLetter.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.HashMap; 9 | 10 | public class FindOrderOfLetter 11 | { 12 | public static void main(String[] args) 13 | { 14 | String[] words = 15 | { "car", "cat", "cbr", "deer", "egg", "god", "rabe", "race", "rat", 16 | "tar" }; 17 | char[] letters = getLetterOrdering(words); 18 | if (letters == null) 19 | System.out.println("not possible"); 20 | else 21 | { 22 | for (char ch : letters) 23 | System.out.print(ch + ","); 24 | } 25 | } 26 | 27 | private static char[] getLetterOrdering(String[] words) 28 | { 29 | HashMap characters = new HashMap(); 30 | for (String word : words) 31 | { 32 | for (int i = 0; i < word.length(); ++i) 33 | { 34 | char character = word.charAt(i); 35 | if (!characters.keySet().contains(character)) 36 | { 37 | characters.put(character, characters.size()); 38 | } 39 | } 40 | } 41 | boolean[][] adjacency = new boolean[characters.size()][characters 42 | .size()]; 43 | for (int i = 0; i < words.length - 1; ++i) 44 | { 45 | for (int j = i + 1; j < words.length; ++j) 46 | { 47 | String prevWord = words[i]; 48 | String nextWord = words[j]; 49 | for (int k = 0; k < Math.min(prevWord.length(), 50 | nextWord.length()); ++k) 51 | { 52 | char prevCharacter = prevWord.charAt(k); 53 | char nextCharacter = nextWord.charAt(k); 54 | if (prevCharacter != nextCharacter) 55 | { 56 | adjacency[characters.get(prevCharacter)][characters 57 | .get(nextCharacter)] = true; 58 | break; 59 | } 60 | } 61 | } 62 | } 63 | 64 | char[] result = new char[characters.size()]; 65 | int resultIndex = 0; 66 | while (!characters.isEmpty()) 67 | { 68 | char lowChar = ' '; 69 | for (Character nextCharacter : characters.keySet()) 70 | { 71 | int nextIndex = characters.get(nextCharacter); 72 | boolean lowest = true; 73 | for (Character prevCharacter : characters.keySet()) 74 | { 75 | int prevIndex = characters.get(prevCharacter); 76 | if (adjacency[prevIndex][nextIndex]) 77 | { 78 | lowest = false; 79 | break; 80 | } 81 | } 82 | if (lowest) 83 | { 84 | lowChar = nextCharacter; 85 | result[resultIndex++] = nextCharacter; 86 | break; 87 | } 88 | } 89 | if (lowChar == ' ') 90 | { 91 | return null; 92 | } else 93 | { 94 | characters.remove(lowChar); 95 | lowChar = ' '; 96 | } 97 | } 98 | return result; 99 | } 100 | 101 | } 102 | 103 | -------------------------------------------------------------------------------- /src/com/dsalgo/FindPathFromRoot.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-path-of-node-from-root.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class FindPathFromRoot 11 | { 12 | public static void main(String[] args) 13 | { 14 | Node a = new Node(1); 15 | Node b = new Node(2); 16 | Node c = new Node(3); 17 | Node d = new Node(4); 18 | Node e = new Node(5); 19 | Node f = new Node(6); 20 | Node g = new Node(7); 21 | Node h = new Node(8); 22 | a.left = b; 23 | a.right = c; 24 | b.left = d; 25 | c.left = e; 26 | c.right = f; 27 | f.left = g; 28 | f.right = h; 29 | 30 | List path = findPath(a, d); 31 | for (Node node : path) 32 | System.out.println(node.value); 33 | } 34 | 35 | private static List findPath(Node root, Node node) 36 | { 37 | if (root == null) 38 | return null; 39 | List path = new ArrayList(); 40 | if (root == node) 41 | { 42 | path.add(root); 43 | return path; 44 | } 45 | List leftPath = findPath(root.left, node); 46 | List rightPath = findPath(root.right, node); 47 | if (leftPath != null) 48 | { 49 | leftPath.add(0, root); 50 | return leftPath; 51 | } 52 | if (rightPath != null) 53 | { 54 | rightPath.add(0, root); 55 | return rightPath; 56 | } 57 | return null; 58 | } 59 | 60 | static class Node 61 | { 62 | Node left; 63 | Node right; 64 | int value; 65 | 66 | public Node(int value) 67 | { 68 | this.value = value; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/com/dsalgo/FindPermutations.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-all-permutations.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class FindPermutations 12 | { 13 | public static void main(String[] args) 14 | { 15 | findAllPermutations("abcde"); 16 | } 17 | 18 | private static void findAllPermutations(String string) 19 | { 20 | Listcharacters=new ArrayList(); 21 | for(char ch:string.toCharArray()) 22 | characters.add(ch); 23 | findAllPermutations(new ArrayList(),characters); 24 | } 25 | 26 | private static void findAllPermutations(List prefix, 27 | List suffix) 28 | { 29 | if(suffix.size()==1) 30 | { 31 | for(Character ch:prefix) 32 | System.out.print(ch); 33 | System.out.println(suffix.get(0)); 34 | return; 35 | } 36 | for(int i=0;i"); 89 | head = head.next; 90 | } 91 | System.out.println(); 92 | } 93 | 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/com/dsalgo/FrogJump.java: -------------------------------------------------------------------------------- 1 | package com.dsalgo; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class FrogJump { 6 | 7 | public static void main(String[] args) { 8 | boolean[] stone = { true, false, true, true, true, false, true, false, 9 | true, false, true, true, false, true }; 10 | System.out.println("Frog jump " + frogJump(stone)); 11 | } 12 | 13 | static List frogJump(boolean[] stone) { 14 | int[][] jumpTable = new int[stone.length + 1][stone.length + 1]; 15 | if (frogJump(stone, 1, 0, jumpTable)) { 16 | List result = new ArrayList(); 17 | int currentStone = 0; 18 | int jump = 1; 19 | while (currentStone < stone.length) { 20 | result.add(currentStone); 21 | jump = jumpTable[currentStone][jump]; 22 | currentStone += jump; 23 | } 24 | result.add(stone.length); 25 | return result; 26 | } 27 | return null; 28 | } 29 | 30 | static boolean frogJump(boolean[] stone, int jump, int currentLocation, 31 | int[][] jumpTable) { 32 | if (currentLocation >= stone.length 33 | || jumpTable[currentLocation][jump] != 0) 34 | return true; 35 | if (jump < 1 || !stone[currentLocation]) 36 | return false; 37 | for (int i = 1; i > -2; --i) { 38 | if (frogJump(stone, jump + i, currentLocation + jump + i, jumpTable)) { 39 | jumpTable[currentLocation][jump] = jump + i; 40 | return true; 41 | } 42 | } 43 | return false; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/com/dsalgo/IncreasingArraySubsequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/back-to-content-increasing-array.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | 9 | public class IncreasingArraySubsequence 10 | { 11 | 12 | /** 13 | * create subsequence of a given array where every element in the 14 | * subsequence is greater than its previous element 15 | * 16 | * @param args 17 | */ 18 | public static void main(String[] args) 19 | { 20 | int[] input = 21 | { 2, 5, 6, 1, 3 }; 22 | int length = input.length; 23 | ArrayList> table = new ArrayList>(); 24 | 25 | for (int i = 0; i < length; ++i) 26 | { 27 | ArrayList> tempTable = new ArrayList>(); 28 | for (ArrayList j : table) 29 | { 30 | if (j.get(j.size() - 1) <= input[i]) 31 | { 32 | ArrayList temp = new ArrayList(); 33 | temp.addAll(j); 34 | temp.add(input[i]); 35 | tempTable.add(temp); 36 | } 37 | } 38 | table.addAll(tempTable); 39 | ArrayList temp = new ArrayList(); 40 | temp.add(input[i]); 41 | table.add(temp); 42 | } 43 | 44 | // output 45 | for (ArrayList i : table) 46 | { 47 | for (Integer j : i) 48 | { 49 | System.out.print(j + ", "); 50 | } 51 | System.out.println(); 52 | } 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/com/dsalgo/IncreasingDecreasingTuple.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/first-increasing-second-decreasing-tuple.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Collections; 10 | import java.util.List; 11 | 12 | public class IncreasingDecreasingTuple 13 | { 14 | static int count = 0; 15 | 16 | /** 17 | * Given N pairs of integers, write an algorithm to sort the pairs so that 18 | * the first number in each pair is sorted increasingly while the second 19 | * number in each pair is sorted decreasingly. The first and second numbers 20 | * in each pair can be swapped. Sometimes there will be no solution, in that 21 | * case return an error. 22 | * 23 | * Examples: 24 | * 25 | * Input: 1 5 7 1 3 8 5 6 26 | * 27 | * Output: 1 7 < - Swapped 1 5 6 5 < - Swapped 8 3 < - Swapped 28 | * 29 | * Input: 1 5 6 9 30 | * 31 | * Output: Not Possible 32 | * 33 | * @param args 34 | */ 35 | public static void main(String[] args) 36 | { 37 | Integer[][] input = 38 | { 39 | { 1, 5 }, 40 | { 7, 1 }, 41 | { 3, 8 }, 42 | { 5, 6 } }; 43 | List < List < Integer > > list = new ArrayList < List < Integer > > (); 44 | for (Integer[] tuple : input) 45 | { 46 | List < Integer > tupleList = new ArrayList < Integer > (); 47 | for (Integer el : tuple) 48 | { 49 | tupleList.add(el); 50 | } 51 | list.add(tupleList); 52 | } 53 | 54 | System.out.println(getArrangeMent(list)); 55 | 56 | } 57 | 58 | public static List < List < List < Integer > > > getArrangeMent( 59 | List < List < Integer > > list) 60 | { 61 | List < List < List < Integer > > > result = new ArrayList < List < List < Integer > > > (); 62 | for (int i = 0; i < list.size(); ++i) 63 | { 64 | List < Integer > tuple = list.get(i); 65 | List < List < Integer > > subList = new ArrayList < List < Integer > > (list); 66 | subList.remove(i); 67 | List < List < List < Integer > > > r1 = getRecurseArrangeMent(tuple, subList); 68 | if (r1 != null) 69 | result.addAll(prepend(tuple, r1)); 70 | List < Integer > rTuple = new ArrayList < Integer > (tuple); 71 | Collections.reverse(rTuple); 72 | List < List < List < Integer > > > r2 = getRecurseArrangeMent(rTuple, 73 | subList); 74 | if (r2 != null) 75 | result.addAll(prepend(rTuple, r2)); 76 | } 77 | return result; 78 | } 79 | 80 | public static List < List < List < Integer > > > getRecurseArrangeMent( 81 | List < Integer > start, List < List < Integer > > list) 82 | { 83 | List < List < List < Integer > > > result = new ArrayList < List < List < Integer > > > (); 84 | if (list.size() == 0) 85 | return result; 86 | 87 | for (int i = 0; i < list.size(); ++i) 88 | { 89 | List < Integer > tuple = list.get(i); 90 | if (tuple.get(0) >= start.get(0) && start.get(1) >= tuple.get(1)) 91 | { 92 | List < List < Integer > > subList = new ArrayList < List < Integer > > (list); 93 | subList.remove(i); 94 | List < List < List < Integer > > > r1 = getRecurseArrangeMent(tuple, 95 | subList); 96 | if (r1 != null) 97 | result.addAll(prepend(tuple, r1)); 98 | } 99 | List < Integer > rTuple = new ArrayList < Integer > (tuple); 100 | Collections.reverse(rTuple); 101 | if (rTuple.get(0) >= start.get(0) && start.get(1) >= rTuple.get(1)) 102 | { 103 | List < List < Integer > > subList = new ArrayList < List < Integer > > (list); 104 | subList.remove(i); 105 | List < List < List < Integer > > > r1 = getRecurseArrangeMent(rTuple, 106 | subList); 107 | if (r1 != null) 108 | result.addAll(prepend(rTuple, r1)); 109 | } 110 | } 111 | if (result.size() != 0) 112 | return result; 113 | return null; 114 | } 115 | 116 | public static List < List < List < Integer > > > prepend(List < Integer > start, 117 | List < List < List < Integer > > > list) 118 | { 119 | List < List < List < Integer > > > results = new ArrayList < List < List < Integer > > > (); 120 | if (list.size() == 0) 121 | { 122 | List < List < Integer > > result = new ArrayList < List < Integer > > (); 123 | result.add(start); 124 | results.add(result); 125 | } else 126 | { 127 | for (List < List < Integer > > result : list) 128 | { 129 | result.add(0, start); 130 | results.add(result); 131 | } 132 | } 133 | return results; 134 | } 135 | } 136 | 137 | -------------------------------------------------------------------------------- /src/com/dsalgo/InorderSuccessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/InorderSuccessor.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class InorderSuccessor 9 | { 10 | 11 | public static void main(String[] args) 12 | { 13 | NextNode a=new NextNode(1); 14 | NextNode b=new NextNode(2); 15 | NextNode c=new NextNode(3); 16 | NextNode d=new NextNode(4); 17 | NextNode e=new NextNode(5); 18 | NextNode f=new NextNode(6); 19 | NextNode g=new NextNode(7); 20 | NextNode h=new NextNode(8); 21 | NextNode i=new NextNode(9); 22 | a.left=b; 23 | a.right=c; 24 | b.right=d; 25 | c.left=e; 26 | c.right=f; 27 | d.left=g; 28 | d.right=h; 29 | g.right=i; 30 | NextNode head=linkInorderSuccessor(a); 31 | while(head!=null) 32 | { 33 | System.out.println(head.value); 34 | head=head.next; 35 | } 36 | 37 | } 38 | 39 | public static NextNode linkInorderSuccessor(NextNode root) 40 | { 41 | NodeContainer linker=new NodeContainer(); 42 | NodeContainer head=new NodeContainer(); 43 | linkInorderSuccessor(root, linker, head); 44 | return head.node; 45 | } 46 | 47 | private static void linkInorderSuccessor(NextNode root, NodeContainer linker, NodeContainer head) 48 | { 49 | if(root==null) 50 | return; 51 | linkInorderSuccessor(root.left,linker,head); 52 | if(head.node==null&&root!=null) 53 | head.node=root; 54 | if(linker.node!=null) 55 | linker.node.next=root; 56 | linker.node=root; 57 | linkInorderSuccessor(root.right, linker, head); 58 | } 59 | static class NextNode 60 | { 61 | public NextNode left; 62 | public NextNode right; 63 | public NextNode next; 64 | public int value; 65 | public NextNode(int value) 66 | { 67 | this.value=value; 68 | } 69 | } 70 | 71 | static class NodeContainer 72 | { 73 | public NextNode node; 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /src/com/dsalgo/InterviewHierarchy.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-longest-interviewer-chain.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class InterviewHierarchy 11 | { 12 | public static void main(String[] args) 13 | { 14 | Employee ceo = new Employee("ceo"); 15 | Employee director1 = new Employee("director1"); 16 | Employee director2 = new Employee("director2"); 17 | Employee director3 = new Employee("director3"); 18 | Employee manager1 = new Employee("manager1"); 19 | Employee manager2 = new Employee("manager2"); 20 | Employee manager3 = new Employee("manager3"); 21 | Employee employee1 = new Employee("employee1"); 22 | Employee employee2 = new Employee("employee2"); 23 | Employee employee3 = new Employee("employee3"); 24 | director1.addInterviewer(ceo); 25 | director2.addInterviewer(ceo).addInterviewer(director1); 26 | director3.addInterviewer(director1).addInterviewer(director2); 27 | manager1.addInterviewer(ceo).addInterviewer(director1) 28 | .addInterviewer(director2).addInterviewer(director3); 29 | manager2.addInterviewer(director2).addInterviewer(director3) 30 | .addInterviewer(manager1); 31 | manager3.addInterviewer(director1).addInterviewer(director2) 32 | .addInterviewer(manager2).addInterviewer(manager1); 33 | employee1.addInterviewer(director1).addInterviewer(director2) 34 | .addInterviewer(manager3).addInterviewer(manager2); 35 | employee2.addInterviewer(manager3).addInterviewer(manager2) 36 | .addInterviewer(manager1).addInterviewer(employee1); 37 | employee3.addInterviewer(employee1).addInterviewer(employee2) 38 | .addInterviewer(director3).addInterviewer(manager2); 39 | 40 | List result = findLongestInterviewChain(employee2); 41 | System.out.println("Longest interview chain of " + employee2.getName()); 42 | for (Employee employee : result) 43 | System.out.print(employee.getName() + ", "); 44 | } 45 | 46 | private static List findLongestInterviewChain(Employee employee) 47 | { 48 | int maxLength = -1; 49 | List longestPath = new ArrayList(); 50 | for (Employee interviewer : employee.getInterviewers()) 51 | { 52 | List path = findLongestInterviewChain(interviewer); 53 | if (path.size() > maxLength) 54 | { 55 | maxLength = path.size(); 56 | longestPath = path; 57 | } 58 | } 59 | longestPath.add(0, employee); 60 | return longestPath; 61 | } 62 | 63 | private static class Employee 64 | { 65 | private List interviewers; 66 | private String name; 67 | 68 | public Employee(String name) 69 | { 70 | this.name = name; 71 | interviewers = new ArrayList(); 72 | } 73 | 74 | public String getName() 75 | { 76 | return name; 77 | } 78 | 79 | public List getInterviewers() 80 | { 81 | return interviewers; 82 | } 83 | 84 | public Employee addInterviewer(Employee employee) 85 | { 86 | this.interviewers.add(employee); 87 | return this; 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/com/dsalgo/IsAveragePossible.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/back-to-content-find-subset-with-given.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class IsAveragePossible 11 | { 12 | public static void main(String[] args) 13 | { 14 | int[] arr = 15 | { 1, 4, 5, 3, 8 }; 16 | double average = 3.5; 17 | for (int i = 1; i <= arr.length; ++i) 18 | { 19 | double sum = i * average; 20 | if (sum == (int) sum) 21 | { 22 | List result = isSumPossible(arr, (int) sum, i); 23 | if (result != null) 24 | { 25 | for (int num : result) 26 | System.out.print(num + ", "); 27 | System.out.println(); 28 | return; 29 | } 30 | } 31 | } 32 | 33 | System.out.println("Not possible"); 34 | } 35 | 36 | private static List isSumPossible(int[] arr, int sum, int count) 37 | { 38 | boolean[][][] memo = new boolean[arr.length + 1][sum + 1][count + 1]; 39 | memo[0][0][0] = true; 40 | 41 | for (int i = 1; i <= arr.length; ++i) 42 | for (int j = 1; j <= sum; ++j) 43 | for (int k = 1; k <= count; ++k) 44 | { 45 | if (k == 1 && j == arr[i - 1]) 46 | memo[i][j][k] = true; 47 | else if (arr[i - 1] > j) 48 | memo[i][j][k] = memo[i - 1][j][k]; 49 | else 50 | memo[i][j][k] = memo[i - 1][j][k] 51 | || memo[i - 1][j - arr[i - 1]][k - 1]; 52 | } 53 | if (memo[arr.length][sum][count] == false) 54 | return null; 55 | int i = arr.length; 56 | int j = sum; 57 | int k = count; 58 | List list = new ArrayList(); 59 | while (i > 0 && j > 0 && k > 0) 60 | { 61 | if (memo[i][j][k] == memo[i - 1][j][k]) 62 | { 63 | 64 | } else if (k == 1 && j == arr[i - 1]) 65 | { 66 | list.add(arr[i - 1]); 67 | break; 68 | } else if (arr[i - 1] <= j 69 | && memo[i][j][k] == memo[i - 1][j - arr[i - 1]][k - 1]) 70 | { 71 | j = j - arr[i - 1]; 72 | k = k - 1; 73 | list.add(arr[i - 1]); 74 | } 75 | i--; 76 | } 77 | return list; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/com/dsalgo/KthLargestOnline.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/find-kth-smallest-element-in-binary.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class KthLargestOnline 9 | { 10 | public static void main(String[] args) 11 | { 12 | BST bst = new BST(); 13 | int[] arr = 14 | { 12, 4, 5, 6, 2, 7, 8, 11, 2, 3 }; 15 | for (int num : arr) 16 | bst.add(num); 17 | System.out.println(bst.getOrdered(4)); 18 | arr = new int[] 19 | { 12, 1, 9, 14, 25 }; 20 | for (int num : arr) 21 | bst.add(num); 22 | System.out.println(bst.getOrdered(6)); 23 | 24 | } 25 | 26 | private static class BST 27 | { 28 | Node root; 29 | 30 | public void add(int num) 31 | { 32 | if (root == null) 33 | { 34 | root = new Node(num); 35 | } else 36 | add(root, num); 37 | } 38 | 39 | private void add(Node root, int num) 40 | { 41 | Node node = new Node(num); 42 | if (node.value < root.value) 43 | { 44 | root.leftWeight++; 45 | if (root.left == null) 46 | root.left = node; 47 | else 48 | add(root.left, num); 49 | } else 50 | { 51 | if (root.right == null) 52 | root.right = node; 53 | else 54 | add(root.right, num); 55 | } 56 | } 57 | 58 | public int getOrdered(int k) 59 | { 60 | return getOrdered(root, k); 61 | } 62 | 63 | private Integer getOrdered(Node root, int k) 64 | { 65 | if (root == null) 66 | return null; 67 | if (root.leftWeight > k) 68 | { 69 | return getOrdered(root.left, k); 70 | } else if (root.leftWeight < k) 71 | { 72 | return getOrdered(root.right, k - root.leftWeight); 73 | } else 74 | { 75 | return root.value; 76 | } 77 | } 78 | } 79 | 80 | private static class Node 81 | { 82 | int value; 83 | int leftWeight; 84 | Node left; 85 | Node right; 86 | 87 | public Node(int value) 88 | { 89 | this.value = value; 90 | this.leftWeight = 1; 91 | } 92 | } 93 | 94 | } 95 | 96 | -------------------------------------------------------------------------------- /src/com/dsalgo/KthLargestSortedMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-kth-largest-element-in-sorted.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class KthLargestSortedMatrix 10 | { 11 | public static void main(String[] args) 12 | { 13 | int[][] matrix = 14 | { 15 | { 5, 7, 8, 9 }, 16 | { 6, 9, 10, 13 }, 17 | { 7, 11, 12, 15 }, 18 | { 8, 13, 16, 17 } }; 19 | int result = findKthLargest(matrix, 8); 20 | System.out.println(result); 21 | } 22 | 23 | private static int findKthLargest(int[][] matrix, int k) 24 | { 25 | for (int i = 0; i < k - 1; ++i) 26 | reArrange(matrix, matrix.length - 1, matrix[0].length - 1); 27 | return matrix[matrix.length - 1][matrix[0].length - 1]; 28 | } 29 | 30 | private static void reArrange(int[][] matrix, int row, int col) 31 | { 32 | int newRow = 0; 33 | int newCol = 0; 34 | if (row == 0 && col == 0) 35 | { 36 | matrix[row][col] = Integer.MIN_VALUE; 37 | return; 38 | } else if (row == 0) 39 | { 40 | newRow = row; 41 | newCol = col - 1; 42 | } else if (col == 0) 43 | { 44 | newRow = row - 1; 45 | newCol = col; 46 | } else if (matrix[row][col - 1] > matrix[row - 1][col]) 47 | { 48 | newRow = row; 49 | newCol = col - 1; 50 | } else 51 | { 52 | newRow = row - 1; 53 | newCol = col; 54 | } 55 | matrix[row][col] = matrix[newRow][newCol]; 56 | reArrange(matrix, newRow, newCol); 57 | } 58 | 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/com/dsalgo/LargestPalindromeIterative.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-largest-palindrome-iterative.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class LargestPalindromeIterative 10 | { 11 | public static void main(String[] args) 12 | { 13 | String str = "abccbabacbcacba"; 14 | String result = findLargestPalindrome(str); 15 | System.out.println(result); 16 | } 17 | 18 | private static String findLargestPalindrome(String str) 19 | { 20 | if (str == null || str.length() == 0) 21 | return ""; 22 | int centers = 2 * str.length() - 1; 23 | int radii = str.length() - 1; 24 | int maxCenter = 0; 25 | int maxRadius = 0; 26 | for (int center = 0; center < centers; ++center) 27 | { 28 | for (int radius = 0; radius <= radii; ++radius) 29 | { 30 | if (center - radius < 0 || center + radius >= centers) 31 | { 32 | break; 33 | } else if ((center + radius) % 2 == 1) 34 | { 35 | continue; 36 | } else if (str.charAt((center - radius) / 2) != str 37 | .charAt((center + radius) / 2)) 38 | { 39 | break; 40 | } else 41 | { 42 | if (radius > maxRadius) 43 | { 44 | maxRadius = radius; 45 | maxCenter = center; 46 | } 47 | } 48 | 49 | } 50 | } 51 | 52 | return str.substring((maxCenter - maxRadius) / 2, 53 | (maxCenter + maxRadius) / 2 + 1); 54 | 55 | } 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /src/com/dsalgo/LargestPalindromeRecursive.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/longest-palindrome-dynamic.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class LargestPalindromeRecursive 10 | { 11 | public static void main(String[] args) 12 | { 13 | String str = "acbcaccccaccc"; 14 | String result = findLargestPalindrome(str); 15 | System.out.println(result); 16 | } 17 | 18 | private static String findLargestPalindrome(String str) 19 | { 20 | if(str==null ||str.length()==0) 21 | return ""; 22 | boolean[][] memo = new boolean[str.length()][str.length()]; 23 | int maxStart = 0; 24 | int maxLength = 1; 25 | for (int startIndex = 0; startIndex < str.length(); ++startIndex) 26 | { 27 | memo[startIndex][startIndex] = true; 28 | } 29 | for (int startIndex = 0; startIndex < str.length() - 1; ++startIndex) 30 | { 31 | if (str.charAt(startIndex) == str.charAt(startIndex + 1)) 32 | { 33 | memo[startIndex][startIndex + 1] = true; 34 | maxStart = startIndex; 35 | maxLength = 2; 36 | } 37 | } 38 | for (int length = 3; length <= str.length(); ++length) 39 | { 40 | for (int startIndex = 0; startIndex < str.length() - length + 1; ++startIndex) 41 | { 42 | int endIndex = startIndex + length - 1; 43 | if (str.charAt(startIndex) == str.charAt(endIndex) 44 | && memo[startIndex + 1][endIndex - 1] == true) 45 | { 46 | memo[startIndex][endIndex] = true; 47 | maxStart = startIndex; 48 | maxLength = length; 49 | } 50 | 51 | } 52 | } 53 | return str.substring(maxStart, maxStart + maxLength); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /src/com/dsalgo/LargestSumSubArray.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | For problem and solution description please visit the link below 4 | http://www.dsalgo.com/2013/02/largest-sum-subarray.html 5 | */ 6 | 7 | package com.dsalgo; 8 | 9 | public class LargestSumSubArray 10 | { 11 | public static void main(String[] args) 12 | { 13 | int[] arr = 14 | { 4, 3, -5, 0, 6, -8, 12, 3, -9, 2, 5, 8, -3, 4, 8, 0, 3, -3, -5, -9, 15 | 4, 2 }; 16 | maxSumSubArray(arr); 17 | } 18 | 19 | private static void maxSumSubArray(int[] arr) 20 | { 21 | int currentStart = 0; 22 | int currentEnd = 0; 23 | int currentSum = 0; 24 | int maxStart = 0; 25 | int maxEnd = 0; 26 | int maxSum = 0; 27 | while (currentEnd != arr.length) 28 | { 29 | currentSum += arr[currentEnd]; 30 | if (currentSum > maxSum) 31 | { 32 | maxSum = currentSum; 33 | maxStart = currentStart; 34 | maxEnd = currentEnd; 35 | } 36 | if (currentSum <= 0) 37 | { 38 | currentStart = currentEnd + 1; 39 | currentSum=0; 40 | } 41 | currentEnd++; 42 | } 43 | System.out.println("Maximum sum = " + maxSum); 44 | System.out.println("Indexes (" + maxStart + "," + maxEnd + ")"); 45 | } 46 | } 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/com/dsalgo/LargestSumSubMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/maximum-sum-submatrix.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class LargestSumSubMatrix 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[][] arr = 13 | { 14 | { 1, -2, -7, 0 }, 15 | { -6, 2, 9, 2 }, 16 | { -4, -2, -1, 4 }, 17 | { -1, -8, 0, -4 } }; 18 | int[] leftRightTopBottom = new int[4]; 19 | int maxsum = findMaximumSumSubMatrix(arr, leftRightTopBottom); 20 | System.out.println("max sum: " + maxsum); 21 | System.out.println("indices left right top bottom"); 22 | for (int index : leftRightTopBottom) 23 | System.out.print(index + ","); 24 | } 25 | 26 | private static int findMaximumSumSubMatrix(int[][] arr, 27 | int[] leftTopRightBottom) 28 | { 29 | leftTopRightBottom[0] = 0; 30 | leftTopRightBottom[1] = 0; 31 | leftTopRightBottom[2] = 0; 32 | leftTopRightBottom[3] = 0; 33 | int rows = arr.length; 34 | int cols = arr[0].length; 35 | int[] sum = new int[cols]; 36 | int[] pos = new int[cols]; 37 | int localMax; 38 | int maxSum = arr[0][0]; 39 | int[][] verticalSum = new int[rows][cols]; 40 | 41 | for (int iRow = 0; iRow < rows; iRow++) 42 | { 43 | for (int jCol = 0; jCol < cols; jCol++) 44 | { 45 | if (jCol == 0) 46 | { 47 | verticalSum[jCol][iRow] = arr[jCol][iRow]; 48 | } else 49 | { 50 | verticalSum[jCol][iRow] = arr[jCol][iRow] 51 | + verticalSum[jCol - 1][iRow]; 52 | } 53 | } 54 | } 55 | 56 | for (int iRow = 0; iRow < rows; iRow++) 57 | { 58 | for (int k = iRow; k < rows; k++) 59 | { 60 | for (int index = 0; index < cols; index++) 61 | { 62 | sum[index] = 0; 63 | pos[index] = 0; 64 | } 65 | localMax = 0; 66 | int tmp = 0; 67 | if (iRow > 0) 68 | { 69 | tmp = verticalSum[iRow - 1][0]; 70 | } 71 | sum[0] = verticalSum[k][0] - tmp; 72 | for (int j = 1; j < cols; j++) 73 | { 74 | tmp = 0; 75 | if (iRow > 0) 76 | { 77 | tmp = verticalSum[iRow - 1][j]; 78 | } 79 | if (sum[j - 1] > 0) 80 | { 81 | sum[j] = sum[j - 1] + verticalSum[k][j] - tmp; 82 | pos[j] = pos[j - 1]; 83 | } else 84 | { 85 | sum[j] = verticalSum[k][j] - tmp; 86 | pos[j] = j; 87 | } 88 | if (sum[j] > sum[localMax]) 89 | { 90 | localMax = j; 91 | } 92 | } 93 | if (sum[localMax] > maxSum) 94 | { 95 | maxSum = sum[localMax]; 96 | leftTopRightBottom[0] = pos[localMax]; 97 | leftTopRightBottom[1] = localMax; 98 | leftTopRightBottom[2] = iRow; 99 | leftTopRightBottom[3] = k; 100 | } 101 | } 102 | } 103 | return maxSum; 104 | } 105 | } 106 | 107 | -------------------------------------------------------------------------------- /src/com/dsalgo/LeastCommonAncestorWithoutRoot.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/LeastCommonAncestorWithoutRoot.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | import java.util.HashSet; 10 | 11 | 12 | public class LeastCommonAncestorWithoutRoot 13 | { 14 | public static void main(String[] args) 15 | { 16 | NodeWithParent a=new NodeWithParent(5); 17 | NodeWithParent b=new NodeWithParent(6); 18 | NodeWithParent c=new NodeWithParent(7); 19 | NodeWithParent d=new NodeWithParent(8); 20 | NodeWithParent e=new NodeWithParent(9); 21 | a.left=b; 22 | b.parent=a; 23 | b.left=c; 24 | c.parent=b; 25 | b.right=d; 26 | d.parent=b; 27 | d.right=e; 28 | e.parent=d; 29 | System.out.println("LCA: "+getLCA(c, e).value); 30 | 31 | } 32 | 33 | public static NodeWithParent getLCA(NodeWithParent a, NodeWithParent b) 34 | { 35 | HashSet table=new HashSet(); 36 | while(a!=null) 37 | { 38 | table.add(a); 39 | a=a.parent; 40 | } 41 | while(b!=null) 42 | { 43 | if(table.contains(b)) 44 | return b; 45 | b=b.parent; 46 | } 47 | return null; 48 | } 49 | 50 | } 51 | 52 | class NodeWithParent 53 | { 54 | public NodeWithParent parent; 55 | public int value; 56 | public NodeWithParent left; 57 | public NodeWithParent right; 58 | 59 | public NodeWithParent(int value) 60 | { 61 | this.value=value; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/com/dsalgo/LeastDifference.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/LeastDifference.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.Arrays; 9 | 10 | 11 | public class LeastDifference 12 | { 13 | public static void main(String[] args) 14 | { 15 | int[]arr={64,57,2,78,43,73,53,86}; 16 | Arrays.sort(arr); 17 | int minDiff=Integer.MAX_VALUE; 18 | for(int i=0;i < arr.length-1;++i) 19 | { 20 | int diff=Math.abs(arr[i]-arr[i+1]); 21 | if(diff < minDiff) 22 | minDiff=diff; 23 | } 24 | System.out.println(minDiff); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/com/dsalgo/LevelOrderWithoutQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/level-order-traversal-without-queue.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | 11 | public class LevelOrderWithoutQueue 12 | { 13 | 14 | /** 15 | * @param args 16 | */ 17 | public static void main(String[] args) 18 | { 19 | Node a = new Node(1); 20 | Node b = new Node(2); 21 | Node c = new Node(3); 22 | Node d = new Node(4); 23 | Node e = new Node(5); 24 | Node f = new Node(8); 25 | Node g = new Node(6); 26 | Node h = new Node(7); 27 | a.left = b; 28 | a.right = c; 29 | b.left = d; 30 | b.right = e; 31 | c.right = f; 32 | f.left = g; 33 | f.right = h; 34 | printLevelOrder(a); 35 | } 36 | 37 | private static void printLevelOrder(Node a) 38 | { 39 | HashMap < Integer, List < Integer > > levelMap = new HashMap < Integer, List < Integer > >(); 40 | printLevelOrder(a, 1, levelMap); 41 | int level = 1; 42 | while (true) 43 | { 44 | List < Integer > list = levelMap.get(level); 45 | if (list == null) 46 | break; 47 | System.out.println(list); 48 | level++; 49 | } 50 | } 51 | 52 | private static void printLevelOrder(Node a, int level, 53 | HashMap < Integer, List < Integer > > levelMap) 54 | { 55 | if (a == null) 56 | return; 57 | List < Integer > list = levelMap.get(level); 58 | if (list == null) 59 | { 60 | list = new ArrayList < Integer > (); 61 | list.add(a.value); 62 | levelMap.put(level, list); 63 | } else 64 | { 65 | list.add(a.value); 66 | } 67 | printLevelOrder(a.left, level + 1, levelMap); 68 | printLevelOrder(a.right, level + 1, levelMap); 69 | } 70 | 71 | static class Node 72 | { 73 | Node left; 74 | Node right; 75 | int value; 76 | 77 | public Node(int value) 78 | { 79 | this.value = value; 80 | } 81 | } 82 | 83 | } 84 | 85 | -------------------------------------------------------------------------------- /src/com/dsalgo/LinkedListKthElementFromEnd.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-kth-node-from-end-in-linked-list.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class LinkedListKthElementFromEnd 10 | { 11 | public static void main(String[] args) 12 | { 13 | Node head = new Node(1); 14 | head.append(2).append(3).append(4).append(5).append(6).append(7) 15 | .append(8).append(9); 16 | Node result = findKFromEnd(head, 3); 17 | System.out.println(result.value); 18 | } 19 | 20 | private static Node findKFromEnd(Node head, int k) 21 | { 22 | Node ahead = head; 23 | while (k-- > 0) 24 | ahead = ahead.next; 25 | while (ahead != null) 26 | { 27 | head = head.next; 28 | ahead = ahead.next; 29 | } 30 | return head; 31 | } 32 | 33 | private static class Node 34 | { 35 | public Node next; 36 | public int value; 37 | 38 | public Node(int value) 39 | { 40 | this.value = value; 41 | } 42 | 43 | public Node append(int value) 44 | { 45 | Node node = new Node(value); 46 | next = node; 47 | return node; 48 | } 49 | } 50 | 51 | } 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/com/dsalgo/LinkedListRandomPointer.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/LinkedListRandomPointer.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | 12 | public class LinkedListRandomPointer 13 | { 14 | 15 | public static void main(String[] args) 16 | { 17 | NodeRandom a=new NodeRandom(4); 18 | NodeRandom b=new NodeRandom(5); 19 | NodeRandom c=new NodeRandom(3); 20 | NodeRandom d=new NodeRandom(6); 21 | NodeRandom e=new NodeRandom(7); 22 | NodeRandom f=new NodeRandom(2); 23 | NodeRandom g=new NodeRandom(9); 24 | NodeRandom h=new NodeRandom(3); 25 | NodeRandom i=new NodeRandom(7); 26 | a.next=b; 27 | b.next=c; 28 | c.next=d; 29 | d.next=e; 30 | e.next=f; 31 | f.next=g; 32 | g.next=h; 33 | h.next=i; 34 | a.random=g; 35 | b.random=a; 36 | c.random=e; 37 | d.random=f; 38 | e.random=e; 39 | f.random=null; 40 | g.random=b; 41 | h.random=i; 42 | i.random=f; 43 | printLinkedList(a); 44 | printLinkedList(deepCopy(a)); 45 | 46 | } 47 | private static void printLinkedList(NodeRandom head) 48 | { 49 | while(head!=null) 50 | { 51 | System.out.print(head); 52 | head=head.next; 53 | } 54 | System.out.println(); 55 | } 56 | public static NodeRandom deepCopy(NodeRandom sourceHead) 57 | { 58 | Map map=new HashMap(); 59 | NodeRandom sourcePtr=sourceHead; 60 | NodeRandom destHead=null; 61 | NodeRandom destPtr=null; 62 | while(sourcePtr!=null) 63 | { 64 | if(destHead==null) 65 | { 66 | destHead=new NodeRandom(sourcePtr.value); 67 | destPtr=destHead; 68 | } 69 | else 70 | { 71 | destPtr.next=new NodeRandom(sourcePtr.value); 72 | destPtr=destPtr.next; 73 | } 74 | map.put(sourcePtr, destPtr); 75 | sourcePtr=sourcePtr.next; 76 | } 77 | sourcePtr=sourceHead; 78 | destPtr=destHead; 79 | while(sourcePtr!=null) 80 | { 81 | destPtr.random=map.get(sourcePtr.random); 82 | sourcePtr=sourcePtr.next; 83 | destPtr=destPtr.next; 84 | } 85 | return destHead; 86 | } 87 | 88 | static class NodeRandom 89 | { 90 | public NodeRandom next; 91 | public NodeRandom random; 92 | public int value; 93 | public NodeRandom(int value) 94 | { 95 | this.value=value; 96 | } 97 | public String toString() 98 | { 99 | if(random==null) 100 | return "{"+hashCode()+"("+value+") r->null}"; 101 | else 102 | return "{"+hashCode()+"("+value+") r->"+random.hashCode()+"}"; 103 | } 104 | } 105 | } 106 | 107 | -------------------------------------------------------------------------------- /src/com/dsalgo/LinkedListRemoveDuplicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/linked-list-remove-duplicates.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.HashSet; 8 | 9 | public class LinkedListRemoveDuplicate 10 | { 11 | public static void main(String[] args) 12 | { 13 | Chain input = new Chain(); 14 | input.add(3).add(5).add(4).add(2).add(3).add(2).add(6).add(3).add(4); 15 | Chain output = removeDuplicate(input); 16 | for (Node node = output.head; node != null; node = node.next) 17 | System.out.print(node.value + "->"); 18 | System.out.println(); 19 | } 20 | 21 | private static Chain removeDuplicate(Chain input) 22 | { 23 | Chain output = new Chain(); 24 | HashSet hashSet = new HashSet(); 25 | for (Node node = input.head; node != null; node = node.next) 26 | { 27 | if (!hashSet.contains(node.value)) 28 | { 29 | hashSet.add(node.value); 30 | output.add(node.value); 31 | } 32 | } 33 | return output; 34 | } 35 | 36 | public static class Node 37 | { 38 | int value; 39 | Node next; 40 | 41 | public Node(int value) 42 | { 43 | this.value = value; 44 | } 45 | } 46 | 47 | private static class Chain 48 | { 49 | Node head; 50 | Node last; 51 | 52 | public Chain add(int value) 53 | { 54 | Node node = new Node(value); 55 | if (head == null) 56 | { 57 | head = node; 58 | last = node; 59 | } else 60 | { 61 | last.next = node; 62 | last = node; 63 | } 64 | return this; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/com/dsalgo/LinkedListWithLoop.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-loop-in-linked-list.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class LinkedListWithLoop 10 | { 11 | public static void main(String[] args) 12 | { 13 | Node head = new Node(1); 14 | Node middle = head.append(2).append(3).append(4).append(5); 15 | Node tail = middle.append(6).append(7).append(8).append(9).append(10) 16 | .append(11); 17 | tail.next = middle; 18 | findLoopInformation(head); 19 | } 20 | 21 | private static void findLoopInformation(Node head) 22 | { 23 | Node slowPointer = head; 24 | Node fastPointer = head; 25 | boolean isLooped = false; 26 | while (fastPointer != null && fastPointer.next != null) 27 | { 28 | slowPointer = slowPointer.next; 29 | fastPointer = fastPointer.next.next; 30 | if (slowPointer == fastPointer) 31 | { 32 | isLooped = true; 33 | break; 34 | } 35 | } 36 | if (isLooped) 37 | { 38 | System.out.println("Linkedlist is looped"); 39 | fastPointer = fastPointer.next; 40 | int count = 1; 41 | while (slowPointer != fastPointer) 42 | { 43 | fastPointer = fastPointer.next; 44 | count++; 45 | } 46 | System.out.println("Loop length = " + count); 47 | slowPointer = head; 48 | fastPointer = head; 49 | while (count-- > 0) 50 | { 51 | fastPointer = fastPointer.next; 52 | } 53 | while (slowPointer != fastPointer) 54 | { 55 | slowPointer = slowPointer.next; 56 | fastPointer = fastPointer.next; 57 | } 58 | System.out.println("Loop starting point = " + slowPointer.value); 59 | } else 60 | { 61 | System.out.println("Linkedlist is NOT looped"); 62 | } 63 | } 64 | 65 | private static class Node 66 | { 67 | public Node next; 68 | public int value; 69 | 70 | public Node(int value) 71 | { 72 | this.value = value; 73 | } 74 | 75 | public Node append(int value) 76 | { 77 | Node node = new Node(value); 78 | next = node; 79 | return node; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/com/dsalgo/LinkedListYShape.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/linked-list-y-shape.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class LinkedListYShape 10 | { 11 | 12 | public static void main(String[] args) 13 | { 14 | Node head1 = new Node(1); 15 | Node middle1 = head1.append(2).append(3).append(4); 16 | middle1.append(6).append(7).append(8).append(9); 17 | Node head2 = new Node(10); 18 | Node middle2 = head2.append(3).append(5).append(6).append(11) 19 | .append(24); 20 | middle2.next = middle1; 21 | findIntersection(head1, head2); 22 | 23 | } 24 | 25 | private static void findIntersection(Node head1, Node head2) 26 | { 27 | int count1 = 0; 28 | int count2 = 0; 29 | Node ptr1 = head1; 30 | Node ptr2 = head2; 31 | 32 | while (true) 33 | { 34 | if (ptr1.next == null) 35 | break; 36 | ptr1 = ptr1.next; 37 | count1++; 38 | } 39 | while (true) 40 | { 41 | if (ptr2.next == null) 42 | break; 43 | ptr2 = ptr2.next; 44 | count2++; 45 | } 46 | boolean isMerged = ptr1 == ptr2; 47 | if (isMerged) 48 | { 49 | System.out.println("The linked lists are merged"); 50 | Node longer = head1; 51 | Node shorter = head2; 52 | if (count1 < count2) 53 | { 54 | longer = head2; 55 | shorter = head1; 56 | } 57 | int diff = Math.abs(count1 - count2); 58 | while (diff-- > 0) 59 | { 60 | longer = longer.next; 61 | } 62 | while (longer != shorter) 63 | { 64 | longer = longer.next; 65 | shorter = shorter.next; 66 | } 67 | System.out.println("Common Node = " + longer.value); 68 | } else 69 | { 70 | System.out.println("The linked lists are NOT merged"); 71 | } 72 | } 73 | 74 | private static class Node 75 | { 76 | public Node next; 77 | public int value; 78 | 79 | public Node(int value) 80 | { 81 | this.value = value; 82 | } 83 | 84 | public Node append(int value) 85 | { 86 | Node node = new Node(value); 87 | next = node; 88 | return node; 89 | } 90 | } 91 | 92 | } 93 | 94 | 95 | -------------------------------------------------------------------------------- /src/com/dsalgo/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/longest-common-subsequence.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class LongestCommonSubsequence 9 | { 10 | public static void main(String[] args) 11 | { 12 | String a = "alfkjalfjlkj"; 13 | String b = "ajflaklfjlaj"; 14 | String result = findLCS(a, b); 15 | System.out.println(result); 16 | } 17 | 18 | private static String findLCS(String a, String b) 19 | { 20 | int[][] memo = new int[a.length() + 1][b.length() + 1]; 21 | 22 | for (int i = a.length() - 1; i >= 0; --i) 23 | for (int j = b.length() - 1; j >= 0; --j) 24 | { 25 | if (a.charAt(i) == b.charAt(j)) 26 | memo[i][j] = memo[i + 1][j + 1] + 1; 27 | else 28 | memo[i][j] = Math.max(memo[i + 1][j], memo[i][j + 1]); 29 | } 30 | 31 | int i = 0; 32 | int j = 0; 33 | 34 | StringBuffer result = new StringBuffer(); 35 | while (i memo[i][j+1]) 43 | i++; 44 | else 45 | j++; 46 | } 47 | return result.toString(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/com/dsalgo/LongestPathInMaze.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-longest-path-in-maze.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class LongestPathInMaze 11 | { 12 | public static void main(String[] args) 13 | { 14 | boolean[][] maze = new boolean[10][10]; 15 | makeRandomMaze(maze); 16 | printMaze(maze); 17 | List path = findLongestPath(maze); 18 | if (path == null) 19 | { 20 | System.out.println("No path possible"); 21 | return; 22 | } 23 | for (Cell cell : path) 24 | System.out.print(cell + ","); 25 | System.out.println(); 26 | } 27 | 28 | private static List findLongestPath(boolean[][] maze) 29 | { 30 | Cell start = new Cell(0, 0); 31 | Cell end = new Cell(maze.length - 1, maze[0].length - 1); 32 | List path = findLongestPath(maze, start, end); 33 | return path; 34 | } 35 | 36 | private static List findLongestPath(boolean[][] maze, Cell start, 37 | Cell end) 38 | { 39 | List result = null; 40 | int rows = maze.length; 41 | int cols = maze[0].length; 42 | if (start.row < 0 || start.col < 0) 43 | return null; 44 | if (start.row == rows || start.col == cols) 45 | return null; 46 | if (maze[start.row][start.col] == true) 47 | return null; 48 | if (start.equals(end)) 49 | { 50 | List path = new ArrayList(); 51 | path.add(start); 52 | return path; 53 | } 54 | maze[start.row][start.col] = true; 55 | Cell[] nextCells = new Cell[4]; 56 | nextCells[0] = new Cell(start.row + 1, start.col); 57 | nextCells[2] = new Cell(start.row, start.col + 1); 58 | nextCells[1] = new Cell(start.row - 1, start.col); 59 | nextCells[3] = new Cell(start.row, start.col - 1); 60 | int maxLength = -1; 61 | for (Cell nextCell : nextCells) 62 | { 63 | List path = findLongestPath(maze, nextCell, end); 64 | if (path != null && path.size() > maxLength) 65 | { 66 | maxLength = path.size(); 67 | path.add(0, start); 68 | result = path; 69 | } 70 | } 71 | maze[start.row][start.col] = false; 72 | if (result == null || result.size() == 0) 73 | return null; 74 | return result; 75 | } 76 | 77 | private static class Cell 78 | { 79 | public int row; 80 | public int col; 81 | 82 | public Cell(int row, int column) 83 | { 84 | this.row = row; 85 | this.col = column; 86 | } 87 | 88 | @Override 89 | public boolean equals(Object obj) 90 | { 91 | if (this == obj) 92 | return true; 93 | if ((obj == null) || (obj.getClass() != this.getClass())) 94 | return false; 95 | Cell cell = (Cell) obj; 96 | if (row == cell.row && col == cell.col) 97 | return true; 98 | return false; 99 | } 100 | 101 | @Override 102 | public String toString() 103 | { 104 | return "(" + row + "," + col + ")"; 105 | } 106 | } 107 | 108 | private static void printMaze(boolean[][] maze) 109 | { 110 | for (int i = 0; i < maze.length; ++i) 111 | { 112 | for (int j = 0; j < maze[i].length; ++j) 113 | { 114 | if (maze[i][j]) 115 | System.out.print("#|"); 116 | else 117 | System.out.print("_|"); 118 | } 119 | System.out.println(); 120 | } 121 | } 122 | 123 | private static void makeRandomMaze(boolean[][] maze) 124 | { 125 | for (int i = 0; i < maze.length; ++i) 126 | { 127 | for (int j = 0; j < maze[0].length; ++j) 128 | { 129 | maze[i][j] = (int) (Math.random() * 3) == 1; 130 | } 131 | } 132 | maze[0][0] = false; 133 | maze[maze.length - 1][maze[0].length - 1] = false; 134 | 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/com/dsalgo/LowestCommonAncestor.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/LowestCommonAncestor.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class LowestCommonAncestor { 9 | 10 | /** 11 | * @param args 12 | */ 13 | public static void main(String[] args) { 14 | 15 | Node a = new Node(1); 16 | Node b = new Node(2); 17 | Node c = new Node(3); 18 | Node d = new Node(4); 19 | Node e = new Node(5); 20 | Node f = new Node(8); 21 | Node g = new Node(6); 22 | Node h = new Node(7); 23 | a.left = b; 24 | a.right = c; 25 | b.left = d; 26 | c.left = e; 27 | c.right = f; 28 | f.left = g; 29 | f.right = h; 30 | LCA(a, c, h); 31 | System.out.println(LCANode.value); 32 | 33 | } 34 | 35 | static Node LCANode = null; 36 | 37 | public static int LCA(Node currentNode, Node n1, Node n2) { 38 | if (currentNode == null) 39 | return 0; 40 | int currentValue = 0; 41 | if (currentNode == n1 || currentNode == n2) 42 | currentValue = 1; 43 | int leftValue = LCA(currentNode.left, n1, n2); 44 | int rightValue = LCA(currentNode.right, n1, n2); 45 | if ((currentValue == 1 && leftValue == 1) 46 | || (currentValue == 1 && rightValue == 1) 47 | || (leftValue == 1 && rightValue == 1)) { 48 | LCANode = currentNode; 49 | return 2; 50 | } 51 | 52 | return currentValue + leftValue + rightValue; 53 | 54 | } 55 | 56 | static class Node { 57 | public Node left; 58 | public Node right; 59 | public int value; 60 | 61 | public Node(int value) { 62 | this.value = value; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxAlternatingSequence.java: -------------------------------------------------------------------------------- 1 | package com.dsalgo; 2 | 3 | public class MaxAlternatingSequence { 4 | 5 | public static void main(String[] args) { 6 | int[] arr={5,3,4,6,7,1,2,8,7,5,7,4,6,3,4,2,8,9,8,9,6,8,5,7}; 7 | 8 | 9 | } 10 | public static int[]getLongestAlternatingSubsequence(int[]arr){ 11 | int startIndex = 0; 12 | int endIndex = 0; 13 | int maxStartIndex = 0; 14 | int maxEndIndex = 0; 15 | int maxLength = 0; 16 | for(int i=0;imaxLength) 30 | maxLength=currentLength; 31 | } 32 | else 33 | { 34 | currentLength=2; 35 | prevDiff=arr[i]-arr[i-1]; 36 | } 37 | } 38 | System.out.println("max arithmetic sequence length = "+maxLength); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxHeapAndBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/max-heap-and-bst-in-same-structure.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | 13 | public class MaxHeapAndBinarySearchTree 14 | { 15 | public static void main(String[] args) 16 | { 17 | List list = new ArrayList(); 18 | for (int i = 0; i < 10; ++i) 19 | { 20 | list.add(new Node((int) (30 * Math.random()), 21 | (int) (30 * Math.random()))); 22 | } 23 | Node root=createHeapAndBST(list); 24 | printNice(root); 25 | } 26 | 27 | private static Node createHeapAndBST(List list) 28 | { 29 | if(list.size()==0) 30 | return null; 31 | Node top=list.get(0); 32 | for(Node node:list) 33 | { 34 | if(node.heapValue>top.heapValue) 35 | top=node; 36 | } 37 | list.remove(top); 38 | List leftList=new ArrayList(); 39 | List rightList=new ArrayList(); 40 | for(Node node:list) 41 | { 42 | if(node.treeValue<=top.treeValue) 43 | leftList.add(node); 44 | else 45 | rightList.add(node); 46 | } 47 | top.left=createHeapAndBST(leftList); 48 | top.right=createHeapAndBST(rightList); 49 | return top; 50 | } 51 | 52 | static class Node 53 | { 54 | public Node left; 55 | public Node right; 56 | public int heapValue; 57 | public int treeValue; 58 | 59 | public Node(int heapValue, int treeValue) 60 | { 61 | this.heapValue = heapValue; 62 | this.treeValue = treeValue; 63 | } 64 | } 65 | 66 | public static void printNice(Node root) 67 | { 68 | if (root == null) 69 | return; 70 | else 71 | { 72 | System.out.print("(" + root.heapValue + "," + root.treeValue + ")"); 73 | if (root.left != null) 74 | { 75 | System.out.print("L->["); 76 | printNice(root.left); 77 | System.out.print("]"); 78 | } 79 | if (root.right != null) 80 | { 81 | System.out.print("R->["); 82 | printNice(root.right); 83 | System.out.print("]"); 84 | } 85 | } 86 | } 87 | } 88 | 89 | 90 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxKUsingMinHeap.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/MaxKUsingMinHeap.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.PriorityQueue; 9 | 10 | public class MaxKUsingMinHeap 11 | { 12 | public static void main(String[] args) 13 | { 14 | int[] arr = 15 | { 3, 46, 2, 56, 3, 38, 93, 45, 6, 787, 34, 76, 44, 6, 7, 86, 8, 44, 56 }; 16 | int[] result = getTopElements(arr, 5); 17 | for (int i : result) 18 | { 19 | System.out.print(i + ","); 20 | } 21 | } 22 | 23 | public static int[] getTopElements(int[] arr, int k) 24 | { 25 | PriorityQueue minHeap = new PriorityQueue(); 26 | for (int i = 0; i < arr.length; ++i) 27 | { 28 | int currentNum = arr[i]; 29 | if (minHeap.size() < k) 30 | minHeap.add(currentNum); 31 | else if (currentNum > minHeap.peek()) 32 | { 33 | minHeap.poll(); 34 | minHeap.add(currentNum); 35 | } 36 | } 37 | int[] result = new int[minHeap.size()]; 38 | int index = 0; 39 | while (!minHeap.isEmpty()) 40 | { 41 | result[index++] = minHeap.poll(); 42 | } 43 | return result; 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxProductSubArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/maximum-product-subarray.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class MaxProductSubArray 10 | { 11 | public static void main(String[] args) 12 | { 13 | int[] arr = 14 | { 1, 2, -1, 4, 0, 5, -6, -5, -6, 2, 0, 3, -4, 3, -2, 4, -3 }; 15 | int[] returnIndices = new int[2]; 16 | long maxProduct = findMaxProduct(arr, returnIndices); 17 | System.out.println("Maximum product " + maxProduct); 18 | System.out.println("Indices " + returnIndices[0] + " - " 19 | + returnIndices[1]); 20 | } 21 | 22 | private static long findMaxProduct(int[] arr, int[] returnIndices) 23 | { 24 | int startIndex = 0; 25 | long maxProduct = 0; 26 | int[] indices = new int[2]; 27 | for (int index = 0; index < arr.length; ++index) 28 | { 29 | if (arr[index] == 0 && index >= startIndex) 30 | { 31 | long product = findMaxProductWithoutZero(arr, startIndex, 32 | index - 1, indices); 33 | if (product > maxProduct) 34 | { 35 | maxProduct = product; 36 | returnIndices[0] = indices[0]; 37 | returnIndices[1] = indices[1]; 38 | } 39 | startIndex = index + 1; 40 | } else if (index == arr.length - 1) 41 | { 42 | long product = findMaxProductWithoutZero(arr, startIndex, index, 43 | indices); 44 | if (product > maxProduct) 45 | { 46 | maxProduct = product; 47 | returnIndices[0] = indices[0]; 48 | returnIndices[1] = indices[1]; 49 | } 50 | } 51 | } 52 | return maxProduct; 53 | } 54 | 55 | private static long findMaxProductWithoutZero(int[] arr, int startIndex, 56 | int endIndex, int[] returnIndices) 57 | { 58 | if (startIndex > endIndex || startIndex < 0 || endIndex >= arr.length) 59 | return 0; 60 | int negativeCount = 0; 61 | int firstNegativeIndex = -1; 62 | int lastNegativeIndex = -1; 63 | for (int index = startIndex; index <= endIndex; ++index) 64 | { 65 | if (arr[index] < 0) 66 | { 67 | negativeCount++; 68 | if (firstNegativeIndex == -1) 69 | firstNegativeIndex = index; 70 | lastNegativeIndex = index; 71 | } 72 | } 73 | if (negativeCount % 2 == 0) 74 | return findMaxProductWithoutNegative(arr, startIndex, endIndex, 75 | returnIndices); 76 | else 77 | { 78 | int[] indices = new int[2]; 79 | long maxProduct = findMaxProductWithoutNegative(arr, 80 | firstNegativeIndex + 1, endIndex, indices); 81 | returnIndices[0] = indices[0]; 82 | returnIndices[1] = indices[1]; 83 | long maxProduct2 = findMaxProductWithoutNegative(arr, startIndex, 84 | lastNegativeIndex - 1, indices); 85 | if (maxProduct2 > maxProduct) 86 | { 87 | maxProduct = maxProduct2; 88 | returnIndices[0] = indices[0]; 89 | returnIndices[1] = indices[1]; 90 | } 91 | return maxProduct; 92 | } 93 | } 94 | 95 | private static long findMaxProductWithoutNegative(int[] arr, 96 | int startIndex, int endIndex, int[] indices) 97 | { 98 | if (startIndex > endIndex || startIndex < 0 || endIndex >= arr.length) 99 | return 0; 100 | long product = 1; 101 | for (int index = startIndex; index <= endIndex; ++index) 102 | product *= arr[index]; 103 | indices[0] = startIndex; 104 | indices[1] = endIndex; 105 | return product; 106 | } 107 | } 108 | 109 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxSubarrayEqualOnesZeros.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/longest-subarray-with-equal-number-of.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class MaxSubarrayEqualOnesZeros 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[] arr = 13 | { 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 14 | 0, 1, 1, 0, 1, 0, 0, 0 }; 15 | printMaxSubarray(arr); 16 | } 17 | 18 | private static void printMaxSubarray(int[] arr) 19 | { 20 | Integer[] diffMap = new Integer[arr.length * 2 + 1]; 21 | diffMap[arr.length] = -1; 22 | int sum = 0; 23 | int maxLength = 0; 24 | int maxStart = -1; 25 | int maxEnd = -1; 26 | for (int i = 0; i < arr.length; ++i) 27 | { 28 | if (arr[i] == 0) 29 | sum -= 1; 30 | else 31 | sum += 1; 32 | Integer prevIndex = diffMap[arr.length + sum]; 33 | if (prevIndex == null) 34 | diffMap[arr.length + sum] = i; 35 | else 36 | { 37 | if (i - prevIndex > maxLength) 38 | { 39 | maxLength = i - prevIndex; 40 | maxStart = prevIndex + 1; 41 | maxEnd = i; 42 | } 43 | } 44 | } 45 | System.out.println("indices (" + maxStart + "," + maxEnd + ")"); 46 | System.out.println("length=" + maxLength); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxSumTreePathNegative.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/maximum-sum-along-any-tree-path-with.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class MaxSumTreePathNegative 9 | { 10 | public static void main(String[] args) 11 | { 12 | Node a = new Node(4); 13 | Node b = new Node(-2); 14 | Node c = new Node(-1); 15 | Node d = new Node(6); 16 | Node e = new Node(-5); 17 | Node f = new Node(-2); 18 | Node g = new Node(7); 19 | Node h = new Node(8); 20 | a.left = b; 21 | a.right = c; 22 | b.left = d; 23 | c.left = e; 24 | c.right = f; 25 | f.left = g; 26 | f.right = h; 27 | int maxSum = findMaxSum(a); 28 | System.out.println(maxSum); 29 | } 30 | 31 | private static int findMaxSum(Node root) 32 | { 33 | int[] localMax = new int [1]; 34 | int[] globalMax = new int [1]; 35 | findMaxSum(root, localMax, globalMax); 36 | return globalMax[0]; 37 | } 38 | 39 | private static void findMaxSum(Node root, int[] localMax, int[] globalMax) 40 | { 41 | if (root == null) 42 | { 43 | localMax[0]=0; 44 | return; 45 | } 46 | localMax[0]=0; 47 | findMaxSum(root.left, localMax, globalMax); 48 | int leftLocal=localMax[0]; 49 | localMax[0]=0; 50 | findMaxSum(root.right, localMax, globalMax); 51 | int rightLocal=localMax[0]; 52 | int maxLocal=Math.max(leftLocal,rightLocal); 53 | if(maxLocal+root.value > 0) 54 | { 55 | localMax[0]=maxLocal+root.value; 56 | if(globalMax[0] < localMax [0]) 57 | globalMax[0] = localMax [0]; 58 | } 59 | else 60 | { 61 | localMax[0]=0; 62 | } 63 | } 64 | 65 | static class Node 66 | { 67 | Node left; 68 | Node right; 69 | int value; 70 | 71 | public Node(int value) 72 | { 73 | this.value = value; 74 | } 75 | } 76 | 77 | } 78 | 79 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaxSumTreePathPositive.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/maximum-sum-along-any-path-of-binary.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class MaxSumTreePathPositive 9 | { 10 | public static void main(String[] args) 11 | { 12 | Node a = new Node(1); 13 | Node b = new Node(2); 14 | Node c = new Node(3); 15 | Node d = new Node(4); 16 | Node e = new Node(5); 17 | Node f = new Node(6); 18 | Node g = new Node(7); 19 | Node h = new Node(8); 20 | a.left = b; 21 | a.right = c; 22 | b.left = d; 23 | c.left = e; 24 | c.right = f; 25 | f.left = g; 26 | f.right = h; 27 | int maxSum = findMaxSum(a); 28 | System.out.println(maxSum); 29 | } 30 | 31 | private static int findMaxSum(Node root) 32 | { 33 | if (root == null) 34 | return 0; 35 | return root.value 36 | + Math.max(findMaxSum(root.left), findMaxSum(root.right)); 37 | } 38 | 39 | static class Node 40 | { 41 | Node left; 42 | Node right; 43 | int value; 44 | 45 | public Node(int value) 46 | { 47 | this.value = value; 48 | } 49 | } 50 | 51 | } 52 | 53 | -------------------------------------------------------------------------------- /src/com/dsalgo/MaximumSumUptoKRecursive.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/MaximumSumUptoKRecursive.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class MaximumSumUptoKRecursive 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[]arr={4,6,3,9}; 13 | System.out.println(getMaxSum(arr, 14)); 14 | } 15 | public static int getMaxSum(int[]arr,int k) 16 | { 17 | Integer[][]memo=new Integer[arr.length+1][k+1]; 18 | return getMaxSum(memo,arr,0,k); 19 | } 20 | private static int getMaxSum(Integer[][]memo,int[]arr,int i,int k) 21 | { 22 | if(i==arr.length) 23 | { 24 | return 0; 25 | } 26 | if(memo[i][k]!=null) 27 | { 28 | return memo[i][k]; 29 | } 30 | if(arr[i]>k) 31 | { 32 | memo[i][k]=getMaxSum(memo,arr, i+1, k); 33 | return memo[i][k]; 34 | } 35 | memo[i][k]=Math.max(getMaxSum(memo,arr,i+1,k), getMaxSum(memo,arr,i+1,k-arr[i])+arr[i]); 36 | return memo[i][k]; 37 | } 38 | 39 | } 40 | 41 | -------------------------------------------------------------------------------- /src/com/dsalgo/MergeInSingleArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/merge-two-sorted-arrays-in-single-array.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class MergeInSingleArray 10 | { 11 | public static void main(String[] args) 12 | { 13 | int M = 10; 14 | int N = 12; 15 | int[] array1 = new int[M + N]; 16 | int[] array2 = new int[N]; 17 | fillElementsSorted(array1, M); 18 | fillElementsSorted(array2, N); 19 | printArray(array1); 20 | printArray(array2); 21 | merge(array1, array2, M, N); 22 | printArray(array1); 23 | } 24 | 25 | private static void printArray(int[] array) 26 | { 27 | for (int i : array) 28 | System.out.print(i + ","); 29 | System.out.println(); 30 | 31 | } 32 | 33 | private static void merge(int[] array1, int[] array2, int M, int N) 34 | { 35 | int index = M + N - 1; 36 | int i = M - 1; 37 | int j = N - 1; 38 | while (true) 39 | { 40 | if (array1[i] > array2[j]) 41 | array1[index--] = array1[i--]; 42 | else 43 | array1[index--] = array2[j--]; 44 | if (j < 0) 45 | break; 46 | if (i < 0) 47 | { 48 | while (index >= 0) 49 | { 50 | array1[index] = array2[index]; 51 | index--; 52 | } 53 | break; 54 | } 55 | } 56 | } 57 | 58 | private static void fillElementsSorted(int[] array1, int fillCount) 59 | { 60 | array1[0] = (int) (Math.random() * 5); 61 | for (int i = 1; i < fillCount; ++i) 62 | { 63 | array1[i] = array1[i - 1] + (int) (Math.random() * 5); 64 | } 65 | } 66 | 67 | } 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/com/dsalgo/MergeNSortedArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | For problem and solution description please visit the link below 4 | http://www.dsalgo.com/2013/02/merge-n-sorted-arrays.html 5 | */ 6 | package com.dsalgo; 7 | import java.util.PriorityQueue; 8 | 9 | 10 | public class MergeNSortedArrays 11 | { 12 | public static void main(String[] args) 13 | { 14 | int[]arr1={2,4,6,8,9,12,14,16}; 15 | int[]arr2={3,6,7,9,22,25,28}; 16 | int[]arr3={2,5,7,8,10,11,16}; 17 | int[]arr4={4,8,23,26,28}; 18 | int[]result=mergeNArrays(new int[][]{arr1,arr2,arr3,arr4}); 19 | for(int i:result) 20 | { 21 | System.out.print(i+","); 22 | } 23 | } 24 | 25 | private static int[] mergeNArrays(int[][] sortedArrays) 26 | { 27 | int totalLength=0; 28 | PriorityQueue heap=new PriorityQueue(); 29 | 30 | for(int i=0;i 48 | { 49 | private int startIndex; 50 | private int[]array; 51 | public ArrayContainer(int[]array) 52 | { 53 | this.array=array; 54 | startIndex=0; 55 | } 56 | public boolean isEmpty() 57 | { 58 | return startIndex==array.length; 59 | } 60 | public int peek() 61 | { 62 | return array[startIndex]; 63 | } 64 | public int getNextInt() 65 | { 66 | return array[startIndex++]; 67 | } 68 | @Override 69 | public int compareTo(ArrayContainer o) 70 | { 71 | return new Integer(peek()).compareTo(o.peek()); 72 | } 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/com/dsalgo/NextLargerNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/NextLargerNumber.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class NextLargerNumber { 12 | 13 | /** 14 | * given a number whose digits are unique find the next bigger number formed 15 | * by those digits 16 | * 17 | * @param args 18 | */ 19 | public static void main(String[] args) throws Exception { 20 | 21 | System.out.println("5963=>" + getNextLarger(5963)); 22 | System.out.println("3784=>" + getNextLarger(3784)); 23 | System.out.println("9531=>" + getNextLarger(9531)); 24 | System.out.println("1234=>" + getNextLarger(1234)); 25 | System.out.println("3=>" + getNextLarger(3)); 26 | } 27 | 28 | private static int getNextLarger(int decimalNumber) { 29 | List digits = numberToDigits(decimalNumber); 30 | int rightBiggerIndex = -1; 31 | for (int i = digits.size() - 1; i > 0; i--) { 32 | if (digits.get(i) > digits.get(i - 1)) { 33 | rightBiggerIndex = i; 34 | break; 35 | } 36 | } 37 | if (rightBiggerIndex != -1) { 38 | swap(digits, rightBiggerIndex, rightBiggerIndex - 1); 39 | sort(digits, rightBiggerIndex, digits.size()); 40 | } 41 | return digitsToNumber(digits); 42 | 43 | } 44 | 45 | private static List numberToDigits(int number) { 46 | List digits = new ArrayList<>(); 47 | while (number > 0) { 48 | digits.add(0, number % 10); 49 | number /= 10; 50 | } 51 | return digits; 52 | } 53 | 54 | private static int digitsToNumber(List digits) { 55 | int number = 0; 56 | for (Integer digit : digits) { 57 | number *= 10; 58 | number += digit; 59 | } 60 | return number; 61 | } 62 | 63 | private static void sort(List digits, int startIndex, int endIndex) { 64 | if (startIndex == endIndex) 65 | return; 66 | for (int k = startIndex; k < endIndex - 1; ++k) 67 | for (int l = startIndex + 1; l < endIndex; ++l) { 68 | if (digits.get(k) > digits.get(l)) 69 | swap(digits, k, l); 70 | } 71 | 72 | } 73 | 74 | private static void swap(List digits, int i, int j) { 75 | Integer temp = digits.get(i); 76 | digits.set(i, digits.get(j)); 77 | digits.set(j, temp); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/com/dsalgo/NextPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/NextPalindrome.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class NextPalindrome 10 | { 11 | public static void main(String[] args) 12 | { 13 | System.out.println(nextPalindrome(112100)); 14 | } 15 | public static int nextPalindrome(int num) 16 | { 17 | return nextPalindrome(num,true); 18 | } 19 | private static int nextPalindrome(int num,boolean firstTime) 20 | { 21 | String numString=""+num; 22 | int leftEndIndex=-1; 23 | int rightStartIndex=-1; 24 | boolean isOdd=numString.length()%2==1; 25 | if(isOdd) 26 | { 27 | leftEndIndex=numString.length()/2; 28 | rightStartIndex=leftEndIndex+1; 29 | } 30 | else 31 | { 32 | leftEndIndex=rightStartIndex=numString.length()/2; 33 | 34 | } 35 | String leftHalf=numString.substring(0,leftEndIndex); 36 | String rightHalf=numString.substring(rightStartIndex); 37 | 38 | String leftReversed=new StringBuffer(leftHalf).reverse().toString(); 39 | String palindrome=null; 40 | if(Integer.parseInt(leftReversed)>Integer.parseInt(rightHalf)||!firstTime) 41 | { 42 | if(isOdd) 43 | palindrome=leftHalf+numString.charAt(leftEndIndex)+leftReversed; 44 | else 45 | palindrome=leftHalf+leftReversed; 46 | return Integer.parseInt(palindrome); 47 | } 48 | else 49 | { 50 | if(isOdd) 51 | { 52 | String leftAndMiddle=leftHalf+numString.charAt(leftEndIndex); 53 | int incrementedLeft=Integer.parseInt(leftAndMiddle)+1; 54 | return nextPalindrome(Integer.parseInt(incrementedLeft+rightHalf),false); 55 | } 56 | else 57 | { 58 | int incrementedLeft=Integer.parseInt(leftHalf)+1; 59 | return nextPalindrome(Integer.parseInt(incrementedLeft+rightHalf),false); 60 | } 61 | } 62 | 63 | } 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/com/dsalgo/NextPowerOfTwo.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/next-power-of-two.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class NextPowerOfTwo 9 | { 10 | public static void main(String[] args) 11 | { 12 | long num = 128; 13 | long result = findNextPowerOfTwo(num); 14 | System.out.println(result); 15 | } 16 | 17 | private static long findNextPowerOfTwo(long num) 18 | { 19 | long result = 1; 20 | while (num != 0) 21 | { 22 | num >>= 1; 23 | result <<= 1; 24 | } 25 | return result; 26 | } 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/com/dsalgo/NextSmallInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/ArrayNextSmallElement.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.LinkedList; 9 | 10 | public class NextSmallInteger 11 | { 12 | 13 | /** 14 | * given an array form another array where each element of previous array is replaced with 15 | * its next minimum number in the array 16 | * @param args 17 | */ 18 | public static void main(String[] args) 19 | { 20 | int[] input={3,4,5,2,7,5,7,3,8,2,5,7,9,1,3}; 21 | int[]output=new int[input.length]; 22 | LinkedList stack=new LinkedList(); 23 | for(int i=input.length-1;i>=0;--i) 24 | { 25 | int currentNum=input[i]; 26 | if(stack.peek()==null) 27 | { 28 | output[i]=0; 29 | stack.push(currentNum); 30 | continue; 31 | } 32 | while(stack.size()!=0 && stack.peek()>=currentNum) 33 | { 34 | stack.pop(); 35 | } 36 | output[i]=stack.peek()==null?0:stack.peek(); 37 | stack.push(currentNum); 38 | } 39 | for(int i=0;i < output.length;++i) 40 | { 41 | System.out.print(output[i]+","); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/com/dsalgo/NumberOfOnes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/count-number-of-ones-till-n-in-binary.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class NumberOfOnes 9 | { 10 | 11 | /** 12 | * given n find the total number of ones in the binary representation of 13 | * numbers 1,2,3,...,n 14 | * 15 | * @param args 16 | */ 17 | public static void main(String[] args) 18 | { 19 | System.out.println(getNumberOfOnes(30)); 20 | } 21 | 22 | public static int getNumberOfOnes(int num) 23 | { 24 | int p = 1, cnt = 0; 25 | 26 | if ((num & 1) != 0) 27 | cnt++; 28 | 29 | while (1 << (p - 1) < num) 30 | { 31 | if ((num & (1 << p)) != 0) 32 | cnt += (1 << (p - 1)) * (p) + num % (1 << p) + 1; 33 | p++; 34 | } 35 | return cnt; 36 | } 37 | 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/com/dsalgo/OneWordPermutationOfOther.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/find-if-two-words-are-anagram-or-not.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | public class OneWordPermutationOfOther 12 | { 13 | public static void main(String[] args) 14 | { 15 | String a = "listen"; 16 | String b = "enlist"; 17 | System.out.println(isPermutation(a, b)); 18 | } 19 | 20 | private static boolean isPermutation(String a, String b) 21 | { 22 | Map < Character, Integer> charMap = new HashMap < Character, Integer>(); 23 | for (char ch : a.toCharArray()) 24 | { 25 | if (charMap.containsKey(ch)) 26 | charMap.put(ch, charMap.get(ch) + 1); 27 | else 28 | charMap.put(ch, 1); 29 | } 30 | for (char ch : b.toCharArray()) 31 | { 32 | if (!charMap.containsKey(ch)) 33 | return false; 34 | if (charMap.get(ch) == 1) 35 | charMap.remove(ch); 36 | else 37 | charMap.put(ch, charMap.get(ch) - 1); 38 | } 39 | if (charMap.keySet().size() == 0) 40 | return true; 41 | return false; 42 | } 43 | 44 | } 45 | 46 | -------------------------------------------------------------------------------- /src/com/dsalgo/PathInMaze.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-all-possible-paths-in-maze.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class PathInMaze 12 | { 13 | public static void main(String[] args) 14 | { 15 | boolean[][] maze = new boolean[10][10]; 16 | makeRandomMaze(maze); 17 | printMaze(maze); 18 | List> paths = findPaths(maze); 19 | if (paths == null) 20 | { 21 | System.out.println("No path possible"); 22 | return; 23 | } 24 | for (List path : paths) 25 | { 26 | for (Cell cell : path) 27 | System.out.print(cell + ","); 28 | System.out.println(); 29 | } 30 | } 31 | 32 | private static List> findPaths(boolean[][] maze) 33 | { 34 | Cell start = new Cell(0, 0); 35 | Cell end = new Cell(maze.length - 1, maze[0].length - 1); 36 | List> paths = findPaths(maze, start, end); 37 | return paths; 38 | } 39 | 40 | private static List> findPaths(boolean[][] maze, Cell start, 41 | Cell end) 42 | { 43 | List> result = new ArrayList>(); 44 | int rows = maze.length; 45 | int cols = maze[0].length; 46 | if (start.row < 0 || start.col < 0) 47 | return null; 48 | if (start.row == rows || start.col == cols) 49 | return null; 50 | if (maze[start.row][start.col] == true) 51 | return null; 52 | if (start.equals(end)) 53 | { 54 | List path = new ArrayList(); 55 | path.add(start); 56 | result.add(path); 57 | return result; 58 | } 59 | maze[start.row][start.col] = true; 60 | Cell[] nextCells = new Cell[4]; 61 | nextCells[0] = new Cell(start.row + 1, start.col); 62 | nextCells[2] = new Cell(start.row, start.col + 1); 63 | nextCells[1] = new Cell(start.row - 1, start.col); 64 | nextCells[3] = new Cell(start.row, start.col - 1); 65 | 66 | for (Cell nextCell : nextCells) 67 | { 68 | List> paths = findPaths(maze, nextCell, end); 69 | if (paths != null) 70 | { 71 | for (List path : paths) 72 | path.add(0, start); 73 | result.addAll(paths); 74 | } 75 | } 76 | maze[start.row][start.col] = false; 77 | if (result.size() == 0) 78 | return null; 79 | return result; 80 | } 81 | 82 | private static class Cell 83 | { 84 | public int row; 85 | public int col; 86 | 87 | public Cell(int row, int column) 88 | { 89 | this.row = row; 90 | this.col = column; 91 | } 92 | 93 | @Override 94 | public boolean equals(Object obj) 95 | { 96 | if (this == obj) 97 | return true; 98 | if ((obj == null) || (obj.getClass() != this.getClass())) 99 | return false; 100 | Cell cell = (Cell) obj; 101 | if (row == cell.row && col == cell.col) 102 | return true; 103 | return false; 104 | } 105 | 106 | @Override 107 | public String toString() 108 | { 109 | return "(" + row + "," + col + ")"; 110 | } 111 | } 112 | 113 | private static void printMaze(boolean[][] maze) 114 | { 115 | for (int i = 0; i < maze.length; ++i) 116 | { 117 | for (int j = 0; j < maze[i].length; ++j) 118 | { 119 | if (maze[i][j]) 120 | System.out.print("#|"); 121 | else 122 | System.out.print("_|"); 123 | } 124 | System.out.println(); 125 | } 126 | } 127 | 128 | private static void makeRandomMaze(boolean[][] maze) 129 | { 130 | for (int i = 0; i < maze.length; ++i) 131 | { 132 | for (int j = 0; j < maze[0].length; ++j) 133 | { 134 | maze[i][j] = (int) (Math.random() * 3) == 1; 135 | } 136 | } 137 | maze[0][0] = false; 138 | maze[maze.length - 1][maze[0].length - 1] = false; 139 | 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/com/dsalgo/PermutationSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/permutation-of-string-as-substring-of.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.HashMap; 8 | 9 | public class PermutationSubstring 10 | { 11 | public static void main(String[] args) 12 | { 13 | String a = "encyclopedia"; 14 | String b = "dope"; 15 | System.out.println(isPermutationSubstring(a, b)); 16 | } 17 | 18 | private static boolean isPermutationSubstring(String a, String b) 19 | { 20 | if (a.length() < b.length()) 21 | return false; 22 | int sameLetterPositive = b.length(); 23 | int sameLetterNegative = 0; 24 | int otherLetter = 0; 25 | HashMap hashMap = new HashMap(); 26 | for (char ch : b.toCharArray()) 27 | { 28 | if (hashMap.containsKey(ch)) 29 | { 30 | hashMap.put(ch, hashMap.get(ch) + 1); 31 | } else 32 | { 33 | hashMap.put(ch, 1); 34 | } 35 | } 36 | for (int i = 0; i < b.length(); ++i) 37 | { 38 | char ch = a.charAt(i); 39 | if (hashMap.containsKey(ch)) 40 | { 41 | int count = hashMap.get(ch); 42 | hashMap.put(ch, count - 1); 43 | if (count == 0) 44 | sameLetterNegative++; 45 | else 46 | sameLetterPositive--; 47 | } else 48 | { 49 | otherLetter--; 50 | } 51 | } 52 | if (sameLetterPositive == 0 && sameLetterNegative == 0 53 | && otherLetter == 0) 54 | return true; 55 | for (int i = b.length(); i < a.length(); ++i) 56 | { 57 | char inclusion = a.charAt(i); 58 | char exclusion = a.charAt(i - b.length()); 59 | if (hashMap.containsKey(exclusion)) 60 | { 61 | int count = hashMap.get(exclusion); 62 | hashMap.put(exclusion, count + 1); 63 | if (count == -1) 64 | sameLetterNegative--; 65 | else 66 | sameLetterPositive++; 67 | } else 68 | { 69 | otherLetter++; 70 | } 71 | if (hashMap.containsKey(inclusion)) 72 | { 73 | int count = hashMap.get(inclusion); 74 | hashMap.put(inclusion, count - 1); 75 | if (count == 0) 76 | sameLetterNegative++; 77 | else 78 | sameLetterPositive--; 79 | } else 80 | { 81 | otherLetter--; 82 | } 83 | if (sameLetterPositive == 0 && sameLetterNegative == 0 84 | && otherLetter == 0) 85 | return true; 86 | } 87 | return false; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/com/dsalgo/PostorderSuccessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/PostorderSuccessor.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class PostorderSuccessor { 9 | 10 | public static void main(String[] args) { 11 | NextNode a = new NextNode(1); 12 | NextNode b = new NextNode(2); 13 | NextNode c = new NextNode(3); 14 | NextNode d = new NextNode(4); 15 | NextNode e = new NextNode(5); 16 | NextNode f = new NextNode(6); 17 | NextNode g = new NextNode(7); 18 | NextNode h = new NextNode(8); 19 | NextNode i = new NextNode(9); 20 | a.left = b; 21 | a.right = c; 22 | b.right = d; 23 | c.left = e; 24 | c.right = f; 25 | d.left = g; 26 | d.right = h; 27 | g.right = i; 28 | NextNode head = linkPostorderSuccessor(a); 29 | while (head != null) { 30 | System.out.println(head.value); 31 | head = head.next; 32 | } 33 | 34 | } 35 | 36 | public static NextNode linkPostorderSuccessor(NextNode root) { 37 | NodeContainer linker = new NodeContainer(); 38 | NodeContainer head = new NodeContainer(); 39 | linkPostorderSuccessor(root, linker, head); 40 | return head.node; 41 | } 42 | 43 | private static void linkPostorderSuccessor(NextNode root, 44 | NodeContainer linker, NodeContainer head) { 45 | if (root == null) 46 | return; 47 | linkPostorderSuccessor(root.left, linker, head); 48 | linkPostorderSuccessor(root.right, linker, head); 49 | if (head.node == null && root != null) 50 | head.node = root; 51 | if (linker.node != null) 52 | linker.node.next = root; 53 | linker.node = root; 54 | 55 | } 56 | 57 | static class NextNode { 58 | public NextNode left; 59 | public NextNode right; 60 | public NextNode next; 61 | public int value; 62 | 63 | public NextNode(int value) { 64 | this.value = value; 65 | } 66 | } 67 | 68 | static class NodeContainer { 69 | public NextNode node; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/com/dsalgo/PotsOfGoldGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/gold-coins-in-pots-game.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class PotsOfGoldGame 10 | { 11 | public static void main(String[] args) 12 | { 13 | int[] goldPots = 14 | { 12, 32, 4, 23, 6, 42, 16, 3, 85, 23, 4, 7, 3, 5, 45, 34, 2, 1 }; 15 | int coins = getMaxGold(goldPots); 16 | System.out.println(coins); 17 | } 18 | 19 | private static int getMaxGold(int[] goldPots) 20 | { 21 | Integer[][]memo=new Integer[goldPots.length][goldPots.length]; 22 | return getMaxGold(goldPots, 0, goldPots.length - 1,memo); 23 | } 24 | 25 | private static int getMaxGold(int[] goldPots, int startIndex, int endIndex,Integer[][]memo) 26 | { 27 | if (startIndex > endIndex) 28 | return 0; 29 | if(memo[startIndex][endIndex]!=null) 30 | return memo[startIndex][endIndex]; 31 | int coinsIfStart = goldPots[startIndex] 32 | + Math.min(getMaxGold(goldPots, startIndex + 2, endIndex,memo), 33 | getMaxGold(goldPots, startIndex + 1, endIndex - 1,memo)); 34 | int coinsIfEnd = goldPots[endIndex] 35 | + Math.min(getMaxGold(goldPots, startIndex, endIndex - 2,memo), 36 | getMaxGold(goldPots, startIndex + 1, endIndex - 1,memo)); 37 | memo[startIndex][endIndex]=Math.max(coinsIfStart, coinsIfEnd); 38 | return memo[startIndex][endIndex]; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/com/dsalgo/PreorderSuccessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/PreorderSuccessor.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class PreorderSuccessor 9 | { 10 | 11 | public static void main(String[] args) 12 | { 13 | NextNode a=new NextNode(1); 14 | NextNode b=new NextNode(2); 15 | NextNode c=new NextNode(3); 16 | NextNode d=new NextNode(4); 17 | NextNode e=new NextNode(5); 18 | NextNode f=new NextNode(6); 19 | NextNode g=new NextNode(7); 20 | NextNode h=new NextNode(8); 21 | NextNode i=new NextNode(9); 22 | a.left=b; 23 | a.right=c; 24 | b.right=d; 25 | c.left=e; 26 | c.right=f; 27 | d.left=g; 28 | d.right=h; 29 | g.right=i; 30 | NextNode head=linkPreorderSuccessor(a); 31 | while(head!=null) 32 | { 33 | System.out.println(head.value); 34 | head=head.next; 35 | } 36 | 37 | } 38 | 39 | public static NextNode linkPreorderSuccessor(NextNode root) 40 | { 41 | NodeContainer linker=new NodeContainer(); 42 | NodeContainer head=new NodeContainer(); 43 | linkPreorderSuccessor(root, linker, head); 44 | return head.node; 45 | } 46 | 47 | private static void linkPreorderSuccessor(NextNode root, NodeContainer linker, NodeContainer head) 48 | { 49 | if(root==null) 50 | return; 51 | if(head.node==null&&root!=null) 52 | head.node=root; 53 | if(linker.node!=null) 54 | linker.node.next=root; 55 | linker.node=root; 56 | linkPreorderSuccessor(root.left,linker,head); 57 | linkPreorderSuccessor(root.right, linker, head); 58 | } 59 | 60 | } 61 | 62 | class NextNode 63 | { 64 | public NextNode left; 65 | public NextNode right; 66 | public NextNode next; 67 | public int value; 68 | public NextNode(int value) 69 | { 70 | this.value=value; 71 | } 72 | } 73 | 74 | class NodeContainer 75 | { 76 | public NextNode node; 77 | } 78 | -------------------------------------------------------------------------------- /src/com/dsalgo/PrintBinartyTreeBottomToTop.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/print-binary-tree-bottom-to-top-level.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.LinkedList; 8 | import java.util.Stack; 9 | 10 | public class PrintBinartyTreeBottomToTop 11 | { 12 | public static void main(String[] args) 13 | { 14 | Node a = new Node(1); 15 | Node b = new Node(2); 16 | Node c = new Node(3); 17 | Node d = new Node(4); 18 | Node e = new Node(5); 19 | Node f = new Node(6); 20 | Node g = new Node(7); 21 | Node h = new Node(8); 22 | a.left = b; 23 | a.right = c; 24 | b.left = d; 25 | c.left = e; 26 | c.right = f; 27 | f.left = g; 28 | f.right = h; 29 | 30 | printLevelFromBottomToTop(a); 31 | } 32 | 33 | private static void printLevelFromBottomToTop(Node root) 34 | { 35 | Node levelMarker = new Node(-1); 36 | LinkedList queue = new LinkedList(); 37 | Stack stack = new Stack(); 38 | queue.add(root); 39 | queue.add(levelMarker); 40 | while (!queue.isEmpty()) 41 | { 42 | Node node = queue.poll(); 43 | stack.push(node); 44 | if (node == levelMarker) 45 | { 46 | if (queue.isEmpty()) 47 | break; 48 | queue.add(levelMarker); 49 | continue; 50 | } 51 | 52 | if (node.right != null) 53 | { 54 | queue.add(node.right); 55 | } 56 | if (node.left != null) 57 | { 58 | queue.add(node.left); 59 | } 60 | } 61 | while (!stack.isEmpty()) 62 | { 63 | Node node = stack.pop(); 64 | if (node == levelMarker) 65 | { 66 | System.out.println(); 67 | continue; 68 | } 69 | System.out.print(node.value + "\t "); 70 | } 71 | } 72 | 73 | static class Node 74 | { 75 | Node left; 76 | Node right; 77 | int value; 78 | 79 | public Node(int value) 80 | { 81 | this.value = value; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/com/dsalgo/PrintBinartyTreeBottomToTopContinuous.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/print-binary-tree-from-bottom-to-top.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.LinkedList; 9 | import java.util.Stack; 10 | 11 | public class PrintBinartyTreeBottomToTopContinuous 12 | { 13 | public static void main(String[] args) 14 | { 15 | Node a = new Node(1); 16 | Node b = new Node(2); 17 | Node c = new Node(3); 18 | Node d = new Node(4); 19 | Node e = new Node(5); 20 | Node f = new Node(6); 21 | Node g = new Node(7); 22 | Node h = new Node(8); 23 | a.left = b; 24 | a.right = c; 25 | b.left = d; 26 | c.left = e; 27 | c.right = f; 28 | f.left = g; 29 | f.right = h; 30 | 31 | printLevelFromBottomToTop(a); 32 | } 33 | 34 | 35 | private static void printLevelFromBottomToTop(Node root) 36 | { 37 | LinkedList queue=new LinkedList(); 38 | Stack stack=new Stack(); 39 | queue.add(root); 40 | while(!queue.isEmpty()) 41 | { 42 | Node node=queue.poll(); 43 | stack.push(node); 44 | if(node.right!=null) 45 | { 46 | queue.add(node.right); 47 | } 48 | if(node.left!=null) 49 | { 50 | queue.add(node.left); 51 | } 52 | } 53 | while(!stack.isEmpty()) 54 | { 55 | System.out.print(stack.pop().value+", "); 56 | } 57 | } 58 | 59 | 60 | static class Node 61 | { 62 | Node left; 63 | Node right; 64 | int value; 65 | 66 | public Node(int value) 67 | { 68 | this.value = value; 69 | } 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /src/com/dsalgo/PrintMatrixSpiral.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/PrintMatrixSpiral.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | public class PrintMatrixSpiral 8 | { 9 | public static void main(String[] args) 10 | { 11 | int[][] matrix = 12 | { 13 | { 3, 4, 5, 6, 2, 5 }, 14 | { 2, 4, 6, 2, 5, 7 }, 15 | { 2, 5, 7, 8, 9, 3 }, 16 | { 2, 4, 7, 3, 5, 8 }, 17 | { 6, 4, 7, 3, 5, 7 } }; 18 | 19 | printSpiral(matrix); 20 | } 21 | 22 | public static void printSpiral(int[][] matrix) 23 | { 24 | printSpiral(matrix, 0); 25 | } 26 | 27 | private static void printSpiral(int[][] matrix, int depth) 28 | { 29 | if (matrix == null || matrix.length == 0) 30 | return; 31 | int rows = matrix.length; 32 | int cols = matrix[0].length; 33 | if (2 * depth > Math.min(rows, cols)) 34 | return; 35 | for (int i = depth; i < cols - depth - 1; ++i) 36 | { 37 | System.out.print(matrix[depth][i] + ","); 38 | } 39 | for (int i = depth; i < rows - depth - 1; ++i) 40 | { 41 | System.out.print(matrix[i][cols - depth - 1] + ","); 42 | } 43 | for (int i = rows - depth; i > depth; --i) 44 | { 45 | System.out.print(matrix[rows - depth - 1][i] + ","); 46 | } 47 | for (int i = rows - depth - 1; i > depth; --i) 48 | { 49 | System.out.print(matrix[i][depth] + ","); 50 | } 51 | printSpiral(matrix, ++depth); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/com/dsalgo/PrintNodeOfSameLevel.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/print-nodes-of-given-level.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class PrintNodeOfSameLevel 10 | { 11 | public static void main(String[] args) 12 | { 13 | Node a = new Node(1); 14 | Node b = new Node(2); 15 | Node c = new Node(3); 16 | Node d = new Node(4); 17 | Node e = new Node(5); 18 | Node f = new Node(6); 19 | Node g = new Node(7); 20 | Node h = new Node(8); 21 | a.left = b; 22 | a.right = c; 23 | b.left = d; 24 | c.left = e; 25 | c.right = f; 26 | f.left = g; 27 | f.right = h; 28 | 29 | printLevelofDepth(a, 5); 30 | } 31 | 32 | private static void printLevelofDepth(Node a, int depth) 33 | { 34 | if (a == null) 35 | return; 36 | if (depth == 1) 37 | { 38 | System.out.println(a.value); 39 | return; 40 | } 41 | printLevelofDepth(a.left, depth - 1); 42 | printLevelofDepth(a.right, depth - 1); 43 | } 44 | 45 | static class Node 46 | { 47 | Node left; 48 | Node right; 49 | int value; 50 | 51 | public Node(int value) 52 | { 53 | this.value = value; 54 | } 55 | } 56 | } 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/com/dsalgo/PythagoreanTriplet.java: -------------------------------------------------------------------------------- 1 | /*For problem and solution description please visit the link below 2 | *http://www.dsalgo.com/2013/04/find-pythagorean-triplets-in-array.html 3 | */ 4 | 5 | package com.dsalgo; 6 | 7 | import java.util.HashSet; 8 | 9 | public class PythagoreanTriplet { 10 | 11 | public static void main(String[] args) { 12 | int[] arr = { 2, 3, 4, 6, 7, 12, 13, 15, 5, 17, 14, 22 }; 13 | findPythagoreanTriplets(arr); 14 | 15 | } 16 | 17 | private static void findPythagoreanTriplets(int[] arr) { 18 | HashSet squares = new HashSet(); 19 | for (int num : arr) 20 | squares.add((long) num * num); 21 | for (int i = 0; i < arr.length - 1; ++i) 22 | for (int j = i + 1; j < arr.length; ++j) { 23 | long square = (long) arr[i] * arr[i] + (long) arr[j] * arr[j]; 24 | if (squares.contains(square)) { 25 | System.out.println(arr[i] + "," + arr[j] + "," 26 | + (long) Math.sqrt(square)); 27 | } 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/com/dsalgo/QueueMinUsingStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/QueueMinUsingStackMin.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | /* 9 | * Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations. 10 | * 11 | * first solution using two stacks 12 | */ 13 | public class QueueMinUsingStack 14 | { 15 | 16 | static StackMinimum stackMinimum1=new StackMinimum(); 17 | static StackMinimum stackMinimum2=new StackMinimum(); 18 | public static void enqueue(int a) 19 | { 20 | stackMinimum1.push(a); 21 | } 22 | 23 | public static int dequeue() 24 | { 25 | if(stackMinimum2.size()==0) 26 | { 27 | while(stackMinimum1.size()!=0) 28 | stackMinimum2.push(stackMinimum1.pop()); 29 | } 30 | return stackMinimum2.pop(); 31 | } 32 | 33 | public int getMinimum() 34 | { 35 | return Math.min( 36 | stackMinimum1.size()==0?Integer.MAX_VALUE:stackMinimum1.getMinimum(), 37 | stackMinimum2.size()==0?Integer.MAX_VALUE:stackMinimum2.getMinimum() 38 | ); 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/com/dsalgo/QueueUsingStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/QueueUsingStack.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.Stack; 9 | 10 | 11 | public class QueueUsingStack 12 | { 13 | private StackstackPop=new Stack(); 14 | private StackstackPush=new Stack(); 15 | 16 | public void enqueue(int a) 17 | { 18 | stackPush.push(a); 19 | } 20 | public int dequeue() 21 | { 22 | if(stackPop.isEmpty()) 23 | while(!stackPush.isEmpty()) 24 | stackPop.push(stackPush.pop()); 25 | return stackPop.pop(); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/com/dsalgo/README.md: -------------------------------------------------------------------------------- 1 | This is the code repository for website www.dsalgo.com 2 | Every program has the link to the page where the problem and solution description is available for the interview quesions. 3 | 4 | This website gives complete java code solutions for data structure and algorithm questions and answers for top level software companies like microsoft, amazon, google and facebook. 5 | -------------------------------------------------------------------------------- /src/com/dsalgo/RemoveDuplicateBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/remove-duplicate-infinite-integer.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.Iterator; 8 | 9 | public class RemoveDuplicateBST 10 | { 11 | public static void main(String[] args) 12 | { 13 | System.out.println("Input\tOutput"); 14 | Iterator inputIterator = new InputIterator(30); 15 | Iterator outputIterator = new OutputIterator(inputIterator); 16 | while (outputIterator.hasNext()) 17 | { 18 | System.out.println("\t<<" + outputIterator.next()); 19 | } 20 | } 21 | 22 | private static class InputIterator implements Iterator 23 | { 24 | int count; 25 | 26 | public InputIterator(int count) 27 | { 28 | this.count = count; 29 | } 30 | 31 | @Override 32 | public boolean hasNext() 33 | { 34 | return count != 0; 35 | } 36 | 37 | @Override 38 | public Integer next() 39 | { 40 | int input = (int) (Math.random() * 30); 41 | System.out.println(">>" + input); 42 | count--; 43 | return input; 44 | } 45 | 46 | @Override 47 | public void remove() 48 | { 49 | 50 | } 51 | } 52 | 53 | private static class OutputIterator implements Iterator 54 | { 55 | Iterator inputIterator; 56 | Integer nextElement; 57 | Node root; 58 | 59 | public OutputIterator(Iterator inputIterator) 60 | { 61 | this.inputIterator = inputIterator; 62 | if (inputIterator.hasNext()) 63 | { 64 | nextElement = inputIterator.next(); 65 | if (nextElement != null) 66 | add(nextElement); 67 | } 68 | } 69 | 70 | private boolean add(int value) 71 | { 72 | return add(root, value); 73 | } 74 | 75 | private boolean add(Node current, int value) 76 | { 77 | Node node = new Node(value); 78 | if (current == null) 79 | { 80 | root = node; 81 | return true; 82 | } 83 | if (current.value == value) 84 | { 85 | return false; 86 | } 87 | if (current.value > value) 88 | { 89 | if (current.left == null) 90 | { 91 | current.left = node; 92 | return true; 93 | } else 94 | { 95 | return add(current.left, value); 96 | } 97 | } else 98 | { 99 | if (current.right == null) 100 | { 101 | current.right = node; 102 | return true; 103 | } else 104 | { 105 | return add(current.right, value); 106 | } 107 | } 108 | } 109 | 110 | @Override 111 | public boolean hasNext() 112 | { 113 | return nextElement != null; 114 | } 115 | 116 | @Override 117 | public Integer next() 118 | { 119 | int output = nextElement; 120 | nextElement = null; 121 | while (inputIterator.hasNext()) 122 | { 123 | int input = inputIterator.next(); 124 | if (add(input)) 125 | { 126 | nextElement = input; 127 | break; 128 | } 129 | } 130 | return output; 131 | } 132 | 133 | @Override 134 | public void remove() 135 | { 136 | 137 | } 138 | } 139 | 140 | private static class Node 141 | { 142 | int value; 143 | Node left; 144 | Node right; 145 | 146 | public Node(int value) 147 | { 148 | this.value = value; 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/com/dsalgo/ReverseKNodes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/ReverseKNodes.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class ReverseKNodes 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[] arr = 13 | { 4, 5, 3, 6, 8, 3, 5, 7, 3, 7, 9, 4, 6 }; 14 | Node head = createLinkedList(arr); 15 | printLinkedList(head); 16 | head = reverse(head, 4); 17 | printLinkedList(head); 18 | } 19 | 20 | static Node reverse(Node head, int k) 21 | { 22 | Node current = head; 23 | Node next = null; 24 | Node prev = null; 25 | int count = 0; 26 | 27 | while (current != null && count < k) 28 | { 29 | next = current.next; 30 | current.next = prev; 31 | prev = current; 32 | current = next; 33 | count++; 34 | } 35 | 36 | if (next != null) 37 | { 38 | head.next = reverse(next, k); 39 | } 40 | return prev; 41 | } 42 | 43 | private static void printLinkedList(Node head) 44 | { 45 | while (head != null) 46 | { 47 | System.out.print(head.value + "->"); 48 | head = head.next; 49 | } 50 | System.out.println(); 51 | } 52 | 53 | private static Node createLinkedList(int[] arr) 54 | { 55 | Node head = null; 56 | Node current = null; 57 | for (int element : arr) 58 | { 59 | if (head == null) 60 | { 61 | head = new Node(element); 62 | current = head; 63 | } else 64 | { 65 | current.next = new Node(element); 66 | current = current.next; 67 | } 68 | } 69 | return head; 70 | } 71 | 72 | static class Node 73 | { 74 | public Node next; 75 | public int value; 76 | 77 | public Node(int value) 78 | { 79 | this.value = value; 80 | } 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/com/dsalgo/ReverseLinkedListIterative.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/ReverseLinkedListIterative.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class ReverseLinkedListIterative 9 | { 10 | public static void main(String[] args) 11 | { 12 | Node a=new Node(4); 13 | Node b=new Node(6); 14 | Node c=new Node(2); 15 | Node d=new Node(9); 16 | Node e=new Node(5); 17 | Node f=new Node(3); 18 | Node g=new Node(6); 19 | Node h=new Node(2); 20 | a.next=b; 21 | b.next=c; 22 | c.next=d; 23 | d.next=e; 24 | e.next=f; 25 | f.next=g; 26 | g.next=h; 27 | a.printLinkedList(); 28 | Node head=reverseLinkedList(a); 29 | head.printLinkedList(); 30 | } 31 | public static Node reverseLinkedList(Node head) 32 | { 33 | Node prev=null; 34 | Node next=null; 35 | Node current=head; 36 | while(current!=null) 37 | { 38 | next=current.next; 39 | current.next=prev; 40 | prev=current; 41 | current=next; 42 | } 43 | return prev; 44 | } 45 | static class Node 46 | { 47 | public Node next; 48 | public int value; 49 | 50 | public Node(int value) 51 | { 52 | this.value = value; 53 | } 54 | public void printLinkedList() 55 | { 56 | Node head=this; 57 | while (head != null) 58 | { 59 | System.out.print(head.value + "->"); 60 | head = head.next; 61 | } 62 | System.out.println(); 63 | } 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/com/dsalgo/ReverseLinkedListRecursive.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/ReverseLinkedListRecursive.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class ReverseLinkedListRecursive 9 | { 10 | public static void main(String[] args) 11 | { 12 | Node a=new Node(4); 13 | Node b=new Node(6); 14 | Node c=new Node(2); 15 | Node d=new Node(9); 16 | Node e=new Node(5); 17 | Node f=new Node(3); 18 | Node g=new Node(6); 19 | Node h=new Node(2); 20 | a.next=b; 21 | b.next=c; 22 | c.next=d; 23 | d.next=e; 24 | e.next=f; 25 | f.next=g; 26 | g.next=h; 27 | a.printLinkedList(); 28 | Node head=reverseLinkedList(a); 29 | head.printLinkedList(); 30 | } 31 | public static Node reverseLinkedList(Node head) 32 | { 33 | if(head.next==null) 34 | return head; 35 | Node newHead=reverseLinkedList(head.next); 36 | head.next.next=head; 37 | head.next=null; 38 | return newHead; 39 | } 40 | static class Node 41 | { 42 | public Node next; 43 | public int value; 44 | 45 | public Node(int value) 46 | { 47 | this.value = value; 48 | } 49 | public void printLinkedList() 50 | { 51 | Node head=this; 52 | while (head != null) 53 | { 54 | System.out.print(head.value + "->"); 55 | head = head.next; 56 | } 57 | System.out.println(); 58 | } 59 | 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /src/com/dsalgo/ReverseWordsInSentence.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/reverse-words-of-sentence.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class ReverseWordsInSentence 10 | { 11 | public static void main(String[] args) 12 | { 13 | String str = "reverse words of a sentence"; 14 | String result = reverseWords(str); 15 | System.out.println(result); 16 | } 17 | 18 | private static String reverseWords(String str) 19 | { 20 | char[] chars = str.toCharArray(); 21 | reverse(chars, 0, chars.length - 1); 22 | int wordStart = 0; 23 | int wordEnd = 0; 24 | while (wordEnd < chars.length) 25 | { 26 | if (chars[wordEnd] == ' ') 27 | { 28 | reverse(chars, wordStart, wordEnd - 1); 29 | wordStart = wordEnd + 1; 30 | } 31 | wordEnd++; 32 | } 33 | reverse(chars, wordStart, wordEnd - 1); 34 | return new String(chars); 35 | } 36 | 37 | private static void reverse(char[] chars, int i, int j) 38 | { 39 | while (i < j) 40 | { 41 | char temp = chars[i]; 42 | chars[i] = chars[j]; 43 | chars[j] = temp; 44 | i++; 45 | j--; 46 | } 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /src/com/dsalgo/RotateKTimes.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/rotate-array-k-times-to-left.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class RotateKTimes 10 | { 11 | public static void main(String[] args) 12 | { 13 | int[] array = 14 | { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 15 | printArray(array); 16 | rotateLeftKTimes(array, 7); 17 | printArray(array); 18 | } 19 | 20 | private static void rotateLeftKTimes(int[] array, int k) 21 | { 22 | reverse(array, 0, array.length - 1); 23 | reverse(array, 0, array.length - k - 1); 24 | reverse(array, array.length - k, array.length - 1); 25 | } 26 | 27 | private static void reverse(int[] array, int i, int j) 28 | { 29 | while (i < j) 30 | { 31 | int temp = array[i]; 32 | array[i] = array[j]; 33 | array[j] = temp; 34 | i++; 35 | j--; 36 | } 37 | } 38 | 39 | private static void printArray(int[] array) 40 | { 41 | for (int i : array) 42 | System.out.print(i + ","); 43 | System.out.println(); 44 | 45 | } 46 | 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/com/dsalgo/RotateString.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/rotate-string-to-make-another.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | 9 | public class RotateString 10 | { 11 | public static void main(String[] args) 12 | { 13 | String string1 = "rotation"; 14 | String string2 = "tionrota"; 15 | System.out.println(isRotationPossible(string1, string2)); 16 | } 17 | 18 | private static boolean isRotationPossible(String string1, String string2) 19 | { 20 | String str = string1 + string1; 21 | return str.contains(string2) && string1.length() == string2.length(); 22 | } 23 | 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/com/dsalgo/RunningMedian.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/RunningMedian.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.Comparator; 9 | import java.util.PriorityQueue; 10 | import java.util.Random; 11 | 12 | 13 | public class RunningMedian 14 | { 15 | PriorityQueue upperQueue; 16 | PriorityQueue lowerQueue; 17 | 18 | public RunningMedian() 19 | { 20 | lowerQueue=new PriorityQueue(20,new Comparator() 21 | { 22 | 23 | @Override 24 | public int compare(Integer o1, Integer o2) 25 | { 26 | 27 | return -o1.compareTo(o2); 28 | } 29 | 30 | }); 31 | upperQueue=new PriorityQueue(); 32 | upperQueue.add(Integer.MAX_VALUE); 33 | lowerQueue.add(Integer.MIN_VALUE); 34 | } 35 | 36 | public double getMedian(int num) 37 | { 38 | //adding the number to proper heap 39 | if(num>=upperQueue.peek()) 40 | upperQueue.add(num); 41 | else 42 | lowerQueue.add(num); 43 | //balancing the heaps 44 | if(upperQueue.size()-lowerQueue.size()==2) 45 | lowerQueue.add(upperQueue.poll()); 46 | else if(lowerQueue.size()-upperQueue.size()==2) 47 | upperQueue.add(lowerQueue.poll()); 48 | //returning the median 49 | if(upperQueue.size()==lowerQueue.size()) 50 | return(upperQueue.peek()+lowerQueue.peek())/2.0; 51 | else if(upperQueue.size()>lowerQueue.size()) 52 | return upperQueue.peek(); 53 | else 54 | return lowerQueue.peek(); 55 | 56 | } 57 | public static void main(String[] args) 58 | { 59 | Random random=new Random(); 60 | RunningMedian runningMedian=new RunningMedian(); 61 | System.out.println("num\tmedian"); 62 | for(int i=0;i<50;++i) 63 | { 64 | int num=random.nextInt(100); 65 | System.out.print(num); 66 | System.out.print("\t"); 67 | System.out.println(runningMedian.getMedian(num)); 68 | } 69 | 70 | } 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /src/com/dsalgo/SameAverageSubset.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/same-average-subset.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | 11 | public class SameAverageSubset 12 | { 13 | public static void main(String[] args) 14 | { 15 | int[] input = 16 | { 4, 1, 7, 8, 3, 5 }; 17 | ArrayList table = new ArrayList(); 18 | HashMap> hashMap = new HashMap>(); 19 | for (int i = 0; i < input.length; ++i) 20 | { 21 | int num = input[i]; 22 | ArrayList tempTable = new ArrayList(); 23 | for (SumCountPair j : table) 24 | { 25 | SumCountPair temp = j.clone(); 26 | temp.add(num); 27 | tempTable.add(temp); 28 | } 29 | table.addAll(tempTable); 30 | SumCountPair sumCountPair = new SumCountPair(); 31 | sumCountPair.add(num); 32 | table.add(sumCountPair); 33 | } 34 | for (SumCountPair j : table) 35 | { 36 | List temp = hashMap.get(j.average()); 37 | if (temp != null) 38 | { 39 | temp.add(j); 40 | } else 41 | { 42 | temp = new ArrayList(); 43 | temp.add(j); 44 | } 45 | hashMap.put(j.average(), temp); 46 | } 47 | for (Double average : hashMap.keySet()) 48 | { 49 | List list = hashMap.get(average); 50 | if (list.size() == 1) 51 | continue; 52 | System.out.print(average + " "); 53 | for (SumCountPair sumCountPair : list) 54 | System.out.print(sumCountPair + ", "); 55 | System.out.println(); 56 | } 57 | 58 | } 59 | 60 | } 61 | 62 | class SumCountPair 63 | { 64 | int sum; 65 | int count; 66 | ArrayList array; 67 | 68 | public SumCountPair() 69 | { 70 | this(0, 0); 71 | } 72 | 73 | public SumCountPair(int sum, int count) 74 | { 75 | this(sum, count, new ArrayList()); 76 | } 77 | 78 | @SuppressWarnings("unchecked") 79 | public SumCountPair(int sum, int count, ArrayList array) 80 | { 81 | this.sum = sum; 82 | this.count = count; 83 | this.array = (ArrayList) array.clone(); 84 | } 85 | 86 | @Override 87 | public SumCountPair clone() 88 | { 89 | return new SumCountPair(sum, count, array); 90 | } 91 | 92 | public void add(int num) 93 | { 94 | sum += num; 95 | count++; 96 | array.add(num); 97 | } 98 | 99 | public double average() 100 | { 101 | return (double) sum / count; 102 | } 103 | 104 | public String toString() 105 | { 106 | return array.toString(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/com/dsalgo/SearchInSortedMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/search-in-sorted-matrix.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class SearchInSortedMatrix 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[][] matrix = 13 | { 14 | { 5, 7, 8, 9 }, 15 | { 6, 9, 11, 13 }, 16 | { 7, 11, 12, 14 }, 17 | { 8, 13, 16, 17 } }; 18 | boolean result = contains(matrix, 14); 19 | System.out.println(result); 20 | 21 | } 22 | 23 | private static boolean contains(int[][] matrix, int k) 24 | { 25 | int row = matrix.length; 26 | int col = matrix[0].length; 27 | int currentRow = 0; 28 | int currentCol = col - 1; 29 | while (currentRow != row && currentCol != -1) 30 | { 31 | if (matrix[currentRow][currentCol] == k) 32 | return true; 33 | else if (matrix[currentRow][currentCol] > k) 34 | currentCol--; 35 | else 36 | currentRow++; 37 | } 38 | return false; 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/com/dsalgo/SeparateWordsInSentence.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/SeparateWordsInSentence.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | import java.util.Stack; 11 | 12 | public class SeparateWordsInSentence 13 | { 14 | public static void main(String[] args) 15 | { 16 | String sentence = "therearesomewordshiddenhere"; 17 | String[] dictionary = 18 | { "the", "a", "i", "here", "so", "hid", "there", "are", "some", "word", 19 | "words", "hid", "hi", "hidden", "he", "here", "her", "rear", 20 | "me", "den" }; 21 | String[] words = getSeparatedWords(sentence, dictionary); 22 | for (String word : words) 23 | System.out.println(word); 24 | 25 | } 26 | 27 | private static String[] getSeparatedWords(String sentence, 28 | String[] dictionary) 29 | { 30 | Set validWords = new HashSet(); 31 | for (String validWord : dictionary) 32 | validWords.add(validWord); 33 | Stack words = new Stack(); 34 | if (isSeparable(sentence, validWords, 0, words)) 35 | { 36 | return words.toArray(new String[] {}); 37 | } 38 | return null; 39 | } 40 | 41 | private static boolean isSeparable(String sentence, Set validWords, 42 | int startIndex, Stack foundWords) 43 | { 44 | if (startIndex == sentence.length()) 45 | return true; 46 | boolean hasWord = false; 47 | for (int i = startIndex + 1; i <= sentence.length(); ++i) 48 | { 49 | String currentSubstring = sentence.substring(startIndex, i); 50 | if (validWords.contains(currentSubstring)) 51 | { 52 | foundWords.push(currentSubstring); 53 | if (isSeparable(sentence, validWords, i, foundWords)) 54 | { 55 | hasWord = true; 56 | break; 57 | } 58 | foundWords.pop(); 59 | } 60 | } 61 | if (!hasWord) 62 | return false; 63 | return true; 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/com/dsalgo/ShortestPathInMaze.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/find-shortest-path-in-maze.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | 11 | public class ShortestPathInMaze 12 | { 13 | public static void main(String[] args) 14 | { 15 | boolean[][] maze = new boolean[10][10]; 16 | makeRandomMaze(maze); 17 | printMaze(maze); 18 | List path = findShortestPath(maze); 19 | if (path == null) 20 | { 21 | System.out.println("No path possible"); 22 | return; 23 | } 24 | for (Cell cell : path) 25 | System.out.print(cell + ","); 26 | } 27 | 28 | private static List findShortestPath(boolean[][] maze) 29 | { 30 | int[][] levelMatrix = new int[maze.length][maze[0].length]; 31 | for (int i = 0; i < maze.length; ++i) 32 | for (int j = 0; j < maze[0].length; ++j) 33 | { 34 | levelMatrix[i][j] = maze[i][j] == true ? -1 : 0; 35 | } 36 | LinkedList queue = new LinkedList(); 37 | Cell start = new Cell(0, 0); 38 | Cell end = new Cell(maze.length - 1, maze[0].length - 1); 39 | queue.add(start); 40 | levelMatrix[start.row][start.col] = 1; 41 | while (!queue.isEmpty()) 42 | { 43 | Cell cell = queue.poll(); 44 | if (cell == end) 45 | break; 46 | int level = levelMatrix[cell.row][cell.col]; 47 | Cell[] nextCells = new Cell[4]; 48 | nextCells[3] = new Cell(cell.row, cell.col - 1); 49 | nextCells[2] = new Cell(cell.row - 1, cell.col); 50 | nextCells[1] = new Cell(cell.row, cell.col + 1); 51 | nextCells[0] = new Cell(cell.row + 1, cell.col); 52 | 53 | for (Cell nextCell : nextCells) 54 | { 55 | if (nextCell.row < 0 || nextCell.col < 0) 56 | continue; 57 | if (nextCell.row == maze.length 58 | || nextCell.col == maze[0].length) 59 | continue; 60 | if (levelMatrix[nextCell.row][nextCell.col] == 0) 61 | { 62 | queue.add(nextCell); 63 | levelMatrix[nextCell.row][nextCell.col] = level + 1; 64 | } 65 | } 66 | } 67 | if (levelMatrix[end.row][end.col] == 0) 68 | return null; 69 | LinkedList path = new LinkedList(); 70 | Cell cell = end; 71 | while (!cell.equals(start)) 72 | { 73 | path.push(cell); 74 | int level = levelMatrix[cell.row][cell.col]; 75 | Cell[] nextCells = new Cell[4]; 76 | nextCells[0] = new Cell(cell.row + 1, cell.col); 77 | nextCells[1] = new Cell(cell.row, cell.col + 1); 78 | nextCells[2] = new Cell(cell.row - 1, cell.col); 79 | nextCells[3] = new Cell(cell.row, cell.col - 1); 80 | for (Cell nextCell : nextCells) 81 | { 82 | if (nextCell.row < 0 || nextCell.col < 0) 83 | continue; 84 | if (nextCell.row == maze.length 85 | || nextCell.col == maze[0].length) 86 | continue; 87 | if (levelMatrix[nextCell.row][nextCell.col] == level - 1) 88 | { 89 | cell = nextCell; 90 | break; 91 | } 92 | } 93 | } 94 | return path; 95 | } 96 | 97 | private static class Cell 98 | { 99 | public int row; 100 | public int col; 101 | 102 | public Cell(int row, int column) 103 | { 104 | this.row = row; 105 | this.col = column; 106 | } 107 | 108 | @Override 109 | public boolean equals(Object obj) 110 | { 111 | if (this == obj) 112 | return true; 113 | if ((obj == null) || (obj.getClass() != this.getClass())) 114 | return false; 115 | Cell cell = (Cell) obj; 116 | if (row == cell.row && col == cell.col) 117 | return true; 118 | return false; 119 | } 120 | 121 | @Override 122 | public String toString() 123 | { 124 | return "(" + row + "," + col + ")"; 125 | } 126 | } 127 | 128 | private static void printMaze(boolean[][] maze) 129 | { 130 | for (int i = 0; i < maze.length; ++i) 131 | { 132 | for (int j = 0; j < maze[i].length; ++j) 133 | { 134 | if (maze[i][j]) 135 | System.out.print("#|"); 136 | else 137 | System.out.print("_|"); 138 | } 139 | System.out.println(); 140 | } 141 | } 142 | 143 | private static void makeRandomMaze(boolean[][] maze) 144 | { 145 | for (int i = 0; i < maze.length; ++i) 146 | { 147 | for (int j = 0; j < maze[0].length; ++j) 148 | { 149 | maze[i][j] = (int) (Math.random() * 3) == 1; 150 | } 151 | } 152 | maze[0][0] = false; 153 | maze[maze.length - 1][maze[0].length - 1] = false; 154 | 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/com/dsalgo/SnakesAndLadders.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/SnakesAndLadders.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.ArrayList; 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | import java.util.Stack; 12 | 13 | public class SnakesAndLadders 14 | { 15 | 16 | private static List snakesAndLadders; 17 | 18 | public static void main(String[] args) 19 | { 20 | 21 | snakesAndLadders = new ArrayList(); 22 | 23 | snakesAndLadders.add(new Movers(9, 31)); 24 | 25 | snakesAndLadders.add(new Movers(17, 7)); 26 | 27 | snakesAndLadders.add(new Movers(28, 84)); 28 | 29 | snakesAndLadders.add(new Movers(85, 41)); 30 | 31 | snakesAndLadders.add(new Movers(51, 67)); 32 | 33 | snakesAndLadders.add(new Movers(54, 34)); 34 | 35 | snakesAndLadders.add(new Movers(62, 19)); 36 | 37 | snakesAndLadders.add(new Movers(64, 60)); 38 | 39 | snakesAndLadders.add(new Movers(71, 91)); 40 | 41 | snakesAndLadders.add(new Movers(80, 99)); 42 | 43 | snakesAndLadders.add(new Movers(87, 24)); 44 | 45 | snakesAndLadders.add(new Movers(93, 73)); 46 | 47 | 48 | int[] moveMap = new int[101]; 49 | 50 | for (Movers movers : snakesAndLadders) 51 | moveMap[movers.start] = movers.end; 52 | 53 | int[] minMove = new int[101]; 54 | int[] dice = new int[101]; 55 | int[]fromCell=new int[101]; 56 | 57 | LinkedList queue = new LinkedList(); 58 | queue.add(1); 59 | boolean finished=false; 60 | while (!queue.isEmpty()&&!finished) 61 | { 62 | int cell = queue.poll(); 63 | for (int i = 1; i <= 6; ++i) 64 | { 65 | int newCell = moveMap[cell + i] == 0 ? cell + i : moveMap[cell + i]; 66 | if (minMove[newCell] == 0) 67 | { 68 | minMove[newCell] = minMove[cell] + 1; 69 | dice[newCell]=i; 70 | fromCell[newCell]=cell; 71 | queue.add(newCell); 72 | } 73 | if(newCell==100) 74 | { 75 | finished=true; 76 | break; 77 | } 78 | 79 | } 80 | 81 | } 82 | int cell=100; 83 | Stack stack=new Stack(); 84 | while(cell!=1) 85 | { 86 | stack.push("new cell "+cell); 87 | stack.push("dice throw "+dice[cell]); 88 | 89 | cell=fromCell[cell]; 90 | } 91 | while(!stack.isEmpty()) 92 | System.out.println(stack.pop()); 93 | } 94 | } 95 | 96 | /** 97 | * Snakes and Ladders basically do the same thing. They move the coin from one 98 | * place to another if they move in positive direction we call them ladders 99 | * otherwise snakes. 100 | * 101 | */ 102 | class Movers 103 | { 104 | 105 | public int start; 106 | 107 | public int end; 108 | 109 | public boolean goingUp; 110 | 111 | public Movers(int start, int end) 112 | { 113 | 114 | this.start = start; 115 | 116 | this.end = end; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/com/dsalgo/SortStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/sort-stack.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.Stack; 9 | 10 | public class SortStack 11 | { 12 | public static void main(String[] args) 13 | { 14 | Stackstack=new Stack(); 15 | stack.push(5); 16 | stack.push(3); 17 | stack.push(9); 18 | stack.push(2); 19 | stack.push(6); 20 | sort(stack); 21 | while(!stack.isEmpty()) 22 | { 23 | System.out.println(stack.pop()); 24 | } 25 | } 26 | 27 | static void sort(Stack stack) 28 | { 29 | if (stack.isEmpty()) 30 | return; 31 | Integer top = stack.pop(); 32 | sort(stack); 33 | insertSorted(top, stack); 34 | return; 35 | } 36 | 37 | static void insertSorted(Integer top, Stack stack) 38 | { 39 | if (stack.isEmpty() || stack.peek() > top) 40 | { 41 | stack.push(top); 42 | return; 43 | } 44 | Integer smaller = stack.pop(); 45 | insertSorted(top, stack); 46 | stack.push(smaller); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/com/dsalgo/StackMinimum.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/StackMinimum.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.Stack; 9 | 10 | public class StackMinimum 11 | { 12 | private Stack stack = new Stack(); 13 | private Stack minStack = new Stack(); 14 | 15 | public Integer push(Integer item) 16 | { 17 | if(stack.empty()) 18 | { 19 | stack.push(item); 20 | minStack.push(item); 21 | return item; 22 | } 23 | Integer currentMin=minStack.peek(); 24 | if(currentMin < item) 25 | minStack.push(currentMin); 26 | else 27 | minStack.push(item); 28 | stack.push(item); 29 | return item; 30 | } 31 | 32 | public Integer pop() 33 | { 34 | if(stack.size()==0) 35 | return null; 36 | minStack.pop(); 37 | return stack.pop(); 38 | } 39 | 40 | public Integer getMinimum() 41 | { 42 | if(minStack.empty()) 43 | return null; 44 | return minStack.peek(); 45 | } 46 | 47 | public int size() 48 | { 49 | return stack.size(); 50 | } 51 | 52 | } 53 | 54 | -------------------------------------------------------------------------------- /src/com/dsalgo/SumPossibleAlongPathBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/does-any-path-adds-up-to-given-sum.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class SumPossibleAlongPathBinaryTree 9 | { 10 | public static void main(String[] args) 11 | { 12 | Node a = new Node(1); 13 | Node b = new Node(2); 14 | Node c = new Node(3); 15 | Node d = new Node(4); 16 | Node e = new Node(5); 17 | Node f = new Node(6); 18 | Node g = new Node(7); 19 | a.left = b; 20 | a.right = c; 21 | b.left = d; 22 | c.left = e; 23 | c.right = f; 24 | f.left = g; 25 | 26 | boolean result = isSumPossibleAlongAnyPath(a, 18); 27 | System.out.println(result); 28 | } 29 | 30 | private static boolean isSumPossibleAlongAnyPath(Node a, int k) 31 | { 32 | return isSumPossibleAlongAnyPath(a, k, k); 33 | } 34 | 35 | private static boolean isSumPossibleAlongAnyPath(Node a, int k,int originalK) 36 | { 37 | if (k == 0) 38 | return true; 39 | if (a == null) 40 | return false; 41 | return isSumPossibleAlongAnyPath(a.left, k - a.value,originalK) 42 | || isSumPossibleAlongAnyPath(a.right, k - a.value,originalK) 43 | || isSumPossibleAlongAnyPath(a.left,originalK,originalK) 44 | || isSumPossibleAlongAnyPath(a.right, originalK,originalK); 45 | } 46 | 47 | static class Node 48 | { 49 | Node left; 50 | Node right; 51 | int value; 52 | 53 | public Node(int value) 54 | { 55 | this.value = value; 56 | } 57 | } 58 | 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/com/dsalgo/SuperImposeBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/superimpose-binary-tree.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class SuperImposeBinaryTree 9 | { 10 | public static void main(String[] args) 11 | { 12 | Node a = new Node(1); 13 | Node b = new Node(2); 14 | Node c = new Node(3); 15 | Node d = new Node(4); 16 | Node e = new Node(5); 17 | Node f = new Node(6); 18 | a.left = b; 19 | a.right = c; 20 | b.left = d; 21 | c.left = e; 22 | c.right = f; 23 | 24 | Node u = new Node(4); 25 | Node v = new Node(7); 26 | Node w = new Node(2); 27 | Node x = new Node(8); 28 | Node y = new Node(1); 29 | Node z = new Node(5); 30 | 31 | u.left = v; 32 | u.right = w; 33 | w.left = x; 34 | w.right = y; 35 | y.right = z; 36 | printNice(a); 37 | System.out.println(); 38 | printNice(u); 39 | System.out.println(); 40 | Node result = superImpose(a, u); 41 | printNice(result); 42 | } 43 | 44 | private static Node superImpose(Node below, Node above) 45 | { 46 | if (above == null) 47 | return below; 48 | if (below == null) 49 | return above; 50 | above.left = superImpose(below.left, above.left); 51 | above.right = superImpose(below.right, above.right); 52 | return above; 53 | } 54 | 55 | public static void printNice(Node root) 56 | { 57 | if (root == null) 58 | return; 59 | else 60 | { 61 | System.out.print(root.value); 62 | if (root.left != null) 63 | { 64 | System.out.print("L->["); 65 | printNice(root.left); 66 | System.out.print("]"); 67 | } 68 | if (root.right != null) 69 | { 70 | System.out.print("R->["); 71 | printNice(root.right); 72 | System.out.print("]"); 73 | } 74 | } 75 | } 76 | 77 | static class Node 78 | { 79 | Node left; 80 | Node right; 81 | int value; 82 | 83 | public Node(int value) 84 | { 85 | this.value = value; 86 | } 87 | 88 | public static void printNice(Node root) 89 | { 90 | if (root == null) 91 | return; 92 | else 93 | { 94 | System.out.print(root.value); 95 | if (root.left != null) 96 | { 97 | System.out.print("L->["); 98 | printNice(root.left); 99 | System.out.print("]"); 100 | } 101 | if (root.right != null) 102 | { 103 | System.out.print("R->["); 104 | printNice(root.right); 105 | System.out.print("]"); 106 | } 107 | } 108 | } 109 | } 110 | } 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/com/dsalgo/SwapWithoutTemp.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/swap-without-temp.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class SwapWithoutTemp 9 | { 10 | public static void main(String[] args) 11 | { 12 | int a = 5; 13 | int b = 6; 14 | a = a ^ b; 15 | b = a ^ b; 16 | a = a ^ b; 17 | System.out.println(a); 18 | System.out.println(b); 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/com/dsalgo/TelephoneDirectory.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/03/get-find-and-delete-all-o1.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class TelephoneDirectory 9 | { 10 | public static void main(String[] args) 11 | { 12 | Directory directory = new Directory(5); 13 | int number1 = directory.getAvailableNumber(); 14 | System.out.println(number1); 15 | int number2 = directory.getAvailableNumber(); 16 | System.out.println(number2); 17 | System.out.println(directory.isAvailable(3)); 18 | int number3 = directory.getAvailableNumber(); 19 | System.out.println(number3); 20 | System.out.println(directory.isAvailable(3)); 21 | int number4 = directory.getAvailableNumber(); 22 | System.out.println(directory.isAvailable(3)); 23 | System.out.println(number4); 24 | int number5 = directory.getAvailableNumber(); 25 | System.out.println(number5); 26 | int number6 = directory.getAvailableNumber(); 27 | System.out.println(number6); 28 | int number7 = directory.getAvailableNumber(); 29 | System.out.println(number7); 30 | directory.release(3); 31 | System.out.println(directory.isAvailable(3)); 32 | int number8 = directory.getAvailableNumber(); 33 | System.out.println(number8); 34 | System.out.println(directory.isAvailable(3)); 35 | } 36 | 37 | private static class Directory 38 | { 39 | Node[] nodes; 40 | Node head; 41 | 42 | public Directory(int maxNumbers) 43 | { 44 | nodes = new Node[maxNumbers]; 45 | for (int i = 0; i < maxNumbers; ++i) 46 | { 47 | nodes[i] = new Node(i); 48 | if (i != 0) 49 | { 50 | nodes[i].previous = nodes[i - 1]; 51 | nodes[i - 1].next = nodes[i]; 52 | } 53 | } 54 | nodes[maxNumbers - 1].next = nodes[0]; 55 | nodes[0].previous = nodes[maxNumbers - 1]; 56 | head = nodes[0]; 57 | } 58 | 59 | public int getAvailableNumber() 60 | { 61 | if (head == null) 62 | return -1; 63 | int temp = head.number; 64 | head.available = false; 65 | if (head.next == head) 66 | head = null; 67 | else 68 | { 69 | head.previous.next = head.next; 70 | head.next.previous = head.previous; 71 | head = head.next; 72 | } 73 | return temp; 74 | } 75 | 76 | public boolean isAvailable(int number) 77 | { 78 | return nodes[number].available; 79 | } 80 | 81 | public void release(int number) 82 | { 83 | if (nodes[number].available == false) 84 | { 85 | nodes[number].available = true; 86 | if (head == null) 87 | { 88 | head = nodes[number]; 89 | nodes[number].next = nodes[number]; 90 | nodes[number].previous = nodes[number]; 91 | } else 92 | { 93 | nodes[number].next = head.next; 94 | nodes[number].previous = head; 95 | head.next.previous = nodes[number]; 96 | head.next = nodes[number]; 97 | } 98 | } 99 | } 100 | 101 | private static class Node 102 | { 103 | boolean available = true; 104 | Node next; 105 | Node previous; 106 | int number; 107 | 108 | public Node(int number) 109 | { 110 | this.number = number; 111 | } 112 | } 113 | } 114 | 115 | } 116 | 117 | -------------------------------------------------------------------------------- /src/com/dsalgo/TowersOfHanoi.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/towers-of-hanoi.html 4 | */ 5 | 6 | package com.dsalgo; 7 | import java.util.Stack; 8 | 9 | 10 | public class TowersOfHanoi 11 | { 12 | public static void main(String[] args) 13 | { 14 | Tower towerSource = new Tower("1"); 15 | Tower towerDestination = new Tower("2"); 16 | Tower towerHelper = new Tower("3"); 17 | towerSource.stack.push(4); 18 | towerSource.stack.push(3); 19 | towerSource.stack.push(2); 20 | towerSource.stack.push(1); 21 | move(towerSource.stack.size(), towerSource, towerDestination, 22 | towerHelper); 23 | } 24 | 25 | private static void move(int size, Tower towerSource, 26 | Tower towerDestination, Tower towerHelper) 27 | { 28 | if (towerSource.stack.isEmpty()) 29 | return; 30 | if (size == 1) 31 | { 32 | System.out.println("Move " + towerSource.stack.peek() 33 | + " from tower " + towerSource.name + " to tower " 34 | + towerDestination.name); 35 | towerDestination.stack.push(towerSource.stack.pop()); 36 | return; 37 | } 38 | move(size - 1, towerSource, towerHelper, towerDestination); 39 | move(1, towerSource, towerDestination, towerHelper); 40 | move(size - 1, towerHelper, towerDestination, towerSource); 41 | } 42 | 43 | private static class Tower 44 | { 45 | public String name; 46 | public Stack stack = new Stack(); 47 | 48 | public Tower(String name) 49 | { 50 | this.name = name; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/com/dsalgo/TwoSumToK.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/TwoSumToK.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | public class TwoSumToK 9 | { 10 | public static void main(String[] args) 11 | { 12 | int[]arr={1,2,3,4,5,6,7,8,9,12,13,14,16,32,44}; 13 | printIndexesForSumK(arr, 16); 14 | } 15 | 16 | public static void printIndexesForSumK(int[]arr,int k) 17 | { 18 | int startIndex=0; 19 | int endIndex=arr.length-1; 20 | while(startIndexk) 32 | endIndex--; 33 | } 34 | } 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /src/com/dsalgo/UnsortedTwoSumToK.java: -------------------------------------------------------------------------------- 1 | /* 2 | For problem and solution description please visit the link below 3 | http://www.dsalgo.com/2013/02/UnsortedTwoSumToK.php.html 4 | */ 5 | 6 | package com.dsalgo; 7 | 8 | import java.util.HashSet; 9 | 10 | 11 | public class UnsortedTwoSumToK 12 | { 13 | public static void main(String[] args) 14 | { 15 | int[]arr={6,7,8,9,1,16,2,3,14,13,4,5,12,32,44}; 16 | printIndexesForSumK(arr, 16); 17 | } 18 | 19 | public static void printIndexesForSumK(int[]arr,int k) 20 | { 21 | HashSet hashSet=new HashSet(); 22 | for(int num:arr) 23 | { 24 | if(hashSet.contains(k-num)) 25 | System.out.println(num+","+(k-num)); 26 | hashSet.add(num); 27 | } 28 | } 29 | 30 | } 31 | 32 | --------------------------------------------------------------------------------