LeetCode – Insert Interval

Problem: Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals (merge if necessary). Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. Java Solution 1 … Read more

ASTParser ignore embedded inner class

When using Eclipse ASTParser, if you want to get all methods and fields of the outer class and ignore the embedded inner class(es), you may try to visit all methods and fields and try to differentiate outer class and inter class.

Each class is a TypeDeclaration in AST, and Inner class is another TypeDeclaration inside the TypeDeclaration in the AST. The key question is: how to know if stuff is in a root TypeDeclaration or a inner TypeDeclaration?

Read more

LeetCode – Pow(x, n)

Problem: Implement pow(x, n). This is a great example to illustrate how to solve a problem during a technical interview. The first and second solution exceeds time limit; the third and fourth are accepted. Java Solution public double myPow(double x, int n){ if(n==0) return 1;   if(n<0){ return 1/helper(x, -n); }   double v = … Read more

LeetCode – Implement strStr() (Java)

Problem: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Java Solution 1 – Naive public int strStr(String haystack, String needle) { if(haystack==null || needle==null) return 0;   if(needle.length() == 0) return 0;   for(int i=0; i<haystack.length(); i++){ if(i + needle.length() > … Read more

LeetCode – Valid Parentheses (Java)

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid. The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not. Analysis A typical problem which can be solved by using a stack data structure. … Read more

LeetCode – Merge Sorted Array (Java)

Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. Analysis The key to solve this problem is moving element … Read more

LeetCode – Merge Two Sorted Lists (Java)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Java Solution The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the … Read more