AdSense

Showing posts with label Hashmap. Show all posts
Showing posts with label Hashmap. Show all posts

Sunday, January 18, 2015

Write all solutions for a^3+b^3 = c^3 + d^3, where a, b, c, d lie between [0, 10^5]

This is a FB interview question. Here are some feasible approaches. I followed the priority queue method:
Using a priority queue is almost certainly the simplest solution, and also the most practical one, since it's O(n) storage (with a log factor if you require bignums). Any solution which involves computing all possible sums and putting them in a map will require O(n^2) storage, which soon becomes impractical.
My naive, non-optimized implementation using a priority queue is O(n^2 log(n)) time. Even so, it took less than five seconds for n = 10000 and about 750 seconds for n = 100000, using a couple of megabytes of storage. It certainly could be improved.
The basic idea, as per your comment, is to initialize a priority queue with pairs (a, a+1) for a in the range [1, N), and then repeatedly increment the second value of the smallest (by sum of cubes) tuple until it reaches N. If at any time the smallest two elements in the queue are equal, you have a solution. (I could paste the code, but you only asked for a hint.)
I certainly didn't fully understand how he maintained O(n) storage in the Queue. When I increment the second value, I still have to store the pairs that has a cube sum that is not equal to the smallest element in the queue. The total space for the queue is still O(n^2), or more accurately O(n^2 / 2).
So when the range goes up to 10^5, it gives me OutOfMemoryError().

However, just for comparison, I also tried the HashMap method, the memory leak occurs even when range only goes to 10^4. This means the Map has a worse performance than the Priority Queue.


public class CubePair implements Comparable {
 //num1 will always be smaller than num2
 private int num1;
 private int num2;
 private int cubeSum;
 public CubePair(int a, int b) {
  if (a > b) {
   int tmp = a;
   a = b;
   b = tmp;
  }
  num1 = a;
  num2 = b;
  cubeSum = (int)(Math.pow(num1, 3) + Math.pow(num2, 3));
 }
 public boolean hasEqualSum(CubePair cp) {
  return cp.cubeSum == cubeSum;
 }
 public boolean equals(CubePair cp) {
  return num1 == cp.num1 && num2 == cp.num2;
 }
 public int getFirst() {
  return num1;
 }
 public int getSecond() {
  return num2;
 }
 public String toString() {
  return String.valueOf(num1) + ", " + String.valueOf(num2) + ";";
 }
 @Override
 public int compareTo(CubePair cp) {
  return cubeSum - cp.cubeSum;
 }
}
import java.util.*;
public class FindCube {
 public List> sameCubeSums(int range) {
  if (range <= 0)
   throw new IllegalArgumentException("range must be positive");
  List> rst = new ArrayList> ();
  PriorityQueue pq = new PriorityQueue ();
  for (int i = 1; i < range; i++) {
   pq.add(new CubePair(i, i + 1));
  }
  int prev = 0;
  int maxSize = 0;
  while (!pq.isEmpty()) {
   maxSize = Math.max(maxSize, pq.size());
   CubePair curr = pq.poll();
   if (pq.isEmpty())
    break;
   if (curr.hasEqualSum(pq.peek())) {
    addList(rst, curr, pq.peek());
    if (curr.getFirst() < pq.peek().getFirst())
     curr = pq.poll();
    else
     pq.poll();
   }
   if (curr.getFirst() <= prev)
    continue;
   for (int i = curr.getSecond() + 1; i <= range; i++) {
    CubePair tmp = new CubePair(curr.getFirst(), i);
    if (tmp.hasEqualSum(pq.peek())) {
     addList(rst, tmp, pq.peek());
    }
    else {
     pq.add(tmp);
    }
   }
   prev = curr.getFirst();
  }
  System.out.println("max queue size: " + maxSize);
  return rst;
 }
 private void addList(List> rst, CubePair pair1, CubePair pair2) {
  List pair = new ArrayList ();
  pair.add(pair1.toString());
  pair.add(pair2.toString());
  rst.add(new ArrayList (pair));
 }
}


Teaser: the HashMap method:

