Coding Interview-Leetcode
Coding Interview-Leetcode
Program Creek
Version 0.0
Contents
5 Word Break II 18
6 Word Ladder 20
9 Merge Intervals 27
10 Insert Interval 29
11 Two Sum 31
14 3Sum 34
15 4Sum 36
16 3Sum Closest 38
19 Valid Parentheses 42
20 Implement strStr() 43
2 | 181
Contents
24 Valid Palindrome 49
25 Spiral Matrix 52
26 Search a 2D Matrix 55
27 Rotate Image 56
28 Triangle 58
30 Maximum Subarray 62
36 Palindrome Partitioning 73
41 Min Stack 79
42 Majority Element 80
43 Combination Sum 82
49 Largest Number 89
50 Combinations 90
52 Gas Station 93
53 Candy 95
54 Jump Game 96
55 Pascals Triangle 97
96 Permutations 169
97 Permutations II 171
You may have been using Java for a while. Do you think a simple Java array question
can be a challenge? Lets use the following problem to test.
Problem: Rotate an array of n elements to the right by k steps. For example, with n
= 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
How many different ways do you know to solve this problem?
In a straightforward way, we can create a new array and then copy elements to the
new array. Then change the original array by using System.arraycopy().
public void rotate(int[] nums, int k) {
if(k > nums.length)
k=k%nums.length;
int j=0;
for(int i=k; i<nums.length; i++){
result[i] = nums[j];
j++;
}
7 | 181
1 Rotate Array in Java
Can we do this in O(1) space and in O(n) time? The following solution does.
Assuming we are given 1,2,3,4,5,6 and order 2. The basic idea is:
1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Rotate first part: 4,3,2,1,5,6
3. Rotate second part: 4,3,2,1,6,5
4. Rotate the whole array: 5,6,1,2,3,4
reverse(arr, 0, a-1);
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr.length-1);
The problem:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
This problem is simple. After understanding the problem, we should quickly realize
that this problem can be solved by using a stack. We can loop through each element
in the given array. When it is a number, push it to the stack. When it is an operator,
pop two numbers from the stack, do the calculation, and push back the result.
The following is the code. It runs great by feeding a small test. However, this code
9 | 181
2 Evaluate Reverse Polish Notation
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
}
The problem is that switch string statement is only available from JDK 1.7. Leetcode
apparently use versions below that.
If you want to use switch statement, you can convert the above by using the following
code which use the index of a string "+-*/".
public class Solution {
public int evalRPN(String[] tokens) {
int returnValue = 0;
for(String t : tokens){
if(!operators.contains(t)){
stack.push(t);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int index = operators.indexOf(t);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}
}
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
}
11 | 181
3 Solution of Longest Palindromic Substring in Java
Naively, we can simply examine every substring and check if it is palindromic. The
time complexity is O(n3). If this is submitted to LeetCode onlinejudge, an error mes-
sage will be returned - "Time Limit Exceeded". Therefore, this approach is just a start,
we need a better algorithm.
public static String longestPalindrome1(String s) {
int maxPalinLength = 0;
String longestPalindrome = null;
int length = s.length();
return longestPalindrome;
}
return true;
}
Let s be the input string, i and j are two indices of the string.
Define a 2-dimension array "table" and let table[i][j] denote whether substring from
i to j is palindrome.
Start condition:
table[i][i] == 1;
table[i][i+1] == 1 => s.charAt(i) == s.charAt(i+1)
Changing condition:
table[i+1][j-1] == 1 && s.charAt(i) == s.charAt(j)
=>
table[i][j] == 1
if(s.length() <=1)
return s;
int maxLen = 0;
String longestStr = null;
//e.g. bcba
//two consecutive same letters are palindrome
for (int i = 0; i <= length - 2; i++) {
if (s.charAt(i) == s.charAt(i + 1)){
table[i][i + 1] = 1;
longestStr = s.substring(i, i + 2);
}
}
printTable(table);
//condition for calculate whole table
for (int l = 3; l <= length; l++) {
for (int i = 0; i <= length-l; i++) {
int j = i + l - 1;
if (s.charAt(i) == s.charAt(j)) {
table[i][j] = table[i + 1][j - 1];
if (table[i][j] == 1 && l > maxLen)
longestStr = s.substring(i, j + 1);
} else {
table[i][j] = 0;
}
printTable(table);
}
}
return longestStr;
}
public static void printTable(int[][] x){
for(int [] y : x){
for(int z: y){
System.out.print(z + " ");
}
System.out.println();
}
System.out.println("------");
}
Given an input, we can use printTable method to examine the table after each itera-
tion. For example, if input string is "dabcba", the final matrix would be the following:
1 0 0 0 0 0
0 1 0 0 0 1
0 0 1 0 1 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
From the table, we can clear see that the longest string is in cell table[1][5].
if (s.length() == 1) {
return s;
}
return longest;
}
Manachers algorithm is much more complicated to figure out, even though it will
bring benefit of time complexity of O(n).
Since it is not typical, there is no need to waste time on that.
Given a string s and a dictionary of words dict, determine if s can be segmented into
a space-separated sequence of one or more dictionary words. For example, given s =
"leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as
"leet code".
15 | 181
4 Solution Word Break
This problem can be solve by using a naive approach, which is trivial. A discussion
can always start from that though.
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
return wordBreakHelper(s, dict, 0);
}
for(String a: dict){
int len = a.length();
int end = start+len;
if(s.substring(start, start+len).equals(a))
if(wordBreakHelper(s, dict, start+len))
return true;
}
return false;
}
}
Time: O(n2)
This solution exceeds the time limit.
for(String a: dict){
int len = a.length();
int end = i + len;
if(end > s.length())
continue;
if(t[end]) continue;
if(s.substring(i, end).equals(a)){
t[end] = true;
}
}
}
return t[s.length()];
}
}
for(String s: dict){
sb.append(s + "|");
}
if(m.matches()){
System.out.println("match");
}
}
The dynamic solution can tell us whether the string can be broken to words, but can
not tell us what words the string is broken to. So how to get those words?
5 Word Break II
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence
where each word is a valid dictionary word. Return all such possible sentences.
For example, given s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"], the
solution is ["cats and dog", "cat sand dog"].
This problem is very similar to Word Break. Instead of using a boolean array to track
the match positions, we need to track the actual words. Then we can use depth first
search to get all the possible paths, i.e., the list of strings.
18 | 181
5 Word Break II
for(String word:dict){
int len = word.length();
int end = i+len;
if(end > s.length())
continue;
if(s.substring(i,end).equals(word)){
if(dp[end] == null){
dp[end] = new ArrayList<String>();
}
dp[end].add(word);
}
}
}
return result;
}
result.add(path);
return;
}
6 Word Ladder
The problem:
Given two words (start and end), and a dictionary, find the length of shortest trans-
formation sequence from start to end, such that:
Only one letter can be changed at a time Each intermediate word must exist in the
dictionary For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" ->"hot" ->"dot" ->"dog" ->"cog", the program
should return its length 5.
Note: Return 0 if there is no such transformation sequence. All words have the same
length. All words contain only lowercase alphabetic characters.
This problem is a classic problem that has been asked frequently during interviews.
20 | 181
6 Word Ladder
In a simplest way, we can start from start word, change one character each time, if it
is in the dictionary, we continue with the replaced word, until start == end.
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
int len=0;
HashSet<String> visited = new HashSet<String>();
startArr[i] = c;
String temp = new String(startArr);
if(dict.contains(temp)){
len++;
start = temp;
if(temp.equals(end)){
return len;
}
}
}
}
return len;
}
}
Apparently, this is not good enough. The following example exactly shows the
problem. It can not find optimal path. The output is 3, but it actually only takes 2.
Input: "a", "c", ["a","b","c"]
Output: 3
Expected: 2
So we quickly realize that this looks like a tree searching problem for which breath
first guarantees the optimal solution.
Assuming we have some words in the dictionary, and the start is "hit" as shown in
the diagram below.
We can use two queues to traverse the tree, one stores the nodes, the other stores the
step numbers.
Updated on 2/27/2015.
public int ladderLength(String start, String end, HashSet<String> dict) {
if (dict.size() == 0)
return 0;
dict.add(end);
wordQueue.add(start);
distanceQueue.add(1);
if (currWord.equals(end)) {
result = Math.min(result, currDistance);
}
LeetCode Problem:
There are two sorted arrays A and B of size m and n respectively. Find the median of the
two sorted arrays. The overall run time complexity should be O(log (m+n)).
This problem can be converted to the problem of finding kth element, k is (As length
+ B Length)/2.
If any of the two arrays is empty, then the kth element is the non-empty arrays kth
element. If k == 0, the kth element is the first element of A or B.
For normal cases(all other cases), we need to move the pointer at the pace of half of
an array length.
public static double findMedianSortedArrays(int A[], int B[]) {
int m = A.length;
int n = B.length;
23 | 181
if ((m + n) % 2 != 0) // odd
return (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1);
else { // even
return (findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1)
+ findKth(A, B, (m + n) / 2 - 1, 0, m - 1, 0, n - 1)) * 0.5;
}
}
24 | 181
8 Regular Expression Matching in Java
is greater than m2, then median is present in one of the below two subarrays. a)
From first element of ar1 to m1 (ar1[0...|_n/2_|]) b) From m2 to last element of ar2
(ar2[|_n/2_|...n-1]) 4) If m2 is greater than m1, then median is present in one of the
below two subarrays. a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1]) b) From
first element of ar2 to m2 (ar2[0...|_n/2_|]) 5) Repeat the above process until size of
both the subarrays becomes 2. 6) If size of the two arrays is 2 then use below formula
to get the median. Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
Problem:
Implement regular expression matching with support for . and *.
. Matches any single character.
* Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Some examples:
isMatch("aa","a") return false
isMatch("aa","aa") return true
isMatch("aaa","aa") return false
isMatch("aa", "a*") return true
isMatch("aa", ".*") return true
isMatch("ab", ".*") return true
isMatch("aab", "c*a*b") return true
8.1 Analysis
First of all, this is one of the most difficulty problems. It is hard to handle many cases.
The problem should be simplified to handle 2 basic cases:
For the 1st case, if the first char of pattern is not ".", the first char of pattern and
string should be the same. Then continue to match the left part.
For the 2nd case, if the first char of pattern is "." or first char of pattern == the first i
char of string, continue to match the left.
Be careful about the offset.
if(p.length() == 0)
return s.length() == 0;
}else{
int len = s.length();
int i = -1;
while(i<len && (i < 0 || p.charAt(0) == . || p.charAt(0) ==
s.charAt(i))){
if(isMatch(s.substring(i+1), p.substring(2)))
return true;
i++;
}
return false;
}
}
}
// special case
if (p.length() == 1) {
//case 2.2: a char & * can stand for 1 or more preceding element,
//so try every sub string
int i = 0;
while (i<s.length() && (s.charAt(i)==p.charAt(0) || p.charAt(0)==.)){
if (isMatch(s.substring(i + 1), p.substring(2))) {
return true;
}
i++;
}
return false;
}
}
27 | 181
9 Merge Intervals
9 Merge Intervals
Problem:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
The key to solve this problem is defining a Comparator first to sort the arraylist of
Intevals. And then merge some intervals.
The take-away message from this problem is utilizing the advantage of sorted list/ar-
ray.
class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}
result.add(prev);
return result;
}
}
10 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].
29 | 181
10 Insert Interval
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval
newInterval) {
result.add(newInterval);
return result;
}
}
11 Two Sum
Given an array of integers, find two numbers such that they add up to a specific target
number.
The function twoSum should return indices of the two numbers such that they add
up to the target, where index1 must be less than index2. Please note that your returned
answers (both index1 and index2) are not zero-based.
For example:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
This problem is pretty straightforward. We can simply examine every possible pair of
numbers in this integer array.
Time complexity in worst case: O(n2).
public static int[] twoSum(int[] numbers, int target) {
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret;
}
31 | 181
Can we do better?
return result;
}
}
Time complexity depends on the put and get operations of HashMap which is nor-
mally O(1).
Time complexity of this solution: O(n).
int i = 0;
int j = numbers.length - 1;
while (i < j) {
int x = numbers[i] + numbers[j];
32 | 181
if (x < target) {
++i;
} else if (x > target) {
j--;
} else {
return new int[] { i + 1, j + 1 };
}
}
return null;
}
Design and implement a TwoSum class. It should support the following operations:
add and find.
add - Add the number to an internal data structure. find - Find if there exists any
pair of numbers which sum is equal to the value.
For example,
add(1);
add(3);
add(5);
find(4) -> true
find(7) -> false
Since the desired class need add and get operations, HashMap is a good option for
this purpose.
public class TwoSum {
private HashMap<Integer, Integer> elements = new HashMap<Integer,
Integer>();
33 | 181
public boolean find(int value) {
for (Integer i : elements.keySet()) {
int target = value - i;
if (elements.containsKey(target)) {
if (i == target && elements.get(target) < 2) {
continue;
}
return true;
}
}
return false;
}
}
14 3Sum
Problem:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a b c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
Naive solution is 3 loops, and this gives time complexity O(n3). Apparently this is not
an acceptable solution, but a discussion can start from here.
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
//sort array
Arrays.sort(num);
34 | 181
14 3Sum
each.add(num[i]);
each.add(num[j]);
each.add(num[k]);
result.add(each);
each.clear();
}
}
}
}
return result;
}
}
* The solution also does not handle duplicates. Therefore, it is not only time ineffi-
cient, but also incorrect.
Result:
Submission Result: Output Limit Exceeded
A better solution is using two pointers instead of one. This makes time complexity of
O(n2).
To avoid duplicate, we can take advantage of sorted arrays, i.e., move pointers by >1
to use same element only once.
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (num.length < 3)
return result;
// sort array
Arrays.sort(num);
int start = i + 1;
int end = num.length - 1;
result.add(temp);
start++;
end--;
//avoid duplicate solutions
while (start < end && num[end] == num[end + 1])
end--;
}
}
return result;
}
15 4Sum
36 | 181
15 4Sum
15.1 Thoughts
while (k < l) {
int sum = num[i] + num[j] + num[k] + num[l];
if (!hashSet.contains(temp)) {
hashSet.add(temp);
result.add(temp);
}
k++;
l--;
}
return result;
}
Here is the hashCode method of ArrayList. It makes sure that if all elements of two
lists are the same, then the hash code of the two lists will be the same. Since each
element in the ArrayList is Integer, same integer has same hash code.
int hashCode = 1;
Iterator<E> i = list.iterator();
while (i.hasNext()) {
E obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
16 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to
a given number, target. Return the sum of the three integers. You may assume that
each input would have exactly one solution. For example, given array S = -1 2 1 -4,
and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
16.1 Thoughts
This problem is similar with 2 Sum. This kind of problem can be solve by using similar
approach, i.e., two pointers from both left and right.
Arrays.sort(num);
38 | 181
int k = num.length - 1;
while (j < k) {
int sum = num[i] + num[j] + num[k];
int diff = Math.abs(sum - target);
if(diff == 0) return 0;
return result;
}
}
Problem:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do
not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input
specs). You are responsible to gather all the input requirements up front.
39 | 181
17.2 Java Solution
char flag = +;
// calculate value
while (str.length() > i && str.charAt(i) >= 0 && str.charAt(i) <= 9) {
result = result * 10 + (str.charAt(i) - 0);
i++;
}
if (flag == -)
result = -result;
Thanks to the comment below. The solution above passes LeetCode online judge,
but it havent considered other characters. I will update this later.
40 | 181
18 Merge Sorted Array
Problem:
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.
The key to solve this problem is moving element of A and B backwards. If B has some
elements left after A is done, also need to handle that case.
The takeaway message from this problem is that the loop condition. This kind of
condition is also used for merging two sorted linked list.
The loop condition also can use m+n like the following.
public void merge(int A[], int m, int B[], int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
19 Valid Parentheses
Problem:
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.
Character is not a frequently used class, so need to know how to use it.
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
42 | 181
}
return stack.empty();
}
20 Implement strStr()
Problem:
Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or
null if needle is not part of haystack.
43 | 181
20.1 Thoughts
First, need to understand the problem correctly, the pointer simply means a sub string.
Second, make sure the loop does not exceed the boundaries of two strings.
if (needleLen == 0)
return haystack;
int k = i;
int j = 0;
return null;
}
From Tia:
You have to check if a String == null before call length(), otherwise it will throw Null-
PointerException.
44 | 181
21 Set Matrix Zeroes
if(firstRowZero){
for(int i=0; i<matrix[0].length; i++)
matrix[0][i] = 0;
}
}
}
Given a sorted array and a target value, return the index if the target is found. If not,
return the index where it would be if it were inserted in order. You may assume no
duplicates in the array.
Here are few examples.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
22.1 Solution 1
Naively, we can just iterate the array and compare target with ith and (i+1)th element.
Time complexity is O(n)
public class Solution {
public int searchInsert(int[] A, int target) {
46 | 181
if(A==null) return 0;
return A.length;
}
}
22.2 Solution 2
This also looks like a binary search problem. We should try to make the complexity to
be O(nlogn).
public class Solution {
public int searchInsert(int[] A, int target) {
if(A==null||A.length==0)
return 0;
return searchInsert(A,target,0,A.length-1);
}
if(target==A[mid])
return mid;
else if(target<A[mid])
return start<mid?searchInsert(A,target,start,mid-1):start;
else
return end>mid?searchInsert(A,target,mid+1,end):(end+1);
}
}
47 | 181
23 Longest Consecutive Sequence Java
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
should be [1, 2, 3, 4]. Its length is 4.
Your algorithm should run in O(n) complexity.
23.1 Thoughts
Because it requires O(n) complexity, we can not solve the problem by sorting the array
first. Sorting takes at least O(nlogn) time.
We can use a HashSet to add and remove elements. HashSet is implemented by using
a hash table. Elements are not ordered. The add, remove and contains methods have
constant time complexity O(1).
public static int longestConsecutive(int[] num) {
// if array is empty, return 0
if (num.length == 0) {
return 0;
}
while (set.contains(left)) {
count++;
set.remove(left);
left--;
}
while (set.contains(right)) {
count++;
set.remove(right);
right++;
}
return max;
}
After an element is checked, it should be removed from the set. Otherwise, time
complexity would be O(mn) in which m is the average length of all consecutive se-
quences.
To clearly see the time complexity, I suggest you use some simple examples and
manually execute the program. For example, given an array 1,2,4,5,3, the program
time is m. m is the length of longest consecutive sequence.
We do have an extreme case here: If n is number of elements, m is average length
of consecutive sequence, and m==n, then the time complexity is O(n2). The reason is
that in this case, no element is removed from the set each time. You can use this array
to get the point: 1,3,5,7,9.
24 Valid Palindrome
24.1 Thoughts
From start and end loop though the string, i.e., char array. If it is not alpha or num-
ber, increase or decrease pointers. Compare the alpha and numeric characters. The
solution below is pretty straightforward.
49 | 181
24 Valid Palindrome
int i=0;
int j=len-1;
while(i<j){
char left, right;
if(i >= j)
break;
left = charArray[i];
right = charArray[j];
if(!isSame(left, right)){
return false;
}
i++;
j--;
}
return true;
}
int index = 0;
while (index < len / 2) {
stack.push(s.charAt(index));
index++;
}
if (len % 2 == 1)
index++;
return true;
}
In the discussion below, April and Frank use two pointers to solve this problem. This
solution looks really simple.
public class ValidPalindrome {
public static boolean isValidPalindrome(String s){
if(s==null||s.length()==0) return false;
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
System.out.println(s);
return true;
}
System.out.println(isValidPalindrome(str));
}
}
25 Spiral Matrix
52 | 181
25 Spiral Matrix
If more than one row and column left, it can form a circle and we process the circle.
Otherwise, if only one row or column left, we process that column or row ONLY.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer>();
int m = matrix.length;
int n = matrix[0].length;
int x=0;
int y=0;
//left - move up
for(int i=0;i<m-1;i++){
result.add(matrix[x--][y]);
}
x++;
y++;
m=m-2;
n=n-2;
}
return result;
}
}
We can also recursively solve this problem. The solutions performance is not better
than Solution or as clear as Solution 1. Therefore, Solution 1 should be preferred.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
if(matrix==null || matrix.length==0)
return new ArrayList<Integer>();
return spiralOrder(matrix,0,0,matrix.length,matrix[0].length);
}
if(m<=0||n<=0)
return result;
//left - move up
if(n>1){
for(int i=0;i<m-1;i++){
result.add(matrix[x--][y]);
}
}
if(m==1||n==1)
result.addAll(spiralOrder(matrix, x, y, 1, 1));
else
result.addAll(spiralOrder(matrix, x+1, y+1, m-2, n-2));
return result;
}
}
26 Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix
has properties:
1) Integers in each row are sorted from left to right. 2) The first integer of each row
is greater than the last integer of the previous row.
For example, consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
55 | 181
26.1 Java Solution
int m = matrix.length;
int n = matrix[0].length;
int start = 0;
int end = m*n-1;
while(start<=end){
int mid=(start+end)/2;
int midX=mid/n;
int midY=mid%n;
if(matrix[midX][midY]==target)
return true;
if(matrix[midX][midY]<target){
start=mid+1;
}else{
end=mid-1;
}
}
return false;
}
}
27 Rotate Image
56 | 181
27 Rotate Image
In the following solution, a new 2-dimension array is created to store the rotated
matrix, and the result is assigned to the matrix at the end. This is WRONG! Why?
public class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0)
return ;
int m = matrix.length;
matrix = result;
}
}
The problem is that Java is pass by value not by refrence! "matrix" is just a reference
to a 2-dimension array. If "matrix" is assigned to a new 2-dimension array in the
method, the original array does not change. Therefore, there should be another loop
to assign each element to the array referenced by "matrix". Check out "Java pass by
value."
public class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0)
return ;
int m = matrix.length;
By using the relation "matrix[i][j] = matrix[n-1-j][i]", we can loop through the matrix.
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n-1-j][i];
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
matrix[j][n-1-i] = temp;
}
}
}
28 Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may
move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
This solution gets wrong answer! I will try to make it work later.
public class Solution {
58 | 181
28 Triangle
if (triangle.size() == 1) {
return Math.min(minTotal, triangle.get(0).get(0));
}
int a, b;
}else{
a = temp[j] + triangle.get(i + 1).get(j);
b = temp[j] + triangle.get(i + 1).get(j + 1);
return minTotal;
}
}
return total[0];
}
29.1 Thoughts
When you see string problem that is about subsequence or matching, dynamic pro-
gramming method should come to your mind naturally. The key is to find the chang-
ing condition.
Let W(i, j) stand for the number of subsequences of S(0, i) in T(0, j). If S.charAt(i) ==
T.charAt(j), W(i, j) = W(i-1, j-1) + W(i-1,j); Otherwise, W(i, j) = W(i-1,j).
public int numDistincts(String S, String T) {
int[][] table = new int[S.length() + 1][T.length() + 1];
60 | 181
29 Distinct Subsequences Total
table[i][0] = 1;
return table[S.length()][T.length()];
}
Do NOT write something like this, even it can also pass the online judge.
public int numDistinct(String S, String T) {
HashMap<Character, ArrayList<Integer>> map = new HashMap<Character,
ArrayList<Integer>>();
if (map.containsKey(c)) {
ArrayList<Integer> temp = map.get(c);
int[] old = new int[temp.size()];
// the relation
for (int j = 0; j < temp.size(); j++)
result[temp.get(j) + 1] = result[temp.get(j) + 1] + old[j];
return result[T.length()];
}
30 Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which
has the largest sum.
For example, given the array [2,1,3,4,1,2,1,5,4], the contiguous subarray [4,1,2,1]
has the largest sum = 6.
This is a wrong solution, check out the discussion below to see why it is wrong. I put
it here just for fun.
public class Solution {
public int maxSubArray(int[] A) {
int sum = 0;
int maxSum = Integer.MIN_VALUE;
if (sum < 0)
sum = 0;
}
return maxSum;
}
}
The changing condition for dynamic programming is "We should ignore the sum of
the previous n-1 elements if nth element is greater than the sum."
public class Solution {
public int maxSubArray(int[] A) {
62 | 181
int max = A[0];
int[] sum = new int[A.length];
sum[0] = A[0];
return max;
}
}
Find the contiguous subarray within an array (containing at least one number) which
has the largest product.
For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest
product = 6.
63 | 181
if(i+l < A.length){
int product = calProduct(A, i, l);
max = Math.max(product, max);
}
}
return max;
}
This is similar to maximum subarray. Instead of sum, the sign of number affect the
product value.
When iterating the array, each element has two possibilities: positive number or
negative number. We need to track a minimum value, so that when a negative number
is given, it can also find the maximum value. We define two local variables, one tracks
the maximum and the other tracks the minimum.
public int maxProduct(int[] A) {
if(A==null || A.length==0)
return 0;
Time is O(n).
64 | 181
32 Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear
only once and return the new length. Do not allocate extra space for another array,
you must do this in place with constant memory.
For example, given input array A = [1,1,2], your function should return length = 2,
and A is now [1,2].
32.1 Thoughts
The problem is pretty straightforward. It returns the length of array with unique
elements, but the original array need to be changed also. This problem should be
reviewed with Remove Duplicates from Sorted Array II.
32.2 Solution 1
int j = 0;
int i = 1;
return j + 1;
}
This method returns the number of unique elements, but does not change the orig-
inal array correctly. For example, if the input array is 1, 2, 2, 3, 3, the array will be
changed to 1, 2, 3, 3, 3. The correct result should be 1, 2, 3. Because arrays size can
not be changed once created, there is no way we can return the original array with
correct results.
32.3 Solution 2
int j = 0;
int i = 1;
return B;
}
32.4 Solution 3
If we only want to count the number of unique elements, the following method is
good enough.
// Count the number of unique elements
public static int countUnique(int[] A) {
int count = 0;
for (int i = 0; i < A.length - 1; i++) {
if (A[i] == A[i + 1]) {
count++;
}
}
return (A.length - count);
}
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3], your function should return length
= 5, and A is now [1,1,2,2,3].
Given the method signature "public int removeDuplicates(int[] A)", it seems that we
should write a method that returns a integer and thats it. After typing the following
solution:
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length == 0)
return 0;
if(curr == pre){
if(!flag){
flag = true;
continue;
}else{
count++;
}
}else{
pre = curr;
flag = false;
}
}
67 | 181
33 Remove Duplicates from Sorted Array II
We can not change the given arrays size, so we only change the first k elements of the
array which has duplicates removed.
public class Solution {
public int removeDuplicates(int[] A) {
if (A == null || A.length == 0)
return 0;
if (curr == pre) {
if (!flag) {
flag = true;
A[o++] = curr;
continue;
} else {
count++;
}
} else {
pre = curr;
A[o++] = curr;
flag = false;
}
}
return prev + 1;
}
}
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc",
which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
The first solution is like the problem of "determine if a string has all unique characters"
in CC 150. We can use a flag array to track the existing characters for the longest
substring without repeating characters.
69 | 181
34 Longest Substring Without Repeating Characters
int result = 0;
int start = 0;
char[] arr = s.toCharArray();
return result;
}
This solution is from Tia. It is easier to understand than the first solution.
The basic idea is using a hash table to track existing characters and their position.
When a repeated character occurs, check from the previously repeated character. How-
ever, the time complexity is higher - O(n3).
public static int lengthOfLongestSubstring(String s) {
When loop hits the second "a", the HashMap contains the following:
a 0
b 1
c 2
d 3
The index i is set to 0 and incremented by 1, so the loop start from second element
again.
35.1 Problem
Given a string, find the longest substring that contains only two unique characters. For
example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique
character is "bcbbbbcccb".
Here is a naive solution. It works. Basically, it has two pointers that track the start of
the substring and the iteration cursor.
public static String subString(String s) {
// checking
71 | 181
35 Longest Substring Which Contains 2 Unique Characters
j = i - helper(str);
}
}
}
// This method returns the length that contains only one character from right
side.
public static int helper(String str) {
// null & illegal checking here
if(str == null){
return 0;
}
if(str.length() == 1){
return 1;
}
return result;
}
Now if this question is extended to be "the longest substring that contains k unique
characters", what should we do? Apparently, the solution above is not scalable.
The above solution can be extended to be a more general solution which would allow
k distinct characters.
36 Palindrome Partitioning
36.1 Problem
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab", Return
[
["aa","b"],
["a","a","b"]
]
if (s == null || s.length() == 0) {
return result;
}
73 | 181
36 Palindrome Partitioning
return result;
}
left++;
right--;
}
return true;
}
The dynamic programming approach is very similar to the problem of longest palin-
drome substring.
public static List<String> palindromePartitioning(String s) {
if (s == null)
if (s.length() <= 1) {
result.add(s);
return result;
}
return result;
}
This problem is pretty straightforward. We first split the string to words array, and
then iterate through the array and add each element to a new string. Note: String-
Builder should be used to avoid creating too many Strings. If the string is very long,
75 | 181
using String is not scalable since String is immutable and too many objects will be
created and garbage collected.
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1
2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.You may assume no duplicate exists in the array.
38.1 Thoughts
When we search something from a sorted array, binary search is almost a top choice.
Binary search is efficient for sorted arrays.
This problems seems like a binary search, and the key is how to break the array to
two parts, so that we only need to work on half of the array each time, i.e., when to
select the left half and when to select the right half.
If we pick the middle element, we can compare the middle element with the left-end
element. If middle is less than leftmost, the left half should be selected; if the middle
is greater than the leftmost, the right half should be selected. Using simple recursion,
this problem can be solve in time log(n).
In addition, in any rotated sorted array, the rightmost element should be less than
the left-most element, otherwise, the sorted array is not rotated and we can simply
76 | 181
pick the leftmost element as the minimum.
// not rotated
if (num[left] < num[right]) {
return num[left];
// go right side
} else if (num[middle] > num[left]) {
return findMin(num, middle, right);
// go left side
} else {
return findMin(num, left, middle);
}
}
39.1 Problem
Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are al-
lowed?
Would this affect the run-time complexity? How and why?
77 | 181
39.2 Java Solution
This is a follow-up problem of finding minimum element in rotated sorted array with-
out duplicate elements. We only need to add one more condition, which checks if
the left-most element and the right-most element are equal. If they are we can simply
drop one of them. In my solution below, I drop the left element whenever the left-most
equals to the right-most.
public int findMin(int[] num) {
return findMin(num, 0, num.length-1);
}
A peak element is an element that is greater than its neighbors. Given an input array
where num[i] 6= num[i+1], find a peak element and return its index. The array may
contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -. For example, in array [1, 2, 3, 1], 3 is
78 | 181
a peak element and your function should return the index number 2.
40.1 Thoughts
This is a very simple problem. We can scan the array and find any element that is
greater can its previous and next. The first and last element are handled separately.
if(curr > prev && curr > next && curr > max){
index = i;
max = curr;
}
}
return index;
}
}
41 Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in
constant time.
push(x) Push element x onto stack. pop() Removes the element on top of the
stack. top() Get the top element. getMin() Retrieve the minimum element in the
stack.
79 | 181
41.1 Thoughts
An array is a perfect fit for this problem. We can use a integer to track the top of the
stack. You can use the Stack class from Java SDK, but I think a simple array is more
efficient and more beautiful.
class MinStack {
private int[] arr = new int[100];
private int index = -1;
80 | 181
42 Majority Element
42 Majority Element
Problem:
Given an array of size n, find the majority element. The majority element is the
element that appears more than b n/2 c times. You may assume that the array is
non-empty and the majority element always exist in the array.
We can sort the array first, which takes time of nlog(n). Then scan once to find the
longest consecutive substrings.
public class Solution {
public int majorityElement(int[] num) {
if(num.length==1){
return num[0];
}
Arrays.sort(num);
int prev=num[0];
int count=1;
for(int i=1; i<num.length; i++){
if(num[i] == prev){
count++;
if(count > num.length/2) return num[i];
}else{
count=1;
prev = num[i];
}
}
return 0;
}
}
Thanks to SK. His/her solution is much efficient and simpler. Since the majority al-
ways take more than a half space, the middle element is guaranteed to be the majority.
Sorting array takes nlog(n). So the time complexity of this solution is nlog(n). Cheers!
public int majorityElement(int[] num) {
if (num.length == 1) {
return num[0];
}
43 Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combi-
nations in C where the candidate numbers sums to T. The same repeated number may
be chosen from C unlimited number of times.
Note: All numbers (including target) will be positive integers. Elements in a combi-
nation (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak). The
solution set must not contain duplicate combinations. For example, given candidate
set 2,3,6,7 and target 7, A solution set is:
[7]
[2, 2, 3]
43.1 Thoughts
The first impression of this problem should be depth-first search(DFS). To solve DFS
problem, recursion is a normal implementation.
Note that the candidates array is not sorted, we need to sort it first.
return result;
}
82 | 181
public void combinationSum(int[] candidates, int target, int j,
ArrayList<Integer> curr, ArrayList<ArrayList<Integer>> result){
if(target == 0){
ArrayList<Integer> temp = new ArrayList<Integer>(curr);
result.add(temp);
return;
}
curr.add(candidates[i]);
combinationSum(candidates, target - candidates[i], i, curr, result);
curr.remove(curr.size()-1);
}
}
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell
one share of the stock), design an algorithm to find the maximum profit.
83 | 181
44.2 Efficient Approach
Instead of keeping track of largest element in the array, we track the maximum profit
so far.
public int maxProfit(int[] prices) {
int profit = 0;
int minElement = Integer.MAX_VALUE;
for(int i=0; i<prices.length; i++){
profit = Math.max(profit, prices[i]-minElement);
minElement = Math.min(minElement, prices[i]);
}
return profit;
}
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many trans-
actions as you like (ie, buy one and sell one share of the stock multiple times). How-
ever, you may not engage in multiple transactions at the same time (ie, you must sell
the stock before you buy again).
45.1 Analysis
This problem can be viewed as finding all ascending sequences. For example, given 5,
1, 2, 3, 4, buy at 1 & sell at 4 is the same as buy at 1 &sell at 2 & buy at 2& sell at 3 &
buy at 3 & sell at 4.
We can scan the array once, and find all pairs of elements that are in ascending
order.
84 | 181
return profit;
}
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two
transactions.
Note: A transaction is a buy & a sell. You may not engage in multiple transactions
at the same time (ie, you must sell the stock before you buy again).
46.1 Analysis
Comparing to I and II, III limits the number of transactions to 2. This can be solve
by "devide and conquer". We use left[i] to track the maximum profit for transactions
before i, and use right[i] to track the maximum profit for transactions after i. You can
use the following example to understand the Java solution:
Prices: 1 4 5 7 6 3 2 9
left = [0, 3, 4, 6, 6, 6, 6, 8]
right= [8, 7, 7, 7, 7, 7, 7, 0]
85 | 181
}
int profit = 0;
for (int i = 0; i < prices.length; i++) {
profit = Math.max(profit, left[i] + right[i]);
}
return profit;
}
47.1 Problem
Say you have an array for which the ith element is the price of a given stock on
day i.Design an algorithm to find the maximum profit. You may complete at most k
transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must
sell the stock before you buy again).
47.2 Analysis
This is a generalized version of Best Time to Buy and Sell Stock III. If we can solve this
problem, we can also use k=2 to solve III.
The problem can be solve by using dynamic programming. The relation is:
local[i][j] = max(global[i-1][j-1] + max(diff,0), local[i-1][j]+diff)
global[i][j] = max(local[i][j], global[i-1][j])
We track two arrays - local and global. The local array tracks maximum profit of j
transactions & the last transaction is on ith day. The global array tracks the maximum
profit of j transactions until ith day.
86 | 181
47 Best Time to Buy and Sell Stock IV
return global[k];
}
48.1 Problem
Write a function to find the longest common prefix string amongst an array of strings.
48.2 Analysis
To solve this problem, we need to find the two loop conditions. One is the length of
the shortest string. The other is iteration over every element of the string array.
int minLen=Integer.MAX_VALUE;
for(String str: strs){
if(minLen > str.length())
minLen = str.length();
}
if(minLen == 0) return "";
if(strs[i].charAt(j) != prev){
return strs[i].substring(0, j);
}
}
88 | 181
}
return strs[0].substring(0,minLen);
}
49 Largest Number
49.1 Problem
Given a list of non negative integers, arrange them such that they form the largest
number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an
integer.
49.2 Analysis
This problem can be solve by simply sorting strings, not sorting integer. Define a
comparator to compare strings by concat() right-to-left or left-to-right.
89 | 181
java.math.BigInteger result = new java.math.BigInteger(sb.toString());
return result.toString();
}
50 Combinations
50.1 Problem
Given two integers n and k, return all possible combinations of k numbers out of 1 ...
n.
For example, if n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
This is my naive solution. It passed the online judge. I first initialize a list with only
one element, and then recursively add available elements to it.
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//illegal case
if (k > n) {
return null;
//if k==n
} else if (k == n) {
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
temp.add(i);
}
result.add(temp);
return result;
//if k==1
90 | 181
50 Combinations
} else if (k == 1) {
return result;
}
return result;
}
if(result.get(0).size() == k) return;
result.clear();
for (ArrayList<Integer> one : prevResult) {
combine(n, k, result);
}
if (n <= 0 || n < k)
return result;
return result;
}
51.1 Problem
Compare two version numbers version1 and version2. If version1 >version2 return 1,
if version1 <version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and
the . character. The . character does not represent a decimal point and is used to
separate number sequences.
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
92 | 181
51.2 Java Solution
The tricky part of the problem is to handle cases like 1.0 and 1. They should be equal.
public int compareVersion(String version1, String version2) {
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");
int i=0;
while(i<arr1.length || i<arr2.length){
if(i<arr1.length && i<arr2.length){
if(Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])){
return -1;
}else if(Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])){
return 1;
}
} else if(i<arr1.length){
if(Integer.parseInt(arr1[i]) != 0){
return 1;
}
} else if(i<arr2.length){
if(Integer.parseInt(arr2[i]) != 0){
return -1;
}
}
i++;
}
return 0;
}
52 Gas Station
52.1 Problem
There are N gas stations along a circular route, where the amount of gas at station i is
gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from
station i to its next station (i+1). You begin the journey with an empty tank at one of
the gas stations.
Return the starting gas stations index if you can travel around the circuit once,
otherwise return -1.
93 | 181
52 Gas Station
52.2 Analysis
To solve this problem, we need to understand: 1) if sum of gas[] >= sum of cost[], then
there exists a start index to complete the circle. 2) if A can not read C in a the sequence
of A>B>C, then B can not make it either.
Proof:
If gas[A] < cost[A], then A can not go to B. Therefore, gas[A] >=cost[A].
We already know A can not go to C, we have gas[A] + gas[B] < cost[A] + cost[B]
And gas[A] >=cost[A],
Therefore, gas[B] < cost[B], i.e., B can not go to C.
In the following solution, sumRemaining tracks the sum of remaining to the current
index. If sumRemaining <0, then every index between old start and current index is
bad, and we need to update start to be the current index.
53 Candy
53.1 Problem
There are N children standing in a line. Each child is assigned a rating value. You are
giving candies to these children subjected to the following requirements:
1. Each child must have at least one candy. 2. Children with a higher rating get
more candies than their neighbors.
What is the minimum candies you must give?
95 | 181
int result = candies[ratings.length - 1];
return result;
}
54 Jump Game
54.1 Problem
Given an array of non-negative integers, you are initially positioned at the first index
of the array. Each element in the array represents your maximum jump length at that
position. Determine if you are able to reach the last index. For example: A = [2,3,1,1,4],
return true. A = [3,2,1,0,4], return false.
We can track the maximum length a position can reach. The key to solve this problem
is to find 2 conditions: 1) the position can not reach next step (return false) , and 2)
the maximum reach the end (return true).
public boolean canJump(int[] A) {
if(A.length <= 1)
return true;
//update max
96 | 181
if(i + A[i] > max){
max = i + A[i];
}
return false;
}
55 Pascals Triangle
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
97 | 181
cur.add(1); //first
for (int j = 0; j < pre.size() - 1; j++) {
cur.add(pre.get(j) + pre.get(j + 1)); //middle
}
cur.add(1);//last
result.add(cur);
pre = cur;
}
return result;
}
56.1 Problem
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordi-
nate (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.
56.2 Analysis
Initially we can assume the result is 0. Then we scan from both sides. If leftHeight
<rightHeight, move right and find a value that is greater than leftHeight. Similarily,
if leftHeight >rightHeight, move left and find a value that is greater than rightHeight.
Additionally, keep tracking the max value.
98 | 181
public int maxArea(int[] height) {
if (height == null || height.length < 2) {
return 0;
}
int max = 0;
int left = 0;
int right = height.length - 1;
return max;
}
57.1 Problem
The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21,
1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
The problem can be solved by using a simple iteration. See Java solution below:
public String countAndSay(int n) {
if (n <= 0)
return null;
99 | 181
int i = 1;
while (i < n) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int j = 1; j < result.length(); j++) {
if (result.charAt(j) == result.charAt(j - 1)) {
count++;
} else {
sb.append(count);
sb.append(result.charAt(j - 1));
count = 1;
}
}
sb.append(count);
sb.append(result.charAt(result.length() - 1));
result = sb.toString();
i++;
}
return result;
}
58.1 Problem
The key to solve this problem is that each of the 4 nucleotides can be stored in 2 bits.
So the 10-letter-long sequence can be converted to 20-bits-long integer. The following
is a Java solution. You may use an example to manually execute the program and see
how it works.
100 | 181
public List<String> findRepeatedDnaSequences(String s) {
List<String> result = new ArrayList<String>();
int hash = 0;
for (int i = 0; i < len; i++) {
if (i < 9) {
//each ACGT fit 2 bits, so left shift 2
hash = (hash << 2) + map.get(s.charAt(i));
} else {
hash = (hash << 2) + map.get(s.charAt(i));
//make length of hash to be 20
hash = hash & (1 << 20) - 1;
return result;
}
The problem:
101 | 181
59 Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are
stored in reverse order and each of their nodes contain a single digit. Add the two numbers
and return it as a linked list. Input: (2 ->4 ->3) + (5 ->6 ->4) Output: 7 ->0 ->8
59.1 Thoughts
59.2 Solution 1
ListNode p1 = l1;
ListNode p2 = l2;
if(flag){
val = p1.val + p2.val + 1;
}else{
if(flag){
val = p2.val + 1;
if(val >= 10){
flag = true;
}else{
flag = false;
}
}else{
val = p2.val;
flag = false;
}
if(flag){
val = p1.val + 1;
if(val >= 10){
flag = true;
}else{
flag = false;
}
}else{
val = p1.val;
flag = false;
}
p3 = p3.next;
}
return newHead.next;
}
}
The hard part is how to make the code more readable. Adding some internal com-
ments and refactoring some code are helpful.
59.3 Solution 2
There is nothing wrong with solution 1, but the code is not readable. We can refactor
the code and make it much shorter and cleaner.
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry =0;
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
59.4 Quesion
What is the digits are stored in regular order instead of reversed order?
Answer: We can simple reverse the list, calculate the result, and reverse the result.
60 Reorder List
The problem:
Given a singly linked list L: L0L1 ... Ln-1Ln, reorder it to: L0LnL1Ln-
1L2Ln-2...
For example, given 1,2,3,4, reorder it to 1,4,2,3. You must do this in-place without
altering the nodes values.
60.1 Thoughts
60.2 Solution
Break list in the middle to two lists (use fast & slow pointers)
Reverse the order of the second list
Merge two list back together
ListNode(int x) {
val = x;
next = null;
}
105 | 181
60 Reorder List
printList(n1);
reorderList(n1);
printList(n1);
}
//use a fast and slow pointer to break the link to two parts.
while (fast != null && fast.next != null && fast.next.next!= null) {
//why need third/second condition?
System.out.println("pre "+slow.val + " " + fast.val);
slow = slow.next;
fast = fast.next.next;
System.out.println("after " + slow.val + " " + fast.val);
}
ListNode p1 = head;
ListNode p2 = second;
p1.next = p2;
p2.next = temp1;
p1 = temp1;
p2 = temp2;
}
}
}
return pre;
}
The three steps can be used to solve other problems of linked list. A little diagram
may help better understand them.
Reverse List:
108 | 181
61 Linked List Cycle
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
if(head == null)
return false;
if(p.next == null)
return false;
while(p.next != null){
if(head == p.next){
return true;
}
p = p.next;
}
return false;
}
}
Result:
Submission Result: Time Limit Exceeded Last executed input: 3,2,0,-4, tail connects
to node index 1
Use fast and low pointer. The advantage about fast/slow pointers is that when a circle
is located, the fast one will catch the slow one for sure.
if(head == null)
return false;
if(head.next == null)
return false;
if(slow == fast)
return true;
}
return false;
}
}
Problem:
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.
copy every node, i.e., duplicate every node, and insert it to the list
copy random pointers for all newly created nodes
break the list to two
111 | 181
62 Copy List with Random Pointer
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null)
return null;
RandomListNode p = head;
return head.next;
}
}
The code above seems totally fine. It follows the steps designed. But it has run-time
errors. Why?
The problem is in the parts of copying random pointer and breaking list.
if (head == null)
return null;
RandomListNode p = head;
return newHead;
}
The break list part above move pointer 2 steps each time, you can also move one at
a time which is simpler, like the following:
while(p != null && p.next != null){
RandomListNode temp = p.next;
p.next = temp.next;
p = temp;
}
From Xiaomengs comment below, we can use a HashMap which makes it simpler.
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode,
RandomListNode>();
RandomListNode newHead = new RandomListNode(head.label);
RandomListNode p = head;
RandomListNode q = newHead;
map.put(head, newHead);
p = p.next;
while (p != null) {
RandomListNode temp = new RandomListNode(p.label);
map.put(p, temp);
q.next = temp;
q = temp;
p = p.next;
}
p = head;
q = newHead;
while (p != null) {
if (p.random != null)
q.random = map.get(p.random);
else
q.random = null;
p = p.next;
q = q.next;
}
return newHead;
}
Problem:
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.
114 | 181
63.1 Key to solve this problem
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 merged list. Finally, when one of them is
empty, simply append it to the merged list, since it is already sorted.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p1 = l1;
ListNode p2 = l2;
p = p.next;
}
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}
}
115 | 181
64 Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its
complexity.
64.1 Thoughts
The simplest solution is using PriorityQueue. The elements of the priority queue
are ordered according to their natural ordering, or by a comparator provided at the
construction time (in this case).
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
ListNode(int x) {
val = x;
next = null;
}
}
p = p.next;
}
return head.next;
}
}
Given a sorted linked list, delete all duplicates such that each element appear only
once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
65.1 Thoughts
The key of this problem is using the right loop condition. And change what is nec-
essary in each loop. You can use different iteration conditions like the following 2
117 | 181
65 Remove Duplicates from Sorted List
solutions.
65.2 Solution 1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
while(p != null){
if(p.val == prev.val){
prev.next = p.next;
p = p.next;
//no change prev
}else{
prev = p;
p = p.next;
}
}
return head;
}
}
65.3 Solution 2
ListNode p = head;
return head;
}
}
66 Partition List
Given a linked list and a value x, partition it such that all nodes less than x come
before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two
partitions.
For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.
The following is a solution I write at the beginning. It contains a trivial problem, but
it took me a long time to fix it.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
119 | 181
66 Partition List
fakeHead1.next = head;
ListNode p = head;
ListNode prev = fakeHead1;
ListNode p2 = fakeHead2;
while(p != null){
if(p.val < 3){
p = p.next;
prev = prev.next;
}else{
prev.next = p.next;
p2.next = p;
p = prev.next;
p2 = p2.next;
}
}
p.next = fakeHead2.next;
return fakeHead1.next;
}
}
The problem of the first solution is that the last nodes next element should be set to
null.
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
ListNode p = head;
ListNode prev = fakeHead1;
ListNode p2 = fakeHead2;
while(p != null){
if(p.val < x){
p = p.next;
prev = prev.next;
}else{
p2.next = p;
prev.next = p.next;
prev.next = fakeHead2.next;
return fakeHead1.next;
}
}
67 LRU Cache
67.1 Problem
Design and implement a data structure for Least Recently Used (LRU) cache. It should
support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the
cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not
already present. When the cache reached its capacity, it should invalidate the least
recently used item before inserting a new item.
The key to solve this problem is using a double linked list which enables us to quickly
move nodes.
121 | 181
67 LRU Cache
import java.util.HashMap;
if (pre != null) {
pre.next = post;
} else {
head = post;
}
if (post != null) {
post.pre = pre;
} else {
end = pre;
}
}
head = node;
if (end == null) {
end = node;
}
}
setHead(newNode);
map.put(key, newNode);
}
}
}
}
class DoubleLinkedListNode {
public int val;
68.1 Problem
Write a program to find the node at which the intersection of two singly linked lists
begins.
For example, the following two linked lists:
A: a1 -> a2
->
c1 -> c2 -> c3
->
B: b1 -> b2 -> b3
First calculate the length of two lists and find the difference. Then start from the longer
list at the diff offset, iterate though 2 lists and find the node.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
124 | 181
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int len1 = 0;
int len2 = 0;
ListNode p1=headA, p2=headB;
if (p1 == null || p2 == null)
return null;
while(p1 != null){
len1++;
p1 = p1.next;
}
while(p2 !=null){
len2++;
p2 = p2.next;
}
int diff = 0;
p1=headA;
p2=headB;
}
p1 = p1.next;
p2 = p2.next;
}
return null;
}
}
125 | 181
69 Java PriorityQueue Class Example
The following examples shows the basic operations of PriorityQueue such as offer(),
peek(), poll(), and size().
import java.util.Comparator;
import java.util.PriorityQueue;
}
}
Output:
pq1: [1, 3, 5, 8, 4, 7, 6, 10, 9]
pq2: [10, 9, 7, 8, 3, 5, 6, 1, 4]
size: 9
peek: 10
size: 9
poll: 10
size: 8
pq2: [9, 8, 7, 4, 3, 5, 6, 1]
Preorder binary tree traversal is a classic interview problem about trees. The key to
solve this problem is to understand the following:
What is preorder? (parent node is processed before its children)
Use Stack from Java Core library
It is not obvious what preorder for some strange cases. However, if you draw a
stack and manually execute the program, how each element is pushed and popped is
127 | 181
obvious.
The key to solve this problem is using a stack to store left and right children, and
push right child first so that it is processed after the left child.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
if(root == null)
return returnList;
while(!stack.empty()){
TreeNode n = stack.pop();
returnList.add(n.val);
if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
}
}
return returnList;
}
}
The key to solve inorder traversal of binary tree includes the following:
128 | 181
71 Solution of Binary Tree Inorder Traversal in Java
if(root == null)
return lst;
while(!stack.empty() || p != null){
return lst;
}
}
The order of "Postorder" is: left child ->right child ->parent node.
Find the relation between the previously visited node and the current node
Use a stack to track nodes
As we go down the tree, check the previously visited node. If it is the parent of
the current node, we should add current node to stack. When there is no children
for current node, pop it from stack. Then the previous node become to be under the
current node for next loop.
//Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
if(root == null)
130 | 181
return lst;
prev = curr;
}
return lst;
}
}
131 | 181
73 Validate Binary Search Tree
Problem:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the nodes key.
The right subtree of a node contains only nodes with keys greater than the nodes
key.
Both the left and right subtrees must also be binary search trees.
All values on the left sub tree must be less than root, and all values on the right sub
tree must be greater than root.
TreeNode(int x) {
val = x;
}
}
// not in range
// left subtree must be < root.val && right subtree must be > root.val
return validate(root.left, min, root.val) && validate(root.right,
root.val, max);
}
}
74.1 Thoughts
Go down through the left, when right is not null, push right to stack.
133 | 181
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
if(p.right != null){
stack.push(p.right);
}
if(p.left != null){
p.right = p.left;
p.left = null;
}else if(!stack.empty()){
TreeNode temp = stack.pop();
p.right=temp;
}
p = p.right;
}
}
}
75 Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that
adding up all the values along the path equals the given sum.
For example: Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
134 | 181
75 Path Sum
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Add all node to a queue and store sum value of each node to another queue. When it
is a leaf node, check the stored sum value.
For the tree above, the queue would be: 5 - 4 - 8 - 11 - 13 - 4 - 7 - 2 - 1. It will check
node 13, 7, 2 and 1. This is a typical breadth first search(BFS) problem.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
nodes.add(root);
values.add(root.val);
while(!nodes.isEmpty()){
TreeNode curr = nodes.poll();
int sumValue = values.poll();
if(curr.left != null){
nodes.add(curr.left);
values.add(sumValue+curr.left.val);
}
if(curr.right != null){
nodes.add(curr.right);
values.add(sumValue+curr.right.val);
}
}
Given inorder and postorder traversal of a tree, construct the binary tree.
76.1 Throughts
From the post-order array, we know that last element is the root. We can find the
root in in-order array. Then we can identify the left and right sub-trees of the root
from in-order array.
Using the length of left sub-tree, we can identify left and right sub-trees in post-order
array. Recursively, we can build up the tree.
136 | 181
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
int k=0;
for(int i=0; i< inorder.length; i++){
if(inorder[i]==rootValue){
k = i;
break;
}
}
return root;
}
}
137 | 181
77 Convert Sorted Array to Binary
Search Tree
Given an array where elements are sorted in ascending order, convert it to a height
balanced BST.
77.1 Thoughts
TreeNode(int x) {
val = x;
}
}
return root;
}
}
138 | 181
78 Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a
height balanced BST.
78.1 Thoughts
If you are given an array, the problem is quite straightforward. But things get a little
more complicated when you have a singly linked list instead of an array. Now you no
longer have random access to an element in O(1) time. Therefore, you need to create
nodes bottom-up, and assign them to its parents. The bottom-up approach enables us
to access the list in its order at the same time as creating nodes.
ListNode(int x) {
val = x;
next = null;
}
}
TreeNode(int x) {
val = x;
}
}
while (p != null) {
len++;
p = p.next;
}
return len;
}
// mid
int mid = (start + end) / 2;
root.left = left;
root.right = right;
return root;
}
}
140 | 181
79 Minimum Depth of Binary Tree
79.1 Thoughts
Need to know LinkedList is a queue. add() and remove() are the two methods to
manipulate the queue.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
nodes.add(root);
counts.add(1);
while(!nodes.isEmpty()){
TreeNode curr = nodes.remove();
int count = counts.remove();
if(curr.left != null){
nodes.add(curr.left);
counts.add(count+1);
}
if(curr.right != null){
nodes.add(curr.right);
counts.add(count+1);
}
return 0;
}
Return 6.
80.1 Thoughts
1) Recursively solve this problem 2) Get largest left sum and right sum 2) Compare to
the stored maximum
TreeNode(int x) {
val = x;
}
}
142 | 181
public int findMax(TreeNode node) {
if (node == null)
return 0;
return current;
}
}
143 | 181
81 Balanced Binary Tree
81.1 Thoughts
TreeNode(int x) {
val = x;
}
}
if (getHeight(root) == -1)
return false;
return true;
}
}
}
82 Symmetric Tree
82.1 Problem
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its
center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
This problem can be solve by using a simple recursion. The key is finding the con-
ditions that return false, such as value is not equal, only one node(left or right) has
value.
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
return isSymmetric(root.left, root.right);
}
145 | 181
if (l == null && r == null) {
return true;
} else if (r == null || l == null) {
return false;
}
if (l.val != r.val)
return false;
if (!isSymmetric(l.left, r.right))
return false;
if (!isSymmetric(l.right, r.left))
return false;
return true;
}
LeetCode Problem:
Clone an undirected graph. Each node in the graph contains a label and a list of its
neighbors.
146 | 181
83 Clone Graph Java
a map is used to store the visited nodes. It is the map between original node and
copied node.
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new
ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null)
return null;
queue.add(node);
map.put(node, newHead);
}
return newHead;
}
}
While analyzing source code of a large number of open source Java projects, I found
Java developers frequently sort in two ways. One is using the sort() method of Col-
lections or Arrays, and the other is using sorted data structures, such as TreeMap and
TreeSet.
149 | 181
84 How Developers Sort in Java?
// Arrays.sort
ObjectName[] arr = new ObjectName[10];
Arrays.sort(arr, new Comparator<ObjectName>() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString());
}
});
This approach is very useful, if you would do a lot of search operations for the
collection. The sorted data structure will give time complexity of O(logn), which is
lower than O(n).
There are still bad practices, such as using self-defined sorting algorithm. Take the
code below for example, not only the algorithm is not efficient, but also it is not
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// merge sort
public static ListNode mergeSortList(ListNode head) {
151 | 181
85 Solution Merge Sort LinkedList in Java
if (countHalf == middle) {
p2.next = null;
r = next;
}
p2 = next;
}
// merge together
ListNode merged = merge(h1, h2);
return merged;
}
if (p1 == null) {
pNew.next = new ListNode(p2.val);
p2 = p2.next;
pNew = pNew.next;
} else if (p2 == null) {
} else {
pNew.next = new ListNode(p2.val);
p2 = p2.next;
pNew = pNew.next;
}
}
}
// printList(fakeHead.next);
return fakeHead.next;
}
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n1 = mergeSortList(n1);
printList(n1);
}
}
}
Output:
233445
Quicksort is a divide and conquer algorithm. It first divides a large list into two
smaller sub-lists and then recursively sort the two sub-lists. If we want to sort an array
without any extra space, Quicksort is a good option. On average, time complexity is
O(n log(n)).
The basic step of sorting an array are as follows:
package algorithm.sort;
int low = 0;
int high = x.length - 1;
154 | 181
if (arr == null || arr.length == 0)
return;
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (high > i)
quickSort(arr, i, high);
}
Output:
9 2 4 7 3 7 10 2 3 4 7 7 9 10
The mistake I made is selecting the middle element. The middle element is not
(low+high)/2, but low + (high-low)/2. For other parts of the programs, just follow the
155 | 181
87 Solution Sort a linked list using insertion sort in Java
algorithm.
Code:
package algorithm.sort;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
innerPointer = innerPointer.next;
}
// finally
pointer = next;
}
return newHead;
}
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n1 = insertionSortList(n1);
printList(n1);
}
}
Output:
233445
88 Maximum Gap
88.1 Problem
Given an unsorted array, find the maximum difference between the successive ele-
ments in its sorted form.
Try to solve it in linear time/space. Return 0 if the array contains less than 2 ele-
ments. You may assume all elements in the array are non-negative integers and fit in
the 32-bit signed integer range.
A straightforward solution would be sorting the array first (O(nlogn) and then finding
the maximum gap. The basic idea is to project each element of the array to an array of
158 | 181
88 Maximum Gap
buckets. Each bucket tracks the maximum and minimum elements. Finally, scanning
the bucket list, we can get the maximum gap.
The key part is to get the interval:
From: interval * (num[i] - min) = 0 and interval * (max -num[i]) = n
interval = num.length / (max - min)
We can use a bucket-sort like algorithm to solve this problem in time of O(n) and space
O(n).
class Bucket{
int low;
int high;
public Bucket(){
low = -1;
high = -1;
}
}
if(buckets[index].low == -1){
buckets[index].low = num[i];
buckets[index].high = num[i];
return result;
}
89.1 Recursion
In order to run this program, the computer needs to build up a chain of multipli-
cations: factorial(n) factorial(n-1) factorial(n-2) ... factorial(1). Therefore,
the computer has to keep track of the multiplications to be performed later on. This
type of program, characterized by a chain of operations, is called recursion. Recursion
can be further categorized into linear and tree recursion. When the amount of infor-
mation needed to keep track of the chain of operations grows linearly with the input,
160 | 181
89 Iteration vs. Recursion in Java
the recursion is called linear recursion. The computation of n! is such a case, because
the time required grows linearly with n. Another type of recursion, tree recursion,
happens when the amount of information grows exponentially with the input. But we
will leave it undiscussed here and go back shortly afterwards.
89.2 Iteration
Compared the two processes, we can find that they seem almost same, especially in
term of mathematical function. They both require a number of steps proportional to
n to compute n!. On the other hand, when we consider the running processes of the
two programs, they evolve quite differently.
In the iterative case, the program variables provide a complete description of the
state. If we stopped the computation in the middle, to resume it only need to supply
the computer with all variables. However, in the recursive process, information is
maintained by the computer, therefore "hidden" to the program. This makes it almost
impossible to resume the program after stopping it.
As described above, tree recursion happens when the amount of information grows
exponentially with the input. For instance, consider the sequence of Fibonacci num-
By the definition, Fibonacci numbers have the following sequence, where each num-
ber is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
A recursive program can be immediately written as:
Program 3:
int fib (int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fib(n-1) + fib(n-2);
}
}
Therefore, to compute fib(5), the program computes fib(4) and fib(3). To computer
fib(4), it computes fib(3) and fib(2). Notice that the fib procedure calls itself twice at
the last line. Two observations can be obtained from the definition and the program:
The ith Fibonacci number Fib(i) is equal to phi(i)/rootsquare(5) rounded to the
nearest integer, which indicates that Fibonacci numbers grow exponentially.
This is a bad way to compute Fibonacci numbers because it does redundant
computation. Computing the running time of this procedure is beyond the
scope of this article, but one can easily find that in books of algorithms, which is
O(phi(n)). Thus, the program takes an amount of time that grows exponentially
with the input.
On the other hand, we can also write the program in an iterative way for computing
the Fibonacci numbers. Program 4 is a linear iteration. The difference in time required
by Program 3 and 4 is enormous, even for small inputs.
Program 4:
int fib (int n) {
int fib = 0;
int a = 1;
for(int i=0; i<n; i++) {
fib = fib + a;
a = fib;
}
return fib;
}
From Wiki:
In computer science, edit distance is a way of quantifying how dissimilar two strings
(e.g., words) are to one another by counting the minimum number of operations required
to transform one string into the other.
There are three operations permitted on a word: replace, delete, insert. For example,
the edit distance between "a" and "b" is 1, the edit distance between "abc" and "def" is
3. This post analyzes how to calculate edit distance by using dynamic programming.
Let dp[i][j] stands for the edit distance between two strings with length i and j, i.e.,
word1[0,...,i-1] and word2[0,...,j-1]. There is a relation between dp[i][j] and dp[i-1][j-1].
Lets say we transform from one string to another. The first string has length i and
its last character is "x"; the second string has length j and its last character is "y". The
following diagram shows the relation.
163 | 181
90 Edit Distance in Java
return dp[len1][len2];
}
91 Single Number
The problem:
Given an array of integers, every element appears twice except for one. Find that single
one.
91.1 Thoughts
The key to solve this problem is bit manipulation. XOR will return 1 only on two
different bits. So if two numbers are the same, XOR will return 0. Finally only one
number left.
165 | 181
int x=0;
for(int a: A){
x = x ^ a;
}
return x;
}
}
92 Single Number II
92.1 Problem
Given an array of integers, every element appears three times except for one. Find that
single one.
166 | 181
For example, 9s binary form is 1001, the gap is 2.
93.1 Thoughts
The key to solve this problem is the fact that an integer x & 1 will get the last digit of
the integer.
while (N > 0) {
// get right most bit & shift right
r = N & 1;
N = N >> 1;
if (1 == r) {
max = count > max ? count : max;
count = 0;
}
}
return max;
}
94 Number of 1 Bits
167 | 181
94.1 Problem
Write a function that takes an unsigned integer and returns the number of 1 bits it
has (also known as the Hamming weight).
For example, the 32-bit integer 11 has binary representation 00000000000000000000000000001011,
so the function should return 3.
95 Reverse Bits
95.1 Problem
168 | 181
return n;
}
if ((a ^ b) != 0) {
return n ^= (1 << i) | (1 << j);
}
return n;
}
96 Permutations
Loop through the array, in each iteration, a new number is added to different loca-
tions of results of previous iteration. Start from an empty List.
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
169 | 181
96 Permutations
result.add(new ArrayList<Integer>());
//System.out.println(temp);
return result;
}
We can also recursively solve this problem. Swap each element with each element
after it.
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
permute(num, 0, result);
return result;
}
97 Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique
permutations.
For example, [1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
For each number in the array, swap it with every element after it. To avoid duplicate,
we need to check the existing sequence first.
171 | 181
97 Permutations II
return returnList;
}
98 Permutation Sequence
98.1 Thoughts
173 | 181
98 Permutation Sequence
// change k to be index
k--;
// set factorial of n
int mod = 1;
for (int i = 1; i <= n; i++) {
mod = mod * i;
}
// find sequence
for (int i = 0; i < n; i++) {
mod = mod / (n - i);
// find the right number(curIndex) of
int curIndex = k / mod;
// update k
k = k % mod;
return result.toString();
}
}
output[s - 1] = true;
buf.append(Integer.toString(s));
}
return buf.toString();
}
}
99 Generate Parentheses
Read the following solution, give n=2, walk though the code. Hopefully you will
quickly get an idea.
public List<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<Integer> diff = new ArrayList<Integer>();
result.add("");
diff.add(0);
175 | 181
ArrayList<Integer> temp2 = new ArrayList<Integer>();
if (i < 2 * n - 1) {
temp1.add(s + "(");
temp2.add(k + 1);
}
return result;
}
Solution is provided first now. I will come back and draw a diagram to explain the
solution.
We can convert the integer to a string/char array, reverse the order, and convert the
string/char array back to an integer. However, this will require extra space for the
string. It doesnt seem to be the right way, if you come with such a solution.
176 | 181
100 Reverse Integer
int res = 0;
int p = x;
while (p > 0) {
int mod = p % 10;
p = p / 10;
res = res * 10 + mod;
}
if (flag) {
res = 0 - res;
}
return res;
}
return rev;
}
As we form a new integer, it is possible that the number is out of range. We can use
the following code to assign the newly formed integer. When it is out of range, throw
an exception.
try{
result = ...;
}catch(InputMismatchException exception){
System.out.println("This is not an integer");
101.1 Thoughts
while (x != 0) {
int left = x / div;
int right = x % 10;
if (left != right)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
}
178 | 181
102 Pow(x, n)
102 Pow(x, n)
Problem:
Implement pow(x, n).
This is a great example to illustrate how to solve a problem during a technical in-
terview. The first and second solution exceeds time limit; the third and fourth are
accepted.
First of all, assuming n is not negative, to calculate x to the power of n, we can simply
multiply x n times, i.e., x * x * ... * x. The time complexity is O(n). The implementation
is as simple as:
public class Solution {
public double pow(double x, int n) {
if(x == 0) return 0;
if(n == 0) return 1;
double result=1;
for(int i=1; i<=n; i++){
result = result * x;
}
return result;
}
}
if(n == 1)
return x;
In this solution, we can handle cases that x <0 and n <0. This solution actually takes
more time than the first solution. Why?
The accepted solution is also recursive, but does division first. Time complexity is
O(nlog(n)). The key part of solving this problem is the while loop.
public double pow(double x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
int k = 1;
//the key part of solving this problem
while (pn / 2 > 0) {
result = result * result;
pn = pn / 2;
k = k * 2;
}
return result;
}
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}