├── AllCombinationOfNumberinArrayForGivenSum.java ├── BalancedBTOrNotUsingMaximumHeight.java ├── BalancedBinaryTreeFromSortedArray.java ├── BalancedBinaryTreeOrNot.java ├── CheckingCable.java ├── CiscoAdvancedChallenge.py ├── CombinationSum.java ├── CombinationSumII.java ├── CountAndSay.java ├── FindLCAinBinaryTree.java ├── FindNodesEachLevelOfBST.java ├── FindPathExistsBetweenTwoNodes.java ├── FindPathSum.java ├── FindSquareRoot.java ├── FirstCharAppearOnceInString.py ├── FlattenBinaryTree.java ├── FourSum.java ├── FrequencyOfIntegerUsingCountSort.java ├── FrequentlyOccuringCharacterWithCondition.java ├── GroupAnagrams.java ├── HeightOfTreeFromArray.java ├── InsertInterval.java ├── IsBinaryTreeABinarySearchTree.java ├── JumpGame1.java ├── KPM.java ├── LCS.java ├── LICENSE ├── LetterCombinationPhoneNumber.java ├── LevelOrderTraversalUsingRecursion.java ├── LongestIncreasingSubSequence.java ├── LongestSubStringContainKUniqueCharacter.java ├── LongestValidParenthesis.java ├── MatchingParenthesis.java ├── MedianOfTwoSortedArray_WithLogComplexity.java ├── MergeIntervals.java ├── MergeKSortedList.java ├── MinimumEditDistance.java ├── ParseStringToInteger.java ├── PartitionList.java ├── PathSum2.java ├── Permutation.java ├── PowOfn.java ├── README.md ├── RandomNumberGenerator.java ├── RecursiveLinkedList.java ├── RegularExpressionMatching.java ├── RemoveDuplicateFromSortedArrayII.java ├── RemoveDuplicates.java ├── RemoveNNodeFromLast.java ├── ReverseNodesInKGroup.java ├── RotateImageInPlace.java ├── ScrambleString.java ├── SearchInRotatedArrayII.java ├── SearchInRotatedSortedArray.java ├── SearchInsertPosition.java ├── SpiralAlgorithm.java ├── StringPermutation.java ├── SubSetsofSet.java ├── SubtringWithConcatenationOfAllWords.java ├── SumOfTwoNumbersToGetThird.java ├── ThreeSum.java ├── TrappingRainWater.java ├── TreeNode.java ├── Trie ├── CustomizeTrie.java ├── NumberEncoder │ ├── .classpath │ ├── .project │ ├── README.txt │ ├── dictionary.txt │ ├── input.txt │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── numberencoding │ │ │ ├── CharacterMapper.java │ │ │ ├── CustomizeTrie.java │ │ │ ├── main │ │ │ └── MainFunction.java │ │ │ └── signature │ │ │ └── ITrie.java │ │ └── test │ │ └── java │ │ └── com │ │ └── numberencoding │ │ ├── CharacterMapperTest.java │ │ └── CustomizeTrieTest.java ├── OutputMain.java ├── PatternExtraction.java ├── Trie.java ├── Trie1.java ├── TrieMap.java ├── TrieNode.java └── TrieST.java ├── ValidateBST.java ├── WordLadder.java ├── WordSearch_Recursion.java ├── ZigZagLevelOrdering.java ├── cube ├── HappyCube │ ├── .project │ ├── README.txt │ ├── output │ │ ├── Blue │ │ │ └── Challenge2 │ │ │ │ └── 20150717_00_02_30.txt │ │ ├── Green │ │ │ └── Challenge2 │ │ │ │ └── 20150717_00_02_30.txt │ │ ├── Purple │ │ │ └── Challenge2 │ │ │ │ └── 20150717_00_02_30.txt │ │ └── Red │ │ │ └── Challenge2 │ │ │ └── 20150717_00_02_30.txt │ ├── pom.xml │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── com │ │ │ └── cube │ │ │ ├── CubeGraphTraversal.java │ │ │ ├── IGraph.java │ │ │ ├── OutputStructure.java │ │ │ ├── controller │ │ │ ├── CubeController.java │ │ │ └── CubeValidation.java │ │ │ ├── helper │ │ │ ├── Constant.java │ │ │ ├── GraphHelper.java │ │ │ └── Util.java │ │ │ ├── model │ │ │ └── Cube.java │ │ │ └── test │ │ │ ├── Challenge1Part1Test.java │ │ │ ├── Challenge1Part2Test.java │ │ │ ├── Challenge2Test.java │ │ │ └── TestHelper.java │ └── target │ │ └── .gitignore └── Main.java ├── general.sc └── python ├── LongestNotRepeatedCharacterSubString.py ├── NumbersWithGivenSum.py ├── PrimeSieve.py ├── binarysearch.py ├── boogle.py ├── bt_maxpathsum.py ├── charorder_topsort.py ├── cycle_graph_dfs.py ├── find_min_depth_bt.py ├── findmax_rotatedarray.py ├── merge_lists.py ├── merge_sort.py ├── mythoughts ├── mythoughts.md ├── pairfind_rotatedarray.py ├── prins_minspanningtree.py ├── search_rotatedarray.py ├── test.py └── topological_sort.py /AllCombinationOfNumberinArrayForGivenSum.java: -------------------------------------------------------------------------------- 1 | //Combination and Perm 2 | class AllCombinationOfNumberinArrayForGivenSum { 3 | 4 | public static void main(String[] args) throws java.lang.Exception { 5 | new AllCombinationOfNumberinArrayForGivenSum().run(); 6 | } 7 | 8 | int N = 10; 9 | int[] arr = { 2, 3, 6, 7 }; 10 | int[] vals = new int[N]; 11 | 12 | void run() { 13 | printCombinations(N, 0, 0); 14 | } 15 | 16 | // from : consider numbers in arr from index "from" 17 | // index: add new number in array vals at index "index" 18 | void printCombinations(int target, int from, int index) { 19 | if (target == 0) { 20 | for (int i = 0; i < index; i++) { 21 | System.out.print(vals[i] + " "); 22 | } 23 | System.out.println(); 24 | } else if (target < 0 || from >= arr.length) { 25 | return; 26 | } else { 27 | vals[index] = arr[from]; 28 | // take arr[from] in set 29 | printCombinations(target - arr[from], from, index + 1); 30 | 31 | // dont take arr[from] in set 32 | printCombinations(target, from + 1, index); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /BalancedBTOrNotUsingMaximumHeight.java: -------------------------------------------------------------------------------- 1 | class TreeNode 2 | { 3 | 4 | 5 | int val; 6 | 7 | TreeNode left; 8 | 9 | TreeNode right; 10 | 11 | 12 | TreeNode(int x) 13 | { 14 | val = x; 15 | } 16 | } 17 | 18 | // a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 19 | // 1 20 | public class BalancedBTOrNotUsingMaximumHeight 21 | { 22 | 23 | 24 | public boolean isBalanced(TreeNode root) 25 | { 26 | if (getDepth(root) == -1) 27 | return false; 28 | 29 | return true; 30 | } 31 | 32 | 33 | private int getDepth(TreeNode root) 34 | { 35 | if (root == null) 36 | return 0; 37 | 38 | int left = getDepth(root.left); 39 | int right = getDepth(root.right); 40 | 41 | if (left == -1 || right == -1 || Math.abs(left - right) > 1) 42 | return -1; 43 | 44 | return Math.max(left, right) + 1; 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /BalancedBinaryTreeFromSortedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Simply get the middle element and all left node will be node.left and right will be right 3 | * @author achoudhary 4 | * 5 | */ 6 | public class BalancedBinaryTreeFromSortedArray { 7 | 8 | public void buildTree(int[] arr) { 9 | Node node = createBalancedBinaryTree(arr, 0, arr.length - 1); 10 | } 11 | 12 | public Node createBalancedBinaryTree(int[] arr, int start, int end) { 13 | 14 | if (start > end) 15 | return null; 16 | 17 | // int mid = (start + end)/2; //avoid for overflow 18 | int mid = start + (end - start) / 2; 19 | Node node = new Node(arr[mid]); 20 | node.left = createBalancedBinaryTree(arr, start, mid - 1); 21 | node.right = createBalancedBinaryTree(arr, mid + 1, end); 22 | 23 | return node; 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /BalancedBinaryTreeOrNot.java: -------------------------------------------------------------------------------- 1 | public class BalancedBinaryTreeOrNot 2 | { 3 | 4 | class Node 5 | { 6 | public int value; 7 | public Node left; 8 | public Node right; 9 | } 10 | 11 | private int findMinimumNodeValue(Node node) 12 | { 13 | 14 | if (node == null) 15 | return 0; 16 | 17 | return Math.min(findMinimumNodeValue(node.left), 18 | findMinimumNodeValue(node.right)) + 1; 19 | 20 | } 21 | 22 | private int findMamimumNodeValue(Node node) 23 | { 24 | 25 | if (node == null) 26 | return 0; 27 | 28 | return Math.max(findMinimumNodeValue(node.left), 29 | findMinimumNodeValue(node.right)) + 1; 30 | 31 | } 32 | 33 | public boolean findBalancedTree(Node root) 34 | { 35 | 36 | return !(findMamimumNodeValue(root) - findMamimumNodeValue(root) > 1); 37 | 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /CheckingCable.java: -------------------------------------------------------------------------------- 1 | 2 | public class CheckingCable { 3 | 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | 7 | String[] input = {"3 5","make 1 2 1000","check 1 3 500","make 3 2 2000","check 1 3 500","check 1 3 1500"}; 8 | 9 | if(input.length > 1){ 10 | String[] basic = input[0].split(" "); 11 | int N = Integer.parseInt(basic[0]); 12 | int instructions = Integer.parseInt(basic[1]); 13 | 14 | int[][] arr = new int[N][N]; 15 | for(int i=1;i= sum){ 26 | output = "YES"; 27 | }else{ 28 | output = "NO"; 29 | } 30 | }else if(i < instructions-1){ 31 | 32 | for(int j=0;j= sum){ //particular row has that link 34 | //if that link has reference with the expected row 35 | if(arr[row][i] > 0){ 36 | 37 | } 38 | } 39 | } 40 | 41 | 42 | for(int j=i+1;j 0){ 45 | //if link is there so A-B-C can be made 46 | if(arr[j][col] >= sum){ 47 | output = "YES"; 48 | } 49 | } 50 | } 51 | } 52 | System.out.println(output); 53 | } 54 | //A-B = B-A 55 | arr[row][col] = sum; 56 | arr[col][row] = sum; 57 | 58 | 59 | for(int k =0 ; k 500 or (regex.count('*') == 0 and regex.count('|')== 0 and (len(regex) < length)): 10 | print(-1) 11 | 12 | 13 | 14 | 15 | 16 | print(regex) 17 | -------------------------------------------------------------------------------- /CombinationSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created by abc on 17/01/2016. 5 | */ 6 | public class CombinationSum { 7 | 8 | public List> combinationSum(int[] candidates, int target) { 9 | 10 | List> result = new ArrayList<>(); 11 | Arrays.sort(candidates); 12 | 13 | List items = new ArrayList<>(); 14 | depthFirstSearch(candidates,result,items,0,target); 15 | 16 | return result; 17 | } 18 | 19 | private void depthFirstSearch(int[] candidates,List> result,List items , int start, int target){ 20 | 21 | if(target < 0){ 22 | return; 23 | } 24 | 25 | if(target == 0){ 26 | result.add(new ArrayList(items)); 27 | return; 28 | } 29 | 30 | for (int i = start; i > combinationSum2(int[] candidates, int target) { 10 | List> result = new ArrayList<>(); 11 | Arrays.sort(candidates); 12 | depthFirstSearchMaintainingUnique(candidates,target,result,new ArrayList(), new HashSet>(),0); 13 | 14 | return result; 15 | 16 | } 17 | 18 | private void depthFirstSearchMaintainingUnique(int[] candidates, int target,List> result, List proxy, Set> uniqueSet, int start){ 19 | if(target < 0) 20 | return; 21 | 22 | if(target == 0){ 23 | if(uniqueSet.add(proxy)) { 24 | result.add(new ArrayList<>(proxy)); 25 | } 26 | return; 27 | } 28 | 29 | for (int i = start; i < candidates.length; i++) { 30 | proxy.add(candidates[i]); 31 | depthFirstSearchMaintainingUnique(candidates,target-candidates[i],result,proxy,uniqueSet,i+1); 32 | proxy.remove(proxy.size()-1); 33 | } 34 | 35 | } 36 | 37 | public static void main(String[] args) { 38 | List> lists = new CombinationSumII().combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8); 39 | for (List val: 40 | lists) { 41 | System.out.println(" Output : "+val); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /CountAndSay.java: -------------------------------------------------------------------------------- 1 | 2 | public class CountAndSay { 3 | 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | String countAndSay = new CountAndSay().countAndSay(1); 7 | System.out.println(countAndSay); 8 | } 9 | 10 | 11 | //count & say 12 | public String countAndSay(int n) { 13 | String output = ""; 14 | int sum = 0; 15 | char[] charArray = (""+n).toCharArray(); 16 | char prev = charArray[0]; 17 | for (int i = 0; i < charArray.length; i++) { 18 | if(charArray[i] == prev){ 19 | sum++; 20 | }else{ 21 | output += ""+sum+""+prev; 22 | prev = charArray[i]; 23 | sum = 1; 24 | } 25 | 26 | } 27 | output += ""+sum+""+prev; 28 | return output; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /FindLCAinBinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class FindLCAinBinaryTree { 5 | 6 | int findLCA(Node root, Node A, Node B) { 7 | 8 | inorder(root); 9 | postorder(root); 10 | 11 | int positionA = inorderList.indexOf(A.value); 12 | int positionB = inorderList.indexOf(B.value); 13 | 14 | List sublist = inorderList.subList(positionA, positionB); 15 | int iNodeValue = 0; 16 | for (Integer val : sublist) { 17 | 18 | iNodeValue = Math.max(iNodeValue, postorderList.indexOf(val)); 19 | 20 | } 21 | 22 | return iNodeValue; 23 | 24 | } 25 | 26 | List inorderList = new ArrayList(); 27 | List postorderList = new ArrayList(); 28 | 29 | public void inorder(Node n) { 30 | 31 | if (n == null) 32 | return; 33 | 34 | inorder(n.left); 35 | inorderList.add(n.value); 36 | inorder(n.right); 37 | 38 | } 39 | 40 | public void postorder(Node n) { 41 | 42 | if (n == null) 43 | return; 44 | 45 | postorder(n.left); 46 | postorderList.add(n.value); 47 | postorder(n.right); 48 | 49 | } 50 | 51 | } 52 | 53 | /* 54 | * Copyright 2004-2015 Pilz Ireland Industrial Automation Ltd. All Rights 55 | * Reserved. PILZ PROPRIETARY/CONFIDENTIAL. 56 | * 57 | * Created on 12 May 2015 58 | */ -------------------------------------------------------------------------------- /FindNodesEachLevelOfBST.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Stack; 4 | 5 | public class FindNodesEachLevelOfBST { 6 | 7 | public List> findNodesInParticularDepth(Node node) { 8 | 9 | Stack main = new Stack(); 10 | Stack local = new Stack(); 11 | 12 | List> nodeList = new ArrayList<>(); 13 | 14 | if (node == null) { 15 | return null; 16 | } 17 | 18 | List list = new ArrayList(); 19 | main.add(node); 20 | nodeList.add(main); // adds te first level 21 | while (!main.isEmpty()) { 22 | 23 | Node elem = main.pop(); 24 | 25 | if (elem.left != null) { 26 | local.add(elem.left); 27 | } 28 | 29 | if (elem.right != null) { 30 | local.add(elem.right); 31 | } 32 | 33 | if (main.isEmpty() && local.size() > 0) { 34 | list = new ArrayList<>(); 35 | 36 | list.addAll(local); 37 | nodeList.add(list); 38 | 39 | main.addAll(local); 40 | local.clear(); 41 | 42 | } 43 | } 44 | 45 | return nodeList; 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /FindPathExistsBetweenTwoNodes.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | 5 | 6 | class Node{ 7 | 8 | public boolean visited =false; 9 | Node left; 10 | Node right; 11 | int value; 12 | } 13 | 14 | public class FindPathExistsBetweenTwoNodes{ 15 | 16 | Node A; 17 | Node B; 18 | public FindPathExistsBetweenTwoNodes(Node A){ 19 | 20 | } 21 | 22 | public boolean findPathBetweenNodes(Node n){ 23 | 24 | Queue queue = new LinkedList(); 25 | 26 | queue.add(n); 27 | 28 | while(!queue.isEmpty()){ 29 | Node head = queue.poll(); 30 | 31 | if(head.value == B.value){ 32 | return true; 33 | } 34 | 35 | Node left = head.left; 36 | Node right = head.right; 37 | if(left != null && !left .visited){ 38 | queue.add(left); 39 | left.visited = true; 40 | } 41 | 42 | 43 | if(right != null && !right .visited){ 44 | queue.add(head.left); 45 | right.visited = true; 46 | } 47 | 48 | } 49 | 50 | return false; 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /FindPathSum.java: -------------------------------------------------------------------------------- 1 | public class FindPathSum { 2 | public boolean hasPathSum(TreeNode root, int sum) { 3 | if (root == null) { 4 | return false; 5 | } 6 | if (sum == root.val && (root.left == null && root.right == null)) 7 | return true; 8 | 9 | return hasPathSum(root.left, sum - root.val) 10 | || hasPathSum(root.right, sum - root.val); 11 | } 12 | 13 | } 14 | 15 | -------------------------------------------------------------------------------- /FindSquareRoot.java: -------------------------------------------------------------------------------- 1 | public class FindSquareRoot { 2 | public int mySqrt(int x) { 3 | long i = 0; 4 | long j = x / 2 + 1; 5 | while (i <= j) { 6 | long mid = (i + j) / 2; 7 | if (mid * mid == x) 8 | return (int) mid; 9 | if (mid * mid < x) 10 | i = mid + 1; 11 | else 12 | j = mid - 1; 13 | } 14 | return (int) j; 15 | } 16 | } 17 | 18 | /* 19 | * Copyright 2004-2015 Pilz Ireland Industrial Automation Ltd. All Rights 20 | * Reserved. PILZ PROPRIETARY/CONFIDENTIAL. 21 | * 22 | * Created on 19 May 2015 23 | */ -------------------------------------------------------------------------------- /FirstCharAppearOnceInString.py: -------------------------------------------------------------------------------- 1 | __author__ = 'achoudhary' 2 | 3 | import operator 4 | 5 | input = "abhaihshek" 6 | list = list(input) 7 | 8 | map = dict() 9 | for key in list: 10 | if key in map: 11 | map[key] += 1 12 | else: 13 | map[key] = 1 14 | 15 | map = sorted(map.items(), key=operator.itemgetter(1)) 16 | print(map) -------------------------------------------------------------------------------- /FlattenBinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * ******************************************************************* 5 | * Given a binary tree, flatten it to a linked list in-place. 6 | * 7 | * @author achoudhary 8 | * @version 1.0.0 9 | ******************************************************************** 10 | */ 11 | 12 | class TreeNode{ 13 | 14 | int value ; 15 | TreeNode left; 16 | TreeNode right; 17 | 18 | TreeNode(int i){ 19 | this.value = i; 20 | } 21 | } 22 | 23 | public class FlattenBinaryTree 24 | { 25 | /** 26 | * recursive method 27 | * 28 | * we need to make sure always keep all the values to the right node, 29 | * so make everything in left as null after assigning the value to right of root node 30 | * 31 | * callig the flatten simply assigns the value to root, as its not going to create any trouble 32 | * dont assign to left or right 33 | * 34 | * @param root 35 | * @return 36 | */ 37 | public TreeNode flatten(TreeNode root){ 38 | 39 | if(root == null) 40 | return root; 41 | 42 | TreeNode rTree = root.right; 43 | if(root.left != null){ 44 | root.right = root.left; 45 | root.left = null; 46 | root = flatten(root.right); 47 | } 48 | 49 | if(rTree != null){ 50 | root.left = rTree; 51 | root = flatten(rTree.right); 52 | } 53 | 54 | 55 | 56 | return root; 57 | } 58 | 59 | /** 60 | * This approach is with stack where we simply add always the right value of the node to stack and 61 | * read later but add left value always directly to a new tree created t. 62 | * 63 | * Later if stack is not empty means it has series of right node, pop one after one 64 | * 65 | * @param root 66 | */ 67 | public void flattenStack(TreeNode root){ 68 | Stack stack = new Stack(); 69 | 70 | TreeNode t = root; 71 | while(t != null || !stack.empty()){ 72 | 73 | if(t.right != null){ 74 | stack.push(t.right); 75 | } 76 | 77 | if(t.left != null){ 78 | t.right = t.left; 79 | t.left = null; 80 | }else if(!stack.empty()){ 81 | t.right = stack.pop(); 82 | } 83 | 84 | t = t.right; 85 | } 86 | } 87 | 88 | } 89 | 90 | -------------------------------------------------------------------------------- /FourSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created by achoudhary on 18/01/2016. 5 | */ 6 | public class FourSum { 7 | 8 | public List> fourSum(int[] nums, int target) { 9 | 10 | Set> set = new HashSet<>(); 11 | 12 | List> result = new ArrayList<>(); 13 | 14 | Arrays.sort(nums); 15 | for (int i = 0; i < nums.length; i++) { 16 | for (int j = i+1; j < nums.length; j++) { 17 | int k = j+1; 18 | int l = nums.length-1; 19 | while(k < l){ 20 | int curr = nums[i]+nums[j]+nums[k]+nums[l]; 21 | if(curr < target){ 22 | k++; 23 | }else if(curr > target){ 24 | l--; 25 | }else if(curr == target){ 26 | List tuple = new ArrayList<>(); 27 | tuple.add(nums[i]); 28 | tuple.add(nums[j]); 29 | tuple.add(nums[k]); 30 | tuple.add(nums[l]); 31 | if(set.add(tuple)){ 32 | result.add(tuple); 33 | } 34 | k++; 35 | l--; 36 | } 37 | } 38 | } 39 | } 40 | 41 | return result; 42 | 43 | 44 | 45 | 46 | } 47 | 48 | 49 | private void depthFirstSearch(int[] nums, List> result,List tuple, int start , int target,int ultimateTarget){ 50 | if(tuple.size() > 4){ 51 | return; 52 | } 53 | 54 | System.err.println("target "+target); 55 | if(target == ultimateTarget && tuple.size() == 4){ 56 | System.out.printf("AAKKAKA "+tuple); 57 | result.add(tuple); 58 | return; 59 | } 60 | 61 | for (int i = start; i < nums.length; i++) { 62 | if(tuple.size() == 0 || tuple.get(tuple.size()-1) < nums[i]) { 63 | tuple.add(nums[i]); 64 | 65 | }else{ 66 | return; 67 | } 68 | depthFirstSearch(nums,result,tuple,i,target+nums[i],ultimateTarget); 69 | tuple.remove(tuple.size()-1); 70 | 71 | 72 | } 73 | } 74 | 75 | 76 | public static void main(String[] args) { 77 | int[] input = new int[]{1,0,-1,0,-2,2}; 78 | System.out.println(new FourSum().fourSum(input , 0)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /FrequencyOfIntegerUsingCountSort.java: -------------------------------------------------------------------------------- 1 | //http://www.careercup.com/question?id=21263687 2 | public class FrequencyOfIntegerUsingCountSort 3 | { 4 | 5 | public static void main(String[] args) 6 | { 7 | int[] input = {1,5,3,7,4,5,6,8,9,5,4,10,4}; 8 | int n = input.length; 9 | for(int i=0;i counts = new HashMap<>(); 12 | for(char c : line.toCharArray()) { 13 | Integer count = counts.get(c); 14 | if (count == null) { 15 | count = 0; 16 | } 17 | counts.put(c, ++count); 18 | } 19 | List> list = new ArrayList<>(counts.entrySet()); 20 | Collections.sort(list, new Comparator>() { 21 | @Override 22 | public int compare(Entry o1, 23 | Entry o2) { 24 | //System.out.println("o2.getValue() - o1.getValue() "+(o2.getValue() - o1.getValue())+" k1 "+o1.getKey()+" o2 "+o2.getKey()); 25 | int matching = o2.getValue() - o1.getValue(); 26 | if(matching == 0){ 27 | matching = o1.getKey() - o2.getKey(); 28 | } 29 | return matching; 30 | } 31 | }); 32 | for(Entry entry : list) { 33 | System.out.println("The character "+entry.getKey() +" has occured for "+ entry.getValue()+" times"); 34 | }} 35 | 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created by achoudhary on 25/01/2016. 5 | */ 6 | public class GroupAnagrams { 7 | 8 | public List> groupAnagrams(String[] strs) { 9 | Arrays.sort(strs); 10 | List> result = new ArrayList<>(); 11 | Map> map = new HashMap<>(); 12 | 13 | for (int i = 0; i < strs.length; i++) { 14 | char[] val = strs[i].toCharArray(); 15 | Arrays.sort(val); 16 | String actual = String.valueOf(val); 17 | if(map.containsKey(actual)){ 18 | List list = map.get(actual); 19 | list.add(strs[i]); 20 | map.put(actual,list); 21 | }else{ 22 | List list = new ArrayList<>(); 23 | list.add(strs[i]); 24 | map.put(actual,list); 25 | } 26 | } 27 | 28 | for(Map.Entry> entry: map.entrySet()) { 29 | result.add(entry.getValue()); 30 | } 31 | 32 | return result; 33 | } 34 | 35 | public static void main(String[] args) { 36 | new GroupAnagrams().groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /HeightOfTreeFromArray.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Queue; 7 | import java.util.Set; 8 | 9 | 10 | public class HeightOfTreeFromArray { 11 | 12 | public static void main(String[] args) { 13 | // TODO Auto-generated method stub 14 | 15 | int HEIGHT = 0; 16 | int[] array = {3,3,3,-1,2,1,0,1,4}; 17 | //maintains the node and its corresponding child 18 | Map> map = new HashMap>(); 19 | 20 | Queue queue = new LinkedList(); 21 | Queue pq = new LinkedList(); 22 | 23 | //iterate through each of the element and save the particular node and its key 24 | for(int i=0;i list = map.get(value); 28 | list.add(i); 29 | }else{ 30 | List list = new ArrayList(); 31 | list.add(i); 32 | map.put(array[i], list); 33 | } 34 | //appends the root node 35 | if(value == -1){ 36 | queue.add(i); 37 | } 38 | } 39 | 40 | Set keySet = map.keySet(); 41 | for(Integer i : keySet){ 42 | System.out.println("Value "+i+" Size "+map.get(i).size()); 43 | } 44 | 45 | //Run Simply DFS on Map and we are done 46 | while(!queue.isEmpty()){ 47 | Integer node = queue.poll(); 48 | List list = map.get(node); 49 | if(list != null && list.size() >0){ 50 | for(Integer child:list){ 51 | pq.add(child); 52 | } 53 | } 54 | 55 | if(queue.isEmpty()){ 56 | if(!pq.isEmpty()){ 57 | queue.addAll(pq); 58 | pq.clear(); 59 | HEIGHT++; 60 | } 61 | } 62 | 63 | } 64 | 65 | System.out.println("Height of the Tree "+HEIGHT); 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /InsertInterval.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * Created by achoudhary on 03/02/2016. 6 | */ 7 | 8 | class Interval { 9 | int start; 10 | int end; 11 | Interval() { start = 0; end = 0; } 12 | Interval(int s, int e) { start = s; end = e; } 13 | } 14 | 15 | public class InsertInterval { 16 | public List insert(List intervals, Interval newInterval) { 17 | ArrayList result = new ArrayList(); 18 | 19 | for(Interval interval: intervals){ 20 | if(interval.end < newInterval.start){ 21 | result.add(interval); 22 | }else if(interval.start > newInterval.end){ 23 | result.add(newInterval); 24 | newInterval = interval; 25 | }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){ 26 | newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end)); 27 | } 28 | } 29 | 30 | result.add(newInterval); 31 | 32 | return result; 33 | } 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /IsBinaryTreeABinarySearchTree.java: -------------------------------------------------------------------------------- 1 | public class IsBinaryTreeABinarySearchTree { 2 | 3 | public boolean isValid(Node root) { 4 | return isBTaBST(root, Integer.MIN_VALUE, 5 | Integer.MAX_VALUE); 6 | } 7 | 8 | boolean isBTaBST(Node n, int min, int max) { 9 | 10 | if (n == null || n.left == null || n.right == null) { 11 | return true; 12 | } 13 | 14 | return n.value > min && n.value < max && isBTaBST(n.left, n.value, max) 15 | && isBTaBST(n.right, min, n.value); 16 | 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /JumpGame1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 08/01/2016. 3 | */ 4 | public class JumpGame1 { 5 | 6 | public boolean canJump(int[] nums) { 7 | if(nums.length == 0) 8 | return false; 9 | 10 | int maxLength = 0; 11 | int steps = 1; 12 | for (int i = 0; i < nums.length; i++) { 13 | steps--; 14 | 15 | if(nums[i] + i > maxLength){ 16 | maxLength = nums[i] + i; 17 | steps = nums[i]; 18 | } 19 | 20 | if(steps == 0 && i < nums.length-1){ 21 | return false; 22 | } 23 | } 24 | 25 | return true; 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(new JumpGame1().canJump(new int[]{2,3,1,0,4})); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /KPM.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class KPM 5 | { 6 | 7 | public static void main(String[] args) 8 | { 9 | // TODO Auto-generated method stub 10 | String str = "AbhishekisthbestboytobeAbhishekisgoingto be amazing good but nkoiAbuishek of it but once again gringotypeAbhishekisthbestbostTo"; 11 | 12 | char[] charArray = str.toCharArray(); 13 | int pointer = 0; 14 | List list = new ArrayList<>(); 15 | List dummy = new ArrayList<>(); 16 | 17 | if (charArray.length > 1) 18 | { 19 | for (int i = 1; i < charArray.length; i++) 20 | { 21 | if(charArray[i] == charArray[pointer]){ 22 | dummy.add(""+charArray[i]); 23 | pointer++; 24 | }else{ 25 | pointer = 0; 26 | if(list.size() < dummy.size()){ 27 | list.clear(); 28 | list.addAll(dummy); 29 | } 30 | dummy.clear(); 31 | } 32 | } 33 | } 34 | else 35 | { 36 | System.err.println(str); 37 | } 38 | 39 | if(dummy.size() > list.size()){ 40 | list.clear();list.addAll(dummy); 41 | } 42 | System.out.println(list); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /LCS.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | 4 | public class LCS { 5 | 6 | public static void main(String[] args) { 7 | 8 | //String a = " ABHISHEK"; 9 | //String b = " BOAHSEK"; 10 | 11 | String a = " CHOUDHRAYABHISHEKAMAZING"; 12 | String b = " RACHELABHISHEKGOINGALONE"; 13 | 14 | 15 | char[] row = a.toCharArray(); 16 | char[] col = b.toCharArray(); 17 | 18 | int[][] table = new int[row.length][col.length]; 19 | for(int i=1;iprev2 ? prev1:prev2 ; 27 | }else if(elem == col[j]){ 28 | table[i][j] = table[i-1][j-1]+1; 29 | } 30 | 31 | 32 | } 33 | 34 | } 35 | 36 | for (int[] arr : table) { 37 | System.out.println(Arrays.toString(arr)); 38 | } 39 | 40 | int i = row.length-1; 41 | int j = col.length-1; 42 | int pointer = table[i][j]; 43 | String output = ""; 44 | while(i > 0 && j > 0){ 45 | if(pointer == table[i][j-1]){ 46 | j--; 47 | }else if(pointer == table[i-1][j]){ 48 | i--; 49 | } else{ 50 | output = output+row[i]; 51 | i--; 52 | j--; 53 | 54 | } 55 | pointer = table[i][j]; 56 | } 57 | 58 | System.out.println(output+" <- output -> "+new StringBuilder(output).reverse().toString()); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /LetterCombinationPhoneNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by abc on 28/01/2016. 8 | */ 9 | public class LetterCombinationPhoneNumber { 10 | 11 | 12 | public List letterCombinations(String digits) { 13 | 14 | List temp = new ArrayList<>(); 15 | List result = new ArrayList<>(); 16 | if(digits == null || digits.length() == 0) 17 | return result; 18 | Map map = new HashMap<>(); 19 | map.put("1",""); 20 | map.put("2","abc"); 21 | map.put("3","def"); 22 | map.put("4","ghi"); 23 | map.put("5","jkl"); 24 | map.put("6","mno"); 25 | map.put("7","pqrs"); 26 | map.put("8","tuv"); 27 | map.put("9","wxyz"); 28 | 29 | depthFirstSearch(digits,map,temp,result); 30 | return result; 31 | } 32 | 33 | private void depthFirstSearch(String digits, Map map,List temp,List result){ 34 | 35 | if(digits.length() == 0){ 36 | String out = ""; 37 | for (char ch: 38 | temp) { 39 | out += ch; 40 | } 41 | result.add(out); 42 | return; 43 | } 44 | 45 | String curr = digits.substring(0,1); 46 | String letters = map.get(curr); 47 | for (int i = 0; i < letters.length(); i++) { 48 | temp.add(letters.charAt(i)); 49 | depthFirstSearch(digits.substring(1),map,temp,result); 50 | temp.remove(temp.size()-1); 51 | } 52 | 53 | } 54 | 55 | 56 | public static void main(String[] args) { 57 | System.out.println(new LetterCombinationPhoneNumber().letterCombinations("9")); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /LevelOrderTraversalUsingRecursion.java: -------------------------------------------------------------------------------- 1 | 2 | public class LevelOrderTraversalUsingRecursion { 3 | 4 | class Node{ 5 | 6 | Node left; 7 | Node right; 8 | int value; 9 | } 10 | 11 | 12 | public void levelOrdeTraversalRecursion(Node n, int level){ 13 | 14 | 15 | if(n != null){ 16 | 17 | if(level == 0){ 18 | System.out.println(n.value); 19 | } 20 | } 21 | levelOrdeTraversalRecursion(n.left, level-1); 22 | levelOrdeTraversalRecursion(n.right, level-1); 23 | 24 | } 25 | 26 | /** 27 | * traverse each level of the tree by calling recursive method. 28 | * For example if we want to print each level till 4 (height) 29 | * --- 30 | * Then recursion will traverse each level and negate as shown above , 4-1 , 4-2, 4-3 ,4-4 31 | * and ultimately it will reach the level 4 the value will become 0 , and it will print 32 | * 33 | * @param root 34 | * @param depth 35 | */ 36 | public void traversal(Node root,int depth){ 37 | for(int i=0;i output = new LinkedList<>(); 17 | List proxy = new LinkedList<>(); 18 | proxy.add(pointer); 19 | 20 | for(int i=1;i 1){ 24 | if(output.size() < proxy.size()){ 25 | output.clear(); 26 | output.addAll(proxy); 27 | } 28 | } 29 | proxy.clear(); 30 | 31 | 32 | } 33 | pointer = val[i]; 34 | proxy.add(pointer); 35 | } 36 | 37 | System.err.println(output); 38 | 39 | } 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /LongestSubStringContainKUniqueCharacter.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /** 4 | * Created by achoudhary on 23/12/2015. 5 | * 6 | * Logic behind the solution - 7 | * Iterate through each character of the input and fill a map with each iterating unique character upto K and build 8 | * a tracker string till the point the map size crosses K. 9 | * As soon as it crosses K, it means other extra character has encountered so tracker currently holds a series of 10 | * string with k unique characters, 11 | * So now its new character, clear the map and do same as aobove but in reverse direction of "tracker" and 12 | * first element of the map will be the new encountered character the 1st half of the logic. Once you have map 13 | * filled with k characters, start the llop or resume i. 14 | */ 15 | public class LongestSubStringContainKUniqueCharacter { 16 | 17 | 18 | public String getLongestStringWithKUniqueCharacters(String input, int k) { 19 | String output = ""; 20 | HashMap map = new HashMap<>(); 21 | String tracker = ""; 22 | 23 | for (int i = 0; i < input.length(); i++) { 24 | char ch = input.charAt(i); 25 | if (map.size() <= k) { 26 | map.put(ch, 0); 27 | tracker += ch; 28 | } 29 | 30 | //windowing logic, track back and refill the map 31 | //with K new items , if found 32 | if (map.size() == k + 1) { 33 | output = ((tracker.length() - 1) > output.length()) ? tracker.substring(0, tracker.length() - 1) : output; 34 | map.clear(); //clears the map to refill 35 | 36 | String proxy = ""; 37 | int backIndex = tracker.length() - 1; 38 | char curr = '\0'; 39 | while (map.size() != k + 1 && backIndex > -1) { 40 | curr = tracker.charAt(backIndex--); 41 | proxy = curr + proxy; //add the new element in the end always 42 | map.put(curr, 0); 43 | } 44 | map.remove(curr); 45 | tracker = proxy.substring(1, proxy.length()); 46 | } 47 | 48 | } 49 | 50 | 51 | if (map.size() != k) { 52 | output = ""; 53 | } else { 54 | output = (tracker.length() > output.length()) ? tracker : output; 55 | } 56 | 57 | return output; 58 | } 59 | 60 | public static void main(String[] args) { 61 | System.out.println("Longest Substring With K Unique Characterd : " + new LongestSubStringContainKUniqueCharacter().getLongestStringWithKUniqueCharacters("abcbbbbcccbdddadacb", 3)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /LongestValidParenthesis.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Created by abc on 03/01/2016. 5 | * 6 | * Use stack to track each starting parenthesis and pop out when closing comes 7 | * 1. If there is a situation when stack is empty it does mean there is either no starting parenthesis 8 | * so all invalid location , so maintain a pointer till we don't reach a valid index where a starting 9 | * parenthesis is available. 10 | * 11 | * 2. So any situation when we get a closing index , we can find the last longest possible pair 12 | * is with current index - last perfect index. 13 | * 14 | * 3. In any case if stack is non empty but we are popping value it does mean we can find the longest 15 | * pair till the index of value present in the head of Stack because head of the stack is the last 16 | * known starting parenthesis which couldn't get any closing yet, so get the longest streak from 17 | * current index - stack.peek() 18 | * 19 | * 20 | * @link https://leetcode.com/problems/longest-valid-parentheses/ 21 | */ 22 | 23 | public class LongestValidParenthesis { 24 | 25 | 26 | public int longestValidParentheses(String s) { 27 | if(s == null || s.length() == 0){ 28 | return 0; 29 | } 30 | int result = 0; 31 | Stack stack = new Stack<>(); 32 | int lastEmptyState = -1; 33 | for(int i=0;i queue = new Stack(); 14 | char pop = 'c'; 15 | if(charArray.length <= 1) 16 | return false; 17 | for (char c : charArray) { 18 | if(c == '(' || c == '{' || c == '['){ 19 | queue.push(c); 20 | }else{ 21 | 22 | if(queue.size()>0){ 23 | pop = queue.pop(); 24 | }else{ 25 | System.out.println("EXTRA"); 26 | output = false; 27 | break; 28 | } 29 | if(c == ')' && pop == '('){ 30 | continue; 31 | } 32 | else if(c == '}' && pop == '{'){ 33 | continue; 34 | } 35 | else if(c == ']' && pop == '['){ 36 | continue; 37 | }else{ 38 | //System.out.println("POPPP "+pop+" CC "+c+" count "+count); 39 | output = false; 40 | break; 41 | } 42 | } 43 | } 44 | if(queue.size() >0) 45 | output = false; 46 | return output; 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /MedianOfTwoSortedArray_WithLogComplexity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by abc on 26/12/2015. 3 | * 4 | * 1) Calculate the medians m1 and m2 of the input arrays ar1[] 5 | and ar2[] respectively. 6 | 2) If m1 and m2 both are equal then we are done. 7 | return m1 (or m2) 8 | 3) If m1 is greater than m2, then median is present in one 9 | of the below two subarrays. 10 | a) From first element of ar1 to m1 (ar1[0...|_n/2_|]) 11 | b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1]) 12 | 4) If m2 is greater than m1, then median is present in one 13 | of the below two subarrays. 14 | a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1]) 15 | b) From first element of ar2 to m2 (ar2[0...|_n/2_|]) 16 | 5) Repeat the above process until size of both the subarrays 17 | becomes 2. 18 | 6) If size of the two arrays is 2 then use below formula to get 19 | the median. 20 | Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2 21 | */ 22 | import java.util.*; 23 | public class MedianOfTwoSortedArray_WithLogComplexity { 24 | 25 | 26 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 27 | 28 | return findMedian(nums1,0 , nums1.length,nums2,0,nums2.length); 29 | } 30 | 31 | 32 | 33 | private double findMedian(int[] array1, int arr1Start, int arr1End , int[] array2, int arr2Start,int arr2End){ 34 | 35 | 36 | if(array1.length == 0 && array2.length != 0){ 37 | return array2[getMedian(array2)]; 38 | }else if(array2.length == 0 && array1.length != 0){ 39 | return array1[getMedian(array1)]; 40 | } 41 | //if size == 2 for both th array. 42 | else if(array1.length == 2 && array2.length == 2){ 43 | return (Math.max(array1[0], array2[0]) + Math.min(array1[1], array2[1]))/2; 44 | } else if(array1.length == 1 && array2.length == 2){ 45 | return array1[0]; 46 | } 47 | 48 | int[] arr1 = Arrays.copyOfRange(array1, arr1Start, arr1End); 49 | int[] arr2 = Arrays.copyOfRange(array2, arr2Start, arr2End); 50 | int first = getMedian(arr1); 51 | int second = getMedian(arr2); 52 | 53 | 54 | 55 | //if arr1 > arr2 , then sub array 56 | // arr1 = 0 .... median of arr1 57 | // arr2 = median of arr2 .... end 58 | if(arr1[first] == arr2[second]){ 59 | return arr1[first]; 60 | } 61 | else if(arr1[first] > arr2[second]){ 62 | return findMedian(arr1,0 , first+1, arr2,second, arr2.length); 63 | }else{ 64 | return findMedian(arr1,first , arr1.length, arr2,0, second+1); 65 | } 66 | 67 | } 68 | 69 | 70 | //find median of an array based on odd and even 71 | //number of items 72 | public int getMedian(int[] arr){ 73 | int n = arr.length; 74 | if(n % 2 == 0){ 75 | return (n + (n/2 -1))/2; 76 | }else{ 77 | return n/2; 78 | } 79 | } 80 | 81 | 82 | 83 | public static void main(String[] args){ 84 | int[] arr1 = {1}; 85 | int[] arr2 = {2, 3}; 86 | System.out.println(" Median of Sorted Array "+new MedianOfTwoSortedArray_WithLogComplexity().findMedianSortedArrays(arr1, arr2)); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /MergeIntervals.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by achoudhary on 01/02/2016. 8 | */ 9 | 10 | 11 | class Interval { 12 | int start; 13 | int end; 14 | Interval() { start = 0; end = 0; } 15 | Interval(int s, int e) { start = s; end = e; } 16 | } 17 | 18 | 19 | public class MergeIntervals { 20 | 21 | public List merge(List intervals) { 22 | 23 | if(intervals.size() <= 1){ 24 | return intervals; 25 | } 26 | 27 | 28 | Collections.sort(intervals,(Interval o1, Interval o2) -> o1.start - o2.start); 29 | 30 | 31 | List result = new ArrayList<>(); 32 | 33 | Interval prev = intervals.get(0); 34 | for (int i = 1; i = curr.start){ 39 | Interval merged = new Interval(prev.start,Math.max(prev.end,curr.end)); 40 | prev = merged; 41 | }else{ 42 | result.add(prev); 43 | prev = curr; 44 | } 45 | 46 | 47 | } 48 | 49 | result.add(prev); 50 | 51 | return result; 52 | } 53 | 54 | 55 | public static void main(String[] args) { 56 | List list = new ArrayList<>(); 57 | 58 | list.add(new Interval(1,4)); 59 | list.add(new Interval(4,5)); 60 | List res = new MergeIntervals().merge(list); 61 | for (Interval i: 62 | res) { 63 | System.out.println(i.start+" "+i.end); 64 | } 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /MergeKSortedList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.PriorityQueue; 3 | 4 | /** 5 | * Created by abc on 31/12/2015. 6 | * Using priorityQueue or concept of heap to solve the problem. 7 | * Just need to implement the comparator 8 | */ 9 | public class MergeKSortedList { 10 | 11 | 12 | 13 | 14 | public ListNode mergeKLists(ListNode[] lists) { 15 | if(null == lists || lists.length ==0){ 16 | return null; 17 | } 18 | 19 | PriorityQueue heap = new PriorityQueue(lists.length,new Comparator(){ 20 | public int compare(ListNode node1 , ListNode node2){ 21 | if(node1.val > node2.val){ 22 | return 1; 23 | } 24 | if(node1.val == node2.val){ 25 | return 0; 26 | }else 27 | return -1; 28 | } 29 | }); 30 | 31 | //just add the header of each ListNode 32 | 33 | for (ListNode node: 34 | lists) { 35 | if(node != null){ 36 | heap.add(node); 37 | } 38 | } 39 | 40 | ListNode result = new ListNode(0); 41 | ListNode dummy = result; 42 | while(heap.size() > 0){ 43 | ListNode np = heap.poll(); 44 | dummy.next = np; 45 | 46 | //since we have header of each list node previously 47 | //now we will simply get next element of each pop element and add to heap 48 | //automatically it will match with previous 49 | if(np.next != null){ 50 | heap.add(np.next); 51 | } 52 | dummy = dummy.next; 53 | 54 | } 55 | 56 | return result.next; 57 | } 58 | 59 | public static void main(String[] args) { 60 | new MergeKSortedList().mergeKLists(null); 61 | } 62 | } 63 | 64 | // Definition for singly-linked list. 65 | class ListNode { 66 | int val; 67 | ListNode next; 68 | 69 | ListNode(int x) { 70 | val = x; 71 | next = null; 72 | } 73 | } 74 | 75 | -------------------------------------------------------------------------------- /MinimumEditDistance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 21/12/2015. 3 | */ 4 | import java.util.*; 5 | 6 | public class MinimumEditDistance { 7 | 8 | 9 | /** 10 | * 11 | * @param word1 12 | * @param word2 13 | * @return 14 | */ 15 | public int minSteps(String word1, String word2){ 16 | char[] charFirst = word1.toCharArray(); //Ctrl+Alt+V 17 | char[] charSec = word2.toCharArray(); 18 | 19 | int[][] table = new int[charSec.length+1][charFirst.length+1]; //column representation is first 20 | 21 | //creating the first skeleton row and column filling 22 | for(int i=0;i<= charFirst.length;i++){ 23 | table[0][i] = i; 24 | } 25 | 26 | for(int i=0;i<= charSec.length;i++){ 27 | table[i][0] = i; 28 | } 29 | 30 | 31 | //make sure to update the array with one increment 32 | //if we keep i it actually means previous row as (i+1) is the main 33 | // row to be tracked as we are supposed to ignore first row and first 34 | //column with default value 35 | for(int i=0;i "+new MinimumEditDistance().minSteps("abcdef","azced")) ; 51 | } 52 | 53 | public void printGrid(int[][] input) 54 | { 55 | for(int i = 0; i < input.length; i++) 56 | { 57 | for(int j = 0; j < input[0].length; j++) 58 | { 59 | System.out.printf("%5d ", input[i][j]); 60 | } 61 | System.out.println(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /ParseStringToInteger.java: -------------------------------------------------------------------------------- 1 | 2 | public class ParseStringToInteger 3 | { 4 | 5 | public static void main(String[] args) 6 | { 7 | System.out.println(new ParseStringToInteger().atoi("-2147483648")); 8 | } 9 | 10 | 11 | 12 | public int atoi(String str) { 13 | 14 | str = str.trim(); 15 | double output = 0; 16 | int counter = 0; 17 | boolean suffix = false; 18 | if(str.length() <= 0){ 19 | return 0; 20 | } 21 | if(str.charAt(0) == '-'){ 22 | suffix = true; 23 | counter++; 24 | }else if(str.charAt(0) == '+'){ 25 | counter++; 26 | } 27 | for(int i=counter;i= '0' && ch <= '9'){ 30 | output = output*10 +(ch-'0'); 31 | counter++; 32 | }else{ 33 | break; 34 | } 35 | } 36 | if(suffix){ 37 | output = -output; 38 | } 39 | if(output > Integer.MAX_VALUE){ 40 | output = Integer.MAX_VALUE; 41 | } 42 | if(output <= Integer.MIN_VALUE){ 43 | output = Integer.MIN_VALUE; 44 | } 45 | 46 | return (int) output; 47 | 48 | 49 | 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /PartitionList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 08/03/2016. 3 | */ 4 | 5 | public class PartitionList { 6 | 7 | /** 8 | * create 2 list 9 | * add all values less than x to list1 and greater than to list2 10 | * then merge the list in the end 11 | * @param head 12 | * @param x 13 | * @return 14 | */ 15 | public ListNode partition(ListNode head, int x) { 16 | 17 | if(head == null) 18 | return null; 19 | 20 | ListNode result = new ListNode(0); 21 | ListNode clone = new ListNode(0); 22 | ListNode p1 = result; 23 | ListNode p2 = clone; 24 | 25 | while(head != null){ 26 | if(head.val < x){ 27 | p1.next= head; 28 | p1 = p1.next; 29 | }else{ 30 | p2.next = head; 31 | p2 = p2.next; 32 | } 33 | head = head.next; 34 | } 35 | 36 | //reset the 2nd list final value to null 37 | p2.next = null; 38 | //merge both the list to build a big list 39 | p1.next = clone.next; 40 | return result.next; 41 | } 42 | 43 | public static void main(String[] args) { 44 | 45 | 46 | } 47 | } 48 | 49 | 50 | 51 | // Definition for singly-linked list. 52 | -------------------------------------------------------------------------------- /PathSum2.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class PathSum2 { 5 | 6 | public List> pathSum(TreeNode root, int sum) { 7 | List> mainList = new ArrayList<>(); 8 | findPath(root,sum,mainList,new ArrayList()); 9 | return mainList; 10 | } 11 | 12 | 13 | public void findPath(TreeNode root, int sum, List> mainList, ArrayList arrayList){ 14 | if(root == null) 15 | return; 16 | 17 | arrayList.add(root.val); 18 | sum -= root.val; 19 | if(root.left == null && root.right == null && sum == 0){ 20 | mainList.add(new ArrayList(arrayList)); 21 | }else{ 22 | findPath(root.left,sum,mainList,arrayList); 23 | findPath(root.right,sum,mainList,arrayList); 24 | } 25 | 26 | arrayList.remove(arrayList.size() - 1); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Permutation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created by abc on 10/01/2016. 5 | */ 6 | public class Permutation { 7 | 8 | public List> permuteUnique(int[] nums) { 9 | List> result = new ArrayList<>(); 10 | 11 | //starts with 1st index 12 | return findPermutation(nums,0, result); 13 | } 14 | 15 | public List> findPermutation(int[] nums, int startIndex , List> result){ 16 | 17 | //if length of start increases the length of input , means we found 18 | //all values , add it to list 19 | if(startIndex >= nums.length){ 20 | result.add(convertToList(nums)); 21 | } 22 | 23 | for (int i = startIndex; i < nums.length; i++) { 24 | //swaps each index of item with all other index of items 25 | //recursively 26 | swap(nums,startIndex,i); 27 | //find the next permutation from start+1 index till last item 28 | findPermutation(nums,startIndex+1,result); 29 | swap(nums,startIndex,i); 30 | } 31 | 32 | return result; 33 | } 34 | 35 | 36 | private List convertToList(int[] array){ 37 | List list = new ArrayList<>(); 38 | for (int i: 39 | array) { 40 | list.add(i); 41 | } 42 | return list; 43 | } 44 | 45 | 46 | private int[] swap(int[] a , int i, int j){ 47 | if(i != j) { 48 | int temp = a[i]; 49 | a[i] = a[j]; 50 | a[j] = temp; 51 | } 52 | 53 | return a; 54 | } 55 | 56 | public static void main(String[] args) { 57 | List> result = new Permutation().permuteUnique(new int[]{1,2,3}); 58 | for (List value: 59 | result) { 60 | System.out.println("-> "+value); 61 | } 62 | //System.out.println("Permutations "+ new Permutation().permuteUnique(new int[]{1,2,3})); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /PowOfn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 11/02/2016. 3 | */ 4 | public class PowOfn { 5 | 6 | 7 | public double power(double x , int n){ 8 | if(n == 0) 9 | return 1; 10 | //just multiple only half of the value and 11 | //simply multiply it twice to get 12 | double value = power(x,n/2); 13 | 14 | 15 | if(n % 2 == 0){ 16 | //means it the pair of 2 values 17 | return value * value; 18 | }else{ 19 | //its odd pair so multiply again 20 | return value * value * x; 21 | } 22 | } 23 | 24 | public double myPow(double x, int n) { 25 | if(n < 0){ 26 | return 1/power(x , -n); 27 | }else{ 28 | return power(x,n); 29 | } 30 | 31 | } 32 | 33 | public static void main(String[] args) { 34 | double v = new PowOfn().myPow(6, 11); 35 | System.out.println(v); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Awesome_Algorithm 2 | -------------------------------------------------------------------------------- /RandomNumberGenerator.java: -------------------------------------------------------------------------------- 1 | 2 | public class RandomNumberGenerator { 3 | 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | 7 | //String input = "1234 5678 123 12345 9876"; 8 | String input = "3 2 5 1 7"; 9 | String[] inarr = input.split(" "); 10 | if(inarr.length==5){ 11 | int A = Integer.parseInt(inarr[0]); 12 | int B = Integer.parseInt(inarr[1]); 13 | int X = Integer.parseInt(inarr[2]); 14 | int K = Integer.parseInt(inarr[3]); 15 | int M = Integer.parseInt(inarr[4]); 16 | //(A * X + B) % M 17 | for(int i=0;i= K-1) 19 | System.out.println(X); 20 | X = (A * X + B) % M; 21 | 22 | } 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /RecursiveLinkedList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class RecursiveLinkedList { 5 | 6 | class Node { 7 | int i; 8 | 9 | public Node(int i) { 10 | this.i = i; 11 | } 12 | 13 | Node next; 14 | } 15 | 16 | public void create(int count) { 17 | List nlist = new ArrayList<>(); 18 | for (int i = 0; i < count; i++) { 19 | nlist.add(new Node(i)); 20 | } 21 | for (int i = 0; i < nlist.size() - 1; i++) { 22 | Node node = nlist.get(i); 23 | node.next = nlist.get(i + 1); 24 | } 25 | 26 | Node node = nlist.get(0); 27 | while (node.next != null) { 28 | System.out.print(node.i + "->"); 29 | node = node.next; 30 | } 31 | System.out.println(node.i); 32 | System.out.println("---------------------"); 33 | System.out.println(); 34 | reverse(nlist.get(0)); 35 | 36 | } 37 | 38 | private void reverse(Node node) { 39 | if (node == null) 40 | return; 41 | Node rest = node.next; 42 | if (rest == null) 43 | return; 44 | reverse(node.next); 45 | System.out.println(rest.i + " b " + node.i); 46 | node.next.next = node; 47 | node.next = null; 48 | node = rest; 49 | 50 | // rest.next = node; 51 | System.out.println(rest.i + " " + node.i); 52 | 53 | // rest.next.next = null; 54 | // while (node.next != null) { 55 | // System.out.print(node.i + "->"); 56 | // node = node.next; 57 | // } 58 | 59 | } 60 | 61 | public static void main(String[] args) { 62 | new RecursiveLinkedList().create(10); 63 | } 64 | } 65 | 66 | /* 67 | * Copyright 2004-2015 Pilz Ireland Industrial Automation Ltd. All Rights 68 | * Reserved. PILZ PROPRIETARY/CONFIDENTIAL. 69 | * 70 | * Created on 2 Jun 2015 71 | */ -------------------------------------------------------------------------------- /RegularExpressionMatching.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 29/12/2015. 3 | */ 4 | public class RegularExpressionMatching { 5 | 6 | 7 | public boolean isMatch(String s, String p) { 8 | 9 | if(p.length() == 0) 10 | return s.length() == 0; 11 | 12 | if(p.length() == 1 || p.charAt(1) != '*'){ 13 | if(s.length() < 1 || (p.charAt(0) != '.' && p.charAt(0) != s.charAt(0))){ 14 | return false; 15 | } 16 | return isMatch(s.substring(1),p.substring(1)); 17 | }else{ 18 | //current index character will be * 19 | //now traverse through each element and check 20 | //since this loop is checking the current character is * , so to pass or match any regex 21 | //it must check the current chracter is either . or exactly matching the character 22 | int len = s.length(); 23 | int i = -1; 24 | while(i < len && (i < 0 || (p.charAt(0) == '.') || p.charAt(0) == s.charAt(i))){ 25 | //if matches happens pass the next character and pattern -> next -> next 26 | //so if [isMatch("abccc",".*bc*")] 27 | //then now it will pass b and c for validation 28 | if(isMatch(s.substring(i+1),p.substring(2))){ 29 | return true; 30 | } 31 | i++; 32 | } 33 | return false; 34 | } 35 | 36 | 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println("Regex matching with Recursion : " + new RegularExpressionMatching().isMatch("aab", "c*a*b")); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /RemoveDuplicateFromSortedArrayII.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | public class RemoveDuplicateFromSortedArrayII 5 | { 6 | 7 | 8 | /** 9 | * Definition for singly-linked list.*/ 10 | public class ListNode { 11 | int val; 12 | ListNode next; 13 | ListNode(int x) { val = x; } 14 | } 15 | 16 | 17 | public ListNode deleteDuplicates(ListNode head) { 18 | ListNode n = new ListNode(0); 19 | n.next = head; 20 | 21 | ListNode p = n; 22 | while(p.next != null && p.next.next != null){ 23 | if(p.next.val == p.next.next.val){ 24 | int duplicate = p.next.val; 25 | 26 | while(p.next != null && p.next.val == duplicate){ 27 | p.next = p.next.next; 28 | } 29 | }else{ 30 | p = p.next; 31 | } 32 | } 33 | 34 | return n.next; 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.List; 3 | 4 | 5 | 6 | 7 | public class RemoveDuplicates 8 | { 9 | 10 | 11 | public static void main(String[] args) 12 | { 13 | int[] nums = {1,1,1,2}; 14 | 15 | int prev = -1; 16 | int index = 0; 17 | int count =0; 18 | List values = new LinkedList<>(); 19 | while(index < nums.length){ 20 | int curr = nums[index]; 21 | 22 | if(curr != prev){ 23 | values.add(curr); 24 | count = 1; 25 | }else if(curr == prev && count < 2){ 26 | values.add(curr); 27 | count++; 28 | }else { 29 | System.err.println(count); 30 | count++; 31 | } 32 | prev = curr; 33 | index++; 34 | } 35 | 36 | 37 | System.err.println(values); 38 | } 39 | 40 | 41 | 42 | 43 | } 44 | 45 | /* 46 | * Copyright 2004-2015 Pilz Ireland Industrial Automation Ltd. All Rights 47 | * Reserved. PILZ PROPRIETARY/CONFIDENTIAL. 48 | * 49 | * Created on 9 Oct 2015 50 | */ -------------------------------------------------------------------------------- /RemoveNNodeFromLast.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | 5 | public class RemoveNNodeFromLast { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | new RemoveNNodeFromLast(); 10 | } 11 | 12 | 13 | public RemoveNNodeFromLast() { 14 | ListNode node1 = new ListNode(1); 15 | ListNode node2 = new ListNode(2); 16 | ListNode node3 = new ListNode(3); 17 | ListNode node4 = new ListNode(4); 18 | ListNode node5 = new ListNode(5); 19 | node1.next = node2; 20 | node2.next = node3; 21 | node3.next = node4; 22 | node4.next = node5; 23 | 24 | ListNode removeNthFromEnd = removeNthFromEnd(node1, 2); 25 | while(removeNthFromEnd.next != null){ 26 | System.out.print(removeNthFromEnd.val+"->"); 27 | removeNthFromEnd = removeNthFromEnd.next; 28 | } 29 | System.out.print(removeNthFromEnd.val); 30 | } 31 | 32 | public ListNode removeNthFromEnd(ListNode head, int n) { 33 | ListNode main = head; 34 | ListNode ref = head; 35 | int i =0; 36 | 37 | while(i < n){ 38 | System.out.println("kya "+ref.val); 39 | ref = ref.next; 40 | i++; 41 | } 42 | if(ref == null) 43 | return main.next; 44 | while(ref.next != null){ 45 | main = main.next; 46 | ref = ref.next; 47 | } 48 | main.next = main.next.next; 49 | 50 | return head; 51 | } 52 | 53 | 54 | 55 | /** 56 | * Definition for singly-linked list.*/ 57 | public class ListNode { 58 | int val; 59 | ListNode next; 60 | ListNode(int x) { val = x; } 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /ReverseNodesInKGroup.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 30/12/2015. 3 | * 4 | * Iterate through head and make a pointer to record each k move. 5 | * Before that keep a pointer to the starting point in each move/group ie prev. 6 | * 7 | * As soon as any group caught or i ==k , reverse the group with prev which holds 8 | * the 1- starting point of each group till the 1 + curent tracker, its like 9 | * reverse everything inbetween 10 | */ 11 | 12 | 13 | // Definition for singly-linked list. 14 | class ListNode { 15 | int val; 16 | ListNode next; 17 | ListNode(int x) { val = x; } 18 | } 19 | 20 | 21 | public class ReverseNodesInKGroup { 22 | 23 | public ListNode reverseKGroup(ListNode head, int k) { 24 | 25 | ListNode curr = new ListNode(0); 26 | curr.next = head; 27 | 28 | ListNode prev = curr; 29 | int i=0; 30 | 31 | while(head != null){ 32 | i++; 33 | //if i equals k, means the group has determined 34 | //now reverse the group 35 | if(i == k){ 36 | i =0; 37 | prev = reverse(prev,head.next); 38 | //we got the reverse version , now move the head to next of returned node 39 | head = prev.next; 40 | }else{ 41 | head = head.next; 42 | } 43 | } 44 | return curr.next; 45 | } 46 | 47 | //reverse the 48 | private ListNode reverse(ListNode start, ListNode end){ 49 | ListNode last=start.next; 50 | ListNode cur=last.next; 51 | 52 | while (cur!=end){ 53 | 54 | last.next=cur.next; 55 | cur.next=start.next; 56 | start.next=cur; 57 | 58 | cur=last.next; 59 | } 60 | return last; 61 | } 62 | 63 | 64 | public static void main(String[] args) { 65 | int[] nodes = {2,3,4,5,6,7,8,9,10,11}; 66 | ListNode curr = null; 67 | ListNode next = new ListNode(1); 68 | curr = next; 69 | for(int i : nodes){ 70 | ListNode node = new ListNode(i); 71 | next.next = node; 72 | next = next.next; 73 | } 74 | 75 | 76 | ListNode test = curr; 77 | //pprint( new ReverseNodesInKGroup().reverseKGroup(test1,2)); 78 | pprint( new ReverseNodesInKGroup().reverseKGroup(test,3)); 79 | //pprint( new ReverseNodesInKGroup().reverseKGroup(test3,5)); 80 | 81 | 82 | } 83 | 84 | private static void pprint(ListNode node){ 85 | while (node != null){ 86 | System.out.print(node.val+" -> "); 87 | node = node.next; 88 | } 89 | System.out.println(); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /RotateImageInPlace.java: -------------------------------------------------------------------------------- 1 | public class RotateImageInPlace 2 | { 3 | 4 | public void rotate(int[][] matrix) 5 | { 6 | 7 | 8 | printArray(matrix, "MAIN ARRAY"); 9 | 10 | //rotate diagonally A = A' 11 | for (int i = 0; i < matrix.length; i++) 12 | { 13 | for (int j = i; j < matrix.length; j++) 14 | { 15 | if(i != j){ 16 | int temp = matrix[i][j]; 17 | matrix[i][j] = matrix[j][i]; 18 | matrix[j][i] = temp; 19 | } 20 | } 21 | } 22 | 23 | printArray(matrix, "A = A'"); 24 | 25 | 26 | //final rotoate the rowwith last to first sequenctially 27 | for (int i = 0; i < matrix.length; i++) 28 | { 29 | for (int j = 0; j < matrix.length/2; j++) 30 | { 31 | int temp = matrix[i][j]; 32 | matrix[i][j] = matrix[i][matrix.length-(j+1)]; 33 | matrix[i][matrix.length-(j+1)] = temp; 34 | } 35 | } 36 | 37 | printArray(matrix, "AFTER ROTATION"); 38 | } 39 | 40 | private void printArray(int[][] matrix,String Title){ 41 | System.out.println(Title); 42 | System.out.println("---------------"); 43 | for (int i = 0; i < matrix.length; i++) 44 | { 45 | for (int j = 0; j < matrix.length; j++) 46 | { 47 | System.out.print(matrix[i][j]+"\t"); 48 | } 49 | System.out.println(); 50 | } 51 | 52 | System.out.println("\n\n"); 53 | 54 | } 55 | 56 | public static void main(String[] args) 57 | { 58 | // TODO Auto-generated method stub 59 | int[][] matrix = new int[][]{ 60 | {1,2,3,4}, 61 | {5,6,7,8}, 62 | {9,10,11,12}, 63 | {13,14,15,16} 64 | }; 65 | 66 | new RotateImageInPlace().rotate(matrix); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /ScrambleString.java: -------------------------------------------------------------------------------- 1 | public class ScrambleString { 2 | 3 | public static void main(String[] args) { 4 | // TODO Auto-generated method stub 5 | System.err.println("==> " + new ScrambleString().isScramble("great", "rgtae")); 6 | } 7 | 8 | public boolean isScramble(String s1, String s2) { 9 | if (s1.length() != s2.length()) 10 | return false; 11 | if (s1.equals(s2)) 12 | return true; 13 | 14 | int[] proxy = new int[26]; 15 | int L = s1.length(); 16 | for (int i = 0; i < L; i++) { 17 | proxy[s1.charAt(i) - 'a']++; 18 | proxy[s2.charAt(i) - 'a']--; 19 | } 20 | 21 | for (int i = 0; i < 26; i++) { 22 | if (proxy[i] != 0) 23 | return false; 24 | } 25 | 26 | 27 | for (int i = 1; i < L; i++) { 28 | String s11 = s1.substring(0, i); 29 | String s12 = s1.substring(i, L); 30 | String s21 = s2.substring(0, i); 31 | String s22 = s2.substring(i, L); 32 | 33 | if (isScramble(s11, s21) && isScramble(s12, s22)) 34 | return true; 35 | s21 = s2.substring(0, L - i); 36 | s22 = s2.substring(L - i, L); 37 | if (isScramble(s11, s22) && isScramble(s12, s21)) 38 | return true; 39 | } 40 | 41 | return false; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /SearchInRotatedArrayII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 22/02/2016. 3 | */ 4 | public class SearchInRotatedArrayII { 5 | 6 | public boolean search(int[] nums, int target) { 7 | int left = 0; 8 | int right = nums.length-1; 9 | 10 | while(left <= right){ 11 | int mid = (left + right)/2; 12 | if(nums[mid] == target) 13 | return true; 14 | 15 | if(nums[left] < nums[mid]){ 16 | if(nums[left] <= target && target < nums[mid]){ 17 | right = mid-1; 18 | }else{ 19 | left = mid+1; 20 | } 21 | }else if(nums[left] > nums[mid]){ 22 | if(nums[mid] < target && target <= nums[right]){ 23 | left = mid+1; 24 | }else{ 25 | right = mid -1; 26 | } 27 | }else{ 28 | left++; 29 | } 30 | } 31 | 32 | 33 | return false; 34 | } 35 | 36 | 37 | public static void main(String[] args) { 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /SearchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 04/01/2016. 3 | * 4 | * Simple Binary Search operation with critical finding of how target falls under category 5 | * https://leetcode.com/problems/search-in-rotated-sorted-array/ 6 | */ 7 | public class SearchInRotatedSortedArray { 8 | 9 | public int search(int[] nums, int target) { 10 | 11 | return tweakedBinarySearch(nums,0,nums.length-1,target); 12 | } 13 | 14 | public int tweakedBinarySearch(int[] nums, int left, int right, int target){ 15 | if(nums == null || nums.length == 0 || left > right){ 16 | return -1; 17 | } 18 | 19 | int mid = left + (right -left)/2; 20 | if(target == nums[mid]){ 21 | return mid; 22 | } 23 | 24 | 25 | //if right rotated 26 | //7 8 9 0 1 2 3 4 5 6 7 27 | if(nums[left] > nums[mid]){ 28 | if((target > nums[mid] && target > nums[right]) || (target < nums[mid])){ 29 | return tweakedBinarySearch(nums,left,mid-1,target); 30 | }else{ 31 | return tweakedBinarySearch(nums,mid+1,right,target); 32 | } 33 | }else{ 34 | //left rotated 35 | //3 4 5 6 7 8 9 0 1 2 36 | if((target > nums[mid] && target > nums[left]) || (target < nums[mid] && target < nums[left])){ 37 | return tweakedBinarySearch(nums,mid+1,right,target); 38 | }else{ 39 | return tweakedBinarySearch(nums,left,mid-1,target); 40 | } 41 | } 42 | 43 | } 44 | 45 | public static void main(String[] args) { 46 | System.out.println(new SearchInRotatedSortedArray().search(new int[]{7,8,9,0,1,2,3,4,5,6},7)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | 2 | public class SearchInsertPosition 3 | { 4 | 5 | public static void main(String[] args) 6 | { 7 | int[] input ={1,3,5,6}; 8 | int output = new SearchInsertPosition().searchInsert(input, 10); 9 | System.out.println(output); 10 | } 11 | 12 | public int searchInsert(int[] nums, int target) { 13 | return binarySearch(nums, target); 14 | } 15 | 16 | 17 | private int binarySearch(int[] nums , int target){ 18 | int lo = 0; 19 | int hi = nums.length-1; 20 | int nearestkey = 0; 21 | while(lo <= hi){ 22 | int mid = lo + (hi -lo)/2; 23 | if(target < nums[mid]){ 24 | hi = mid-1; 25 | }else if(target > nums[mid]){ 26 | lo = mid+1; 27 | }else{ 28 | return mid; 29 | } 30 | nearestkey = Math.max(hi, lo); 31 | } 32 | return nearestkey; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /SpiralAlgorithm.java: -------------------------------------------------------------------------------- 1 | public class SpiralAlgorithm { 2 | 3 | public static void findSpiral(int x, int y, int count) { 4 | 5 | int i = 0; 6 | while (i < count) { 7 | if (x <= 0 && y <= 0 && x == y) { 8 | if (y < 0) 9 | y = -y; 10 | y++; 11 | } else if (x < y) { 12 | if (x < 0) 13 | x = -x; 14 | x++; 15 | } else if (x == y) { 16 | y = -y; 17 | } else if (x > y) { 18 | x = -x; 19 | } 20 | System.out.println("(" + x + " ," + y + ")"); 21 | i++; 22 | } 23 | 24 | } 25 | 26 | public static void main(String[] args) { 27 | findSpiral(-1, -1, 15); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /StringPermutation.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | //read recursive version of permutation from https://www.youtube.com/watch?v=MQcwxQK2DPA 5 | 6 | public class StringPermutation 7 | { 8 | 9 | public static void main(String[] args) 10 | { 11 | // TODO Auto-generated method stub 12 | String input = "abhiSheK"; 13 | List permute = StringPermutation.permute(input); 14 | for (String string : permute) 15 | { 16 | System.out.println("--> "+string); 17 | } 18 | } 19 | 20 | public static List permute(String str){ 21 | ArrayList permutations = new ArrayList(); 22 | if(str == null){ 23 | return null; 24 | } 25 | else if(str.length() == 0){ 26 | permutations.add(""); 27 | return permutations; 28 | } 29 | 30 | 31 | char ch = str.charAt(0); 32 | String remainder = str.substring(1); 33 | List wordList = permute(remainder); 34 | 35 | for (String word : wordList) 36 | { 37 | for(int i=0;i<=word.length();i++){ 38 | permutations.add(insertCharAt(word,ch,i)); 39 | } 40 | } 41 | return permutations; 42 | } 43 | 44 | public static String insertCharAt(String word, char ch, int i){ 45 | String start = word.substring(0,i); 46 | String end = word.substring(i); 47 | return start + ch + end; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /SubSetsofSet.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | 6 | public class SubSetsofSet 7 | { 8 | 9 | 10 | 11 | 12 | 13 | 14 | private List> subsetsAgain(List list, int index){ 15 | List> allSubsets = null; 16 | 17 | if(list.size() == index){ 18 | allSubsets = new ArrayList<>(); 19 | allSubsets.add(new ArrayList()); 20 | return allSubsets; 21 | } 22 | 23 | int value = list.get(index); 24 | allSubsets = subsetsAgain(list, index+1); 25 | 26 | List> output = new ArrayList<>(); 27 | for (List list2 : allSubsets) 28 | { 29 | List newsubset = new ArrayList<>(); 30 | newsubset.addAll(list2); 31 | newsubset.add(value); 32 | output.add(newsubset); 33 | } 34 | allSubsets.addAll(output); 35 | 36 | return allSubsets; 37 | 38 | } 39 | 40 | 41 | public static void main(String[] args) 42 | { 43 | List> finaloutput = new SubSetsofSet().subsetsAgain(Arrays.asList(1, 2, 3,4), 0); 44 | for (List subsets : finaloutput) { 45 | System.out.println(subsets); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /SubtringWithConcatenationOfAllWords.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by abc on 01/01/2016. 8 | */ 9 | public class SubtringWithConcatenationOfAllWords { 10 | 11 | public List findSubstring(String s, String[] words) { 12 | 13 | 14 | List result = new ArrayList<>(); //holds the result 15 | //add each word in the map to maintain the counter 16 | Map holder = new HashMap<>(); 17 | //maintained the other map if any case same words are repeated twice 18 | //or thrice like abc abc bef 19 | Map matcher = new HashMap<>(); 20 | for (String key: 21 | words) { 22 | if(holder.containsKey(key)){ 23 | int value = holder.get(key); 24 | holder.put(key,++value); 25 | }else { 26 | holder.put(key, 1); 27 | } 28 | matcher.put(key,0); 29 | } 30 | 31 | 32 | 33 | //holds the pointer to start the matching 34 | int total = s.length(); 35 | int wordLength = words[0].length(); 36 | int allWordsSize = (words.length * wordLength); 37 | 38 | System.err.println("allWordsSizeallWordsSize "+allWordsSize+" BHA "+total); 39 | for(int i=0; i< total;i++){ 40 | //next matching will be unnecessary because the remaining 41 | //string cant hold all the matches 42 | if((total - i) < allWordsSize) { 43 | System.err.println("------------------------------ "+i); 44 | break; 45 | } 46 | 47 | 48 | int curr = i; 49 | for(int j=0;j 0); 70 | 71 | } 72 | 73 | 74 | return result; 75 | } 76 | 77 | public static void main(String[] args) { 78 | System.out.println(new SubtringWithConcatenationOfAllWords().findSubstring("lingmindraboofooowingdingbarrwingmonkeypoundcake",new String[]{"fooo","barr","wing","ding","wing"})); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /SumOfTwoNumbersToGetThird.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | /** 4 | * A HashTable maintains the value left to match the target by subtracting 1st item with the target 5 | * if any value matches the required current value of the loop it does mean the hashtable value holds 6 | * the other element to get the required sum. 7 | * @author achoudhary 8 | * 9 | */ 10 | public class SumOfTwoNumbersToGetThird { 11 | public int[] twoSum(int[] numbers, int target) { 12 | int[] output = new int[2]; 13 | 14 | Map map = new HashMap(); 15 | for(int i=0;i< numbers.length;i++){ 16 | if(map.containsKey(numbers[i])){ 17 | int value = map.get(numbers[i]); 18 | output[0] = value+1; 19 | output[1] = i; 20 | break; 21 | }else{ 22 | map.put(target-numbers[i], i); 23 | } 24 | } 25 | 26 | return output; 27 | } 28 | 29 | public static void main(String[] args) 30 | { 31 | int[] numbers={3,2,4}; 32 | int[] output = new SumOfTwoNumbersToGetThird().twoSum(numbers, 6); 33 | System.out.println(output[0]+" "+output[1]); 34 | } 35 | } -------------------------------------------------------------------------------- /ThreeSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created by achoudhary on 26/01/2016. 5 | */ 6 | public class ThreeSum { 7 | 8 | public List> threeSum(int[] nums) { 9 | 10 | 11 | 12 | List> result = new ArrayList<>(); 13 | 14 | if(nums.length < 3) 15 | return result; 16 | 17 | Arrays.sort(nums); 18 | Set> proxy = new HashSet<>(); 19 | 20 | 21 | for (int i = 0; i < nums.length-2; i++) { 22 | 23 | if(i ==0 || nums[i] > nums[i-1]) { 24 | 25 | int target = -nums[i]; 26 | int start = i + 1; 27 | int end = nums.length - 1; 28 | 29 | while (start < end) { 30 | 31 | if (nums[start] + nums[end] == target) { 32 | List value = new ArrayList<>(); 33 | value.add(nums[i]); 34 | value.add(nums[start]); 35 | value.add(nums[end]); 36 | 37 | proxy.add(value); 38 | 39 | start++; 40 | end--; 41 | 42 | } else if (nums[start] + nums[end] > target) { 43 | end--; 44 | } else { 45 | start++; 46 | } 47 | } 48 | } 49 | } 50 | 51 | result.addAll(proxy); 52 | 53 | return result; 54 | } 55 | 56 | public static void main(String[] args) { 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by achoudhary on 06/01/2016. 3 | */ 4 | public class TrappingRainWater { 5 | 6 | public int trap(int[] height) { 7 | if(height.length == 0) 8 | return 0; 9 | int output = 0; 10 | int[] leftMax = new int[height.length]; //hold the max left value 11 | int[] rightMax = new int[height.length]; //holds the right max value for any ith element 12 | 13 | int max = height[0]; 14 | /** 15 | * iterate through ascending order to track maxLeft element 16 | * for each ith Element 17 | */ 18 | for (int i = 1; i < height.length; i++) { 19 | leftMax[i] = max; 20 | if(height[i] > max){ 21 | max = height[i]; 22 | } 23 | 24 | } 25 | 26 | 27 | /** 28 | * iterate through descending order to track maxRight element 29 | * for each ith Element 30 | */ 31 | max = height[height.length-1]; 32 | for (int i = height.length-2; i >= 0; i--) { 33 | rightMax[i] = max; 34 | if(height[i] > max){ 35 | max = height[i]; 36 | } 37 | } 38 | 39 | 40 | for (int i = 1; i < height.length - 1; i++) { 41 | int trap = Math.min(leftMax[i], rightMax[i]) - height[i]; 42 | if (trap > 0) 43 | output += trap; 44 | } 45 | return output; 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /TreeNode.java: -------------------------------------------------------------------------------- 1 | //Mock Class 2 | public class TreeNode { 3 | TreeNode right; 4 | TreeNode left; 5 | int val; 6 | TreeNode(int x) { val = x; } 7 | } 8 | -------------------------------------------------------------------------------- /Trie/CustomizeTrie.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileReader; 7 | import java.io.IOException; 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.LinkedList; 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.Scanner; 14 | import java.util.SortedMap; 15 | import java.util.TreeMap; 16 | 17 | public class CustomizeTrie { 18 | 19 | private static final Map charTOIntMap = new HashMap(); 20 | public static final SortedMap> dictionary = new TreeMap>(); 21 | 22 | public CustomizeTrie() { 23 | charTOIntMap.put('E', 0); 24 | 25 | charTOIntMap.put('J', 1); 26 | charTOIntMap.put('N', 1); 27 | charTOIntMap.put('Q', 1); 28 | 29 | charTOIntMap.put('R', 2); 30 | charTOIntMap.put('W', 2); 31 | charTOIntMap.put('X', 2); 32 | 33 | charTOIntMap.put('D', 3); 34 | charTOIntMap.put('S', 3); 35 | charTOIntMap.put('Y', 3); 36 | 37 | charTOIntMap.put('F', 4); 38 | charTOIntMap.put('T', 4); 39 | 40 | charTOIntMap.put('A', 5); 41 | charTOIntMap.put('M', 5); 42 | 43 | charTOIntMap.put('C', 6); 44 | charTOIntMap.put('I', 6); 45 | charTOIntMap.put('V', 6); 46 | 47 | charTOIntMap.put('B', 7); 48 | charTOIntMap.put('K', 7); 49 | charTOIntMap.put('U', 7); 50 | 51 | charTOIntMap.put('L', 8); 52 | charTOIntMap.put('O', 8); 53 | charTOIntMap.put('P', 8); 54 | 55 | charTOIntMap.put('G', 9); 56 | charTOIntMap.put('H', 9); 57 | charTOIntMap.put('Z', 9); 58 | } 59 | 60 | public void add(String word) { 61 | String intPattern = findPattern(word); 62 | // System.out.println(intPattern); 63 | List wordList = dictionary.get(intPattern); 64 | // if null , create the list 65 | if (wordList == null) { 66 | wordList = new ArrayList<>(); 67 | } 68 | // add the value in the list 69 | wordList.add(word); 70 | // update the Map 71 | dictionary.put(intPattern, wordList); 72 | } 73 | 74 | /** 75 | * Build the DataStructure Trie Dictionary 76 | * @param fileName 77 | */ 78 | public void buildTrie(String fileName){ 79 | try (BufferedReader br = new BufferedReader(new FileReader( 80 | fileName))) { 81 | 82 | String sCurrentLine; 83 | 84 | while ((sCurrentLine = br.readLine()) != null) { 85 | // System.out.println(sCurrentLine); 86 | this.add(sCurrentLine.trim()); 87 | } 88 | 89 | } catch (IOException e) { 90 | e.printStackTrace(); 91 | } 92 | 93 | } 94 | 95 | 96 | public void encodeNumber(String fileName){ 97 | File Numbers = new File(fileName); 98 | try { 99 | Scanner nc = new Scanner(Numbers); 100 | while(nc.hasNext()){ 101 | String num = nc.next(); 102 | String match = ""; 103 | lost = ""; 104 | search(num,match,num); 105 | state = false; 106 | } 107 | nc.close(); 108 | 109 | } catch (FileNotFoundException e) { 110 | // TODO Auto-generated catch block 111 | e.printStackTrace(); 112 | } 113 | } 114 | 115 | private String findPattern(String word) { 116 | String output = ""; 117 | for (char ch : word.toCharArray()) { 118 | if (Character.isLetter(ch)) { 119 | output += charTOIntMap.get(Character.toUpperCase(ch)); 120 | } 121 | } 122 | return output; 123 | } 124 | 125 | 126 | 127 | public SortedMap searchPrefix(SortedMap baseMap, String prefix) { 128 | 129 | if(prefix.length() > 0) { 130 | char nextLetter = (char) (prefix.charAt(prefix.length() -1)+ 1); 131 | String end = prefix.substring(0, prefix.length()-1) + nextLetter; 132 | String range = prefix.substring(0, 2); 133 | // String leaf = prefix.substring(0, prefix.length()-1); 134 | SortedMap mo = baseMap.subMap(range,end); 135 | 136 | return mo; 137 | } 138 | return baseMap; 139 | } 140 | 141 | 142 | 143 | 144 | 145 | /** 146 | * prints the output in console 147 | * @param rawInput 148 | * @param output 149 | */ 150 | private void print(String rawInput,String output){ 151 | System.out.println(rawInput+" : "+output.trim()); 152 | } 153 | 154 | /** 155 | * Lookup essentially takes each phone number and attempts to find a matching within the 156 | * SortedMap called map. 157 | * 158 | * @param String num, String match, String original 159 | * num represents the phone number that is being matched. 160 | * match stores a copy of a dictionary word if a match is found 161 | * original is the dictionary unmodified 162 | * 163 | * 164 | */ 165 | private String lost = ""; 166 | private boolean state = false; 167 | public void search(String input, String match,String rawInput){ 168 | String local = ""; 169 | int index = 0; 170 | String prefix = input.replaceAll("[/-]+", ""); 171 | if(prefix.length() == 1){ 172 | return; 173 | } 174 | 175 | SortedMap> dataset = searchPrefix(dictionary, prefix); 176 | for(Map.Entry> entry :dataset.entrySet()) { 177 | for(int i = 0; i < entry.getValue().size(); i++){ 178 | String cleanedValue = entry.getValue().get(i).replaceAll("\"", ""); 179 | String key = entry.getKey(); 180 | boolean con = key.equals(prefix) || prefix.startsWith(key); 181 | if(match.replace(" ", "").length() == rawInput.length()){ 182 | //System.err.println("3"); 183 | print(rawInput, lost+" " + match); 184 | }else if((prefix.length() - cleanedValue.length()) == 1&& con){ 185 | //System.err.println("2"); 186 | print(rawInput, lost+" " + match + entry.getValue().get(i) + " " +prefix.substring(prefix.length()-1, prefix.length())); 187 | }else if(cleanedValue.length() < prefix.length()&& con){ 188 | index = cleanedValue.length(); 189 | local = entry.getValue().get(i); 190 | String lo = prefix.substring(cleanedValue.length(), prefix.length()); 191 | search(lo,match + entry.getValue().get(i) + " ",rawInput); 192 | }else if (prefix.length() == cleanedValue.length()&& con){ 193 | //System.err.println("1"); 194 | print(rawInput, lost+ " " + match + cleanedValue); 195 | state = true; 196 | 197 | } 198 | } 199 | 200 | } 201 | 202 | if(!state){ 203 | preprocessSearch(input, match, rawInput, local, index, prefix); 204 | } 205 | //reset the lost 206 | lost = ""; 207 | } 208 | 209 | private void preprocessSearch(String input, String match, String rawInput, String local, int index, String prefix) { 210 | if( match.length()< input.length() ){ 211 | String m = match.replace(" ", ""); 212 | if(m.length() == 0){ 213 | //System.out.println("AYYA LA"); 214 | if(index > 0) 215 | lost = local; 216 | match += prefix.substring(index, index+1) + " "; 217 | prefix = prefix.substring(index+1, prefix.length()); 218 | search(prefix,match,rawInput); 219 | }else if (m.substring(m.length()-1).matches("[0-9]+")){ 220 | return; 221 | } 222 | }else { 223 | String testMatch = match.trim(); 224 | char charAt = testMatch.charAt(testMatch.length()-1); 225 | if(Character.isDigit(charAt)) 226 | return; 227 | match += prefix.substring(0,1) + " "; 228 | prefix = prefix.substring(1); 229 | search(prefix,match,rawInput); 230 | } 231 | } 232 | 233 | 234 | } 235 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | NumberEncoder 4 | NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. 5 | 6 | 7 | 8 | org.eclipse.jdt.core.javabuilder 9 | 10 | 11 | 12 | org.eclipse.jdt.core.javanature 13 | 14 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/README.txt: -------------------------------------------------------------------------------- 1 | Go to package com.numberencoding.main 2 | 3 | Run The File MainFunction.java 4 | It will show you following in the console- 5 | Enter the path of dictionary file or 0 to exit: 6 | (enter the path of dictionary file) 7 | 8 | Enter the path of Input file to process or 0 to exit : 9 | (enter the path of input file) 10 | 11 | 12 | Sample: 13 | 14 | Enter the path of dictionary file or 0 to exit: 15 | dictionary.txt 16 | Enter the path of Input file to process or 0 to exit : 17 | input.txt 18 | 19 | 38- : so 20 | 10 : je 21 | 7-3593-50 : 7 da 9 da 0 22 | -11/0 : 1 je 23 | /93-8- : 9 so 24 | 25 | The entire input file process is in loop , so once a dictionary is loaded you can keep adding different input files 26 | for testing unless user doesn't enter 0. -------------------------------------------------------------------------------- /Trie/NumberEncoder/dictionary.txt: -------------------------------------------------------------------------------- 1 | an 2 | blau 3 | Bo" 4 | Boot 5 | bo"s 6 | da 7 | Fee 8 | fern 9 | Fest 10 | fort 11 | je 12 | jemand 13 | mir 14 | Mix 15 | Mixer 16 | Name 17 | neu 18 | o"d 19 | Ort 20 | so 21 | Tor 22 | Torf 23 | Wasser -------------------------------------------------------------------------------- /Trie/NumberEncoder/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.numberencoding 6 | NumberEncoder 7 | 1.0 8 | jar 9 | 10 | NumberEncoder 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 4.11 22 | test 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/src/main/java/com/numberencoding/CharacterMapper.java: -------------------------------------------------------------------------------- 1 | package com.numberencoding; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * 8 | * This class is responsible for mapping each Charcater representation to the number 9 | * & store everything in a HashTable based datastructure (HashMap used here) 10 | * 11 | * @author abc 12 | * 13 | */ 14 | public class CharacterMapper 15 | { 16 | 17 | 18 | public Map buildCharacterMapper() 19 | { 20 | Map charTOIntMap = new HashMap(); 21 | charTOIntMap.put('E', 0); 22 | 23 | charTOIntMap.put('J', 1); 24 | charTOIntMap.put('N', 1); 25 | charTOIntMap.put('Q', 1); 26 | 27 | charTOIntMap.put('R', 2); 28 | charTOIntMap.put('W', 2); 29 | charTOIntMap.put('X', 2); 30 | 31 | charTOIntMap.put('D', 3); 32 | charTOIntMap.put('S', 3); 33 | charTOIntMap.put('Y', 3); 34 | 35 | charTOIntMap.put('F', 4); 36 | charTOIntMap.put('T', 4); 37 | 38 | charTOIntMap.put('A', 5); 39 | charTOIntMap.put('M', 5); 40 | 41 | charTOIntMap.put('C', 6); 42 | charTOIntMap.put('I', 6); 43 | charTOIntMap.put('V', 6); 44 | 45 | charTOIntMap.put('B', 7); 46 | charTOIntMap.put('K', 7); 47 | charTOIntMap.put('U', 7); 48 | 49 | charTOIntMap.put('L', 8); 50 | charTOIntMap.put('O', 8); 51 | charTOIntMap.put('P', 8); 52 | 53 | charTOIntMap.put('G', 9); 54 | charTOIntMap.put('H', 9); 55 | charTOIntMap.put('Z', 9); 56 | return charTOIntMap; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/src/main/java/com/numberencoding/main/MainFunction.java: -------------------------------------------------------------------------------- 1 | package com.numberencoding.main; 2 | 3 | import java.util.Scanner; 4 | 5 | import com.numberencoding.CustomizeTrie; 6 | import com.numberencoding.signature.ITrie; 7 | 8 | /** 9 | * Main function which takes input as dictionary file and input file 10 | * 11 | * @author abc 12 | * 13 | */ 14 | public class MainFunction { 15 | 16 | public static void main(String[] args) { 17 | 18 | Scanner scanIn = new Scanner(System.in); 19 | ITrie trie = new CustomizeTrie(); 20 | boolean buildTrie = false; 21 | String input = ""; 22 | while (!input.equals("0")) { 23 | while (!buildTrie) { 24 | System.out.println("Enter the path of dictionary file or 0 to exit: "); 25 | input = scanIn.nextLine(); 26 | if(input.equals("0")) 27 | System.exit(0); 28 | buildTrie = trie.buildTrie(input); 29 | } 30 | 31 | System.out.println("Enter the path of Input file to process or 0 to exit : "); 32 | input = scanIn.nextLine(); 33 | ((CustomizeTrie) trie).encodeNumber(input); 34 | } 35 | scanIn.close(); 36 | System.exit(0); 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/src/main/java/com/numberencoding/signature/ITrie.java: -------------------------------------------------------------------------------- 1 | package com.numberencoding.signature; 2 | 3 | /** 4 | * This defines the basic framework of Trie 5 | * @author abc 6 | * 7 | */ 8 | public interface ITrie { 9 | 10 | public boolean buildTrie(String fileName); 11 | 12 | public void search(String input, String match,String rawInput); 13 | } 14 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/src/test/java/com/numberencoding/CharacterMapperTest.java: -------------------------------------------------------------------------------- 1 | package com.numberencoding; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.Map; 6 | 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | public class CharacterMapperTest { 11 | 12 | 13 | CharacterMapper mapper; 14 | @Before 15 | public void setUp() throws Exception { 16 | mapper = new CharacterMapper(); 17 | } 18 | 19 | @Test 20 | public void test() { 21 | Map buildCharacterMapper = mapper.buildCharacterMapper(); 22 | assertNotNull(buildCharacterMapper); 23 | assertTrue(buildCharacterMapper.get('F')==4); 24 | assertTrue(buildCharacterMapper.get('T')==4); 25 | 26 | assertTrue(buildCharacterMapper.get('A')==5); 27 | assertTrue(buildCharacterMapper.get('M')==5); 28 | assertTrue(buildCharacterMapper.get('B')!=4); 29 | 30 | assertTrue(buildCharacterMapper.get('G')==9); 31 | assertTrue(buildCharacterMapper.get('H')==9); 32 | assertTrue(buildCharacterMapper.get('Z')==9); 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Trie/NumberEncoder/src/test/java/com/numberencoding/CustomizeTrieTest.java: -------------------------------------------------------------------------------- 1 | package com.numberencoding; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.SortedMap; 8 | 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | 12 | public class CustomizeTrieTest { 13 | 14 | CustomizeTrie customizeTrie; 15 | @Before 16 | public void setUp() throws Exception { 17 | customizeTrie = new CustomizeTrie(); 18 | } 19 | 20 | @Test 21 | public void testBuildTrie() { 22 | boolean buildTrie = customizeTrie.buildTrie("dictionary.txt"); 23 | assertTrue(buildTrie); 24 | SortedMap> dataStructure = customizeTrie.getDataStructure(); 25 | for (Map.Entry> entry : dataStructure.entrySet()) { 26 | System.out.println(entry.getKey()+" : "+entry.getValue()); 27 | } 28 | assertArrayEquals(dataStructure.get("10").toArray(new String[]{}), new String[]{"je"}); 29 | assertArrayEquals(dataStructure.get("253302").toArray(new String[]{}), new String[]{"Wasser"}); 30 | assertArrayEquals(dataStructure.get("4824").toArray(new String[]{}), new String[]{"fort","Torf"}); 31 | assertArrayEquals(dataStructure.get("562").toArray(new String[]{}), new String[]{"mir","Mix"}); 32 | assertArrayEquals(dataStructure.get("783").toArray(new String[]{}), new String[]{"bo\"s"}); 33 | } 34 | 35 | 36 | 37 | @Test 38 | public void testSearch() { 39 | fail("Can Not Implement as Console will be printed for this"); // TODO 40 | 41 | } 42 | 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Trie/PatternExtraction.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //http://stackoverflow.com/questions/29053153/encoding-numbers-to-words 4 | import java.io.BufferedReader; 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileReader; 8 | import java.io.IOException; 9 | import java.util.Arrays; 10 | import java.util.HashMap; 11 | import java.util.LinkedList; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.Scanner; 15 | import java.util.TreeMap; 16 | 17 | public class PatternExtraction { 18 | 19 | static Map> bucketedWords = new TreeMap<>(); 20 | //SortedMap> map = new TreeMap>(); 21 | static Trie trie = new Trie(); 22 | private final Map charTOIntMap = new HashMap(); 23 | 24 | public PatternExtraction() { 25 | charTOIntMap.put("E", 0); 26 | 27 | charTOIntMap.put("J", 0); 28 | charTOIntMap.put("N", 0); 29 | charTOIntMap.put("Q", 0); 30 | 31 | charTOIntMap.put("R", 0); 32 | charTOIntMap.put("W", 0); 33 | charTOIntMap.put("X", 0); 34 | 35 | charTOIntMap.put("D", 0); 36 | charTOIntMap.put("S", 0); 37 | charTOIntMap.put("Y", 0); 38 | 39 | charTOIntMap.put("F", 0); 40 | charTOIntMap.put("T", 0); 41 | 42 | charTOIntMap.put("A", 0); 43 | charTOIntMap.put("M", 0); 44 | 45 | charTOIntMap.put("C", 0); 46 | charTOIntMap.put("I", 0); 47 | charTOIntMap.put("V", 0); 48 | 49 | charTOIntMap.put("B", 0); 50 | charTOIntMap.put("K", 0); 51 | charTOIntMap.put("U", 0); 52 | 53 | charTOIntMap.put("L", 0); 54 | charTOIntMap.put("O", 0); 55 | charTOIntMap.put("P", 0); 56 | 57 | charTOIntMap.put("G", 0); 58 | charTOIntMap.put("H", 0); 59 | charTOIntMap.put("Z", 0); 60 | 61 | } 62 | 63 | // private List listOfStringsFromTel(String telephone){ 64 | // 65 | // } 66 | 67 | private static List> _findEncodings(String number, int startAt) { 68 | LinkedList> result = new LinkedList<>(); 69 | if (startAt == number.length()) { 70 | result.add(new LinkedList()); 71 | return result; 72 | } 73 | for (int endAt = startAt + 1; endAt <= number.length(); endAt++) { 74 | List words = bucketedWords.get(number.substring(startAt, 75 | endAt)); 76 | if (words != null) { 77 | List> encodings = _findEncodings(number, endAt); 78 | for (String word : words) { 79 | for (List encoding : encodings) { 80 | List enc = new LinkedList<>(encoding); 81 | enc.add(0, word); 82 | result.add(enc); 83 | } 84 | } 85 | } 86 | } 87 | return result; 88 | } 89 | 90 | private static List> findEncodings(String number) { 91 | return _findEncodings(number, 0); 92 | } 93 | 94 | private static List> modernEncodings(String number, int startAt) { 95 | LinkedList> result = new LinkedList<>(); 96 | 97 | if (startAt == number.length()) { 98 | result.add(new LinkedList()); 99 | return result; 100 | } 101 | 102 | for (int endAt = startAt + 1; endAt <= number.length(); endAt++) { 103 | List words = trie.search(number.substring(startAt, endAt)); 104 | // List words = bucketedWords.get(number.substring(startAt, 105 | // endAt)); 106 | if (words != null) { 107 | List> encodings = _findEncodings(number, endAt); 108 | for (String word : words) { 109 | for (List encoding : encodings) { 110 | List enc = new LinkedList<>(encoding); 111 | enc.add(0, word); 112 | result.add(enc); 113 | } 114 | } 115 | } 116 | } 117 | 118 | return result; 119 | } 120 | 121 | public static void main(String[] args) { 122 | CustomizeTrie trie = new CustomizeTrie(); 123 | trie.buildTrie("dictionary.txt"); 124 | trie.encodeNumber("input.txt"); 125 | 126 | 127 | 128 | 129 | // try (BufferedReader br = new BufferedReader(new FileReader( 130 | // "dictionary1.txt"))) { 131 | // 132 | // String sCurrentLine; 133 | // 134 | // while ((sCurrentLine = br.readLine()) != null) { 135 | // // System.out.println(sCurrentLine); 136 | // trie.add(sCurrentLine.trim()); 137 | // } 138 | // 139 | // } catch (IOException e) { 140 | // e.printStackTrace(); 141 | // } 142 | 143 | // Map> map = trie.dictionary; 144 | // for (Map.Entry> entry : map.entrySet()) { 145 | // System.out.println("Key = " + entry.getKey() + ", Value = " 146 | // + entry.getValue()); 147 | // } 148 | 149 | // Astlo 150 | //List> search = trie.search("1078135"); 151 | //System.out.println(search); 152 | // for (String string : search) { 153 | // System.err.println(string); 154 | // } 155 | 156 | // callothermain(); 157 | 158 | } 159 | 160 | public static void callothermain() { 161 | bucketedWords.put("562", Arrays.asList("mir", "Mix", "Ail", "tpi")); 162 | bucketedWords.put("482", Arrays.asList("tor")); 163 | bucketedWords.put("10", Arrays.asList("je")); 164 | bucketedWords.put("78", Arrays.asList("Bo\"")); 165 | bucketedWords.put("35", Arrays.asList("da")); 166 | 167 | System.out.println(findEncodings("562482")); 168 | System.out.println(findEncodings("107835")); 169 | } 170 | 171 | } 172 | 173 | /* 174 | * Copyright 2004-2015 Pilz Ireland Industrial Automation Ltd. All Rights 175 | * Reserved. PILZ PROPRIETARY/CONFIDENTIAL. 176 | * 177 | * Created on 10 Jul 2015 178 | */ -------------------------------------------------------------------------------- /Trie/Trie.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | public class Trie { 12 | 13 | private final Map nodeMap = new HashMap(); 14 | private final Map intMap = new HashMap(); 15 | private final List descendentChildrens = new ArrayList(); 16 | private static final Map charTOIntMap = new HashMap(); 17 | 18 | public Trie() { 19 | 20 | // charTOIntMap.put("\\", 10); 21 | // charTOIntMap.put("\"", 10); 22 | } 23 | 24 | public void add(final String word) { 25 | // checkArgument(StringUtils.isNotBlank(word), "word can not be blank"); 26 | if (word != null && !word.isEmpty()) { 27 | Trie current = this; 28 | descendentChildrens.add(word); 29 | for (final Character c : word.toCharArray()) { 30 | if (!current.nodeMap.containsKey(c)) { 31 | current.nodeMap.put(c, new Trie()); 32 | } 33 | current = current.nodeMap.get(c); 34 | current.descendentChildrens.add(word); 35 | // get the Character 36 | 37 | // current.descendentChildrens.charTOIntMap(findPattern(word)); 38 | } 39 | } 40 | } 41 | 42 | public void addWithKey(final String word) { 43 | updateMap(); 44 | // checkArgument(StringUtils.isNotBlank(word), "word can not be blank"); 45 | if (word != null && !word.isEmpty()) { 46 | Trie current = this; 47 | descendentChildrens.add(word); 48 | for (final Character c : word.toCharArray()) { 49 | if (Character.isLetter(c)) { 50 | Integer index = charTOIntMap.get(Character.toString(c) 51 | .toUpperCase()); 52 | if (!current.intMap.containsKey(index)) { 53 | // current.nodeMap.put(c, new Trie()); 54 | current.intMap.put(index, new Trie()); 55 | } 56 | current = current.intMap.get(index); 57 | current.descendentChildrens.add(word); 58 | } 59 | } 60 | } 61 | } 62 | 63 | public List search(final String wordStart) { 64 | // checkNotNull(wordStart, "wordStart cannot be null"); 65 | if (wordStart == null) 66 | return null; 67 | Trie current = this; 68 | for (final Character c : wordStart.toCharArray()) { 69 | current = current.nodeMap.get(c); 70 | if (current == null) { 71 | return Collections.emptyList(); 72 | } 73 | } 74 | return Collections.unmodifiableList(current.descendentChildrens); 75 | } 76 | 77 | public List searchWithKey(final String wordStart) { 78 | 79 | // checkNotNull(wordStart, "wordStart cannot be null"); 80 | if (wordStart == null) 81 | return null; 82 | Trie current = this; 83 | for (final Character c : wordStart.toCharArray()) { 84 | current = current.intMap.get(Character.getNumericValue(c)); 85 | if (current == null) { 86 | return Collections.emptyList(); 87 | } 88 | } 89 | List finalOuput = current.descendentChildrens; 90 | finalOuput = updateFurther(current.descendentChildrens, wordStart); 91 | return finalOuput; 92 | } 93 | 94 | /** 95 | * 96 | * @param descendentChildrens2 97 | * @return 98 | */ 99 | private List updateFurther(List foundChildrens, String word) { 100 | List value = new LinkedList<>(); 101 | for (String string : foundChildrens) { 102 | int count = string.length() - string.replace("\"", "").length(); 103 | if ((string.length() == word.length()) 104 | || (string.length() == (word.length() + count))) { 105 | value.add(string); 106 | } 107 | } 108 | return value; 109 | } 110 | 111 | private List> _findEncodings(String number, int startAt) { 112 | Trie current = this; 113 | LinkedList> result = new LinkedList<>(); 114 | if (startAt == number.length()) { 115 | result.add(new LinkedList()); 116 | return result; 117 | } 118 | for (int endAt = startAt + 1; endAt <= number.length(); endAt++) { 119 | current = current.intMap.get(number.substring(startAt, endAt)); 120 | List words = current.descendentChildrens; 121 | System.out.println("wordswords " + words); 122 | if (words != null) { 123 | List> encodings = _findEncodings(number, endAt); 124 | for (String word : words) { 125 | for (List encoding : encodings) { 126 | List enc = new LinkedList<>(encoding); 127 | enc.add(0, word); 128 | result.add(enc); 129 | } 130 | } 131 | } 132 | } 133 | return result; 134 | } 135 | 136 | List> findEncodings(String number) { 137 | return _findEncodings(number, 0); 138 | } 139 | 140 | private static void updateMap() { 141 | // TODO:achoudhary Auto-generated method stub 142 | charTOIntMap.put("E", 0); 143 | 144 | charTOIntMap.put("J", 1); 145 | charTOIntMap.put("N", 1); 146 | charTOIntMap.put("Q", 1); 147 | 148 | charTOIntMap.put("R", 2); 149 | charTOIntMap.put("W", 2); 150 | charTOIntMap.put("X", 2); 151 | 152 | charTOIntMap.put("D", 3); 153 | charTOIntMap.put("S", 3); 154 | charTOIntMap.put("Y", 3); 155 | 156 | charTOIntMap.put("F", 4); 157 | charTOIntMap.put("T", 4); 158 | 159 | charTOIntMap.put("A", 5); 160 | charTOIntMap.put("M", 5); 161 | 162 | charTOIntMap.put("C", 6); 163 | charTOIntMap.put("I", 6); 164 | charTOIntMap.put("V", 6); 165 | 166 | charTOIntMap.put("B", 7); 167 | charTOIntMap.put("K", 7); 168 | charTOIntMap.put("U", 7); 169 | 170 | charTOIntMap.put("L", 8); 171 | charTOIntMap.put("O", 8); 172 | charTOIntMap.put("P", 8); 173 | 174 | charTOIntMap.put("G", 9); 175 | charTOIntMap.put("H", 9); 176 | charTOIntMap.put("Z", 9); 177 | } 178 | 179 | private String findPattern(String word) { 180 | String output = ""; 181 | for (char ch : word.toCharArray()) { 182 | if (Character.isLetter(ch)) { 183 | output += charTOIntMap 184 | .get(Character.toString(ch).toUpperCase()); 185 | } 186 | } 187 | return output; 188 | } 189 | 190 | /** 191 | * Search the list of matching pattern in Trie. Modified the exact search 192 | * logic here . 193 | * 194 | * Changes made for handling UpperCase 195 | * 196 | * @param wordStart 197 | * @return 198 | */ 199 | public Set specificSearch(final String wordStart) { 200 | 201 | return null; 202 | } 203 | 204 | // public static void main(String[] args) { 205 | // Trie trie = new Trie(); 206 | // try (BufferedReader br = new BufferedReader( 207 | // new FileReader( 208 | // "D:\\Downloads\\numberencoding\\numberencoding\\dictionary.txt"))) { 209 | // 210 | // String sCurrentLine; 211 | // 212 | // while ((sCurrentLine = br.readLine()) != null) { 213 | // // System.out.println(sCurrentLine); 214 | // trie.add(sCurrentLine.trim()); 215 | // } 216 | // 217 | // } catch (IOException e) { 218 | // e.printStackTrace(); 219 | // } 220 | // 221 | // Set search = trie.search("Abbaumater"); 222 | // for (String string : search) { 223 | // System.err.println(string); 224 | // } 225 | // 226 | // } 227 | } -------------------------------------------------------------------------------- /Trie/Trie1.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | import java.util.Map.Entry; 9 | 10 | public class Trie1 { 11 | private TrieNode root; 12 | 13 | public Trie1() { 14 | root = new TrieNode(); 15 | } 16 | 17 | // Inserts a word into the trie. 18 | public void insert(String word) { 19 | HashMap children = root.children; 20 | 21 | for (int i = 0; i < word.length(); i++) { 22 | char c = word.charAt(i); 23 | 24 | TrieNode t; 25 | if (children.containsKey(c)) { 26 | t = children.get(c); 27 | } else { 28 | t = new TrieNode(c); 29 | children.put(c, t); 30 | } 31 | 32 | children = t.children; 33 | 34 | // set leaf node 35 | if (i == word.length() - 1) 36 | t.isLeaf = true; 37 | } 38 | } 39 | 40 | // Returns if the word is in the trie. 41 | public boolean search(String word) { 42 | TrieNode t = searchNode(word); 43 | 44 | if (t != null && t.isLeaf) 45 | return true; 46 | else 47 | return false; 48 | } 49 | 50 | // Returns if there is any word in the trie 51 | // that starts with the given prefix. 52 | public boolean startsWith(String prefix) { 53 | if (searchNode(prefix) == null) 54 | return false; 55 | else 56 | return true; 57 | } 58 | 59 | public TrieNode searchNode(String str) { 60 | Map children = root.children; 61 | TrieNode t = null; 62 | for (int i = 0; i < str.length(); i++) { 63 | char c = str.charAt(i); 64 | if (children.containsKey(c)) { 65 | t = children.get(c); 66 | children = t.children; 67 | } else { 68 | return null; 69 | } 70 | } 71 | 72 | return t; 73 | } 74 | 75 | public static void main(String[] args) { 76 | Trie1 trie = new Trie1(); 77 | try (BufferedReader br = new BufferedReader( 78 | new FileReader( 79 | "D:\\Downloads\\numberencoding\\numberencoding\\dictionary.txt"))) { 80 | 81 | String sCurrentLine; 82 | 83 | while ((sCurrentLine = br.readLine()) != null) { 84 | // System.out.println(sCurrentLine); 85 | trie.insert(sCurrentLine.trim()); 86 | } 87 | 88 | } catch (IOException e) { 89 | e.printStackTrace(); 90 | } 91 | 92 | TrieNode searchNode = trie.searchNode("Abba"); 93 | HashMap children = searchNode.children; 94 | System.out.println("childrenchildren " + children.size()); 95 | for (Entry entry : children.entrySet()) { 96 | TrieNode value = entry.getValue(); 97 | System.out.println(entry.getKey() + "/" + entry.getValue()); 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /Trie/TrieMap.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | /** 4 | * Implements very fast dictionary storage and retrieval. Only depends upon the 5 | * core String class. 6 | * 7 | * @author Melinda Green - � 2010 Superliminal Software. Free for all uses with 8 | * attribution. 9 | */ 10 | public class TrieMap { 11 | /* 12 | * Implementation of a trie tree. (see http://en.wikipedia.org/wiki/Trie) 13 | * though I made it faster and more compact for long key strings by building 14 | * tree nodes only as needed to resolve collisions. Each letter of a key is 15 | * the index into the following array. Values stored in the array are either 16 | * a Leaf containing the user's value or another TrieMap node if more than 17 | * one key shares the key prefix up to that point. Null elements indicate 18 | * unused, I.E. available slots. 19 | */ 20 | private Object[] mChars = new Object[256]; 21 | private Object mPrefixVal; // Used only for values of prefix keys. 22 | 23 | // Simple container for a string-value pair. 24 | private static class Leaf { 25 | public String mStr; 26 | public Object mVal; 27 | 28 | public Leaf(String str, Object val) { 29 | mStr = str; 30 | mVal = val; 31 | } 32 | } 33 | 34 | public TrieMap() { 35 | } 36 | 37 | public boolean isEmpty() { 38 | if (mPrefixVal != null) { 39 | return false; 40 | } 41 | for (Object o : mChars) { 42 | if (o != null) { 43 | return false; 44 | } 45 | } 46 | return true; 47 | } 48 | 49 | /** 50 | * Inserts a key/value pair. 51 | * 52 | * @param key 53 | * may be empty or contain low-order chars 0..255 but must not be 54 | * null. 55 | * @param val 56 | * Your data. Any data class except another TrieMap. Null values 57 | * erase entries. 58 | */ 59 | public void put(String key, Object val) { 60 | assert key != null; 61 | assert !(val instanceof TrieMap); // Only we get to store TrieMap nodes. 62 | // TODO: Allow it. 63 | if (key.length() == 0) { 64 | // All of the original key's chars have been nibbled away 65 | // which means this node will store this key as a prefix of other 66 | // keys. 67 | mPrefixVal = val; // Note: possibly removes or updates an item. 68 | return; 69 | } 70 | char c = key.charAt(0); 71 | Object cObj = mChars[c]; 72 | if (cObj == null) { // Unused slot means no collision so just store and 73 | // return; 74 | if (val == null) { 75 | return; // Don't create a leaf to store a null value. 76 | } 77 | mChars[c] = new Leaf(key, val); 78 | return; 79 | } 80 | if (cObj instanceof TrieMap) { 81 | // Collided with an existing sub-branch so nibble a char and 82 | // recurse. 83 | TrieMap childTrie = (TrieMap) cObj; 84 | childTrie.put(key.substring(1), val); 85 | if (val == null && childTrie.isEmpty()) { 86 | mChars[c] = null; // put() must have erased final entry so prune 87 | // branch. 88 | } 89 | return; 90 | } 91 | // Collided with a leaf 92 | if (val == null) { 93 | mChars[c] = null; // Null value means to remove any previously 94 | // stored value. 95 | return; 96 | } 97 | assert cObj instanceof Leaf; 98 | // Sprout a new branch to hold the colliding items. 99 | Leaf cLeaf = (Leaf) cObj; 100 | TrieMap branch = new TrieMap(); 101 | branch.put(key.substring(1), val); // Store new value in new subtree. 102 | branch.put(cLeaf.mStr.substring(1), cLeaf.mVal); // Plus the one we 103 | // collided with. 104 | mChars[c] = branch; 105 | } 106 | 107 | /** 108 | * Retrieve a value for a given key or null if not found. 109 | */ 110 | public Object get(String key) { 111 | assert key != null; 112 | if (key.length() == 0) { 113 | // All of the original key's chars have been nibbled away 114 | // which means this key is a prefix of another. 115 | return mPrefixVal; 116 | } 117 | char c = key.charAt(0); 118 | Object cVal = mChars[c]; 119 | if (cVal == null) { 120 | return null; // Not found. 121 | } 122 | assert cVal instanceof Leaf || cVal instanceof TrieMap; 123 | if (cVal instanceof TrieMap) { // Hash collision. Nibble first char, and 124 | // recurse. 125 | return ((TrieMap) cVal).get(key.substring(1)); 126 | } 127 | if (cVal instanceof Leaf) { 128 | // cVal contains a user datum, but does the key match its substring? 129 | Leaf cPair = (Leaf) cVal; 130 | if (key.equals(cPair.mStr)) { 131 | return cPair.mVal; // Return user's data value. 132 | } 133 | } 134 | return null; // Not found. 135 | } 136 | 137 | /** 138 | * Simple example test program. 139 | */ 140 | public static void main(String[] args) { 141 | // Insert a bunch of key/value pairs. 142 | TrieMap trieMap = new TrieMap(); 143 | trieMap.put("123", "456"); 144 | trieMap.put("Java", "rocks"); 145 | trieMap.put("Melinda", "too"); 146 | trieMap.put("Moo", "cow"); // Will collide with "Melinda". 147 | trieMap.put("Moon", "walk"); // Collides with "Melinda" and turns "Moo" 148 | // into a prefix. 149 | trieMap.put("", "Root"); // You can store one value at the empty key if 150 | // you like. 151 | 152 | // Test for inserted, nonexistent, and deleted keys. 153 | System.out.println("123 = " + trieMap.get("123")); 154 | System.out.println("Java = " + trieMap.get("Java")); 155 | System.out.println("Melinda = " + trieMap.get("Melinda")); 156 | System.out.println("Moo = " + trieMap.get("Moo")); 157 | System.out.println("Moon = " + trieMap.get("Moon")); 158 | System.out.println("Mo = " + trieMap.get("Mo")); // Should return null. 159 | System.out.println("Empty key = " + trieMap.get("")); // Should return 160 | // "Root". 161 | System.out.println("Moose = " + trieMap.get("Moose")); // Never added so 162 | // should return 163 | // null. 164 | System.out.println("Nothing = " + trieMap.get("Nothing")); // Ditto. 165 | trieMap.put("123", null); // Removes this leaf entry. 166 | System.out.println("After removal, 123 = " + trieMap.get("123")); // Should 167 | // now 168 | // return 169 | // null. 170 | trieMap.put("Moo", null); // Removes this prefix entry. (Special case to 171 | // test internal logic). 172 | System.out.println("After removal, Moo = " + trieMap.get("Moo")); // Should 173 | // now 174 | // return 175 | // null. 176 | trieMap.put("Moon", null); // Internal test of branch pruning. 177 | } 178 | } -------------------------------------------------------------------------------- /Trie/TrieNode.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.HashMap; 4 | 5 | class TrieNode { 6 | char c; 7 | HashMap children = new HashMap(); 8 | boolean isLeaf; 9 | 10 | public TrieNode() { 11 | } 12 | 13 | public TrieNode(char c) { 14 | this.c = c; 15 | } 16 | } -------------------------------------------------------------------------------- /ValidateBST.java: -------------------------------------------------------------------------------- 1 | 2 | //http://www.programcreek.com/2012/12/leetcode-validate-binary-search-tree-java/ 3 | public class ValidateBST { 4 | 5 | 6 | 7 | public boolean isValidBST(TreeNode root) { 8 | 9 | return isValidate(root,Integer.MIN_VALUE,Integer.MAX_VALUE); 10 | } 11 | 12 | private boolean isValidate(TreeNode node, int left, int right){ 13 | 14 | if(node == null) 15 | return true; 16 | 17 | if(node.val <= left || node.val >= right) 18 | return false; 19 | 20 | return isValidate(node.left, Math.min(right, node.val), left) && isValidate(node.right, right, Math.max(left, node.val)); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /WordLadder.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Queue; 6 | 7 | 8 | public class WordLadder { 9 | 10 | public static void main(String[] args) { 11 | // TODO Auto-generated method stub 12 | 13 | String input = "hit"; 14 | String goal = "cog"; 15 | String[] matched = {"hot","dog","dot","lot","log","sog","mot","pot"}; 16 | LinkedList availableList = new LinkedList(Arrays.asList(matched)); 17 | LinkedList distanceQueue = new LinkedList(); 18 | LinkedList queue = new LinkedList(); 19 | 20 | availableList.add(goal); 21 | 22 | queue.add(input); 23 | distanceQueue.add(1); 24 | int result = Integer.MAX_VALUE; 25 | while(!queue.isEmpty()){ 26 | String currWord = queue.pop(); 27 | int currDist = distanceQueue.pop(); 28 | 29 | if(currWord.equals(goal)){ 30 | result = Math.min(result, currDist); 31 | } 32 | 33 | for(int i=0;i= r || column >= c || column<0){ 39 | return false; 40 | } 41 | if(visited[row][column]) 42 | return false; 43 | String charAt = ""+matchingString.charAt(match); 44 | if(!charAt.equals(input[row][column])){ 45 | return false; 46 | } 47 | visited[row][column] = true; 48 | boolean result = (findWord(input,row+1,column,match+1,matchingString,visited) 49 | || findWord(input,row-1,column,match+1,matchingString,visited) 50 | || findWord(input,row,column+1,match+1,matchingString,visited) 51 | || findWord(input,row,column-1,match+1,matchingString,visited)); 52 | visited[row][column] = false; 53 | 54 | 55 | return result; 56 | 57 | } 58 | 59 | public static void main(String[] args) { 60 | WordSearch_Recursion wordSearch = new WordSearch_Recursion(); 61 | boolean findWord = wordSearch.searchWord("ABAB"); 62 | System.out.println("VALU "+findWord); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /ZigZagLevelOrdering.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.Stack; 5 | 6 | /** 7 | * Created by achoudhary on 11/03/2016. 8 | */ 9 | 10 | // Definition for a binary tree node. 11 | 12 | 13 | class TreeNode { 14 | int val; 15 | TreeNode left; 16 | TreeNode right; 17 | TreeNode(int x) { val = x; } 18 | } 19 | 20 | public class ZigZagLevelOrdering { 21 | 22 | public List> zigzagLevelOrder(TreeNode root) { 23 | 24 | List> result = new ArrayList<>(); 25 | if(root == null) 26 | return result; 27 | 28 | 29 | 30 | Stack currStack = new Stack<>(); 31 | Stack nextStack = new Stack<>(); 32 | Stack tmp; 33 | currStack.push(root); 34 | boolean leftOrdering = true; 35 | 36 | while(!currStack.isEmpty()){ 37 | List proxyResult = new ArrayList<>(); 38 | 39 | while(!currStack.empty()){ 40 | TreeNode node = currStack.pop(); 41 | proxyResult.add(node.val); 42 | if(leftOrdering){ 43 | if(node.left != null){ 44 | nextStack.push(node.left); 45 | } 46 | if(node.right != null){ 47 | nextStack.push(node.right); 48 | } 49 | }else{ 50 | if(node.right != null){ 51 | nextStack.push(node.right); 52 | } 53 | if(node.left != null){ 54 | nextStack.push(node.left); 55 | } 56 | 57 | } 58 | } 59 | 60 | 61 | result.add(proxyResult); 62 | tmp = currStack; 63 | currStack = nextStack; 64 | nextStack = tmp; 65 | leftOrdering = !leftOrdering; 66 | } 67 | 68 | return result; 69 | } 70 | 71 | public static void main(String[] args) { 72 | 73 | } 74 | } 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /cube/HappyCube/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | HappyCube 4 | NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. 5 | 6 | 7 | 8 | org.eclipse.jdt.core.javabuilder 9 | 10 | 11 | 12 | org.eclipse.jdt.core.javanature 13 | 14 | -------------------------------------------------------------------------------- /cube/HappyCube/README.txt: -------------------------------------------------------------------------------- 1 | Open the package com.cube.test. 2 | 3 | There are 3 test cases - 4 | a)Challenge1Part1Test - Runs Part a of challenge 1 5 | b)Challenge1Part2Test - Runs Part b of challenge 1 6 | c)Challenge2Test - Runs the challenge 2 7 | 8 | Run any of the test case above , it will create a directory named output. Inside output directory, you will find 9 | all given Cube name colored directory. Under each directory you will find each test case linked sub directory.. 10 | 11 | output directory Structure 12 | __________________________ 13 | 14 | output 15 | Blue 16 | ........Challenge1part1 17 | ........Challenge1part2 18 | ........Challenge2 19 | Green 20 | ........Challenge1part1 21 | ........Challenge1part2 22 | ........Challenge2 23 | Purple 24 | ........Challenge1part1 25 | ........Challenge1part2 26 | ........Challenge2 27 | Red 28 | ........Challenge1part1 29 | ........Challenge1part2 30 | ........Challenge2 -------------------------------------------------------------------------------- /cube/HappyCube/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.cube 5 | HappyCube 6 | jar 7 | 1.0-SNAPSHOT 8 | HappyCube 9 | http://maven.apache.org 10 | 11 | 12 | junit 13 | junit 14 | 4.11 15 | test 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/CubeGraphTraversal.java: -------------------------------------------------------------------------------- 1 | package com.cube; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import com.cube.controller.CubeController; 9 | import com.cube.helper.GraphHelper; 10 | import com.cube.model.Cube; 11 | 12 | /** 13 | * This class is responsible to iterate through each orientation (permutations/rotations) of block/piece 14 | * and pass it to {@link CubeController} for validating its existence in the expected unfolded or all cube structure. 15 | * 16 | * This class is based on Graph Traversal mechanism using backtracking recursion. 17 | * @author abc 18 | * 19 | */ 20 | public class CubeGraphTraversal implements IGraph 21 | { 22 | 23 | 24 | private Map> tracker = new HashMap<>(); 25 | private CubeController controller; 26 | private OutputStructure outputStructure; 27 | 28 | /** 29 | * returns all the orientations of each piece or block , see {@link GraphHelper} 30 | * 31 | * @param pieces_left 32 | * @return 33 | */ 34 | private Map> getNodeOrientations(List pieces_left) 35 | { 36 | for (int[][] piece : pieces_left) 37 | { 38 | List findAllOrientations = GraphHelper.findAllOrientations(piece); 39 | tracker.put(piece, findAllOrientations); 40 | } 41 | 42 | return tracker; 43 | 44 | } 45 | 46 | /** 47 | * handles the backtracking of Graph Traversal based on each orientation . 48 | * Its like each edge permutation of Node in the graph. Here the permutation defines about 49 | * left, right , top and bottom of each block or piece of happy cube 50 | * 51 | * @param slotid recursively increment the slot_id, max expected is 6 52 | * @param pieces_left pieces left while backtraking 53 | * @param isUnfoldedActive Unfolded representation or not 54 | * @return 55 | */ 56 | private List traverseGraph(int slotid, List pieces_left, boolean isUnfoldedActive) 57 | { 58 | if (slotid == 6) 59 | { 60 | List list = controller.getList(); 61 | outputStructure.betterPrint(controller.getList(),unfold); 62 | if(isSingleOutput){ 63 | return list; 64 | } 65 | controller = new CubeController(outputStructure); 66 | outputStructure.reset(); 67 | return list; 68 | } 69 | 70 | for (int[][] piece : pieces_left) 71 | { 72 | List list = tracker.get(piece); 73 | for (int[][] orientationPiece : list) 74 | { 75 | List buildCubeBlock = null; 76 | 77 | 78 | if(isUnfoldedActive){ 79 | buildCubeBlock = controller.buildUnfoldedCube( 80 | slotid, orientationPiece); 81 | }else{ 82 | buildCubeBlock = controller 83 | .buildCubeInAnyForm(orientationPiece); 84 | } 85 | 86 | if (buildCubeBlock != null && buildCubeBlock.size() == slotid + 1) 87 | { 88 | List subList = new ArrayList(pieces_left); 89 | subList.remove(piece); 90 | traverseGraph(slotid + 1, subList,isUnfoldedActive); 91 | } 92 | } 93 | } 94 | return null; 95 | 96 | } 97 | 98 | 99 | 100 | /** 101 | * client exposed method to traverse the graph. 102 | * 103 | * @param pieces_left returns 2D array representation matrix of block structure (1,0) 104 | * @param colorBlocks name of the block 105 | * @param printRequired do you want the console to print the output for debugging 106 | * @param filePrintRequired do you want to print the content into a file placed in currProjDir/colorBlock/... 107 | * @param unfoldedActive do you want unfolded representation of cube or all permutation 108 | * @return 109 | */ 110 | public List traverse(List pieces_left,String colorBlocks,boolean printRequired,boolean filePrintRequired,boolean unfoldedActive){ 111 | getNodeOrientations(pieces_left); 112 | outputStructure = new OutputStructure(colorBlocks,printRequired,filePrintRequired); 113 | controller = new CubeController(outputStructure); 114 | return traverseGraph(0,pieces_left,unfoldedActive); 115 | 116 | } 117 | 118 | 119 | 120 | 121 | boolean isSingleOutput; 122 | boolean unfold; 123 | /** 124 | * 125 | * @param isSingleOutput do you want to display only one result 126 | */ 127 | public CubeGraphTraversal(boolean isSingleOutput,boolean unfold) 128 | { 129 | this.isSingleOutput = isSingleOutput; 130 | this.unfold = unfold; 131 | } 132 | 133 | 134 | 135 | } 136 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/IGraph.java: -------------------------------------------------------------------------------- 1 | package com.cube; 2 | 3 | import java.util.List; 4 | 5 | import com.cube.model.Cube; 6 | 7 | /** 8 | * Interface represents a Graph based structure to traverse. 9 | * It can be updated based on other Graph traversal 10 | * @author abc 11 | * 12 | */ 13 | public interface IGraph { 14 | 15 | public List traverse(List pieces_left,String colorBlocks,boolean printRequired,boolean filePrintRequired,boolean unfoldedActive); 16 | } 17 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/OutputStructure.java: -------------------------------------------------------------------------------- 1 | package com.cube; 2 | 3 | import java.io.File; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.io.PrintWriter; 7 | import java.text.DateFormat; 8 | import java.text.SimpleDateFormat; 9 | import java.util.Date; 10 | import java.util.HashSet; 11 | import java.util.List; 12 | import java.util.Set; 13 | 14 | import com.cube.helper.Constant; 15 | import com.cube.model.Cube; 16 | 17 | /** 18 | * This class is responsible to handle entire Output Handling of the Happy Cube 19 | * 20 | * @author abc 21 | * 22 | */ 23 | public class OutputStructure 24 | { 25 | 26 | 27 | private int[][] outputArr = new int[Constant.ROW][Constant.COLUMN]; 28 | 29 | private static Set uniquePatterns = new HashSet<>(); 30 | 31 | String colorBlocks; 32 | 33 | boolean printRequired; 34 | 35 | boolean filePrintRequired; 36 | 37 | 38 | /** 39 | * 40 | * @param colorBlocks 41 | * name of the Color Block 42 | * @param printRequired 43 | * is printing in console required 44 | * @param filePrintRequired 45 | * is content should be print in file 46 | */ 47 | public OutputStructure(String colorBlocks, boolean printRequired, boolean filePrintRequired) 48 | { 49 | this.colorBlocks = colorBlocks; 50 | this.printRequired = printRequired; 51 | this.filePrintRequired = filePrintRequired; 52 | File file = new File(colorBlocks); 53 | file.mkdirs(); 54 | } 55 | 56 | 57 | public void reset() 58 | { 59 | outputArr = new int[Constant.ROW][Constant.COLUMN]; 60 | } 61 | 62 | 63 | public void updateOutput(int[][] input, int row, int column) 64 | { 65 | for (int i = 0; i < 5; i++) 66 | { 67 | for (int j = 0; j < 5; j++) 68 | { 69 | outputArr[row + i][column + j] = input[i][j]; 70 | } 71 | // System.out.println(); 72 | } 73 | } 74 | 75 | 76 | public int[][] getOutputArr() 77 | { 78 | return outputArr; 79 | } 80 | 81 | 82 | public void print() 83 | { 84 | String output = ""; 85 | for (int i = 0; i < Constant.ROW; i++) 86 | { 87 | for (int j = 0; j < Constant.COLUMN; j++) 88 | { 89 | output += outputArr[i][j] == 0 ? " " : "o"; 90 | } 91 | output += "\n"; 92 | } 93 | if (uniquePatterns.add(output)) 94 | { 95 | if (printRequired) 96 | { 97 | System.out.println(output); 98 | } 99 | if (filePrintRequired) 100 | { 101 | console(output); 102 | } 103 | } 104 | } 105 | 106 | 107 | /** 108 | * print console output in file 109 | * 110 | * @param message 111 | */ 112 | private void console(String message) 113 | { 114 | DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss"); 115 | Date date = new Date(); 116 | PrintWriter out; 117 | try 118 | { 119 | out = new PrintWriter(new FileWriter(colorBlocks + "/" + dateFormat.format(date) + ".txt", true), true); 120 | } 121 | catch (IOException e) 122 | { 123 | 124 | throw new RuntimeException(e); 125 | 126 | } 127 | out.write(message); 128 | out.close(); 129 | } 130 | 131 | 132 | /** 133 | * Prints all available unique cube 134 | * 135 | * @param list 136 | * @param unfold 137 | */ 138 | public void betterPrint(List list, boolean unfold) 139 | { 140 | boolean invalid = false; 141 | for (Cube cube : list) 142 | { 143 | int[][] element = cube.getElement(); 144 | int column = cube.getStartColumn(); 145 | int row = cube.getStartIndex(); 146 | int irow = 0; 147 | int icol = 0; 148 | for (int i = row; i < row + 5; i++) 149 | { 150 | for (int j = column; j < column + 5; j++) 151 | { 152 | if (!unfold && outputArr[i][j] == 1) 153 | { 154 | invalid = true; 155 | break; 156 | } 157 | outputArr[i][j] = element[irow][icol++]; 158 | } 159 | icol = 0; 160 | irow++; 161 | } 162 | } 163 | if (!invalid) 164 | print(); 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/controller/CubeController.java: -------------------------------------------------------------------------------- 1 | package com.cube.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.cube.OutputStructure; 7 | import com.cube.helper.Constant; 8 | import com.cube.model.Cube; 9 | 10 | /** 11 | * Controller class responsible to delegate each action happens over the cube . 12 | * 13 | * It builds the unfolded or all permutation cube 14 | * @author abc 15 | * 16 | */ 17 | public class CubeController { 18 | 19 | private List cubeList = new ArrayList<>(); 20 | private int[][] store = new int[Constant.ROW][Constant.COLUMN]; 21 | private OutputStructure outputStructure; 22 | 23 | public CubeController(OutputStructure outputStructure) { 24 | this.outputStructure = outputStructure; 25 | } 26 | 27 | public List getList() { 28 | return cubeList; 29 | } 30 | 31 | /** 32 | * This method handles the representation of a Cube to its Unfolded form. 33 | * This method is responsible for presentation the cube in Unfolded format. 34 | * Its getting called recursively for each orientation of any piece of cube, 35 | * all other occurrence is being verified and the one which fits takes the 36 | * advantage. 37 | * 38 | * It defines a matrix named store(graph).Store is nothing but a 39 | * representation of Graph For each iteration over cube orientations, it 40 | * sets the value to the matrix store in the correct state.Matrix acts like 41 | * a big blank graph which multiple nodes define with no definition. a) For 42 | * sequence 0, it just a blank Cube , so it doesn't need to face any 43 | * validation while adding to the graph. So first node being added to the 44 | * graph. (node1) b) Then next node try to set to left of Node1. So while 45 | * validating the same, it needs to make sure the xor status as defined in 46 | * {@link CubeValidation}. Once thats achieved it adds the Node to left of 47 | * node1 and it changes the graph edge references of both nodes 1 and 2. c) 48 | * Following on each of the nodes, and there validation almost does the 49 | * similar task only difference is reference setting 50 | * 51 | * @param sequence 52 | * @param matrix 53 | * @return 54 | */ 55 | public List buildUnfoldedCube(int sequence, int[][] matrix) { 56 | if (sequence == 0) { 57 | // since just a blank scenario , add the cube 58 | Cube cube = new Cube(matrix); 59 | cube.setStartIndex(10); 60 | cube.setStartColumn(10); 61 | cubeList.add(cube); 62 | outputStructure.updateOutput(matrix, 10, 10); 63 | } 64 | if (cubeList.size() > 0) { 65 | switch (sequence) { 66 | 67 | case 1: 68 | // Right 69 | Cube cube1 = cubeList.get(0); 70 | if (CubeValidation.fitRightBasicSequence(cube1, matrix, store)) { 71 | Cube cube = new Cube(matrix); 72 | cube.setStartIndex(10); 73 | cube.setStartColumn(15); 74 | cube1.right = cube; 75 | cube.left = cube1; 76 | cubeList.add(cube); 77 | outputStructure.updateOutput(matrix, 10, 15); 78 | } 79 | break; 80 | case 2: 81 | // Left of Middle Node 82 | cube1 = cubeList.get(0); 83 | if (CubeValidation.fitLeftBasicSequence(cube1, matrix, store)) { 84 | Cube cube = new Cube(matrix); 85 | cube.setStartIndex(10); 86 | cube.setStartColumn(5); 87 | cube1.left = cube; 88 | cube.right = cube1; 89 | cubeList.add(cube); 90 | outputStructure.updateOutput(matrix, 10, 5); 91 | } 92 | break; 93 | 94 | case 3: 95 | // Top of Middle Node 96 | cube1 = cubeList.get(0); 97 | if (CubeValidation.fitTopBasicSequence(cube1, matrix, store)) { 98 | Cube cube = new Cube(matrix); 99 | cube.setStartIndex(5); 100 | cube.setStartColumn(10); 101 | cube1.top = cube; 102 | cube.bottom = cube1; 103 | cubeList.add(cube); 104 | outputStructure.updateOutput(matrix, 5, 10); 105 | } 106 | break; 107 | case 4: 108 | // Bottom of Middle Node 109 | cube1 = cubeList.get(0); 110 | if (CubeValidation.fitBottomBasicSequence(cube1, matrix, store)) { 111 | Cube cube = new Cube(matrix); 112 | cube.setStartIndex(15); 113 | cube.setStartColumn(10); 114 | cube1.bottom = cube; 115 | cube.top = cube1; 116 | cubeList.add(cube); 117 | outputStructure.updateOutput(matrix, 15, 10); 118 | } 119 | break; 120 | case 5: 121 | Cube cube4 = cubeList.get(4); 122 | if (CubeValidation.fitBottomBasicSequence(cube4, matrix, store)) { 123 | Cube cube = new Cube(matrix); 124 | cube.setStartIndex(20); 125 | cube.setStartColumn(10); 126 | cube4.bottom = cube; 127 | cube.top = cube4; 128 | cubeList.add(cube); 129 | outputStructure.updateOutput(matrix, 20, 10); 130 | } 131 | break; 132 | // Last or tail of the Tree 133 | } 134 | } 135 | return cubeList; 136 | } 137 | 138 | /** 139 | * This method actively inherits the same concept as defined in method 140 | * buildUnfoldedCube but this method doesn't work based on only unfolded 141 | * representation. This method will check for all available locations over 142 | * the graph to build a perfect match 143 | * 144 | * @param matrix 145 | * @return 146 | */ 147 | public List buildCubeInAnyForm(int[][] matrix) { 148 | try { 149 | if (cubeList.size() > 0) { 150 | for (int i = 0; i < cubeList.size(); i++) { 151 | Cube cube = cubeList.get(i); 152 | if (cube.left == null && CubeValidation.fitLeftBasicSequence(cube, matrix, store)) { 153 | Cube leftcube = new Cube(matrix); 154 | // reset the left 155 | leftcube.setStartIndex(cube.getStartIndex()); 156 | leftcube.setStartColumn(cube.getStartColumn() - 5); 157 | cube.left = leftcube; 158 | leftcube.right = cube; 159 | cubeList.add(leftcube); 160 | updateStore(matrix, leftcube.getStartIndex(), leftcube.getStartColumn()); 161 | break; 162 | } else if (cube.right == null && CubeValidation.fitRightBasicSequence(cube, matrix, store)) { 163 | Cube newcube = new Cube(matrix); 164 | cube.right = newcube; 165 | newcube.left = cube; 166 | newcube.setStartIndex(cube.getStartIndex()); 167 | newcube.setStartColumn(cube.getStartColumn() + 5); 168 | updateStore(matrix, newcube.getStartIndex(), newcube.getStartColumn()); 169 | cubeList.add(newcube); 170 | break; 171 | } else if (cube.top == null && CubeValidation.fitTopBasicSequence(cube, matrix, store)) { 172 | Cube newcube = new Cube(matrix); 173 | cube.top = newcube; 174 | newcube.bottom = cube; 175 | newcube.setStartIndex(cube.getStartIndex() - 5); 176 | newcube.setStartColumn(cube.getStartColumn()); 177 | updateStore(matrix, newcube.getStartIndex(), newcube.getStartColumn()); 178 | cubeList.add(newcube); 179 | break; 180 | } else if (cube.bottom == null && CubeValidation.fitBottomBasicSequence(cube, matrix, store)) { 181 | Cube newcube = new Cube(matrix); 182 | cube.bottom = newcube; 183 | newcube.top = cube; 184 | newcube.setStartIndex(cube.getStartIndex() + 5); 185 | newcube.setStartColumn(cube.getStartColumn()); 186 | updateStore(matrix, newcube.getStartIndex(), newcube.getStartColumn()); 187 | cubeList.add(newcube); 188 | break; 189 | } 190 | } 191 | } else { 192 | Cube cube = new Cube(matrix); 193 | cubeList.add(cube); 194 | cube.setStartIndex(10); 195 | cube.setStartColumn(30); 196 | updateStore(matrix, 10, 30); 197 | } 198 | } catch (Exception e) { 199 | // System.err.println("Error occured from : " + 200 | // e.getLocalizedMessage()); 201 | } 202 | 203 | return cubeList; 204 | } 205 | 206 | /** 207 | * Update the Graph will latest updated value to ensure the validation check 208 | * 209 | * @param matrix 210 | * @param row 211 | * @param column 212 | */ 213 | private void updateStore(int[][] matrix, int row, int column) { 214 | int irow = 0; 215 | int icol = 0; 216 | for (int i = row; i < row + 5; i++) { 217 | for (int j = column; j < column + 5; j++) { 218 | store[i][j] = matrix[irow][icol++]; 219 | } 220 | icol = 0; 221 | irow++; 222 | } 223 | } 224 | 225 | } 226 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/controller/CubeValidation.java: -------------------------------------------------------------------------------- 1 | package com.cube.controller; 2 | 3 | import com.cube.helper.Util; 4 | import com.cube.model.Cube; 5 | 6 | /** 7 | * This class holds the responsibility for validation the cube . 8 | * Ideally a cube is nothing but a Graph Node in datastructure. 9 | * 10 | * Since its a Graph, it has multiple child and we fixed it to 11 | * 4. More details {@link Cube} Since its being maintained by Graph, so traversing became simply 12 | * like DFS over any Graph or Tree 13 | * 14 | * @author abc 15 | * 16 | */ 17 | public class CubeValidation 18 | { 19 | 20 | 21 | /** 22 | * if right sequence agreed to collaborate 1-0 XOR 23 | * 24 | * @param cube the main cube 25 | * @param matrix to be compared with this 26 | * @return if matrix can be attached to right of the cube 27 | */ 28 | public static boolean fitRightBasicSequence(Cube cube, int[][] matrix, int[][] store) 29 | { 30 | return xorColumns(cube.getRight(), Util.getLeft(matrix)) 31 | && revalidateXor(cube.getStartIndex(), 32 | cube.getStartColumn() + 5, cube, matrix, store); 33 | } 34 | 35 | /** 36 | * if Left sequence agreed to collaborate 1-0 XOR 37 | * 38 | * @param cube 39 | * @param matrix 40 | * @return if matrix can be attached to left of the cube 41 | */ 42 | public static boolean fitLeftBasicSequence(Cube cube, int[][] matrix, int[][] store) 43 | { 44 | return xorColumns(cube.getLeft(), Util.getRight(matrix)) 45 | && revalidateXor(cube.getStartIndex(), 46 | cube.getStartColumn() - 5, cube, matrix, store); 47 | } 48 | 49 | /** 50 | * if top sequence agreed to collaborate 1-0 XOR 51 | * 52 | * @param cube 53 | * @param matrix 54 | * @return if matrix can be attached to top of the cube 55 | */ 56 | public static boolean fitTopBasicSequence(Cube cube, int[][] matrix, int[][] store) 57 | { 58 | return xorColumns(Util.getBottom(matrix), cube.getTop()) 59 | && revalidateXor(cube.getStartIndex() - 5, 60 | cube.getStartColumn(), cube, matrix, store); 61 | } 62 | 63 | /** 64 | * if bottom sequence agreed to collaborate 1-0 XOR 65 | * 66 | * @param cube 67 | * @param matrix 68 | * @return if matrix can be attached to bottom of the cube 69 | */ 70 | public static boolean fitBottomBasicSequence(Cube cube, int[][] matrix, int[][] store) 71 | { 72 | return xorColumns(cube.getBottom(), Util.getTop(matrix)) 73 | && revalidateXor(cube.getStartIndex() + 5, 74 | cube.getStartColumn(), cube, matrix, store); 75 | } 76 | 77 | 78 | /** 79 | * On placing component to any edge reference of {@link Cube} ie left, right ... 80 | * its must to see the surrounding as well. Because validation is fine with the reference node, but 81 | * there is a chance that the desired position has other neighbor as well. 82 | * 83 | * So conceptualize the thing , while adding any piece to Graph, this validates its verifies XORing with 84 | * each side of its neighbor 85 | * 86 | * @param oRow 87 | * @param oCol 88 | * @param cube 89 | * @param matrix 90 | * @param store 91 | * @return 92 | * @throws ArrayIndexOutOfBoundsException 93 | */ 94 | private static boolean revalidateXor(int oRow, int oCol, Cube cube, 95 | int[][] matrix, int[][] store) throws ArrayIndexOutOfBoundsException 96 | { 97 | // System.out.println(" Orow " + oRow + " Col " + oCol); 98 | int[] topLayerFromArray = { store[oRow + 5][oCol], store[oRow + 5][oCol + 1], 99 | store[oRow + 5][oCol + 2], store[oRow + 5][oCol + 3], 100 | store[oRow + 5][oCol + 4] };// bottom 101 | int[] bottomLayerFromArray = { store[oRow - 1][oCol], store[oRow - 1][oCol + 1], 102 | store[oRow - 1][oCol + 2], store[oRow - 1][oCol + 3], 103 | store[oRow - 1][oCol + 4] };// top 104 | 105 | return xorColumns(Util.getBottom(matrix), topLayerFromArray) 106 | && xorColumns(Util.getTop(matrix), bottomLayerFromArray) 107 | && xorEverything(matrix,store); 108 | } 109 | 110 | private static boolean xorEverything(int[][] thisCube, int[][] otherCube){ 111 | boolean result = true; 112 | for(int i=0;i<5;i++){ 113 | for(int j=0;j<5;j++){ 114 | if (thisCube[i][j] == 0 && otherCube[i][j] == 0) 115 | { 116 | continue; 117 | } 118 | else 119 | { 120 | if ((thisCube[i][j] ^ otherCube[i][j]) == 0) 121 | { 122 | result = false; 123 | break; 124 | } 125 | } 126 | } 127 | } 128 | return result; 129 | } 130 | 131 | 132 | /** 133 | * Since everything is based on matrix representation , simply use the concept of XOR. 134 | * So if any 2 pieces can be fit together if either both the sides are 0 , or 1 side is 135 | * 0 and other is 1. 136 | * 137 | * So XORing simply did the job to validate cell position validation 138 | * 139 | * @param thisCube 140 | * @param otherCube 141 | * @return 142 | */ 143 | private static boolean xorColumns(int[] thisCube, int[] otherCube) 144 | { 145 | boolean result = true; 146 | for (int i = 0; i < 5; i++) 147 | { 148 | if (thisCube[i] == 0 && otherCube[i] == 0) 149 | { 150 | continue; 151 | } 152 | else 153 | { 154 | if ((thisCube[i] ^ otherCube[i]) == 0) 155 | { 156 | result = false; 157 | break; 158 | } 159 | } 160 | } 161 | return result; 162 | } 163 | 164 | } 165 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/helper/Constant.java: -------------------------------------------------------------------------------- 1 | package com.cube.helper; 2 | 3 | /** 4 | * Holds the Constant 5 | * @author abc 6 | * 7 | */ 8 | public interface Constant 9 | { 10 | 11 | 12 | public static final int ROW = 30; 13 | 14 | public static final int COLUMN = 60; 15 | } 16 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/helper/GraphHelper.java: -------------------------------------------------------------------------------- 1 | package com.cube.helper; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * This class is responsible for handling all the rotations of any Node 8 | * As its Matrix, so its rotating matrix in every direction clock-wise 9 | * anticlock wise 10 | * 11 | * It as well mainatins a method for mirror and flip 12 | * 13 | * @author abc 14 | * 15 | */ 16 | public class GraphHelper 17 | { 18 | 19 | /** 20 | * returns the flipping of entire block/piece 21 | * @param theArray the original block content as matrix 22 | * @return 23 | */ 24 | public static int[][] flipInPlace(int[][] theArray) 25 | { 26 | for (int i = 0; i < (theArray.length / 2); i++) 27 | { 28 | int[] temp = theArray[i]; 29 | theArray[i] = theArray[theArray.length - i - 1]; 30 | theArray[theArray.length - i - 1] = temp; 31 | } 32 | return theArray; 33 | } 34 | 35 | /** 36 | * flip the block from left to right 37 | * @param theArray theArray the original block content as matrix 38 | * @return 39 | */ 40 | public static int[][] flipLeftToRight(int[][] theArray) 41 | { 42 | 43 | for (int i = 0; i < theArray.length; i++) 44 | { 45 | for (int curr = 0; curr < (theArray[0].length + 1) / 2; curr++) 46 | { 47 | 48 | int saved = theArray[i][curr]; 49 | theArray[i][curr] = theArray[i][theArray[0].length - 1 - curr]; 50 | theArray[i][theArray[0].length - 1 - curr] = saved; 51 | } 52 | } 53 | return theArray; 54 | } 55 | 56 | /** 57 | * returns the mirror of cube 58 | * @param width columns 59 | * @param height number of rows 60 | * @param theArray 61 | * @return 62 | */ 63 | public static int[][] mirror(int width, int height, int[][] theArray) 64 | { 65 | int[][] out = new int[height][width]; 66 | for (int i = 0; i < height; i++) 67 | { 68 | for (int j = 0; j < width; j++) 69 | { 70 | out[i][width - j - 1] = theArray[i][j]; 71 | } 72 | } 73 | return out; 74 | } 75 | 76 | /** 77 | * rotates the matrix to clock wise 78 | * @param pixels 79 | * @return 80 | */ 81 | public static int[][] rotateClockWise(int[][] theArray) 82 | { 83 | 84 | int[][] rotate = new int[theArray[0].length][theArray.length]; 85 | 86 | for (int i = 0; i < theArray[0].length; i++) 87 | { 88 | for (int j = 0; j < theArray.length; j++) 89 | { 90 | rotate[i][theArray.length - 1 - j] = theArray[j][i]; 91 | } 92 | } 93 | return rotate; 94 | } 95 | 96 | /** 97 | * rotates the component anti clock-wise 98 | * @param pixels 99 | * @return 100 | */ 101 | public static int[][] rotateAntiClockwise(int[][] pixels) 102 | { 103 | 104 | int[][] newarray = new int[pixels[0].length][pixels.length]; 105 | 106 | for (int i = 0; i < pixels.length; i++) 107 | { 108 | for (int j = 0; j < pixels[0].length; j++) 109 | { 110 | newarray[pixels[0].length - 1 - j][i] = pixels[i][j]; 111 | } 112 | } 113 | 114 | return newarray; 115 | } 116 | 117 | /** 118 | * returns all 360 rotations in clock-wise in given matrix 119 | * @param matrix 120 | * @return 121 | */ 122 | public static List findAllPossibleRightRotations(int[][] matrix) 123 | { 124 | List allPossibleRotations = new ArrayList<>(); 125 | for (int i = 0; i < 3; i++) 126 | { 127 | matrix = rotateClockWise(matrix); 128 | allPossibleRotations.add(matrix); 129 | } 130 | return allPossibleRotations; 131 | } 132 | 133 | /** 134 | * returns all 360 rotations made anti clock-wise in given matrix 135 | * @param matrix 136 | * @return 137 | */ 138 | public static List findAllPossibleLefttRotations(int[][] matrix) 139 | { 140 | List allPossibleRotations = new ArrayList<>(); 141 | for (int i = 0; i < 3; i++) 142 | { 143 | matrix = rotateAntiClockwise(matrix); 144 | allPossibleRotations.add(matrix); 145 | } 146 | return allPossibleRotations; 147 | } 148 | 149 | /** 150 | * find all orientations of any matrix or piece provided 151 | * @param matrix 152 | * @return 153 | */ 154 | public static List findAllOrientations(int[][] matrix) 155 | { 156 | List allPossibleRotations = new ArrayList<>(); 157 | allPossibleRotations.add(matrix); 158 | allPossibleRotations.add(flipInPlace(matrix)); 159 | allPossibleRotations 160 | .add(mirror(matrix[0].length, matrix.length, matrix)); 161 | 162 | allPossibleRotations 163 | .addAll(findAllPossibleRightRotations(allPossibleRotations 164 | .get(0))); 165 | 166 | allPossibleRotations 167 | .addAll(findAllPossibleRightRotations(allPossibleRotations 168 | .get(2))); 169 | 170 | return allPossibleRotations; 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/helper/Util.java: -------------------------------------------------------------------------------- 1 | package com.cube.helper; 2 | 3 | /** 4 | * Utilities 5 | * @author abc 6 | * 7 | */ 8 | public class Util 9 | { 10 | 11 | /** 12 | * get right vertical elements of an array 13 | * @param element 14 | * @return 15 | */ 16 | public static int[] getRight(int[][] element) 17 | { 18 | int[] right = new int[element.length]; 19 | for (int i = 0; i < element.length; i++) 20 | { 21 | right[i] = element[i][4]; 22 | } 23 | return right; 24 | } 25 | 26 | /** 27 | * returns left vertical elements of an array 28 | * @param element 29 | * @return 30 | */ 31 | public static int[] getLeft(int[][] element) 32 | { 33 | int[] left = new int[element.length]; 34 | for (int i = 0; i < element.length; i++) 35 | { 36 | left[i] = element[i][0]; 37 | } 38 | return left; 39 | } 40 | 41 | /** 42 | * get top row of a 2d array or matrix 43 | * @param element 44 | * @return 45 | */ 46 | public static int[] getTop(int[][] element) 47 | { 48 | return element[0]; 49 | } 50 | 51 | /** 52 | * get last row of a 2D array or matrix 53 | * @param element 54 | * @return 55 | */ 56 | public static int[] getBottom(int[][] element) 57 | { 58 | return element[element.length - 1]; 59 | } 60 | 61 | 62 | /** 63 | * Convert String array to Matrix like representation 64 | * 65 | * @param cube 66 | * @return 67 | */ 68 | public static int[][] convertToArray(String[] cube) 69 | { 70 | 71 | int[][] matrix = new int[5][5]; 72 | int rowIndex = 0; 73 | 74 | for (String row : cube) 75 | { 76 | char[] charArray = row.toCharArray(); 77 | int columnIndex = 0; 78 | for (char c : charArray) 79 | { 80 | if (c == ' ') 81 | { 82 | matrix[rowIndex][columnIndex] = 0; 83 | } 84 | else 85 | { 86 | matrix[rowIndex][columnIndex] = 1; 87 | } 88 | columnIndex++; 89 | } 90 | rowIndex++; 91 | } 92 | return matrix; 93 | } 94 | 95 | 96 | 97 | } 98 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/model/Cube.java: -------------------------------------------------------------------------------- 1 | package com.cube.model; 2 | 3 | /** 4 | * Model class of cube , like skeleton of any cube Block 5 | * It behaves a graph with 4 nodes left , right , top and bottom 6 | * @author abc 7 | * 8 | */ 9 | public class Cube 10 | { 11 | 12 | 13 | int[][] element = new int[5][5]; 14 | 15 | // hold the reference of adjacent Node 16 | public Cube left; 17 | 18 | public Cube right; 19 | 20 | public Cube top; 21 | 22 | public Cube bottom; 23 | 24 | // maintains the start row and column index 25 | int startRow; 26 | 27 | int startColumn; 28 | 29 | 30 | public int getStartColumn() 31 | { 32 | return startColumn; 33 | } 34 | 35 | 36 | public void setStartColumn(int startColumn) 37 | { 38 | this.startColumn = startColumn; 39 | } 40 | 41 | 42 | public Cube(int[][] element) 43 | { 44 | this.element = element; 45 | } 46 | 47 | 48 | public Cube() 49 | { 50 | 51 | } 52 | 53 | 54 | public int[] getLeft() 55 | { 56 | int[] left = new int[element.length]; 57 | for (int i = 0; i < element.length; i++) 58 | { 59 | left[i] = element[i][0]; 60 | } 61 | return left; 62 | } 63 | 64 | 65 | public int[] getRight() 66 | { 67 | int[] right = new int[element.length]; 68 | for (int i = 0; i < element.length; i++) 69 | { 70 | right[i] = element[i][4]; 71 | } 72 | return right; 73 | } 74 | 75 | 76 | public int[] getBottom() 77 | { 78 | return element[4]; 79 | } 80 | 81 | 82 | public int[] getTop() 83 | { 84 | return element[0]; 85 | } 86 | 87 | 88 | public int[][] getElement() 89 | { 90 | return element; 91 | } 92 | 93 | 94 | public void setStartIndex(int startIndex) 95 | { 96 | this.startRow = startIndex; 97 | } 98 | 99 | 100 | public int getStartIndex() 101 | { 102 | return startRow; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/test/Challenge1Part1Test.java: -------------------------------------------------------------------------------- 1 | package com.cube.test; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.cube.CubeGraphTraversal; 7 | 8 | /** 9 | * Print Single Unfolded representation of any color block set 10 | * This is the first challenge of Part 1 11 | * @author abc 12 | * 13 | */ 14 | public class Challenge1Part1Test { 15 | public static void main(String[] args) { 16 | CubeGraphTraversal traversal = new CubeGraphTraversal(true,true); //true means only one result 17 | 18 | TestHelper helper = new TestHelper(); 19 | Map> cubeBlocksinMatrix = helper.getCubeBlocksinMatrix(); 20 | for (Map.Entry> entry : cubeBlocksinMatrix.entrySet()) { 21 | String key = entry.getKey(); 22 | List value = entry.getValue(); 23 | traversal.traverse( value,"output/"+key+"/Challenge1part1",false,true,true); 24 | // do stuff 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/test/Challenge1Part2Test.java: -------------------------------------------------------------------------------- 1 | package com.cube.test; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.cube.CubeGraphTraversal; 7 | 8 | /** 9 | * Print all Unfolded representation of any color block set 10 | * This is the first challenge of Part 2 11 | * @author abc 12 | * 13 | */ 14 | public class Challenge1Part2Test { 15 | public static void main(String[] args) { 16 | CubeGraphTraversal traversal = new CubeGraphTraversal(false,true); //true means only one result 17 | 18 | TestHelper helper = new TestHelper(); 19 | Map> cubeBlocksinMatrix = helper.getCubeBlocksinMatrix(); 20 | for (Map.Entry> entry : cubeBlocksinMatrix.entrySet()) { 21 | String key = entry.getKey(); 22 | List value = entry.getValue(); 23 | traversal.traverse( value,"output/"+key+"/Challenge1part2",false,true,true); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/test/Challenge2Test.java: -------------------------------------------------------------------------------- 1 | package com.cube.test; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.cube.CubeGraphTraversal; 7 | 8 | /** 9 | * Print Single Unfolded representation of any color block set 10 | * This is the first challenge of Part 1 11 | * @author abc 12 | * 13 | */ 14 | public class Challenge2Test { 15 | public static void main(String[] args) { 16 | CubeGraphTraversal traversal = new CubeGraphTraversal(false,false); //true means only one result 17 | 18 | TestHelper helper = new TestHelper(); 19 | Map> cubeBlocksinMatrix = helper.getCubeBlocksinMatrix(); 20 | for (Map.Entry> entry : cubeBlocksinMatrix.entrySet()) { 21 | String key = entry.getKey(); 22 | List value = entry.getValue(); 23 | traversal.traverse( value,"output/"+key+"/Challenge2",false,true,false); 24 | // do stuff 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cube/HappyCube/src/main/java/com/cube/test/TestHelper.java: -------------------------------------------------------------------------------- 1 | package com.cube.test; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import com.cube.helper.Util; 9 | 10 | public class TestHelper { 11 | List listOfMatrix = new ArrayList<>(); 12 | Map> cubeBlocksMap = new HashMap<>(); 13 | public TestHelper() { 14 | createPurpleCube("Purple"); 15 | createBlueCube("Blue"); 16 | createRedCube("Red"); 17 | createGreenCube("Green"); 18 | } 19 | 20 | private void createPurpleCube(String color){ 21 | String[] tPiece0 = { "oo o ", "oooo ", "oooo ", " oooo", " o " }; 22 | String[] tPiece1 = { " oo", "oooo ", "ooooo", " ooo ", " o o " }; 23 | String[] tPiece2 = { " o ", "oooo ", " oooo", "oooo ", " o " }; 24 | String[] tPiece3 = { "oo oo", " oooo", "oooo ", " ooo ", " o o " }; 25 | String[] tPiece4 = { " o o", " oooo", "ooooo", "oooo ", "o oo " }; 26 | String[] tPiece5 = { " o oo", " ooo ", " oooo", "oooo ", "oo o " }; 27 | 28 | commonwork(color,tPiece0,tPiece1,tPiece2,tPiece3,tPiece4,tPiece5); 29 | 30 | } 31 | 32 | private void createRedCube(String color){ 33 | // RED Couldn't find any permutation to unfold red node to 6 34 | String[] tPiece0 = { " oo", " ooo ", "ooooo", " ooo ", " o oo" }; 35 | String[] tPiece1 = { " o o ", "oooo ", " oooo", "oooo ", " o " }; 36 | String[] tPiece2 = { " oo o", "ooooo", " ooo ", "ooooo", "o oo" }; 37 | String[] tPiece3 = { " o ", "oooo ", " oooo", "oooo ", " o " }; 38 | String[] tPiece4 = { " oo ", "ooooo", " ooo ", "ooooo", "o o " }; 39 | String[] tPiece5 = { " oo ", " ooo ", "ooooo", " ooo ", "oo oo" }; 40 | commonwork(color,tPiece0,tPiece1,tPiece2,tPiece3,tPiece4,tPiece5); 41 | 42 | } 43 | private void createBlueCube(String color){ 44 | // BLUE 45 | String[] tPiece0 = { " o ", " ooo ", "ooooo", " ooo ", " o " }; 46 | String[] tPiece1 = { " o o", "ooooo", " ooo ", "ooooo", " o oo" }; 47 | String[] tPiece2 = { " o o ", " ooo ", "ooooo", " ooo ", " o " }; 48 | String[] tPiece3 = { "o o ", "ooooo", " ooo ", "ooooo", " o o " }; 49 | String[] tPiece4 = { "o o o", "ooooo", " ooo ", "ooooo", "o o o" }; 50 | String[] tPiece5 = { " o o ", "oooo ", " oooo", "oooo ", "oo o " }; 51 | 52 | commonwork(color,tPiece0,tPiece1,tPiece2,tPiece3,tPiece4,tPiece5); 53 | 54 | } 55 | 56 | private void createGreenCube(String color){ 57 | // Green 58 | String[] tPiece0 = { " o ", "oooo ", " oooo", "oooo ", " o o " }; 59 | String[] tPiece1 = { " o o", "ooooo", " ooo ", "oooo ", " o o " }; 60 | String[] tPiece2 = { " o o", " oooo", "oooo ", "ooooo", "o o " }; 61 | String[] tPiece3 = { " o ", " oooo", "oooo ", " oooo", "oo o " }; 62 | String[] tPiece4 = { "o o o", "ooooo", " ooo ", "ooooo", "o o " }; 63 | String[] tPiece5 = { " o o ", " ooo ", "ooooo", " ooo ", " o oo" }; 64 | 65 | commonwork(color,tPiece0,tPiece1,tPiece2,tPiece3,tPiece4,tPiece5); 66 | 67 | } 68 | 69 | private void commonwork(String cubeColor,String[] tPiece0,String[] tPiece1,String[] tPiece2,String[] tPiece3,String[] tPiece4,String[] tPiece5){ 70 | int[][] convertToArray1 = Util.convertToArray(tPiece0); 71 | int[][] convertToArray2 = Util.convertToArray(tPiece1); 72 | int[][] convertToArray3 = Util.convertToArray(tPiece2); 73 | int[][] convertToArray4 = Util.convertToArray(tPiece3); 74 | int[][] convertToArray5 = Util.convertToArray(tPiece5); 75 | int[][] convertToArray6 = Util.convertToArray(tPiece4); 76 | 77 | List listOfMatrix = new ArrayList<>(); 78 | 79 | listOfMatrix.add(convertToArray1); 80 | listOfMatrix.add(convertToArray2); 81 | listOfMatrix.add(convertToArray3); 82 | listOfMatrix.add(convertToArray4); 83 | listOfMatrix.add(convertToArray5); 84 | listOfMatrix.add(convertToArray6); 85 | 86 | cubeBlocksMap.put(cubeColor, listOfMatrix); 87 | } 88 | 89 | public Map> getCubeBlocksinMatrix(){ 90 | return cubeBlocksMap; 91 | } 92 | 93 | } 94 | 95 | -------------------------------------------------------------------------------- /cube/HappyCube/target/.gitignore: -------------------------------------------------------------------------------- 1 | /classes/ 2 | /test-classes/ 3 | -------------------------------------------------------------------------------- /cube/Main.java: -------------------------------------------------------------------------------- 1 | package cube; 2 | import java.util.Arrays; 3 | 4 | public class Main { 5 | public static void main(String args[]) { 6 | String s[] = {"a", "b", "c", "d"}; 7 | double d [][]= { 8 | {0.50, 0.20, 0.20, 0.30}, 9 | {0.50, 1.10, 0.50, 0.80}, 10 | {0.50, 0.70, 0.40}, 11 | {0.50, 0.70}, 12 | {0.50}, 13 | }; 14 | System.out.println(Arrays.toString(s)); 15 | System.out.println(Arrays.deepToString(d)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /general.sc: -------------------------------------------------------------------------------- 1 | import java.util.Date 2 | 3 | val list = List(1,2,3,4,5) 4 | list.foreach(num => print(num +1)) //won't return anything 5 | 6 | 7 | val list2 = List(1,2,3,4,6,7,8,12,14,13,14,15,15,17,18) 8 | 9 | val oddOne:PartialFunction[Int, Int] = { 10 | case x: Int if x % 2 == 0 => x * 3 11 | } 12 | 13 | val evenOne:PartialFunction[Int, Int] = { 14 | case x: Int if x % 2 != 0 => x + 5 15 | } 16 | 17 | 18 | 19 | val result0 = list2.collect(oddOne orElse evenOne) 20 | 21 | val set1 = list2.toSet 22 | val stream1 = list2.toStream 23 | stream1 take 5 print 24 | 25 | stream1 take 2 print 26 | 27 | 28 | val set2 = Set("Phoenix" -> "Arizona", "Austin" -> "Texas") 29 | set2.toMap 30 | 31 | list2.headOption 32 | list2.head 33 | 34 | list2.find(_ % 2 != 0) 35 | 36 | list2.slice(1,50) 37 | 38 | 39 | //stream 40 | //can generate value as a stream till infinity 41 | def streamer(a:Int):Stream[Int] = Stream.cons(a, streamer(a+2)) 42 | val stream2 = streamer(10) 43 | 44 | stream2 take 50 toList 45 | 46 | stream2 take 3 toList 47 | 48 | (stream2 drop 5) take 5 toList 49 | 50 | 51 | val isOdd:PartialFunction[Int,String] = { 52 | case x : Int if x % 2 != 0 && x < 100 => "Its is Odd" 53 | } 54 | 55 | val isEven:PartialFunction[Int,String] = { 56 | case x : Int if x % 2 == 0 => "Its is Odd" 57 | } 58 | 59 | val isNeg:PartialFunction[Int,String]={ 60 | case x:Int if x < 0 => "I am Negative" 61 | } 62 | 63 | val isGreat:PartialFunction[Int,Int]={ 64 | case x:Int if x > 100 => 100 65 | } 66 | 67 | val array = Array(87, 44, 5, 4, 200, 10, 39, 100) 68 | 69 | val result3 = array groupBy { 70 | isOdd orElse 71 | isEven orElse 72 | isNeg orElse 73 | isGreat 74 | } 75 | 76 | 77 | val result1 = array forall(_ <= 200) 78 | 79 | val list3 = List(5,4,3,2,1) 80 | 81 | //fold left 82 | val result4 = (3 /: list3){ 83 | (`pappu1`,`pappu2`) => `pappu1` - `pappu2` 84 | } 85 | 86 | val result5 = (((((3 - 5)-4)-3)-2)-1) 87 | 88 | 89 | val result6 = (list3 :\ 0){ 90 | (`pappu1`,`pappu2`) => `pappu1` - `pappu2` 91 | } 92 | 93 | list3.sum 94 | 95 | 96 | //////////////////////////////////foldLeft is Tail recursion////////// 97 | val MAX_SIZE = 1000000 98 | val startDate = new Date 99 | (1 to MAX_SIZE) reduceLeft (_ + _) 100 | val endDate = new Date 101 | (1 to MAX_SIZE) reduceRight (_ + _) 102 | val superEndDate = new Date 103 | 104 | 105 | endDate.getTime - startDate.getTime 106 | superEndDate.getTime - endDate.getTime 107 | 108 | val list4 = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9)) 109 | list4.transpose 110 | 111 | list4.mkString(" + ") 112 | 113 | list.mkString("<"," = ",">") 114 | 115 | val strBuilder = new StringBuilder() 116 | strBuilder.append("Let's c how numbers can be assembled: ") 117 | list.filter(it => it > 2 && it < 8).addString(strBuilder," $ ") 118 | strBuilder.mkString 119 | 120 | var history = List[String]() 121 | 122 | def addHistory(s: String): Unit ={ 123 | history = history :+ s 124 | } 125 | 126 | val lst = list.map{ 127 | x => addHistory("History %s".format(x)) 128 | x * 2 129 | } 130 | 131 | print(history) 132 | 133 | val l2 = lst.map{ x => addHistory("Adding 1 to %s".format(x)); x + 1} 134 | 135 | val l3 = list.view.map{ x => addHistory("Adding 1 to %s".format(x)); x + 1}.map{ 136 | x => addHistory(" multiply by 2 to %s".format(x)); x * 2}.force 137 | 138 | list.view.map(_ + 4).map(_ * 10).force 139 | 140 | print(history) -------------------------------------------------------------------------------- /python/LongestNotRepeatedCharacterSubString.py: -------------------------------------------------------------------------------- 1 | __author__ = 'achoudhary' 2 | 3 | ## 4 | # Iterate through each character of the array and add the occurances of each caharacter index 5 | # into a hashtable. 6 | # 1st occurance of any character till any next repeated occurance of character stopped the substring 7 | # then again the start pointer moves to current node or the repeating character and again the 8 | # same logic starts 9 | ## 10 | 11 | inputs = ["Abhishekzrpoiepooliooopabcdefghijklmn","abcabaabccfdsaewer","Abhishek","CharliedaadaabcdefghijklmnmbrijeshoAlphaBeta","AABCdefghhijkl"] 12 | 13 | 14 | for input in inputs: 15 | index = 0 16 | charFreqIndex = {} 17 | currIndex = 0 18 | maxsize = 0 19 | 20 | pointA = 0 21 | pointB = 0 22 | #iterate through each character 23 | for char in input: 24 | 25 | if not charFreqIndex.has_key(char): 26 | values = [index] 27 | charFreqIndex[char] = values 28 | # print("NA ",char,' = ',index) 29 | 30 | else: 31 | #fetch all the values of the current available list of particular key 32 | subvalues = charFreqIndex.get(char) 33 | lastAvailableIndex = subvalues[-1] #get the last value 34 | #print(char,subvalues) 35 | 36 | #if last index for a character in the list is more than the previous sstarting point of pointer 37 | #that means we have found the repeating character 38 | if lastAvailableIndex >= currIndex: 39 | size = (index-1) - currIndex 40 | #change the A and B point to get the new pointers 41 | if maxsize < size: 42 | pointA = currIndex 43 | pointB = index-1 44 | maxsize = max(maxsize,size) 45 | 46 | currIndex = index 47 | 48 | subvalues.append(index) 49 | charFreqIndex[char] = subvalues 50 | 51 | #increase counter 52 | index += 1 53 | 54 | #fail safe condition if last element in the list is non repeating , 55 | #logic doesn't found any break point to stop 56 | size = index - currIndex 57 | if maxsize < size: 58 | pointA = currIndex 59 | pointB = index 60 | maxsize = max(maxsize,size) 61 | 62 | 63 | print("Input ",input," MAXSIZE ",maxsize, "Output ",input[pointA:pointB]) -------------------------------------------------------------------------------- /python/NumbersWithGivenSum.py: -------------------------------------------------------------------------------- 1 | __author__ = 'achoudhary' 2 | 3 | input = [1,2,4,7,11,15] 4 | val = 26 5 | pointer1 = 0 6 | pointer2 = len(input)-1 7 | 8 | found = False 9 | while (not found): 10 | print(pointer1,pointer2) 11 | if pointer1 >= pointer2: 12 | break 13 | elif input[pointer1]+input[pointer2] < val: 14 | pointer1 += 1 15 | elif input[pointer1]+input[pointer2] > val: 16 | pointer2 -= 1 17 | elif input[pointer1]+input[pointer2] == val: 18 | found = True 19 | break 20 | 21 | 22 | 23 | if found: 24 | print("Output is : ",input[pointer1]," & ",input[pointer2]) 25 | else: 26 | print("Not Possible") 27 | -------------------------------------------------------------------------------- /python/PrimeSieve.py: -------------------------------------------------------------------------------- 1 | __author__ = 'abhishekchoudhary' 2 | 3 | # consider any N input 4 | #example N = 30 5 | 6 | #name O(n) = N add a dictionary with all values as Prime 7 | N = 130 8 | i =j= 2 #first prime number 9 | dict = {} 10 | while (i < N): 11 | dict[i] = True 12 | i += 1 13 | 14 | 15 | #iterate through each of the elements and find the unmarked element 16 | while j < N: 17 | 18 | if dict[j]: 19 | k = j 20 | while k+j < N: 21 | k += j 22 | dict[k] = False 23 | if dict[j]: 24 | #Displays the Prime Number 25 | print("Prime Number ",j) 26 | j += 1 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /python/binarysearch.py: -------------------------------------------------------------------------------- 1 | # Input will be list 2 | # Find the value 3 | input_arr = [ 2, 3, 4, 10, 40 ] 4 | finder = 2 5 | 6 | 7 | # def binary_search_util <- arr 8 | def binary_search_util(arr, left, right): 9 | # find middle element based on size of the array = middle 10 | 11 | # check middle is >= 1 12 | print('left %s right %s '%(left,right)) 13 | 14 | if right >= 1: 15 | middle = left + (right-1)/2 16 | 17 | print('Middle %s value %s'%(middle,arr[middle])) 18 | 19 | # if middle elem == finder : Return Found 20 | if arr[middle] == finder: 21 | return True 22 | # if middle of sorted array is > finder 23 | if arr[middle] > finder: 24 | # return binary_search_util <- arr[middle:len(arr)] 25 | print('Item is less than middle %s'%(middle-1)) 26 | return binary_search_util(arr,left,middle-1) 27 | # elif sorted array < finder 28 | elif arr[middle] < finder: 29 | # return binary_search_util <- arr[0:middle] 30 | return binary_search_util(arr,middle+1,right) 31 | else: 32 | return False 33 | else: 34 | return False 35 | 36 | # def function binary_search 37 | def binary_search(): 38 | # define sorted array sort_arr by sorting the input 39 | sorted_arr = sorted(input_arr) 40 | # call binary_search_util 41 | return binary_search_util(sorted_arr,0,len(sorted_arr)-1) 42 | 43 | print(binary_search()) 44 | 45 | -------------------------------------------------------------------------------- /python/boogle.py: -------------------------------------------------------------------------------- 1 | # define the input 2 | 3 | # expected list of output 4 | 5 | ''' 6 | {{'G', 'I', 'Z'}, 7 | {'U', 'E', 'K'}, 8 | {'Q', 'S', 'E'}} 9 | 10 | 11 | {"GEEKS", "FOR", "QUIZ", "GO"} 12 | 13 | https://www.geeksforgeeks.org/boggle-find-possible-words-board-characters/ 14 | 15 | ''' 16 | 17 | graph = [['G', 'I', 'Z'], 18 | ['U', 'E', 'K'], 19 | ['Q', 'S', 'E']] 20 | 21 | input_list = ["GEEKS", "FOR", "QUIZ", "GO"] 22 | 23 | result_set = set() 24 | 25 | 26 | def main(): 27 | # for each of the index [x][y] iterate through neighbours and do DFS 28 | # for x in graph: 29 | visited = [[False for x in range(len(graph)+1)] for y in range(len(graph[0])+1)] 30 | 31 | for x in range(len(graph)): 32 | # for y in col graph 33 | for y in range(len(graph[0])): 34 | # define visited as size of array (X*X) 35 | dfs_utl(x,y,visited,'') 36 | # dfs_utl(0,0,visited,'') 37 | print('Final Matching Values are %s'%list(result_set)) 38 | 39 | 40 | 41 | 42 | def find_word_in_str(str): 43 | for each in input_list: 44 | if each in str: 45 | return (True,each) 46 | 47 | return (False,'') 48 | 49 | 50 | # define dfs util function -> visited, x,y, res 51 | def dfs_utl(i,j,visited,res): 52 | # if x >= len(X) or y >= len(X) 53 | if i > len(graph)-1 or j > len(graph[0])-1 or i < 0 or j < 0 : 54 | return 55 | # visited -> True 56 | visited[i][j] = True 57 | 58 | # res += graph[x][y] 59 | 60 | res += graph[i][j] 61 | 62 | # print('Res is %s'%res) 63 | # check res contains any of the word in the list, if YES -> PRINT 64 | find_word_tuple = find_word_in_str(res) 65 | if find_word_tuple[0]: 66 | # print('Word Found is %s with String %s'%(find_word_tuple[1],res)) 67 | result_set.add(find_word_tuple[1]) 68 | 69 | # Looping through entire set 70 | 71 | 72 | # 8 steps of going/looping 73 | # dfs util (x+1,y) 74 | if not visited[i+1][j]: 75 | dfs_utl(i+1,j,visited,res) 76 | # dfs util (x-1,y) 77 | if not visited[i-1][j]: 78 | dfs_utl(i-1,j,visited,res) 79 | # dfs util (x,y+1) 80 | if not visited[i][j+1]: 81 | dfs_utl(i,j+1,visited,res) 82 | # dfs util (x,y-1) 83 | if not visited[i][j-1]: 84 | dfs_utl(i,j-1,visited,res) 85 | if not visited[i+1][j+1]: 86 | dfs_utl(i+1,j+1,visited,res) 87 | if not visited[i-1][j-1]: 88 | dfs_utl(i-1,j-1,visited,res) 89 | if not visited[i+1][j-1]: 90 | dfs_utl(i+1,j-1,visited,res) 91 | if not visited[i-1][j+1]: 92 | dfs_utl(i-1,j+1,visited,res) 93 | 94 | # visited[x][y] = False 95 | visited[i][j] = False 96 | # res = res[0:len(res)-1] 97 | res = res[0:len(res)-1] 98 | 99 | 100 | main() 101 | -------------------------------------------------------------------------------- /python/bt_maxpathsum.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.data = data 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | 9 | class Solution: 10 | 11 | """ 12 | 1. Node Only 13 | 2. Max of Left Child + Node 14 | 3. Max of Right Child + Node 15 | 4. Max of left Child + Node + Max of Right Child 16 | """ 17 | 18 | 19 | def max_path_sum(self,node): 20 | if node is None: 21 | return 0 22 | 23 | left_val = self.max_path_sum(node.left) 24 | right_val = self.max_path_sum(node.right) 25 | 26 | parent_max = max(max(left_val,right_val)+node.data,node.data) 27 | self.ans = max(self.ans, max(parent_max, node.data+left_val+right_val)) 28 | 29 | return parent_max 30 | 31 | def is_full_path(node): 32 | # check if the node is None return its True 33 | if node is None: 34 | return True 35 | 36 | if node.left is None and node.right is None: 37 | return True 38 | 39 | # if node has left and node.right 40 | if node.left is not None and node.right is not None: 41 | return (is_full_path(node.left) and is_full_path(node.right)) 42 | # recursion with node.left 43 | # recursion with node.right 44 | return False 45 | 46 | 47 | def top_view_util(node,curr_value,max_left,max_right): 48 | if node is None: 49 | return 50 | 51 | # if curr_value < max_left or curr_value > max_right: 52 | # print('Max_right %s data %s curr_value %s'%(max_right,node.data,curr_value)) 53 | # print(node.data) 54 | 55 | 56 | # print('Max_right %s data %s curr_value %s'%(max_right,node.data,curr_value)) 57 | if curr_value < max_left: 58 | print(node.data) 59 | print('left inside %s with current %s'%(max_left,curr_value)) 60 | max_left = min(max_left,curr_value) 61 | elif curr_value > max_right: 62 | print(node.data) 63 | print('Max_right inside %s with current %s'%(max_right,curr_value)) 64 | max_right = max(max_right,curr_value) 65 | 66 | 67 | if node.left is not None: 68 | top_view_util(node.left,curr_value-1,max_left,max_right) 69 | 70 | if node.right is not None: 71 | top_view_util(node.right,curr_value+1,max_left,max_right) 72 | 73 | 74 | 75 | def top_view_tree(node): 76 | 77 | if node is None: 78 | return 79 | # define a queue and add the root node with current_value as 0 and max_left & max_right with all 0 80 | queue = [node] 81 | print(node.data, end = ' ') 82 | # define all the constants 83 | current_value = [0] 84 | max_left = 0 85 | max_right = 0 86 | 87 | # while queue is not empty 88 | while len(queue) > 0: 89 | # pop first element from queue 90 | element = queue.pop() 91 | this_value = current_value.pop() 92 | 93 | # if node has left element 94 | if element.left is not None: 95 | # print('Element Left %s'%(element.left)) 96 | # if current_value -= 1 is les than max_left print and set the max_left to current_value 97 | left_value = this_value - 1 98 | if left_value < max_left: 99 | print(element.left.data, end = ' ') 100 | max_left = left_value 101 | 102 | # q.append node <- left 103 | queue.append(element.left) 104 | current_value.append(this_value-1) 105 | 106 | 107 | # if node has right element 108 | if element.right is not None: 109 | # if current_value -= 1 is les than max_left print and set the max_left to current_value 110 | right_value = this_value + 1 111 | if right_value > max_right: 112 | print(element.right.data, end = ' ') 113 | max_right = right_value 114 | 115 | # q.append node <- left 116 | queue.append(element.right) 117 | current_value.append(this_value+1) 118 | 119 | 120 | def remove_nodes_with_length_util(node,level,k): 121 | if node is None: 122 | return None 123 | 124 | node.left = remove_nodes_with_length_util(node.left,level+1,k) 125 | node.right = remove_nodes_with_length_util(node.right,level+1,k) 126 | 127 | if node.left is None and node.right is None and level < k: 128 | return None 129 | 130 | return node 131 | 132 | 133 | def remove_nodes_with_length_less_than(node,k): 134 | return remove_nodes_with_length_util(node,1,k) 135 | 136 | 137 | def inorder(node): 138 | if node is not None: 139 | inorder(node.left) 140 | print(node.data, end = ' ') 141 | inorder(node.right) 142 | 143 | 144 | def sum_root_leaf_path_util(node,result): 145 | 146 | # if node is none return none 147 | if node is None: 148 | return 0 149 | 150 | # if node is not None, then add the 151 | ''' 152 | 6 -> 60 -> 600 153 | 6 -> (3+60) -> (2 + 630) 154 | 155 | 6 -> (3+60) -> (5+630) -> (4+6350) 156 | ''' 157 | result = node.data + result*10 158 | 159 | # if node <- left and <- right is None, thats where path ends return the val 160 | # found the leaf child so return 161 | if node.left is None and node.right is None: 162 | return result 163 | 164 | # call left and right with sum 165 | return sum_root_leaf_path_util(node.left,result) + sum_root_leaf_path_util(node.right,result) 166 | 167 | 168 | def sum_root_leaf_path(node): 169 | return sum_root_leaf_path_util(node,0) 170 | 171 | 172 | # Driver program 173 | root = Node(10) 174 | root.left = Node(2) 175 | root.right = Node(10) 176 | root.left.left = Node(20) 177 | root.left.right = Node(1) 178 | root.right.right = Node(-25) 179 | root.right.right.left = Node(3) 180 | root.right.right.right = Node(4) 181 | root.right.right.right.left = Node(40) 182 | root.right.right.right.left.left = Node(41) 183 | 184 | sol = Solution() 185 | sol.ans = -float("inf") 186 | # print(sol.ans) 187 | 188 | 189 | 190 | # Driver Program 191 | root = Node(10); 192 | root.left = Node(20); 193 | root.right = Node(30); 194 | 195 | root.left.right = Node(40); 196 | root.left.left = Node(50); 197 | root.right.left = Node(60); 198 | root.right.right = Node(70); 199 | 200 | root.left.left.left = Node(80); 201 | root.left.left.right = Node(90); 202 | root.left.right.left = Node(80); 203 | root.left.right.right = Node(90); 204 | root.right.left.left = Node(80); 205 | root.right.left.right = Node(90); 206 | root.right.right.left = Node(80); 207 | root.right.right.right = Node(90); 208 | 209 | # print(is_full_path(root)) 210 | root = Node(1) 211 | root.left = Node(2) 212 | root.right = Node(3) 213 | root.left.right = Node(4) 214 | root.left.right.right = Node(5) 215 | root.left.right.right.right = Node(6) 216 | 217 | # top_view_tree(root) 218 | 219 | root = Node(1) 220 | root.left = Node(2) 221 | root.right = Node(3) 222 | root.left.left = Node(4) 223 | root.left.right = Node(5) 224 | root.left.left.left = Node(7) 225 | root.right.right = Node(6) 226 | root.right.right.left = Node(8) 227 | # print("Inorder Traversal of Original tree" ) 228 | # inorder(root) 229 | # result_node = remove_nodes_with_length_less_than(root,4) 230 | # print() 231 | # print("Inorder Traversal of Final tree" ) 232 | # inorder(result_node) 233 | 234 | root = Node(6) 235 | root.left = Node(3) 236 | root.right = Node(5) 237 | root.left.left = Node(2) 238 | root.left.right = Node(5) 239 | root.right.right = Node(4) 240 | root.left.right.left = Node(7) 241 | root.left.right.right = Node(4) 242 | print('Sum of all paths is %s'%(sum_root_leaf_path(root))) 243 | 244 | 245 | 246 | 247 | -------------------------------------------------------------------------------- /python/charorder_topsort.py: -------------------------------------------------------------------------------- 1 | # Inputs are words 2 | # Expected in sequence if characters in ascending Order 3 | 4 | # b a a 5 | # a b c d 6 | # a b c a 7 | # c a b 8 | # c a d 9 | from collections import defaultdict 10 | words = ["caa", "aaa", "aab"] 11 | V = 3 12 | 13 | # define a 2D graph with rows and columns equal to the size of first word : graph 14 | graph = defaultdict(list) 15 | 16 | 17 | # topoligical_sort_util(vertex,visisted,stack): 18 | def topological_sort_util(vertex,visited,stack): 19 | # visited[vertex] = True 20 | visited[vertex] = True 21 | # for each in graph[vertex]: 22 | for idx in graph[vertex]: 23 | # if not visited[each]: 24 | if not visited[idx]: 25 | # topoligical_sort_util(each,visited,stack) 26 | topological_sort_util(idx,visited,stack) 27 | # stack.insert(0,vertex) 28 | stack.insert(0,vertex) 29 | 30 | 31 | 32 | 33 | # topilogical Sort 34 | # def top_sort(): 35 | def topological_sort(): 36 | # visited = [False for each in range(V)] 37 | visited = [False for idx in range(V)] 38 | # stack = [] 39 | stack = [] 40 | # for idx in range(V): 41 | for idx in range(V): 42 | # if not visited[idx]: 43 | if not visited[idx]: 44 | # topoligical_sort_util(idx,visisted,stack) 45 | topological_sort_util(idx,visited,stack) 46 | 47 | print(stack) 48 | # for each in range(len(stack)): 49 | # print(chr(int(each)+97)) 50 | 51 | 52 | 53 | # def function to create elements in graph 54 | def build_graph(): 55 | # for each pair of words in sequence 56 | for idx in range(len(words)-1): 57 | word1 = words[idx] 58 | word2 = words[idx+1] 59 | # if word1[i] != word2[i]: 60 | for each in range(min(len(word1),len(word2))): 61 | if word1[each] != word2[each]: 62 | # graph[Firs Word Index][ord(word1[i])-ord('a')] = [ord(word2[i])-ord('a')] 63 | graph[ord(word1[each])-ord('a')].append(ord(word2[each])-ord('a')) 64 | topological_sort() 65 | 66 | build_graph() 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /python/cycle_graph_dfs.py: -------------------------------------------------------------------------------- 1 | # Define graph 2 | # Define V 3 | 4 | from collections import defaultdict 5 | # define function for adding graph 6 | ''' 7 | 1 - 0 8 | 0 - 2 9 | 2 - 1 10 | 0 - 3 11 | 3 - 4 12 | ''' 13 | 14 | V = 5 15 | # add Graph in defaultDict 16 | graph = defaultdict(list) 17 | graph[1].append(0) 18 | graph[0].append(2) 19 | graph[2].append(0) 20 | graph[0].append(3) 21 | graph[3].append(4) 22 | 23 | # Because its Acyclic Graph 24 | graph[0].append(1) 25 | graph[2].append(0) 26 | graph[0].append(2) 27 | graph[3].append(0) 28 | graph[4].append(3) 29 | 30 | # def dfs util --> idx,visited, parent 31 | def dfs_util(vertex, visited, parent): 32 | # visited set to True 33 | visited[vertex] = True 34 | # for each of the neighbour of the graph idx 35 | for neighbour in graph[vertex]: 36 | # if not visited 37 | if not visited[neighbour]: 38 | # dfs util 39 | dfs_util(neighbour,visited,vertex) 40 | # elif parent != each: 41 | elif parent != neighbour: 42 | print('Parent %s neighbour %s '%(parent,neighbour)) 43 | # found Cycle/True 44 | return True 45 | # Returns False 46 | return False 47 | 48 | 49 | # def dfs 50 | def dfs(): 51 | # define visited as False of all elements of V 52 | visited = [False for each in range(V)] 53 | # call dfs util 54 | 55 | if(dfs_util(0,visited, -1)): 56 | print('Cycle Found !!!') 57 | else: 58 | print('No Cycle Found ') 59 | 60 | 61 | dfs() 62 | -------------------------------------------------------------------------------- /python/find_min_depth_bt.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.data = value 4 | self.left = None 5 | self.right = None 6 | 7 | def minimum_depth(root): 8 | # it has 3 properties 9 | # if the root is None return 0 10 | if root is None: 11 | return 0 12 | 13 | # if left and right both are None then return 1 14 | if root.left is None and root.right is None: 15 | return 1 16 | 17 | # if root left is None, the recursion with root.right +1 18 | if root.left is None: 19 | return minimum_depth(root.right) + 1 20 | # if root right is None, the recursion with root.left +1 21 | if root.right is None: 22 | return minimum_depth(root.left) + 1 23 | 24 | # check the minimum of root<-left or root<-right and add +1 25 | return min(minimum_depth(root.left),minimum_depth(root.right)) + 1 26 | 27 | 28 | def minimum_depth_level_order(root): 29 | pass 30 | # Level Order Traversing 31 | # define a queue and add root as first element and keep sum as 1 32 | result =1 33 | final_result = 0 34 | queue = [] 35 | # define subqueue 36 | subqueue = [] 37 | queue.append(root) 38 | sum_dict = {} 39 | sum_dict[result] = [root.data] 40 | 41 | # while queue has element 42 | while len(queue) > 0: 43 | curr = queue.pop() 44 | 45 | # print(curr.left, curr.right ) 46 | # pop the element from queue and check it has children , add children(s) to subqueue 47 | if curr.left is not None: 48 | subqueue.append(curr.left) 49 | 50 | if curr.right is not None: 51 | subqueue.append(curr.right) 52 | 53 | 54 | # if any of the elem is missing either left/right child, you hit the depth, return the sum 55 | if curr.left is None or curr.right is None: 56 | print('Find the Depth First in %s'%result) 57 | # else: 58 | # result += 1 59 | 60 | if len(queue) <= 0: 61 | result += 1 62 | sum_dict[result] = [each.data for each in subqueue] 63 | queue.extend(subqueue) 64 | subqueue = [] 65 | 66 | # if queue is empty, then append the subqueue to queue anc clear subqueue and increment the sum += 1 67 | return sum_dict 68 | 69 | 70 | def uncovered_iterate_left(node, result): 71 | # if None return sum 72 | if node is None: 73 | return result 74 | 75 | # recursive iterate through left and keep on adding it 76 | return uncovered_iterate_left(node.left,result+node.data) 77 | 78 | def uncovered_iterate_right(node, result): 79 | # if None return sum 80 | if node is None: 81 | return result 82 | 83 | # recursive iterate through left and keep on adding it 84 | return uncovered_iterate_left(node.right,result+node.data) 85 | 86 | # def covered_iterate_left(node): 87 | # if node is None: 88 | # return result 89 | 90 | # return node.data + 91 | 92 | # def covered_iterate(node): 93 | # pass 94 | 95 | def all_sum(node): 96 | if node is None: 97 | return 0 98 | 99 | return node.data + all_sum(node.left) + all_sum(node.right) 100 | 101 | def covered_uncovered(node): 102 | total_uncovered_sum = node.data + uncovered_iterate_left(node.left,0) + uncovered_iterate_right(node.right,0) 103 | total_tree_sum = all_sum(node) 104 | 105 | print('Uncovered Sum %s Tree Sum %s '%(total_uncovered_sum,total_tree_sum)) 106 | covered_sum = total_tree_sum - total_uncovered_sum 107 | 108 | return total_uncovered_sum == covered_sum 109 | 110 | 111 | 112 | 113 | root = Node(1) 114 | root.left = Node(2) 115 | root.right = Node(3) 116 | root.left.left = Node(4) 117 | root.left.right = Node(5) 118 | 119 | # print(minimum_depth(root)) 120 | # print('The Minimum Depth level Order %s '%minimum_depth_level_order(root)) 121 | 122 | 123 | 124 | root = Node(8) 125 | root.left = Node(3) 126 | 127 | root.left.left = Node(1) 128 | root.left.right = Node(6) 129 | root.left.right.left = Node(4) 130 | root.left.right.right = Node(7) 131 | 132 | root.right = Node(10) 133 | root.right.right = Node(14) 134 | root.right.right.left = Node(13) 135 | 136 | print(covered_uncovered(root)) 137 | 138 | -------------------------------------------------------------------------------- /python/findmax_rotatedarray.py: -------------------------------------------------------------------------------- 1 | # Input array 2 | arr = [5, 6, 1, 2, 3, 4] 3 | # Expected Max 4 | 5 | # binary search approach to find the output. 6 | 7 | # def a function <- left , right 8 | def find_maximum(left, right): 9 | # if left is greater than right then return -1 (should not happen) 10 | if left > right: 11 | return -1 12 | # if left is equal to right then return the index of left 13 | if arr[left] == arr[right]: 14 | return arr[left] 15 | # calculate middle element, left + (high - left) // 2 16 | mid = left + (right - left) // 2 17 | 18 | # if mid > left and arr[mid - 1] > arr[mid] 19 | if mid > left and arr[mid - 1] > arr[mid]: 20 | # found the maximum element , return that mid -1 21 | return arr[mid-1] 22 | # elif mid < right and arr[mid + 1] < arr[mid] 23 | elif mid < right and arr[mid + 1] < arr[mid]: 24 | # found the maximum element mid 25 | return arr[mid] 26 | 27 | # if arr[mid] > arr[left] 28 | if arr[mid] > arr[left]: 29 | # call function < mid+1, right 30 | return find_maximum(mid+1,right) 31 | # else 32 | else: 33 | # call function <- low, mid -1 34 | return find_maximum(left,mid-1) 35 | 36 | 37 | print(find_maximum(0,len(arr)-1)) -------------------------------------------------------------------------------- /python/merge_lists.py: -------------------------------------------------------------------------------- 1 | class LinkedList: 2 | def __init__(self): 3 | self.head = None 4 | 5 | # Inserts a new Node at front of the list. 6 | def push(self,new_data): 7 | new_node = self.Node(new_data) 8 | new_node.next = self.head 9 | self.head = new_node 10 | 11 | def printlist(self): 12 | temp = self.head 13 | while temp != None: 14 | print(temp.data, end=', ') 15 | temp = temp.next 16 | print() 17 | 18 | # Linked list Node 19 | class Node: 20 | def __init__(self, d): 21 | self.data = d 22 | self.next = None 23 | 24 | 25 | def merge(self, other): 26 | print('I am startibg Merge') 27 | pointer1_curr = self.head 28 | pointer2_curr = other.head 29 | # pointer1 <- list1.head 30 | # pointer2 <- list2.head 31 | # while pointer1 is not none, continue the loop and pointer2 is not none 32 | while pointer1_curr is not None and pointer2_curr is not None: 33 | # increment pointer1 to next 34 | pointer1_next = pointer1_curr.next 35 | pointer2_next = pointer2_curr.next 36 | 37 | pointer1_curr.next = pointer2_curr 38 | pointer2_curr.next = pointer1_next 39 | other.head = pointer2_curr 40 | 41 | 42 | def reverse_in_group(self, curr_list, threshold): 43 | # set previous as current list head 44 | current = curr_list 45 | prev = None 46 | nextelem = None 47 | count = 0 48 | 49 | 50 | # while curr is not None 51 | while current is not None and count < threshold: 52 | nextelem = current.next 53 | current.next = prev 54 | prev = current 55 | current = nextelem 56 | count += 1 57 | 58 | if nextelem is not None: 59 | curr_list.next = self.reverse_in_group(nextelem,threshold) 60 | 61 | return prev 62 | 63 | 64 | 65 | 66 | 67 | # list1 = LinkedList() 68 | # list1.push(3) 69 | # list1.push(2) 70 | # list1.push(1) 71 | 72 | # list1.printlist() 73 | 74 | # list2 = LinkedList() 75 | # list2.push(8) 76 | # list2.push(7) 77 | # list2.push(6) 78 | # list2.push(5) 79 | # list2.push(4) 80 | 81 | # list2.printlist() 82 | 83 | 84 | # list1.merge(list2) 85 | # list1.printlist() 86 | 87 | # list2.printlist() 88 | 89 | llist = LinkedList() 90 | llist.push(9) 91 | llist.push(8) 92 | llist.push(7) 93 | llist.push(6) 94 | llist.push(5) 95 | llist.push(4) 96 | llist.push(3) 97 | llist.push(2) 98 | llist.push(1) 99 | 100 | llist.head = llist.reverse_in_group(llist.head,3) 101 | llist.printlist() 102 | 103 | -------------------------------------------------------------------------------- /python/merge_sort.py: -------------------------------------------------------------------------------- 1 | # Find the middle element of the main array 2 | # middle = (left+right)/2 3 | # Divide the array by the above 4 | # mergesort(arr,left, middle) 5 | # mergesort(arr,middle+1,right) 6 | # for each of the array, keep on dividing it untill it reaches 1 7 | # once 1, compare and sort the value and then start merging 8 | 9 | # define mergesort <- arr 10 | def mergesort(arr): 11 | if len(arr) > 1: 12 | # get middle by diving with length of array <- mid 13 | mid = len(arr)//2 14 | # extract left array arr[:mid] 15 | left = arr[:mid] 16 | # extract right arrat arr[mid:] 17 | right = arr[mid:] 18 | 19 | # re-call mergesort by left array 20 | mergesort(left) 21 | # re-call mergesort by right array 22 | mergesort(right) 23 | 24 | # Merge Starts From here 25 | # define i,j, k = 0 26 | i = j = k = 0 27 | # while i is less than len of left and j is less than len of right 28 | while i < len(left) and j < len(right): 29 | # if left <- i is less than right<-j 30 | if left[i] < right[j]: 31 | # arr[k] = left <- i 32 | arr[k] = left[i] 33 | i += 1 34 | # i += 1 35 | # else 36 | else: 37 | # arr[k] = right <- j 38 | arr[k] = right[j] 39 | j += 1 40 | # j += 1 41 | # k += 1 42 | k += 1 43 | 44 | # while i is less than len<- left 45 | while i < len(left): 46 | # arr[k] = left[i] 47 | arr[k] = left[i] 48 | i += 1 49 | k += 1 50 | 51 | while j < len(right): 52 | # arr[k] = left[i] 53 | arr[k] = right[j] 54 | j += 1 55 | k += 1 56 | 57 | 58 | arr = [12, 11, 13, 5, 6, 7] 59 | mergesort(arr) 60 | print(arr) -------------------------------------------------------------------------------- /python/mythoughts: -------------------------------------------------------------------------------- 1 | 2 | #1 3 | Somebody asked me why do I prefer Impertive(Dataset/Dataframe) over Declarative query(Sql/SparkSql) in distributed system? 4 | Because as of now, atleast in case of distributed system, underlying Query Optimizer is not very advanced, 5 | so I have seen several cases when a non-preetier scala/python code performed way better/faster than small and easy-to-read sql 6 | syntax AND in distributed system, speed and optimization matter a lot, so atleast for now I've a reason :-) 7 | 8 | 9 | 10 | #2 11 | Why is it important to know #datastructure for #bigdata ? 12 | Almost all major distributed #nosql databases are based on SSTables, 13 | which makes compaction important & that makes mergesort super important which in general known as 14 | LSM-tree (merging & compaction). 15 | It doesn't mean B-Tree is going anywhere, the enormous development and optimizations around B-tree for last many years 16 | has made the datastructure - King (databases) !!! 17 | Basically, LSM-trees are faster for writes and but slower to Read not because of SSTable datastructure but 18 | more around the distributed principles like validating different data structures, compaction , slots and others. 19 | 20 | If you notice carefully, I have named few datastructures above, if I try to go in more details, I may end up writing a big big blog, 21 | so yeah Datastructures are Very Important !!! 22 | 23 | -------------------------------------------------------------------------------- /python/mythoughts.md: -------------------------------------------------------------------------------- 1 | 2 | #1 3 | Somebody asked me why do I prefer Impertive(Dataset/Dataframe) over Declarative query(Sql/SparkSql) in distributed system? 4 | Because as of now, atleast in case of distributed system, underlying Query Optimizer is not very advanced, 5 | so I have seen several cases when a non-preetier scala/python code performed way better/faster than small and easy-to-read sql 6 | syntax AND in distributed system, speed and optimization matter a lot, so atleast for now I've a reason :-) 7 | 8 | 9 | 10 | #2 11 | Why is it important to know #datastructure for #bigdata ? 12 | All major distributed #nosql databases are based on SSTables, 13 | which makes compaction important & that makes mergesort super important which in general known as 14 | LSM-tree (merging & compaction). 15 | It doesn't mean B-Tree is going anywhere, the enormous development and optimizations around B-tree for last many years 16 | has made the datastructure - King (databases) !!! 17 | 18 | Basically, LSM-trees are faster for writes and but slower to Read not because of SSTable datastructure but 19 | more around the distributed principles like validating different data structures, compaction , slots, storage and others. 20 | 21 | If you notice carefully, I have named few datastructures above, if I try to go in more details, I may end up writing a big big blog, 22 | so yeah Datastructures are Very Important, even for #bigdata !!! 23 | 24 | 25 | #3 26 | Why Colum-Oriented Storage (#parquet, Apache Arrow) 27 | Column Oriented Storage like #parquet is an excellent choice for OLAP system (read-only) not only for accessing data smartly but for compression as well. 28 | Optimize further, consider Sorted Order in Column Storage which makes compression based on initial columns, a niche trick !!! 29 | 30 | But the biggest problem while scanning rows is - the Bandwidth of getting data from Disk to memory & Column Storage are again a great system for efficient use of CPU cycles. 31 | Like a chunk of compressed Columnar data can fit comfortably in CPU's L1 cache & iterate through it in a tight loop without any function calls, So much efficient CPU Cycles!!! 32 | This concept is already widely used and known as Vectorized Processing #apachearrow 33 | 34 | 35 | #4 36 | -------------------------------------------------------------------------------- /python/pairfind_rotatedarray.py: -------------------------------------------------------------------------------- 1 | # Input 2 | 3 | # Find the sum 4 | 5 | # 11, 15, 6, 7, 9, 10 6 | # Try to find the pivot for the above 7 | arr = [4, 5, 6, 7, 8, 9, 1, 2, 3] 8 | 9 | # def find_pivot <- left, right 10 | def find_pivot(left,right): 11 | # if left == high then return left 12 | if left == right: 13 | return left 14 | 15 | # mid = left+high/2 16 | mid = (left+right)/2 17 | # if mid < high and arr_mid > arr_mid+1 18 | if mid < right and arr[mid] > arr[mid+1]: 19 | # return mid 20 | return mid 21 | # elif mid > low and arr_mid < arr_mid-1 22 | elif mid > left and arr[mid] < arr[mid-1]: 23 | # return mid-1 24 | return mid-1 25 | 26 | # if arr_low >= arr_mid 27 | if arr[left] >= arr[mid]: 28 | # find_pivot <- left, mid-1 29 | return find_pivot(left,mid-1) 30 | # find_pivot <- mid+1, right 31 | return find_pivot(mid+1,right) 32 | 33 | 34 | # def find count of matching sum 35 | def find_matching_count(expected): 36 | count = 0 37 | # pivot = find_pivot 38 | pivot = find_pivot(0,len(arr)-1) 39 | # left = pivot 40 | left = pivot 41 | # right = pivot+1 42 | right = pivot+1 43 | 44 | # while left is not equal to right 45 | while left != right: 46 | # value = arr of left + right 47 | value = arr[left] + arr[right] 48 | 49 | # if value is less than expected move right by 1 in rotation mode 50 | if value == expected: 51 | count += 1 52 | print('Found => %s , %s'%(left,right)) 53 | if right == len(arr) - 1: 54 | # right = 0 55 | right = 0 56 | # else 57 | else: 58 | # right += 1 59 | right += 1 60 | elif value < expected: 61 | # if right == len(arr)-1: 62 | if right == len(arr) - 1: 63 | # right = 0 64 | right = 0 65 | # else 66 | else: 67 | # right += 1 68 | right += 1 69 | else: 70 | if left == 0: 71 | left = len(arr)-1 72 | else: 73 | left -= 1 74 | 75 | return count 76 | 77 | 78 | 79 | # print(find_pivot(0,len(arr)-1)) 80 | print(find_matching_count(6)) -------------------------------------------------------------------------------- /python/prins_minspanningtree.py: -------------------------------------------------------------------------------- 1 | # Define Graph 2 | # define V (length of all elements) 3 | ''' 4 | graph = [ [0, 2, 0, 6, 0], 5 | [2, 0, 3, 8, 5], 6 | [0, 3, 0, 0, 7], 7 | [6, 8, 0, 0, 9], 8 | [0, 5, 7, 9, 0]] 9 | ''' 10 | 11 | import sys 12 | graph =[[0, 2, 0, 6, 0], 13 | [2, 0, 3, 8, 5], 14 | [0, 3, 0, 0, 7], 15 | [6, 8, 0, 0, 9], 16 | [0, 5, 7, 9, 0]] 17 | V = 5 18 | INF = 99999 19 | minset = [False for each in range(V)] 20 | key = [INF for each in range(V)] 21 | parent = [INF for each in range(V)] 22 | 23 | # find minimum value not part of min set 24 | # def min_value(minset, keyset) 25 | def min_value(minset,keyset): 26 | # curr_min = sys.maxsize 27 | curr_min = sys.maxsize 28 | # curr_idx = sys.maxsize 29 | curr_idx = sys.maxsize 30 | # loop through range (V) 31 | for idx in range(V): 32 | # if not minSet[idx] and keyset[idx] < curr_min: 33 | if not minset[idx] and keyset[idx] < curr_min: 34 | # curr_idx 35 | curr_min = keyset[idx] 36 | curr_idx = idx 37 | # return curr_idx 38 | return curr_idx 39 | 40 | # Define minSet which contains all visited vertices with empty {} 41 | # define parent,key = len V 42 | # set key[0] = 0 and rest INF(99999) 43 | key[0] = 0 44 | parent[0] = 0 45 | # while len of minSet != V: 46 | while not all(minset): 47 | # X = min_value(): 48 | x = min_value(minset,key) 49 | print('Current Minimum %s'%(x)) 50 | # minSet[X] = True 51 | minset[x] = True 52 | # for idx of the vertices 53 | for idx in range(V): 54 | # if each != idx and value of idx != 0 55 | curr_value = graph[x][idx] 56 | if key[idx] > curr_value and curr_value > 0: 57 | # if curr_value < key[idx]: 58 | # key[idx] = graph[each][idx] 59 | key[idx] = curr_value 60 | # parent[idx] = each 61 | parent[idx] = idx 62 | 63 | print(key) 64 | print(parent) 65 | -------------------------------------------------------------------------------- /python/search_rotatedarray.py: -------------------------------------------------------------------------------- 1 | # Take the onput as values {5, 6, 7, 8, 9, 10, 1, 2, 3}; 2 | # check for key 3 3 | 4 | # try to find the pivot value 5 | ''' 6 | 3, 4, 5, 6, 1, 2 it returns 3 7 | ''' 8 | # def find_pivot <- left , right 9 | # find the middle of the array , above starts with 0 and size of arr - 1 10 | # if right is less than right return left -1 11 | # if right === left ... 12 | 13 | # calculate mid 14 | 15 | # if mid > left and arr[mid] < arr[mid-1] 16 | # return mid-1 17 | # if middle is less than right and arr[mid] > arr[mid+1] 18 | # return mid 19 | # if arr of low is greater than/= arr of mid 20 | # call find pivot <- left, mid-1 21 | # find pivot <- mid+1, right 22 | 23 | -------------------------------------------------------------------------------- /python/test.py: -------------------------------------------------------------------------------- 1 | class Shark: 2 | 3 | def swim(self,value): 4 | print("The shark is swimming %s"%value) 5 | dop = Dolphin(2) 6 | 7 | def be_awesome(self): 8 | print("The shark is being awesome.") 9 | 10 | class Dolphin: 11 | def __init__(self, d): 12 | print(self.d) 13 | 14 | 15 | ssh = Shark() 16 | ssh.swim(20) -------------------------------------------------------------------------------- /python/topological_sort.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | # Define Graph 3 | graph = defaultdict(list) 4 | graph[5].append(2) 5 | graph[5].append(0) 6 | graph[4].append(0) 7 | graph[4].append(1) 8 | graph[2].append(3) 9 | graph[3].append(1) 10 | 11 | # Define length of the Graph 12 | V = 6 13 | 14 | 15 | # def top_sort_util: 16 | def topoligical_sort_util(vertex,visited,stack): 17 | # visited[x] = True 18 | visited[vertex] = True 19 | # for each in graph (loop thorugh all neighbours) 20 | for each in graph[vertex]: 21 | # if not visited: 22 | if not visited[vertex]: 23 | # top_sort_util(stack,visited, each) 24 | top_sort_util(each,visited,stack) 25 | 26 | # stack.insert as first item 27 | stack.insert(0,vertex) 28 | 29 | # def function top_sort() 30 | def topological_sort(): 31 | # set visited to len of V and set it as False 32 | visited = [False for each in range(V)] 33 | # define stack = [] (array) 34 | stack = [] 35 | # loop through V 36 | for idx in range(V): 37 | # if not visited[idx]: 38 | if not visited[idx]: 39 | # top_sort_util(stack,visited, index) 40 | topoligical_sort_util(idx,visited,stack) 41 | 42 | print("Sorted Path is %s"%(stack)) 43 | 44 | 45 | topological_sort() 46 | 47 | 48 | --------------------------------------------------------------------------------