public List> sameCubeSums2(int range) {
  if (range <= 0)
   throw new IllegalArgumentException("range must be positive");
  Map> map = new HashMap>();
  List> rst = new ArrayList> ();
  for (int i = 1; i < range; i++) {
   for (int j = i + 1; j <= range; j++) {
    int cubeSum = (int)(Math.pow(i, 3) + Math.pow(j, 3));
    if (!map.containsKey(cubeSum)) {
     map.put(cubeSum, new ArrayList ());
     map.get(cubeSum).add(String.valueOf(i) + "; " + String.valueOf(j));
    }
    else 
     map.get(cubeSum).add(String.valueOf(i) + "; " + String.valueOf(j));
   }
  }
  for (List pairs : map.values()) {
   if (pairs.size() > 1) 
    rst.add(pairs);
  }
  return rst;
 }

Thursday, January 8, 2015

Anagrams and good hash key


Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Anagrams, are two collections of words that are consisted with same characters. It is not hard to check if two strings are anagrams (use a hashset to store all characters of one and check the other), however, how can we check a group of strings that contains different anagrams? Naturally we will think of using a map to store each group of anagrams with a hash key, then the next problem is, how to determine a good hash key?

At first, I thought that if two strings are consisted of same characters, the sum of all characters should be the same. That is true, however, it is possible that two strings composed of different words also have the same sum of characters. (e.g., "duh", "ill"). Here is a good one I found online: 

private int getKey(String s) {
        int key = 0;
        int a = 378551;
        int b = 63689;
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            int tmp = s.charAt(i) - 'a';
            count[tmp]++;
        }
        for (int num : count) {
            key = key * a + num;
            a = a * b;
        }
        return key;
    }


The rest of the method is trivial.


 public List anagrams(String[] strs) {
        if (strs == null)
            throw new NullPointerException("Null string array!");
        List rst = new ArrayList ();
        if (strs.length <= 1)
            return rst;
        Map> map = new HashMap> ();
        for (String s: strs) {
            int key = getKey(s);
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList());
            }
            map.get(key).add(s);
        }
        for (ArrayList a : map.values()) {
            if (a.size() > 1)
                rst.addAll(a);
        }
        return rst;
        
    }
    private int getKey(String s) {
        int key = 0;
        int a = 378551;
        int b = 63689;
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            int tmp = s.charAt(i) - 'a';
            count[tmp]++;
        }
        for (int num : count) {
            key = key * a + num;
            a = a * b;
        }
        return key;
    }

Friday, January 2, 2015

Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).

Two maps are used to store the words in the list and those in the string.  I used two hash sets at first because I didn't realize that duplicates are allowed in the list. For example, "aaa" and ["a", "a"].

Another mistake I made was that the increment of index in S cannot be the word length in the list, since those that are not in the list can be in any length. For example, "afoobar" and ["foo", "bar"].

The inner loop is used to check if the substring is a concatenation of all words in the list. Thus, index i becomes the starting index of the substring, which will be added into the result list if all conditions are satisfied.

If any condition is not satisfied, e.g., the substring cannot be found in the list, or the word occurs more than once, we break the inner loop and start from the next index.

The map is cleared at the beginning of every outer loop. If an index is found, or if a concatenation cannot be found from the last index, everything inside the map is useless. We need to start all over again. :)

Update: 2015 - 01 - 15
Walk through:
1. Store all strings in the list to a map.
2. Since all strings in the list needs to be included, the loop will exit at S.length() - L.length * L[0].length().
3. Use another loop to check for the concatenation of the words in the list. Use count to check if all strings in the list are included.
    1. If the substring that equals to the length of the words is not in the list map, break;
    2. If the number of any string in the list exceeds the number of that string in the list, break;
4. Add the start index if count == L.length.
5. Increment index, clear map.


public class SubstringWithConcatenation {
    public List findSubstring(String S, String[] L) {
        if (S == null || L == null)
            throw new NullPointerException("Null string or list!");
        List rst = new ArrayList ();
        if (S.length() == 0 || L.length == 0)
            return rst;
        int len = L[0].length();
        if (len > S.length())
            return rst;
        HashMap L_map = new HashMap ();
        for (int i = 0; i < L.length; i++) {
            if (!L_map.containsKey(L[i]))
                L_map.put(L[i], 1);
            else
                L_map.put(L[i], L_map.get(L[i]) + 1);
        }
        HashMap hm = new HashMap ();
        for (int i = 0; i <= S.length() - L.length * len; i++) {
            hm.clear();
            int count = 0;
            for (count = 0; count < L.length; count++) {
                int pos = i + count * len;
                String tmp = S.substring(pos, pos + len);
                if (!L_map.containsKey(tmp)) 
                    break;
                if (!hm.containsKey(tmp)) {
                        hm.put(tmp, 1);
                }
                else {
                    hm.put(tmp, hm.get(tmp) + 1);
                    if (hm.get(tmp) > L_map.get(tmp))
                        break;
                }
            }
            if (count == L.length)
                rst.add(i);
        }
        return rst;
    }
}

