The post Water and Jug Problem appeared first on Coddicted.

]]>

You are given two jugs with capacities *x* and *y* litres. There is an infinite amount of water supply available.

You need to determine whether it is possible to measure exactly *z* litres using these two jugs.

If *z* liters of water is measurable, you must have *z* liters of water contained within **one or both buckets** by the end.

Operations allowed:

- Fill any of the jugs completely with water.
- Empty any of the jugs.
- Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

**Example 1:** (From the famous *“Die Hard”* example)

Input: x = 3, y = 5, z = 4 Output: True

**Example 2:**

Input: x = 2, y = 6, z = 5 Output: False

''' https://leetcode.com/problems/water-and-jug-problem/ ''' ''' The idea is to get the GCD of given Jugs' capacity and if mod of required value from GCD is 0 then we could obtain that required value from given Jugs. ''' class Solution(object): def getGCD(self, x, y): while x != y: if x > y: x = x - y else: y = y - x return x def canMeasureWater(self, x, y, z): """ :type x: int :type y: int :type z: int :rtype: bool """ if z <= 0: return True if x <= 0 or y <= 0: return x + y == z if z > x + y: return False gcd = self.getGCD(x,y) if gcd == 1: return True elif z % gcd == 0: return True return False

The post Water and Jug Problem appeared first on Coddicted.

]]>The post Power of Three appeared first on Coddicted.

]]>Given an integer, write a function to determine if it is a power of three.

**Follow up:**

Could you do it without using any loop / recursion?

/*https://leetcode.com/problems/power-of-three/*/ public class PowerOfThree { public boolean isPowerOfThree(int n) { if(n==0) return false; while(n!=1) { //System.out.println(n); int remainder = n%3; if(remainder!=0) return false; n = n/3; } return true; } public static void main(String args[]) { PowerOfThree p = new PowerOfThree(); System.out.println(p.isPowerOfThree(6)); } }

The post Power of Three appeared first on Coddicted.

]]>The post Delete Node in a Linked List appeared first on Coddicted.

]]>Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Suppose the linked list is `1 -> 2 -> 3 -> 4`

and you are given the third node with value `3`

, the linked list should become `1 -> 2 -> 4`

after calling your function.

