Ways to complete Kraken

Problem

Kraken is m*n grids on a rectangular board. From the top left to reach the bottom right corner while moving one grid at a time in either the down, right or down-right diagonal directions

Solution

public class Solution {
    public int krakenCount(int m, int n) {
        if (m == 0 || n == 0) return 0;
        if (m == 1 || n == 1) return 1;
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) dp[i][0] = 1;
        for (int j = 0; j < n; j++) dp[0][j] = 1;
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = dp[i-1][j] + dp[i][j-1] + dp[i-1][j-1];
            }
        }
        return dp[m-1][n-1];
    }
}

Minimum Genetic Mutation

Solution

Backtracking

public class Solution {
    public int minMutation(String start, String end, String[] bank) {
        Queue<String> q = new LinkedList<>();
        q.offer(start);
        int count = 0;
        char[] genes = new char[]{'A','C','G','T'};
        Set<String> set = new HashSet<>();
        for (String s: bank) set.add(s);
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                String pre = q.poll();
                for (int j = 0; j < pre.length(); j++) {
                    for (char gene: genes) {
                        StringBuilder sb = new StringBuilder(pre);
                        sb.setCharAt(j, gene);
                        String cur = sb.toString();
                        if (end.equals(cur) && set.contains(end)) return count+1;
                        else if (set.contains(cur)) {
                            set.remove(cur);
                            q.offer(cur);
                        }
                    }
                }
            }
            count++;
        }
        return -1;
    }
}

BFS

public class Solution {
    public int minMutation(String start, String end, String[] bank) {
        if (start == null || end == null || bank == null || bank.length == 0 || start.length() != end.length()) return -1;
        return helper(start, end, bank, new ArrayList<String>(), 0);
    }
    public int helper(String start, String end, String[] bank, List<String> path, int count) {
        int min = -1;
        if (start.equals(end)) return 0;
        if (count >= end.length()) return min;
        for (String gene: bank) {
            if (!path.contains(gene) && isNext(start, gene)) {
                path.add(gene);
                int res = helper(gene, end, bank, path, count++);
                if (res != -1) min = Math.min(Integer.MAX_VALUE, res+1);
                path.remove(gene);
            }
        }
        return min;
    }
    public boolean isNext(String s1, String s2) {
        if (s1 == null || s2 == null || s1.length() != s2.length()) return false;
        int diff = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i) && ++diff > 1) return false;
        }
        return true;
    }
}

Longest Phrases in a Tweet

Maximum Size Subarray Sum equals or less than K

Using Queue

public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        if (nums == null || nums.length == 0) return 0;
        Queue<Integer> q = new LinkedList<>();
        int sum = 0, max = 0;
        for (int num: nums) {
            if (sum+num <= k) {
                q.offer(num);
                sum+=num;
            }
            else {
                while (sum+num > k) {
                    max = Math.max(max, q.size());
                    int pre = q.poll();
                    sum-=pre;
                }
                sum+=num;
                q.offer(num);
                max = Math.max(max, q.size());
            }
        }
        max = Math.max(max, q.size());
        return max;
    }
}

Brute Force

public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        if (nums == null || nums.length == 0) return 0;
        int len = nums.length;
        int[] sum = new int[len+1];
        sum[0] = 0;
        for (int i = 1; i <= len; i++) {
            sum[i] = sum[i-1]+nums[i-1];
        }
        int max = 0;
        for (int i = 0; i < len; i++) {
            //if (sum[i] <= k) max = Math.max(max, i);
            for (int j = i+1; j <= len; j++) {
                if (sum[j]-sum[i] <= k) max = Math.max(max, j-i);
            }
        }
        return max;
    }
}

Information Masking

Example

(111)222-3456 --> --3456
+123(444)555-6789 --> +--*-6789
333 444 5678 --> --5678
(333)444-5678 --> --5678

jackandrose@gmail .com --> je@gmail .com

Solution