Tuesday, December 30, 2014

Isomorphic Strings

Given two (dictionary) words as Strings, determine if they are isomorphic. Two words are called isomorphic 
if the letters in one word can be remapped to get the second word. Remapping a letter means replacing all 
occurrences of it with another letter while the ordering of the letters remains unchanged. No two letters 
may map to the same letter, but a letter may map to itself. 

Example: 
given "foo", "app"; returns true 
we can map 'f' -> 'a' and 'o' -> 'p' 
given "bar", "foo"; returns false 
we can't map both 'a' and 'r' to 'o' 

given "turtle", "tletur"; returns true 
we can map 't' -> 't', 'u' -> 'l', 'r' -> 'e', 'l' -> 'u', 'e' -'r' 

given "ab", "ca"; returns true 
we can map 'a' -> 'c', 'b'

Click here for the original problem.
I implement two methods, the first one map the character to the first occurred index for both strings, and check if the encodings are the same for both strings. The second one is more traditional, map characters in the first string to the same index one in the second string. However, both methods require two maps.


import java.util.*;
public class IsomorphicString {
 //map index
 public boolean isIsomorphic(String a, String b) {
  if (a.length() != b.length()) 
   return false;
  a = a.toLowerCase();
  b = b.toLowerCase();
  
  Map amap = new HashMap ();
  Map bmap = new HashMap ();
  
  for (int i = 0; i < a.length(); i++) {
   if (!amap.containsKey(a.charAt(i)))
    amap.put(a.charAt(i), i);
   if (!bmap.containsKey(b.charAt(i))) 
    bmap.put(b.charAt(i), i);
  }
  for (int i = 0; i < a.length(); i++) {
   if (amap.get(a.charAt(i)) != bmap.get(b.charAt(i)))
    return false;
  }
  return true;
 }
 //map character
 public boolean isIsomorphic2 (String a, String b) {
  if (a.length() != b.length()) 
   return false;
  a = a.toLowerCase();
  b = b.toLowerCase();
  
  Map amap = new HashMap ();
  Map bmap = new HashMap ();
  
  for (int i = 0; i < a.length(); i++) {
   if (amap.containsKey(a.charAt(i))) {
    if(amap.get(a.charAt(i)) != b.charAt(i))
     return false; 
   }
   if (bmap.containsKey(b.charAt(i))) {
    if (bmap.get(b.charAt(i)) != a.charAt(i))
     return false;
   }
   amap.put(a.charAt(i), b.charAt(i));
   bmap.put(b.charAt(i), a.charAt(i));
  }
  return true;
 }

}

Tuesday, December 16, 2014

Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.

Another problem can be solved by hash map! I remember one of my SWE friend posted on FB about hash map: "It's incredibly fast!"

Well, I haven't reached to that state. But using hash map does have lots of convenience.

This problem, we use a HashMap <Integer, Integer> to track if the number in the array has been counted in one of the sequences. The key is the element, the value is either 0 (not in any sequence) and 1 (already in a sequence).

We search the map to get the sequence for a particular element, and compare to the longest sequence so far.

public class LongestSequence {
    public int longestConsecutive(int[] num) {
        if (num == null || num.length == 0)
            return 0;
        HashMap hm = new HashMap();
        for (int i : num)
            hm.put(i, 0);
        int max = 1;
        for (int i : num)
        {
            //already checked as part of a sequence
            if (hm.get(i) == 1)
                continue;
            int tmp = i;
            int currmax = 1;
            while(hm.containsKey(tmp+1))
            {
                currmax++;
                hm.put(tmp, 1);
                tmp++;
            }
            tmp = i;
            while (hm.containsKey(tmp-1))
            {
                currmax++;
                hm.put(tmp,1);
                tmp--;
            }
            max = Math.max(max, currmax);
        }

        return max;
        
    }
}

Hash map for deep copy

A deep copy indicates all data and pointers are copied. The original object and the copied one don't depend on each other.

The Clone Graph and Copy List with Random Pointer can both be solved by using a hash map. Basically, the idea is to use the map to store the original node and the copied new node. For Clone Graph, we search the map for neighbor lists while for Copy List with Random Pointer, we search for the random node that the original node points to.

Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
       1
      / \
     /   \
    0 --- 2
         / \
         \_/

