Wednesday, June 29, 2016

Water and jug problem

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
Credits:
Special thanks to @vinod23 for adding this problem and creating all test cases

another key to understand this solution is the calculation of greatest common divisor.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        /*//this code is for measuring and filling the z
        if(x==0&&y==0&&z!=0)return false;
        if(x==0&&y==0&&z==0)return true;
       return x + y == z || z % dieHard(x,y) == 0;*/
       //this code is for a condition that what's left in x and y is z
       return x + y == z || (x+y)>=z&&z % dieHard(x,y) == 0;
    }
    //mx + ny = z
    private int dieHard(int a,int b){
        return b==0? a: dieHard(b,a%b);
    }
}

Calculate greatest common divisor

https://en.wikipedia.org/wiki/Euclidean_algorithm

The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number.

A more efficient version of the algorithm shortcuts these steps, instead replacing the larger of the two numbers by its remainder when divided by the smaller of the two (with this version, the algorithm stops when reaching a zero remainder). With this improvement, the algorithm never requires more steps than five times the number of digits (base 10) of the smaller integer. 

Note that we ignored the quotient in each step except to notice when the remainder reached 0, signalling that we had arrived at the answer.

Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Note:Be careful about the overflow when multiple two integers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Solution {
    public boolean isPerfectSquare(int num) {
        int l=0,r=num/2+1;//for num=1, for num=4. it is a waste of calculation after the 4. 
//but as a general approach, this keeps code concise
 while(l<=r){
  int m = l+(r-l)/2;
  long ans = (long)m*(long)m;//overflow
  if(ans==num)return true;
  if(ans>num)r=m-1;
  if(ans<num)l=m+1;
 }
 return false;
    }
}

Tuesday, June 28, 2016

Container With Most Water

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.

It is easy to come up a brute force solution that calculate area between any two vertical lines and then trace a max area. That runs out of time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Solution {
    public int maxArea(int[] height) {
        long max = Integer.MIN_VALUE;
        long[][] areas = new long[height.length][height.length];
        for(int i=0;i<height.length;i++){
            for(int j=0;j<height.length;j++){
                //i==j, area=0, area is initialized as 0 so no need to compute it
                if(i!=j&&areas[i][j]==0){
                    areas[i][j]=areas[j][i]=Math.abs(i-j)*Math.min(height[i],height[j]);
                    max = Math.max(max,areas[i][j]);
                }
            }
        }
        return (int)max;
    }
}

Below is a better solution that start from max bottom size, then step by step, while reducing bottom size, it tries to find bigger height to hopefully find a bigger area.

This solution is easy understand but it only beats less than 2% of other submissions.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution {
    public int maxArea(int[] height) {
        int i=0,j=height.length-1;
        int max = Integer.MIN_VALUE;
        int area = 0;
        while(i<j){
                //i==j, area=0, area is initialized as 0 so no need to compute it
                area=Math.abs(i-j)*Math.min(height[i],height[j]);
                max = Math.max(max,area);
            if(height[i]<height[j])//remove shorter line to find bigger height
                i++;
            else
                j--;
            }

        return max;
    }
}

Sunday, June 26, 2016

Ugly Number

Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Solution {
    public boolean isUgly(int num) {
        if(num==0)return false;
        //divid as much as possible to each of 2, 3 and 5 and see if result is 1
        //if result is nnot 1, then it is not ugly number
        while(num%2==0)num=num/2;//num must be multiple times of 2
        while(num%3==0)num=num/3;
        while(num%5==0)num=num/5;
        return num==1;
    }
}
Ugly Number 2
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
Hint:
  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Lessons learned:
overflow:int to long when int multiply int. special case: n=1
key: priority queue and k sorted list merging.
key: repeated numbers should not be duplicated added. e.g. 6=2*3, 6 will be added twice if not checking.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution {
    public int nthUglyNumber(int n) {
        if(n==1)return 1;
        PriorityQueue<Long> pq = new PriorityQueue<Long>();
        pq.add(1l);//first ugly number is 1
        int cnt=0;
        long minUgly=1;
        while(cnt<n){
            minUgly= pq.poll();//access one ugly number
            cnt++;//so counter increase 1
            if(!pq.contains(minUgly*2l))pq.add(minUgly*2l);
            if(!pq.contains(minUgly*3l))pq.add(minUgly*3l);
            if(!pq.contains(minUgly*5l))pq.add(minUgly*5l);

        }
        return (int)minUgly;
    }
}
Super Ugly Numbers: this actually just need to change few lines of code in ugly number 2.

Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.
Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.