public class Solution {
    public static String emailMask(String email) {
        StringBuilder sb = new StringBuilder();
        sb.append("E:");
        sb.append(email.charAt(0));
        sb.append("*****");
        int lastIndex = email.lastIndexOf('@')-1;
        sb.append(email.substring(lastIndex));
        return sb.toString();
    }
    public static String phoneMask(String phone) {
        StringBuilder sb = new StringBuilder();
        sb.append("P:");
        boolean hasCode = false;
        if (phone.charAt(0) == '+') {
            hasCode = true;
            phone = phone.substring(1);
        }
        if (phone.charAt(0) == '(') phone = phone.substring(1);
        String delimiters = "\\D";
        String[] nums = phone.trim().split(delimiter);
        if (hasCode) sb.append("+");
        int n = nums.length;
        for (int i = 0; i < n-1; i++) {
            int len = nums[i].length();
            for (int i = 0; i < len; i++) sb.append("*");
            sb.append("-");
        }
        sb.append(nums[n-1]);
        return sb.toString();
    }
    public static void main(String args[] ) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        while ((input = br.readLine()) != null){
            //String input = br.readLine();
            String[] inputs = input.trim().split(":");
            if (inputs[0].trim().equals("E")) System.out.println(emailMask(inputs[1].trim()));
            else if (inputs[0].trim().equals("P")) System.out.println(phoneMask(inputs[1].trim()));
        }
        br.close();
    }
}

First Unique Character in a String

public class Solution {
    public int firstUniqChar(String s) {
        if (s == null || s.length() == 0) return -1;
        int[] dict = new int[26];
        for (int i = 0; i < s.length(); i++) {
            dict[s.charAt(i)-'a']++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (dict[s.charAt(i)-'a'] == 1) return i;
        }
        return -1;
    }
}

Tweet Recommendation

Hacking Time

Apache Log Success Rates

Evaluate Expression Tree

Timeseries Data Aggregation

SQL

Student/Department

SELECT d.DEPT_NAME, COUNT(s.STUDENT_ID) as STUDENT_COUNT
FROM Departments (AS) d
LEFT JOIN Students (AS) s on d.DEPT_ID = s.DEPT_ID
GROUP BY d.DEPT_ID
ORDER BY STUDENT_COUNT DESC, d.DEPT_NAME;

ORDERS

SELECT o.customerNumber AS customer
FROM ORDERS AS o
GROUP BY customerNumber
ORDER BY count(orderNumber) DESC
limit 1;

OR

SELECT customerNumber 
FROM ORDERS
WHERE ROWNUM <= 1
GROUP BY customerNumber
ORDER BY COUNT(orderNumber) DESC;

Investments in 2012

SELECT ROUND(SUM(TIV_2012), 2)
FROM Insurance
WHERE Insurance.PID IN
(SELECT PID
FROM Insurance I1, Insurance I2
WHERE I1.TIV_2011 = I2.TIV_2011 AND I1.PID != I2.PID)
AND Insurance.PID NOT IN
(SELECT I1.PID
FROM Insurance I1, Insurance I2
WHERE I1.LAT = I2.LAT AND I1.LON = I2.LON AND I1.PID != I2.PID);

Employee/Department

SELECT d.Name, COUNT(e.ID) AS ID_COUNT
FROM Department (AS) d
LEFT JOIN Employee (AS) e
ON(WHERE) e.DEPT_ID = d.DEPT_ID
GROUP BY d.Name
ORDER BY ID_COUNT DESC, NAME

Parent/Child/Tree

SELECT Id, CASE
WHEN M IS NULL THEN 'Leaf'
WHEN P_id IS NULL THEN 'Root'
ELSE 'Inner'
END AS TypeNode
FROM
(
SELECT DISTINCT hijo.*, padre.P_id AS M
FROM Tree hijo
LEFT JOIN Tree padre
ON (hijo.Id = padre.P_id)
)
ORDER BY Id;

linspiration
161 声望53 粉丝