Update: 2015 - 01 - 03

Use an arrayList to store the odd nodes, and use the map to store node - copy pairs. Start from the input node, pop its neighbor list and add its neighbors to the map and array.

The next step is to copy neighbor lists. Iterate in the list, get the new node from the map and copy the neighbors.
class UndirectedGraphNode {
      int label;
      List neighbors;
      UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
  };
 
public class CloneGraph {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null)
            return node;
        HashMap hm = new HashMap();
        List nodes = new ArrayList ();
        nodes.add(node);
        hm.put(node, new UndirectedGraphNode(node.label));
        int size = 0;
        while (size < nodes.size()) {
            UndirectedGraphNode tmp = nodes.get(size++);
            if (tmp.neighbors != null) {
                for (UndirectedGraphNode neighbor : tmp.neighbors) {
                    if (!hm.containsKey(neighbor)) {
                        hm.put(neighbor, new UndirectedGraphNode(neighbor.label));
                        nodes.add(neighbor);
                    }
                }
            }
        }
        for (UndirectedGraphNode no : nodes) {
            UndirectedGraphNode tmp = hm.get(no);
            if (no.neighbors != null) {
                tmp.neighbors = new ArrayList ();
                for (UndirectedGraphNode neighbor : no.neighbors) {
                    UndirectedGraphNode neighbor2 = hm.get(neighbor);
                    tmp.neighbors.add(neighbor2);
                }
            }
        }
        return hm.get(node);
    }
}


Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
class RandomListNode {
      int label;
      RandomListNode next, random;
      RandomListNode(int x) { this.label = x; }
  };
 
public class CopyList {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null)
            return null;
        RandomListNode dummy = new RandomListNode(0);
        RandomListNode pre = dummy;
        RandomListNode newNode;
        HashMap hm = new HashMap();
        while (head != null)
        {
            if (hm.containsKey(head))
                newNode = hm.get(head);
            else
            {
                newNode = new RandomListNode(head.label);
                hm.put(head, newNode);
            }
            if (head.random != null)
            {
                if (hm.containsKey(head.random))
                    newNode.random = hm.get(head.random);
                else
                {
                    newNode.random = new RandomListNode(head.random.label);
                    hm.put(head.random, newNode.random);
                }
            }
            pre.next = newNode;
            pre = newNode;
            head = head.next;
        }
        return dummy.next;
    }
}

Friday, December 12, 2014

Max points on a line

I don't think this one is a very hard one as long as all the conditions are considered:

1. duplicate points;
2. share lines parallel to y-axis;
3. share lines parallel to x-axis;
4. slopes.

Use a HashMap to store <slope, number of points> pair.


 class Point {
      int x;
      int y;
      Point() { x = 0; y = 0; }
      Point(int a, int b) { x = a; y = b; }
  }
 
public class MaxPointsonALine {
    public int maxPoints(Point[] points) {
        if (points == null || points.length == 0)
            return 0;
        HashMap hm = new HashMap();
        int max = 1;
        
        for (int i = 0; i < points.length; i++)
        {
            //Reinitialize the map since the shared points of each point are different
            hm.clear();
            //put the point itself into the map, use Integer_MIN_VALUE as the key
            hm.put((double)Integer.MIN_VALUE, 1);
            //in case there are duplicates in the array
            int dupli = 0;
            //all the shared points prior to i has been checked in the previous loops, thus we only need to
            //consider shared points after i
            for (int j = i + 1; j < points.length; j++)
            {
                //here comes the duplicates
                if (points[j].x == points[i].x && points[j].y == points[i].y)
                {
                    dupli++;
                    continue;
                }
                double key = 0.0;
                //share a line parallel to y-axis, we know the slop = infinity
               if (points[j].x == points[i].x)
                    key = (double)Integer.MAX_VALUE;
                //just the slope
                // because (double)0/-1 is -0.0, so we should use 0.0+-0.0=0.0 to solve 0.0 !=-0.0
                // problem
                else
                    key = 0.0 + 
                    (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
                
                if (!hm.containsKey(key))
                    hm.put(key, 2);
                else
                    hm.put(key, hm.get(key) + 1);
                
            }
            //now we add duplicates to the values in the map and compare them with the max
            for (int tmp : hm.values())
            {
                if (tmp + dupli > max)
                    max = tmp + dupli;
            }
        }
        return max;
    }
}