Note: this implement is not optimized and runs timeout. putting here for demonstrate thought of solution.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        
  if(n==1)return 1;
        PriorityQueue<Long> pq = new PriorityQueue<Long>();
        pq.add(1l);//first ugly number is 1
        int cnt=0;
        long minUgly=1;
        while(cnt<n){
            minUgly= pq.poll();//access one ugly number
            //System.out.println(minUgly);
            cnt++;//so counter increase 1
            for(int p:primes){
             if(!pq.contains(minUgly*p))pq.add(minUgly*p);
            }

        }
        return (int)minUgly;
    }
}

Count Primes

Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hint:
  1. Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
  2. As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better?
  3. Let's write down all of 12's factors:
    2 × 6 = 12
    3 × 4 = 12
    4 × 3 = 12
    6 × 2 = 12
    
    As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since pq, we could derive that p ≤ √n.
    Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
    public int countPrimes(int n) {
       int count = 0;
       for (int i = 1; i < n; i++) {
          if (isPrime(i)) count++;
       }
       return count;
    }
    
    private boolean isPrime(int num) {
       if (num <= 1) return false;
       // Loop's ending condition is i * i <= num instead of i <= sqrt(num)
       // to avoid repeatedly calling an expensive function sqrt().
       for (int i = 2; i * i <= num; i++) {
          if (num % i == 0) return false;
       }
       return true;
    } 
     
     
     

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public int countPrimes(int n) {
        boolean isPrime[] = new boolean[n];
        if(n<2)return 0;
        //first of all, assume all numbers are prime
        for(int i=2;i<n;i++){
            isPrime[i]=true;
        }
        //then mark the non-prime ones: it can be divided by other numbers other than 1 and itself
        for(int i=2;i*i<n;i++){
            //becuase it is multiply so use i*i instead of i
            if(isPrime[i]){//since we start from smallest prime, we will have less number to to through the second loop, since all current prime's multiplications will be marked as non-prime
                //then mark all its multiplies as non prime
                for(int j=2;j*i<n;j++){
                    isPrime[j*i]=false;
                }
            }
        }
        int cnt = 0;
        for(int i=2;i<n;i++){
            if(isPrime[i])cnt++;
        }
        return cnt;
    }
}

Saturday, June 25, 2016

Sherlock and Anagrams

Given a string , find the number of "unordered anagrammatic pairs" of substrings.
Input Format
First line contains , the number of testcases. Each testcase consists of string in one line.
Constraints


String contains only the lowercase letters of the English alphabet.
Output Format
For each testcase, print the required answer in one line.
Sample Input#00
2
abba
abcd
Sample Output#00
4
0
Sample Input#01
5
ifailuhkqq
hucpoltgty
ovarjsnrbf
pvmupwjjjf
iwwhrlkpek
Sample Output#01
3
2
2
6
3
Explanation
Sample00
Let's say denotes the substring .
testcase 1:
For S=abba, anagrammatic pairs are: , , and .
testcase 2:
No anagrammatic pairs.
Sample01
Left as an exercise to you.

Analysis

this seems complex, I have no optimized way to work it out. brute force way is working and basic idea is as follow:

1. categorize the substrings into categories according to their length, because anagram is between strings with same length(same length, same number of characters). single character is also a substring.

2. within each category, calculate the number of anagram pairs

3. sum numbers from all categories.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] ss = new String[n];
        for(int i=0;i<n;i++){
            checkAnagramPairs(in.next());
        }
        
    }
    /**
    two steps:
    1.categorize the substrings, same length strings are put together
    2. figure out num of pairs in each category
    3. sum 2
    */
    private static void checkAnagramPairs(String s){
        if(s==null||s.length()==1)System.out.println(0);
        Map<Integer,List<String>> stats = new HashMap<Integer,List<String>>();
        for(int i=0;i<s.length();i++){
            for(int j=i+1;j<=s.length();j++){
                if(stats.get(j-i)==null){
                    List<String> l = new ArrayList<String>();
                    l.add(s.substring(i,j));
                    stats.put(j-i,l);
                }else{
                    stats.get(j-i).add(s.substring(i,j));
                }
            }
        }
        int ttl = 0;
        for(Map.Entry<Integer,List<String>> e:stats.entrySet()){
            ttl+=getNumOfAnagramPairs(e.getValue());
        }
        System.out.println(ttl);
    }
    private static int getNumOfAnagramPairs(List<String> l){
        int ttl = 0;
        for(int i=0;i<l.size();i++){
            for(int j=i+1;j<l.size();j++){
                if(isAnagramPair(l.get(i),l.get(j))){
                    ttl++;
                }
            }
        }
        return ttl;
    }
    private static boolean isAnagramPair(String s1,String s2){
        char[] c1 = s1.toCharArray();
        Arrays.sort(c1);
        char[] c2 = s2.toCharArray();
        Arrays.sort(c2);
        s1 = new String(c1);
        s2 = new String(c2);
        return s1.equals(s2);
    }
}