''' https://leetcode.com/problems/delete-node-in-a-linked-list/ ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ nxt = node.next node.val = nxt.val node.next = nxt.next nxt.next = None

The post Delete Node in a Linked List appeared first on Coddicted.

]]>The post Decode Ways appeared first on Coddicted.

]]>
A message containing letters from `A-Z`

is being encoded to numbers using the following mapping:

'A' -> 1 'B' -> 2 ... 'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,

Given encoded message `"12"`

,

it could be decoded as `"AB"`

(1 2) or `"L"`

(12).

The number of ways decoding `"12"`

is 2.

/* https://leetcode.com/problems/decode-ways/ */ import java.util.ArrayList; import java.util.List; class DecodeWays { public int numDecodings(String s) { if(s==null || s.equals("")) return 0; List> list = new ArrayList<>(); helper(s, list, new ArrayList ()); return list.size(); } public void helper(String s, List > list, ArrayList a) { if(s.length()==0) { System.out.println(a); list.add(new ArrayList (a)); a = new ArrayList<>(); return; } if(s.length()>0) { a.add(s.substring(0, 1)); helper(s.substring(1), list, a); } if(s.length()>=2) { String temp = s.substring(0, 2); if(Integer.parseInt(temp)<27) { a.add(temp); helper(s.substring(2), list, a); } } } public static void main(String args[]) { DecodeWays d = new DecodeWays(); System.out.println(d.numDecodings("6065812287883668764831544958683283296479682877898293612168136334983851946827579555449329483852397155")); } }

The post Decode Ways appeared first on Coddicted.

]]>The post Verify Preorder Serialization of a Binary Tree appeared first on Coddicted.

]]>One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as `#`

.

_9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # #

For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,#"`

, where `#`

represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character `'#'`

representing `null`

pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as `"1,,3"`

.

**Example 1:**

`"9,3,4,#,#,1,#,#,2,#,6,#,#"`

Return `true`

**Example 2:**

`"1,#"`

Return `false`

**Example 3:**

`"9,#,#,1"`

Return `false`

/* https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ */ import java.util.Stack; public class VerifyPreorderSerialization { //the idea is to use a stack and push the element into the stack when the //the current item is not equal to "#" and when the current item is equal //to the "#", then check the top element on the stack public boolean isValidSerialization(String preorder) { Stackstack = new Stack (); String[] s = preorder.split(","); //if the length of array is 0 //then there is no node in the binary tree //return false if(s.length==0) { return false; } //if the length of the array is 1 //check if s[0] is equal to "#", then tree consists of null node //check if s[0] is not equal to "#", then return false (valid binary //tree with single node will have "9,#,#") if(s.length==1) { if(s[0].equals("#")) return true; else return false; } //push the first element in the array into the stack stack.push(s[0]); for(int i=1;i stack, String symbol) { //if the stack is empty or the top element in the stack is not equals //to "#" then push the symbol on to the stack if(stack.isEmpty() || !"#".equals(stack.peek())) { stack.push(symbol); } else { //check if the size of the stack is greater than 1 if(stack.size()>1) { //pop the top element that ie "#" and check if the next top //element is not "#" stack.pop(); //if the top element is not "#" then pop the top element //else return false if(!"#".equals(stack.peek())) stack.pop(); else return false; return pushPoundSymbol(stack, "#"); } else return false; } return true; } public static void main(String args[]) { VerifyPreorderSerialization v = new VerifyPreorderSerialization(); //String serializedString = "9,3,4,#,#,1,#,#,2,#,6,#,#"; String serializedString = "4,#,#,1"; System.out.println(v.isValidSerialization(serializedString)); } }

''' https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ ''' class Solution(object): def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ lst = [] index = -1 preorder = preorder.split(",") ln = len(preorder) root_flag = False if len(preorder) == 1 and preorder[0] == '#': return True for i,c in enumerate(preorder): # enumerate over each element in preorder tree if c == '#': if not lst: return False lst[-1].append(True) while index >= 0 and len(lst[-1]) > 2: lst.pop() index -= 1 if index == -1 and i + 1 != ln: return False else: root_flag = True if lst: x = lst[index] x.append(True) index += 1 lst.append([c]) while index >= 0: x = lst[index] if len(x) == 3: index -= 1 else: break return not (index >= 0)

The post Verify Preorder Serialization of a Binary Tree appeared first on Coddicted.

]]>The post Implement Reverse DNS Look Up Cache appeared first on Coddicted.

]]>Reverse DNS look up is using an internet IP address to find a domain name. For example, if you type 74.125.200.106 in browser, it automatically redirects to google.in.

How to implement Reverse DNS Look Up cache? Following are the operations needed from cache.

1) Add a IP address to URL Mapping in cache.

2) Find URL for a given IP address.

One solution is to use Hashing.

In this post, a Trie based solution is discussed. One advantage of Trie based solutions is, worst case upper bound is O(1) for Trie, for hashing, the best possible average case time complexity is O(1). Also, with Trie we can implement prefix search (finding all urls for a common prefix of IP addresses).

The general disadvantage of Trie is large amount of memory requirement, this is not a major problem here as the alphabet size is only 11 here. Ten characters are needed for digits from ‘0’ to ‘9’ and one for dot (‘.’).

The idea is to store IP addresses in Trie nodes and in the last node we store the corresponding domain name.

/* http://www.geeksforgeeks.org/implement-reverse-dns-look-cache/ */ import java.util.HashMap; import java.util.Map; public class ReverseDNSLookup { public void insert(TrieNode node, String[] ipAdd, String[] urls) { for(int i=0;ichild; String url; TrieNode() { this.child = new HashMap<>(); } public String toString() { return child.toString()+" : "+url; } }

The post Implement Reverse DNS Look Up Cache appeared first on Coddicted.

]]>The post Knapsack Problem appeared first on Coddicted.

]]>Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don’t pick it (0-1 property).

A simple solution is to consider all subsets of items and calculate the total weight and value of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the maximum value subset.

**1) Optimal Substructure:**

To consider all subsets of items, there can be two cases for every item: (1) the item is included in the optimal subset, (2) not included in the optimal set.

Therefore, the maximum value that can be obtained from n items is max of following two values.

1) Maximum value obtained by n-1 items and W weight (excluding nth item).

2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth item (including nth item).

If weight of nth item is greater than W, then the nth item cannot be included and case 1 is the only possibility.

/* http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/ */ class KnapsackDP { // Recursive public int solve(int[] value, int[] weight, int w) { return helper(value, weight, w, 0); } public int helper(int[] value, int[] weight, int w, int i) { if(i>=value.length) return 0; if(weight[i] > w) return helper(value, weight, w, i+1); else return Math.max(value[i]+helper(value, weight, w-weight[i], i+1), helper(value, weight, w, i+1)); } //DP public int solveDP(int[] value, int[] weight, int w) { int[][] dp = new int[value.length+1][w+1]; for(int i=0; i<=value.length; i++) { for(int j=0; j<=w; j++) { if(i==0 || j==0) dp[i][j] = 0; else { if(weight[i-1] <= j) dp[i][j] = Math.max(value[i-1] + dp[i-1][j-weight[i-1]], dp[i-1][j]); else dp[i][j] = dp[i-1][j]; } } } return dp[value.length][w]; } public static void main(String args[]) { int value[] = {60, 100, 120}; int weight[] = {10, 20, 30}; int w = 50; KnapsackDP k = new KnapsackDP(); System.out.println(k.solveDP(value, weight, w)); } }

The post Knapsack Problem appeared first on Coddicted.

]]>The post Remove duplicates from an unsorted linked list appeared first on Coddicted.

]]>Write a removeDuplicates() function which takes a list and deletes any duplicate nodes from the list. The list is not sorted.

For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.

**METHOD 1 (Using two loops)**

This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and inner loop compares the picked element with rest of the elements.

Time Complexity: O(n^2)

**METHOD 2 (Use Sorting)**

In general, Merge Sort is the best suited sorting algorithm for sorting linked lists efficiently.

1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked list. O(nLogn)

2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n)

Please note that this method doesn’t preserve the original order of elements.

Time Complexity: O(nLogn)

**METHOD 3 (Use Hashing)**

We traverse the link list from head to end. For every newly encountered element, we check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table.

/* http://www.geeksforgeeks.org/remove-duplicates-from-an-unsorted-linked-list/ */ //the idea is to use hashset, loop through each node and check whether //the node is already present in the hashset or not //if present then delete the node from hashset //otherwise add it to hashset import java.util.HashSet; import java.util.Set; public class DeleteDuplicateFromUnsortedList { public void deleteDuplicates(ListNode head) { if(head == null || head.next == null) return; Setset = new HashSet (); ListNode p = head; while(p != null) { printLinkedList(head); if(!set.contains(p.val)) { set.add(p.val); p = p.next; } else { ListNode p2 = head; while(p2.next!=p) p2 = p2.next; p2.next = p.next; p = p2.next; } } } public static void main(String args[]) { //12->11->12->21->41->43->21 ListNode head = new ListNode(12); head.next = new ListNode(11); head.next.next = new ListNode(12); head.next.next.next = new ListNode(21); head.next.next.next.next = new ListNode(41); head.next.next.next.next.next = new ListNode(43); head.next.next.next.next.next.next = new ListNode(21); DeleteDuplicateFromUnsortedList d = new DeleteDuplicateFromUnsortedList(); d.deleteDuplicates(head); d.printLinkedList(head); } public void printLinkedList(ListNode head) { ListNode p = head; while(p!=null) { System.out.print(p.val + "\t"); p = p.next; } System.out.println(); } } class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } }

The post Remove duplicates from an unsorted linked list appeared first on Coddicted.

]]>The post Invert Binary Tree appeared first on Coddicted.

]]>Invert a binary tree.

4 / \ 2 7 / \ / \ 1 3 6 9

to

4 / \ 7 2 / \ / \ 9 6 3 1

**Trivia:**

''' https://leetcode.com/problems/invert-binary-tree/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root or (not root.left and not root.right): return root self.invertTree(root.left) self.invertTree(root.right) temp = root.left root.left = root.right root.right = temp return root

The post Invert Binary Tree appeared first on Coddicted.

]]>The post Count number of ways to cover a distance appeared first on Coddicted.

]]>Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps.

/* http://www.geeksforgeeks.org/count-number-of-ways-to-cover-a-distance/ */ class CountWaysToCoverDistance { public int count(int dist) { if(dist==0) return 1; if(dist < 0) return 0; return count(dist-1) + count(dist-2) + count(dist-3); } public static void main(String args[]) { int dist = 4; CountWaysToCoverDistance c = new CountWaysToCoverDistance(); System.out.println(c.count(dist)); } }

/* http://www.geeksforgeeks.org/count-number-of-ways-to-cover-a-distance/ */ class CountWaysToCoverDistanceDP { public int count(int dist) { int[] dp = new int[dist+1]; //dp[i] indicate the number of ways distance i can be covered using // 1, 2 or 3 steps dp[0] = 1; dp[1] = 1; dp[2] = 2; for(int i=3;i<=dist;i++) { dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; } return dp[dist]; } public static void main(String args[]) { int dist = 4; CountWaysToCoverDistanceDP c = new CountWaysToCoverDistanceDP(); System.out.println(c.count(dist)); } }

The post Count number of ways to cover a distance appeared first on Coddicted.

]]>