Java QnA
Java QnA
You may have been using Java for a while. Do you think a simple Java array question
can be a challenge? Let’s 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++;
}
Space is O(n) and time is O(n). You can check out the difference between Sys-
tem.arraycopy() and Arrays.copyOf().
13 | 531
288
7 of 246
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. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4
288
8 of 246
1 Rotate Array in Java
reverse(arr, 0, a-1);
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr.length-1);
288
9 of 246
2 Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid op-
erators are +, -, *, /. Each operand may be an integer or another expression. For
example:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
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. However, this code contains compilation errors in leet-
code. Why?
public class Test {
17 | 531
11 of 246
10 288
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 a JDK version below 1.7.
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;
12 of 246
11 288
2 Evaluate Reverse Polish Notation
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;
}
}
13 of 246
12 288
3 Isomorphic Strings
Given two strings s and t, determine if they are isomorphic. Two strings are isomor-
phic if the characters in s can be replaced to get t.
For example,"egg" and "add" are isomorphic, "foo" and "bar" are not.
3.1 Analysis
We need to define a method which accepts a map & a value, and returns the value’s
key in the map.
if(s.length() != t.length())
return false;
return true;
}
21 | 531
15 of 246
13 288
3 Isomorphic Strings
return null;
}
16 of 246
14 288
4 Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transfor-
mation sequence from start to end, such that only one letter can be changed at a time
and each intermediate word must exist in the dictionary. For example, given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
One shortest transformation is "hit" ->"hot" ->"dot" ->"dog" ->"cog", the program
should return its length 5.
4.1 Analysis
UPDATED on 06/07/2015.
So we quickly realize that this is a search problem, and breath-first search guarantees
the optimal solution.
class WordNode{
String word;
int numSteps;
23 | 531
17 of 246
15 288
4 Word Ladder
wordDict.add(endWord);
while(!queue.isEmpty()){
WordNode top = queue.remove();
String word = top.word;
if(word.equals(endWord)){
return top.numSteps;
}
arr[i]=temp;
}
}
}
return 0;
}
}
18 of 246
16 288
5 Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation
sequence(s) from start to end, such that: 1) Only one letter can be changed at a time,
2) Each intermediate word must exist in the dictionary.
For example, given: start = "hit", end = "cog", and dict = ["hot","dot","dog","lot","log"],
return:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
5.1 Analysis
class WordNode{
String word;
int numSteps;
WordNode pre;
25 | 531
19 of 246
17 288
5 Word Ladder II
dict.add(end);
int minStep = 0;
int preNumSteps = 0;
while(!queue.isEmpty()){
WordNode top = queue.remove();
String word = top.word;
int currNumSteps = top.numSteps;
if(word.equals(end)){
if(minStep == 0){
minStep = top.numSteps;
}
preNumSteps = currNumSteps;
20 of 246
18 288
5 Word Ladder II
arr[i]=temp;
}
}
return result;
}
}
21 of 246
19 288
6 Median of Two Sorted Arrays
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)).
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;
}
}
29 | 531
23 of 246
20 288
6 Median of Two Sorted Arrays
Solution 1 is a general solution to find the kth element. We can also come up with a
simpler solution which only finds the median of two sorted arrays for this particular
problem. Thanks to Gunner86. The description of the algorithm is awesome!
1) Calculate the medians m1 and m2 of the input arrays ar1[] and ar2[]
respectively.
2) If m1 and m2 both are equal then we are done, and return m1 (or m2)
3) If m1 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
24 of 246
21 288
7 Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element
in the sorted order, not the kth distinct element.
For example, given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array’s length.
Time is O(nlog(n))
This problem can also be solve by using the quickselect approach, which is similar to
quicksort.
public int findKthLargest(int[] nums, int k) {
if (k < 1 || nums == null) {
return 0;
}
while (true) {
31 | 531
25 of 246
22 288
7 Kth Largest Element in an Array
if (left == right) {
break;
}
if (k == left + 1) {
return pivot;
} else if (k < left + 1) {
return getKth(k, nums, start, left - 1);
} else {
return getKth(k, nums, left + 1, end);
}
}
We can use a min heap to solve this problem. The heap stores the top k elements.
Whenever the size is greater than k, delete the min. Time complexity is O(nlog(k)).
Space complexity is O(k) for storing the top k numbers.
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> q = new PriorityQueue<Integer>(k);
for(int i: nums){
q.offer(i);
if(q.size()>k){
q.poll();
}
}
return q.peek();
}
26 of 246
23 288
8 Wildcard Matching
Implement wildcard pattern matching with support for ’?’ and ’*’.
return j == p.length();
}
33 | 531
27 of 246
24 288
9 Regular Expression Matching in Java
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).
The function prototype should be: bool isMatch(const char *s, const char *p)
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
9.1 Analysis
First of all, this is one of the most difficulty problems. It is hard to think through all
different 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 remaining 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 remaining part.
if(p.length() == 0)
return s.length() == 0;
}else{
35 | 531
29 of 246
25 288
9 Regular Expression Matching in Java
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) {
30 of 246
26 288
9 Regular Expression Matching in Java
return false;
} else {
return isMatch(s.substring(1), p.substring(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;
}
}
31 of 246
27 288
10 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;
}
}
39 | 531
33 of 246
28 288
10 Merge Intervals
result.add(prev);
return result;
}
}
34 of 246
29 288
11 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].
41 | 531
35 of 246
30 288
11 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;
}
}
36 of 246
31 288
12 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;
}
Can we do better?
43 | 531
37 of 246
32 288
12 Two Sum
return result;
}
}
Time complexity depends on the put and get operations of HashMap which is nor-
mally O(1).
Time complexity of this solution is O(n).
38 of 246
33 288
13 Two Sum II Input array is sorted
int i = 0;
int j = numbers.length - 1;
while (i < j) {
int x = numbers[i] + numbers[j];
if (x < target) {
++i;
} else if (x > target) {
j--;
} else {
return new int[] { i + 1, j + 1 };
}
}
return null;
}
45 | 531
39 of 246
34 288
14 Two Sum III Data structure design
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>();
47 | 531
41 of 246
35 288
14 Two Sum III Data structure design
}
}
42 of 246
36 288
15 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);
each.add(num[i]);
each.add(num[j]);
each.add(num[k]);
result.add(each);
each.clear();
}
49 | 531
43 of 246
37 288
15 3Sum
}
}
}
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);
44 of 246
38 288
15 3Sum
start++;
end--;
//avoid duplicate solutions
while (start < end && num[end] == num[end + 1])
end--;
}
}
return result;
}
45 of 246
39 288
16 4Sum
16.1 Thoughts
while (k < l) {
int sum = num[i] + num[j] + num[k] + num[l];
53 | 531
47 of 246
40 288
16 4Sum
temp.add(num[j]);
temp.add(num[k]);
temp.add(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());
}
48 of 246
41 288
17 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).
17.1 Analysis
This problem is similar to 2 Sum. This kind of problem can be solved by using a
similar approach, i.e., two pointers from both left and right.
Arrays.sort(nums);
55 | 531
49 of 246
42 288
17 3Sum Closest
return result;
}
50 of 246
43 288
18 String to Integer (atoi)
18.1 Analysis
// calculate value
while (str.length() > i && str.charAt(i) >= ’0’ && str.charAt(i) <= ’9’) {
result = result * 10 + (str.charAt(i) - ’0’);
57 | 531
51 of 246
44 288
18 String to Integer (atoi)
i++;
}
if (flag == ’-’)
result = -result;
52 of 246
45 288
19 Merge Sorted Array
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.
19.1 Analysis
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.
59 | 531
53 of 246
46 288
19 Merge Sorted Array
while (k >= 0) {
if (j < 0 || (i >= 0 && A[i] > B[j]))
A[k--] = A[i--];
else
A[k--] = B[j--];
}
}
54 of 246
47 288
20 Valid Parentheses
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.
20.1 Analysis
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;
}
}
}
return stack.empty();
}
61 | 531
55 of 246
48 288
21 Longest Valid Parentheses
Given a string containing just the characters ’(’ and ’)’, find the length of the longest
valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2. An-
other example is ")()())", where the longest valid parentheses substring is "()()", which
has length = 4.
21.1 Analysis
This problem is similar with Valid Parentheses, which can be solved by using a stack.
return result;
63 | 531
57 of 246
49 288
21 Longest Valid Parentheses
58 of 246
50 288
22 Implement strStr()
Problem:
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1
if needle is not part of haystack.
if(needle.length() == 0)
return 0;
int m = i;
for(int j=0; j<needle.length(); j++){
if(needle.charAt(j)==haystack.charAt(m)){
if(j==needle.length()-1)
return i;
m++;
}else{
break;
}
}
}
return -1;
}
65 | 531
59 of 246
51 288
22 Implement strStr()
return 0;
int h = haystack.length();
int n = needle.length();
if (n > h)
return -1;
if (n == 0)
return 0;
while (i <= h - n) {
int success = 1;
for (int j = 0; j < n; j++) {
if (needle.charAt(0) != haystack.charAt(i)) {
success = 0;
i++;
break;
} else if (needle.charAt(j) != haystack.charAt(i + j)) {
success = 0;
i = i + j - next[j - 1];
break;
}
}
if (success == 1)
return i;
}
return -1;
}
if (needle.charAt(index) == needle.charAt(i)) {
next[i] = next[i - 1] + 1;
} else {
next[i] = 0;
}
}
60 of 246
52 288
22 Implement strStr()
return next;
}
61 of 246
53 288
23 Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length
of a subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal
length of 2 under the problem constraint.
23.1 Analysis
We can use 2 points to mark the left and right boundaries of the sliding window. When
the sum is greater than the target, shift the left pointer; when the sum is less than the
target, shift the right pointer.
int start=0;
int sum=0;
int i=0;
boolean exists = false;
while(i<=nums.length){
if(sum>=s){
exists=true; //mark if there exists such a subarray
if(start==i-1){
return 1;
}
}else{
if(i==nums.length)
break;
69 | 531
63 of 246
54 288
23 Minimum Size Subarray Sum
sum = sum+nums[i];
i++;
}
}
if(exists)
return result;
else
return 0;
}
int i = 0;
int sum = nums[0];
if(j<nums.length){
sum = sum + nums[j];
}else{
return result;
}
}
}else{
//if sum is large enough, move left cursor
if(sum >= s){
result = Math.min(j-i+1, result);
sum = sum - nums[i];
i++;
64 of 246
55 288
23 Minimum Size Subarray Sum
if(j<nums.length){
sum = sum + nums[j];
}else{
if(i==0){
return 0;
}else{
return result;
}
}
}
}
}
return result;
}
65 of 246
56 288
24 Search Insert Position
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
24.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) {
if(A==null) return 0;
return A.length;
}
}
24.2 Solution 2
This also looks like a binary search problem. We should try to make the complexity to
be O(log(n)).
public class Solution {
public int searchInsert(int[] A, int target) {
73 | 531
67 of 246
57 288
24 Search Insert Position
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);
}
}
68 of 246
58 288
25 Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements
sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence
should be [1, 2, 3, 4]. Its length is 4.
Your algorithm should run in O(n) complexity.
25.1 Analysis
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--;
}
75 | 531
69 of 246
59 288
25 Longest Consecutive Sequence
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.
70 of 246
60 288
26 Valid Palindrome
26.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.
int i=0;
int j=len-1;
while(i<j){
char left, right;
77 | 531
71 of 246
61 288
26 Valid Palindrome
right = charArray[j];
}
if(i >= j)
break;
left = charArray[i];
right = charArray[j];
if(!isSame(left, right)){
return false;
}
i++;
j--;
}
return true;
}
72 of 246
62 288
26 Valid Palindrome
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);
73 of 246
63 288
26 Valid Palindrome
return true;
}
System.out.println(isValidPalindrome(str));
}
}
74 of 246
64 288
27 ZigZag Conversion
And then read line by line: "PAHNAPLSIIGYIR" Write the a method convert("PAYPALISHIRING",
3) which returns "PAHNAPLSIIGYIR".
81 | 531
75 of 246
65 288
27 ZigZag Conversion
}
}
return sb.toString();
}
76 of 246
66 288
28 Add Binary
Given two binary strings, return their sum (also a binary string).
For example, a = "11", b = "1", the return is "100".
int pa = a.length()-1;
int pb = b.length()-1;
int flag = 0;
StringBuilder sb = new StringBuilder();
while(pa >= 0 || pb >=0){
int va = 0;
int vb = 0;
if(flag == 1){
83 | 531
77 of 246
67 288
28 Add Binary
sb.append("1");
}
78 of 246
68 288
29 Length of Last Word
Very simple question. We just need a flag to mark the start of letters from the end. If
a letter starts and the next character is not a letter, return the length.
public int lengthOfLastWord(String s) {
if(s==null || s.length() == 0)
return 0;
int result = 0;
int len = s.length();
return result;
}
85 | 531
79 of 246
69 288
30 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 {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if (triangle.size() == 1) {
return Math.min(minTotal, triangle.get(0).get(0));
}
int a, b;
87 | 531
81 of 246
70 288
30 Triangle
}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];
}
82 of 246
71 288
31 Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function
should return true if any value appears at least twice in the array, and it should return
false if every element is distinct.
return false;
}
89 | 531
83 of 246
72 288
32 Contains Duplicate II
Given an array of integers and an integer k, return true if and only if there are two
distinct indices i and j in the array such that nums[i] = nums[j] and the difference
between i and j is at most k.
91 | 531
85 of 246
73 288
32 Contains Duplicate II
map.put(nums[i], i);
}
return false;
}
86 of 246
74 288
33 Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in
the array such that the difference between nums[i] and nums[j] is at most t and the
difference between i and j is at most k.
set.add(c);
if (i >= k)
set.remove(nums[i - k]);
}
return false;
}
93 | 531
87 of 246
75 288
33 Contains Duplicate III
if (!subSet.isEmpty())
return true;
set.add((long) nums[j]);
if (j >= k) {
set.remove((long) nums[j - k]);
}
}
return false;
}
88 of 246
76 288
34 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].
34.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.
34.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 array’s size can
95 | 531
89 of 246
77 288
34 Remove Duplicates from Sorted Array
not be changed once created, there is no way we can return the original array with
correct results.
34.3 Solution 2
int j = 0;
int i = 1;
return B;
}
34.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++;
90 of 246
78 288
34 Remove Duplicates from Sorted Array
}
}
return (A.length - count);
}
91 of 246
79 288
35 Remove Duplicates from Sorted Array
II
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 that’s 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;
}
}
99 | 531
93 of 246
80 288
35 Remove Duplicates from Sorted Array II
We can not change the given array’s 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;
}
}
94 of 246
81 288
35 Remove Duplicates from Sorted Array II
return prev + 1;
}
}
95 of 246
82 288
36 Longest Substring Without Repeating
Characters
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.
public int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
boolean[] flag = new boolean[256];
int result = 0;
int start = 0;
char[] arr = s.toCharArray();
103 | 531
97 of 246
83 288
36 Longest Substring Without Repeating Characters
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 posi-
tion. When a repeated character occurs, check from the previously repeated character.
However, the time complexity is higher - O(n3̂).
public static int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
char[] arr = s.toCharArray();
int pre = 0;
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.
98 of 246
84 288
37 Longest Substring Which Contains 2
Unique Characters
In this solution, a hashmap is used to track the unique elements in the map. When a
third character is added to the map, the left pointer needs to move right.
You can use "abac" to walk through this solution.
public int lengthOfLongestSubstringTwoDistinct(String s) {
int max=0;
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
int start=0;
if(map.size()>2){
max = Math.max(max, i-start);
while(map.size()>2){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}
105 | 531
99 of 246
85 288
37 Longest Substring Which Contains 2 Unique Characters
}
}
return max;
}
Now if this question is extended to be "the longest substring that contains k unique
characters", what should we do?
if(map.size()>k){
max = Math.max(max, i-start);
while(map.size()>k){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}
}
}
return max;
}
100 of246
86 of 288
37 Longest Substring Which Contains 2 Unique Characters
Time is O(n).
101 of246
87 of 288
38 Substring with Concatenation of All
Words
You are given a string, s, and a list of words, words, that are all of the same length.
Find all starting indices of substring(s) in s that is a concatenation of each word in
words exactly once and without any intervening characters.
For example, given: s="barfoothefoobarman" & words=["foo", "bar"], return [0,9].
38.1 Analysis
This problem is similar (almost the same) to Longest Substring Which Contains 2
Unique Characters.
Since each word in the dictionary has the same length, each of them can be treated
as a single character.
//frequency of words
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(String w: words){
if(map.containsKey(w)){
map.put(w, map.get(w)+1);
}else{
map.put(w, 1);
}
}
109 | 531
103 of246
88 of 288
38 Substring with Concatenation of All Words
count++;
while(currentMap.get(sub)>map.get(sub)){
String left = s.substring(start, start+len);
currentMap.put(left, currentMap.get(left)-1);
count--;
start = start + len;
}
if(count==words.length){
result.add(start); //add to result
return result;
}
104 of246
89 of 288
39 Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all
the characters in T in complexity O(n).
For example, S = "ADOBECODEBANC", T = "ABC", Minimum window is "BANC".
if(target.containsKey(c)){
if(map.containsKey(c)){
if(map.get(c)<target.get(c)){
count++;
}
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
count++;
111 | 531
105 of246
90 of 288
39 Minimum Window Substring
}
}
if(count == t.length()){
char sc = s.charAt(left);
while (!map.containsKey(sc) || map.get(sc) > target.get(sc)) {
if (map.containsKey(sc) && map.get(sc) > target.get(sc))
map.put(sc, map.get(sc) - 1);
left++;
sc = s.charAt(left);
}
return result;
}
106 of246
91 of 288
40 Reverse Words in a String
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,
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 "";
}
113 | 531
107 of246
92 of 288
41 Find Minimum in Rotated Sorted
Array
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.
41.1 Analysis
This problem is a binary search and the key is breaking the array to two parts, so that
we only need to work on half of the array each time.
If we pick the middle element, we can compare the middle element with the leftmost
(or rightmost) element. If the middle element is less than leftmost, the left half should
be selected; if the middle element is greater than the leftmost (or rightmost), the right
half should be selected. Using recursion or iteration, this problem can be solved 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
pick the leftmost element as the minimum.
// not rotated
if (num[left] < num[right]) {
return num[left];
115 | 531
109 of246
93 of 288
41 Find Minimum in Rotated Sorted Array
// go right side
} else if (num[middle] > num[left]) {
return findMin(num, middle, right);
// go left side
} else {
return findMin(num, left, middle);
}
}
int left=0;
int right=nums.length-1;
//not rotated
if(nums[left]<nums[right])
return nums[left];
return nums[left];
}
110 of246
94 of 288
42 Find Minimum in Rotated Sorted
Array II
42.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?
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);
}
117 | 531
111 of246
95 of 288
42 Find Minimum in Rotated Sorted Array II
}else{
return findMin(num, left, middle);
}
}
112 of246
96 of 288
43 Search in Rotated Sorted Array
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).
You are given a target value to search. If found in the array return its index, other-
wise return -1. You may assume no duplicate exists in the array.
public int binarySearch(int[] nums, int left, int right, int target){
if(left>right)
return -1;
if(target == nums[mid])
return mid;
119 | 531
113 of246
97 of 288
43 Search in Rotated Sorted Array
int left = 0;
int right= nums.length-1;
while(left<=right){
int mid = left + (right-left)/2;
if(target==nums[mid])
return mid;
if(nums[left]<=nums[mid]){
if(nums[left]<=target&& target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else{
if(nums[mid]<target&& target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}
}
return -1;
}
114 of246
98 of 288
44 Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array": what if duplicates are allowed? Write
a function to determine if a given target is in the array.
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]==target)
return true;
if(nums[left]<nums[mid]){
if(nums[left]<=target&& target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else if(nums[left]>nums[mid]){
if(nums[mid]<target&&target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}else{
left++;
}
}
return false;
}
121 | 531
115 of246
99 of 288
45 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.
45.1 Analysis
UPDATED ON 6/17/2015
To make constant time of getMin(), we need to keep track of the minimum element
for each element in the stack.
Define a node class that holds element value, min value, and pointer to elements below
it.
class Node {
int value;
int min;
Node next;
Node(int x) {
value = x;
next = null;
min = x;
}
}
class MinStack {
Node head;
123 | 531
117 of 246
100 288
45 Min Stack
head = temp;
}
}
return head.value;
}
return head.min;
}
}
118 of 246
101 288
46 Majority Element
Given an array of size n, find the majority element. The majority element is the element
that appears more than ⌊ n/2 ⌋ times. (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!
125 | 531
119 of 246
102 288
46 Majority Element
Arrays.sort(num);
return num[num.length / 2];
}
return result;
}
120 of 246
103 288
47 Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
The algorithm should run in linear time and in O(1) space.
return result;
}
for(int i: nums){
127 | 531
121 of 246
104 288
47 Majority Element II
c1=c2=0;
for(int i: nums){
if(i==n1.intValue()){
c1++;
}else if(i==n2.intValue()){
c2++;
}
}
if(c1>nums.length/3)
result.add(n1);
if(c2>nums.length/3)
result.add(n2);
return result;
}
122 of 246
105 288
48 Remove Element
Given an array and a value, remove all instances of that value in place and return the
new length. (Note: The order of elements can be changed. It doesn’t matter what you
leave beyond the new length.)
j++;
}
return i;
}
129 | 531
123 of 246
106 288
49 Largest Rectangle in Histogram
Given n non-negative integers representing the histogram’s bar height where the width
of each bar is 1, find the area of largest rectangle in the histogram.
49.1 Analysis
The key to solve this problem is to maintain a stack to store bars’ indexes. The stack
only keeps the increasing bars.
131 | 531
125 of 246
107 288
49 Largest Rectangle in Histogram
int max = 0;
int i = 0;
while (!stack.isEmpty()) {
int p = stack.pop();
int h = height[p];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(h * w, max);
}
return max;
}
126 of 246
108 288
50 Longest Common Prefix
50.1 Problem
Write a function to find the longest common prefix string amongst an array of strings.
50.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);
}
}
}
return strs[0].substring(0,minLen);
}
133 | 531
127 of 246
109 288
51 Largest Number
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.)
51.1 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.
}
});
return sb.toString();
}
135 | 531
129 of 246
110 288
52 Simplify Path
//stack.push(path.substring(0,1));
int start = 0;
for(int i=1; i<path.length(); i++){
if(path.charAt(i) == ’/’){
stack.push(path.substring(start, i));
start = i;
}else if(i==path.length()-1){
stack.push(path.substring(start));
}
}
if(top.equals("/.") || top.equals("/")){
//nothing
}else if(top.equals("/..")){
back++;
}else{
if(back > 0){
137 | 531
131 of 246
111 288
52 Simplify Path
back--;
}else{
result.push(top);
}
}
}
return sb.toString();
}
132 of 246
112 288
53 Compare Version Numbers
53.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
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;
139 | 531
133 of 246
113 288
53 Compare Version Numbers
134 of 246
114 288
54 Gas Station
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 station’s index if you can travel around the circuit once,
otherwise return -1.
54.1 Analysis
To solve this problem, we need to understand and use the following 2 facts: 1) if the
sum of gas >= the sum of cost, then the circle can be completed. 2) if A can not reach
C in a the sequence of A–>B–>C, then B can not make it either.
Proof of fact 2:
If gas[A] < cost[A], then A can not even reach B.
So to reach C from A, gas[A] must >= cost[A].
Given that A can not reach 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 reach C.
141 | 531
135 of 246
115 288
54 Gas Station
136 of 246
116 288
55 Pascal’s Triangle
Given numRows, generate the first numRows of Pascal’s triangle. For example, given
numRows = 5, the result should be:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
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;
}
143 | 531
137 of 246
117 288
56 Pascal’s Triangle II
Given an index k, return the kth row of the Pascal’s triangle. For example, when k =
3, the row is [1,3,3,1].
56.1 Analysis
This problem is related to Pascal’s Triangle which gets all rows of Pascal’s triangle. In
this problem, only one row is required to return.
if (rowIndex < 0)
return result;
result.add(1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = result.size() - 2; j >= 0; j--) {
result.set(j + 1, result.get(j) + result.get(j + 1));
}
result.add(1);
}
return result;
}
145 | 531
139 of 246
118 288
57 Container With Most Water
57.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.
57.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.
int max = 0;
int left = 0;
int right = height.length - 1;
147 | 531
141 of 246
119 288
57 Container With Most Water
return max;
}
142 of 246
120 288
58 Candy
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?
58.1 Analysis
149 | 531
143 of 246
121 288
58 Candy
return result;
}
144 of 246
122 288
59 Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each
bar is 1, compute how much water it is able to trap after raining.
For example, given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
59.1 Analysis
This problem is similar to Candy. It can be solve by scanning from both sides and
then get the total.
if(height==null || height.length<=2)
return result;
151 | 531
145 of 246
123 288
59 Trapping Rain Water
right[i]=height[i];
max = height[i];
}
}
//calculate totoal
for(int i=0; i<height.length; i++){
result+= Math.min(left[i],right[i])-height[i];
}
return result;
}
146 of 246
124 288
60 Count and Say
60.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;
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++;
}
153 | 531
147 of 246
125 288
60 Count and Say
return result;
}
148 of 246
126 288
61 Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target
value. Your algorithm’s runtime complexity must be in the order of O(log n). If the
target is not found in the array, return [-1, -1]. For example, given [5, 7, 7, 8, 8, 10] and
target value 8, return [3, 4].
61.1 Analysis
Based on the requirement of O(log n), this is a binary search problem apparently.
return arr;
}
public void binarySearch(int[] nums, int left, int right, int target, int[]
arr){
if(right<left)
return;
155 | 531
149 of 246
127 288
61 Search for a Range
if(nums[mid]<target){
binarySearch(nums, mid+1, right, target, arr);
}else if(nums[mid]>target){
binarySearch(nums, left, mid-1, target, arr);
}else{
arr[0]=mid;
arr[1]=mid;
150 of 246
128 288
62 Basic Calculator
62.1 Analysis
This problem can be solved by using a stack. We keep pushing element to the stack,
when ’)" is met, calculate the expression up to the first "(".
if (i == arr.length - 1) {
stack.push(sb.toString());
}
} else {
if (sb.length() > 0) {
stack.push(sb.toString());
sb = new StringBuilder();
}
if (arr[i] != ’)’) {
stack.push(new String(new char[] { arr[i] }));
157 | 531
151 of 246
129 288
62 Basic Calculator
} else {
// when meet ’)’, pop and calculate
ArrayList<String> t = new ArrayList<String>();
while (!stack.isEmpty()) {
String top = stack.pop();
if (top.equals("(")) {
break;
} else {
t.add(0, top);
}
}
int temp = 0;
if (t.size() == 1) {
temp = Integer.valueOf(t.get(0));
} else {
for (int j = t.size() - 1; j > 0; j = j - 2) {
if (t.get(j - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(j));
} else {
temp += Integer.valueOf(t.get(j));
}
}
temp += Integer.valueOf(t.get(0));
}
stack.push(String.valueOf(temp));
}
}
}
int temp = 0;
for (int i = t.size() - 1; i > 0; i = i - 2) {
if (t.get(i - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(i));
} else {
temp += Integer.valueOf(t.get(i));
}
}
temp += Integer.valueOf(t.get(0));
return temp;
}
152 of 246
130 288
63 Group Anagrams
Given an array of strings, return all groups of strings that are anagrams.
63.1 Analysis
An anagram is a type of word play, the result of rearranging the letters of a word or
phrase to produce a new word or phrase, using all the original letters exactly once; for
example Torchwood can be rearranged into Doctor Who.
If two strings are anagram to each other, their sorted sequence is the same.
Updated on 5/1/2016.
if(map.containsKey(ns)){
map.get(ns).add(str);
}else{
ArrayList<String> al = new ArrayList<String>();
al.add(str);
map.put(ns, al);
}
}
result.addAll(map.values());
return result;
}
159 | 531
153 of 246
131 288
63 Group Anagrams
If average length of verbs is m and words array length is n, then the time is O(n*m*log(m)).
154 of 246
132 288
64 Shortest Palindrome
64.1 Analysis
We can solve this problem by using one of the methods which is used to solve the
longest palindrome substring problem.
Specifically, we can start from the center and scan two sides. If read the left bound-
ary, then the shortest palindrome is identified.
return result;
}
161 | 531
155 of 246
133 288
64 Shortest Palindrome
return sb.append(s).toString();
}
156 of 246
134 288
65 Rectangle Area
Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle
is defined by its bottom left corner and top right corner coordinates.
65.1 Analysis
This problem can be converted as a overlap internal problem. On the x-axis, there are
(A,C) and (E,G); on the y-axis, there are (F,H) and (B,D). If they do not have overlap,
the total area is the sum of 2 rectangle areas. If they have overlap, the total area should
minus the overlap area.
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int
H) {
if(C<E||G<A )
return (G-E)*(H-F) + (C-A)*(D-B);
if(D<F || H<B)
return (G-E)*(H-F) + (C-A)*(D-B);
163 | 531
157 of 246
135 288
66 Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges for
consecutive numbers.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
66.1 Analysis
if(nums.length==1){
result.add(nums[0]+"");
}
if(i==nums.length-1){
result.add(nums[i]+"");
}
first = nums[i];
}
165 | 531
159 of 246
136 288
66 Summary Ranges
pre = nums[i];
}
return result;
}
160 of 246
137 288
67 Increasing Triplet Subsequence
67.1 Analysis
This problem can be converted to be finding if there is a sequence such that the_smallest_so_far
<the_second_smallest_so_far <current. We use x, y and z to denote the 3 number re-
spectively.
if (x >= z) {
x = z;// update x to be a smaller value
} else if (y >= z) {
y = z; // update y to be a smaller value
} else {
return true;
}
}
return false;
}
167 | 531
161 of 246
138 288
68 Get Target Number Using Number List
and Arithmetic Operations
Given a list of numbers and a target number, write a program to determine whether
the target number can be calculated by applying "+-*/" operations to the number list?
You can assume () is automatically added when necessary.
For example, given 1,2,3,4 and 21, return true. Because (1+2)*(3+4)=21
68.1 Analysis
This is a partition problem which can be solved by using depth first search.
int i = 0;
int j = list.size() - 1;
return false;
}
169 | 531
163 of 246
139 288
68 Get Target Number Using Number List and Arithmetic Operations
return result;
}
return result;
}
164 of 246
140 288
69 Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
this is a simple problem which can be solved by using two pointers scanning from
beginning and end of the array.
public String reverseVowels(String s) {
ArrayList<Character> vowList = new ArrayList<Character>();
vowList.add(’a’);
vowList.add(’e’);
vowList.add(’i’);
vowList.add(’o’);
vowList.add(’u’);
vowList.add(’A’);
vowList.add(’E’);
vowList.add(’I’);
vowList.add(’O’);
vowList.add(’U’);
int i=0;
int j=s.length()-1;
while(i<j){
if(!vowList.contains(arr[i])){
i++;
continue;
}
if(!vowList.contains(arr[j])){
j--;
continue;
}
char t = arr[i];
arr[i]=arr[j];
arr[j]=t;
i++;
j--;
171 | 531
165 of 246
141 288
69 Reverse Vowels of a String
166 of 246
142 288
70 Flip Game
You are playing the following Flip Game with your friend: Given a string that con-
tains only these two characters: + and -, you and your friend take turns to flip two
consecutive "++" into "–". The game ends when a person can no longer make a move
and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid move.
if(s==null)
return result;
return result;
}
173 | 531
167 of 246
143 288
71 Flip Game II
You are playing the following Flip Game with your friend: Given a string that con-
tains only these two characters: + and -, you and your friend take turns to flip two
consecutive "++" into "–". The game ends when a person can no longer make a move
and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++", return true. The starting player can guarantee a win
by flipping the middle "++" to become "+–+".
return canWinHelper(s.toCharArray());
}
arr[i]=’+’;
arr[i+1]=’+’;
//if there is a flip which makes the other player lose, the first
play wins
if(!win){
return true;
}
}
}
return false;
}
175 | 531
169 of 246
144 288
71 Flip Game II
Roughly, the time is n*n*...n, which is O(nn̂). The reason is each recursion takes O(n)
and there are totally n recursions.
170 of 246
145 288
72 Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it while maintaining
the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should
be [1, 3, 12, 0, 0].
177 | 531
171 of 246
146 288
73 Valid Anagram
return true;
}
If the inputs contain unicode characters, an array with length of 26 is not enough.
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())
179 | 531
173 of 246
147 288
73 Valid Anagram
return false;
if(map.size()>0)
return false;
return true;
}
174 of 246
148 288
74 Group Shifted Strings
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc"
->"bcd". We can keep "shifting" which forms the sequence: "abc" ->"bcd" ->... ->"xyz".
Given a list of strings which contains only lowercase alphabets, group all strings
that belong to the same shifting sequence, return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
for(String s: strings){
char[] arr = s.toCharArray();
if(arr.length>0){
int diff = arr[0]-’a’;
for(int i=0; i<arr.length; i++){
if(arr[i]-diff<’a’){
arr[i] = (char) (arr[i]-diff+26);
}else{
arr[i] = (char) (arr[i]-diff);
}
}
}
181 | 531
175 of 246
149 288
74 Group Shifted Strings
}
}
result.addAll(map.values());
return result;
}
176 of 246
150 288
75 Top K Frequent Elements
We can solve this problem by using a counter, and then sort the counter by value.
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> result = new ArrayList<Integer>();
for(int i: nums){
if(counter.containsKey(i)){
counter.put(i, counter.get(i)+1);
}else{
counter.put(i, 1);
}
}
int i=0;
for(Map.Entry<Integer, Integer> entry: sortedMap.entrySet()){
result.add(entry.getKey());
i++;
if(i==k)
break;
}
return result;
}
}
183 | 531
177 of 246
151 288
75 Top K Frequent Elements
if(diff==0){
return 1;
}else{
return diff;
}
}
}
178 of 246
152 288
76 Find Peak Element
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
a peak element and your function should return the index number 2.
76.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;
}
}
185 | 531
179 of 246
153 288
77 Word Pattern
Given a pattern and a string str, find if str follows the same pattern. Here follow means
a full match, such that there is a bijection between a letter in pattern and a non-empty
word in str.
if(pattern.length()!=arr.length)
return false;
if(map.containsKey(c)){
if(!map.get(c).equals(s))
return false;
}else{
if(map.containsValue(s))
return false;
map.put(c, s);
}
}
return true;
}
187 | 531
181 of 246
154 288
78 Set Matrix Zeroes
78.1 Analysis
This problem should be solved in place, i.e., no other array should be used. We can
use the first column and the first row to track if a row/column should be set to 0.
Since we used the first row and first column to mark the zero row/column, the
original values are changed.
Step 1: First row contains zero = true; First column contains zero = false;
189 | 531
183 of 246
155 288
78 Set Matrix Zeroes
184 of 246
156 288
78 Set Matrix Zeroes
if(firstRowZero){
for(int i=0; i<matrix[0].length; i++)
matrix[0][i] = 0;
}
}
}
185 of 246
157 288
79 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;
193 | 531
187 of 246
158 288
79 Spiral Matrix
break;
}
//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 solution’s 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);
}
188 of 246
159 288
79 Spiral Matrix
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;
}
}
189 of 246
160 288
80 Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral
order. For example, given n = 4,
[
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
]
int x=0;
int y=0;
int step = 0;
for(int i=0;i<total;){
while(y+step<n){
i++;
result[x][y]=i;
y++;
}
y--;
x++;
while(x+step<n){
i++;
result[x][y]=i;
x++;
}
x--;
y--;
while(y>=0+step){
i++;
197 | 531
191 of 246
161 288
80 Spiral Matrix II
result[x][y]=i;
y--;
}
y++;
x--;
step++;
while(x>=0+step){
i++;
result[x][y]=i;
x--;
}
x++;
y++;
}
return result;
}
192 of 246
162 288
81 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]
]
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;
199 | 531
193 of 246
163 288
81 Search a 2D Matrix
if(matrix[midX][midY]<target){
start=mid+1;
}else{
end=mid-1;
}
}
return false;
}
}
194 of 246
164 288
82 Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix
has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in each
column are sorted in ascending from top to bottom.
For example, consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
In a naive approach, we can use the matrix boundary to reduce the search space. Here
is a simple recursive implementation.
public boolean searchMatrix(int[][] matrix, int target) {
int i1=0;
int i2=matrix.length-1;
int j1=0;
int j2=matrix[0].length-1;
public boolean helper(int[][] matrix, int i1, int i2, int j1, int j2, int
target){
if(i1>i2||j1>j2)
return false;
for(int j=j1;j<=j2;j++){
if(target < matrix[i1][j]){
return helper(matrix, i1, i2, j1, j-1, target);
}else if(target == matrix[i1][j]){
return true;
201 | 531
195 of 246
165 288
82 Search a 2D Matrix II
}
}
for(int i=i1;i<=i2;i++){
if(target < matrix[i][j1]){
return helper(matrix, i1, i-1, j1, j2, target);
}else if(target == matrix[i][j1]){
return true;
}
}
for(int j=j1;j<=j2;j++){
if(target > matrix[i2][j]){
return helper(matrix, i1, i2, j+1, j2, target);
}else if(target == matrix[i2][j]){
return true;
}
}
for(int i=i1;i<=i2;i++){
if(target > matrix[i][j2]){
return helper(matrix, i1, i+1, j1, j2, target);
}else if(target == matrix[i][j2]){
return true;
}
}
return false;
}
int i=m;
int j=0;
196 of 246
166 288
82 Search a 2D Matrix II
}
}
return false;
}
197 of 246
167 288
83 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;
205 | 531
199 of 246
168 288
83 Rotate Image
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;
}
}
}
200 of 246
169 288
84 Valid Sudoku
Determine if a Sudoku is valid. The Sudoku board could be partially filled, where
empty cells are filled with the character ’.’.
207 | 531
201 of 246
170 288
84 Valid Sudoku
if (board[i][j] != ’.’) {
if (m[(int) (board[i][j] - ’1’)]) {
return false;
}
m[(int) (board[i][j] - ’1’)] = true;
}
}
}
return true;
}
202 of 246
171 288
85 Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to
bottom right which minimizes the sum of all numbers along its path.
A native solution would be depth-first search. It’s time is too expensive and fails the
online judgement.
public int minPathSum(int[][] grid) {
return dfs(0,0,grid);
}
if(i<grid.length-1){
return grid[i][j] + dfs(i+1, j, grid);
}
if(j<grid[0].length-1){
return grid[i][j] + dfs(i, j+1, grid);
}
return 0;
}
209 | 531
203 of 246
172 288
85 Minimum Path Sum
int m = grid.length;
int n = grid[0].length;
return dp[m-1][n-1];
}
204 of 246
173 288
86 Unique Paths
A robot is located at the top-left corner of a m x n grid. It can only move either down
or right at any point in time. The robot is trying to reach the bottom-right corner of
the grid.
How many possible unique paths are there?
if(i<m-1){
return dfs(i+1,j,m,n);
}
if(j<n-1){
return dfs(i,j+1,m,n);
}
return 0;
}
211 | 531
205 of 246
174 288
86 Unique Paths
//left column
for(int i=0; i<m; i++){
dp[i][0] = 1;
}
//top row
for(int j=0; j<n; j++){
dp[0][j] = 1;
}
return dp[m-1][n-1];
}
206 of 246
175 288
87 Unique Paths II
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1)
return 0;
//left column
for(int i=1; i<m; i++){
if(obstacleGrid[i][0]==1){
dp[i][0] = 0;
}else{
dp[i][0] = dp[i-1][0];
}
}
//top row
213 | 531
207 of 246
176 288
87 Unique Paths II
}
}
return dp[m-1][n-1];
}
208 of 246
177 288
88 Number of Islands
Given a 2-d grid map of ’1’s (land) and ’0’s (water), count the number of islands. An
island is surrounded by water and is formed by connecting adjacent lands horizontally
or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
The basic idea of the following solution is merging adjacent lands, and the merging
should be done recursively.
public int numIslands(char[][] grid) {
if(grid==null||grid.length==0||grid[0].length==0)
return 0;
int m=grid.length;
int n=grid[0].length;
int count=0;
for(int i=0;i<m; i++){
for(int j=0;j<n; j++){
if(grid[i][j]==’1’){
count++;
merge(grid, i, j);
}
}
}
215 | 531
209 of 246
178 288
88 Number of Islands
return count;
}
if(grid[i][j]==’1’){
grid[i][j]=’0’;
merge(grid, i-1,j);
merge(grid, i+1,j);
merge(grid, i,j-1);
merge(grid, i,j+1);
}
}
210 of 246
179 288
89 Number of Islands II
A 2d grid map of m rows and n columns is initially filled with water. We may perform
an addLand operation which turns the water at position (row, col) into a land. Given a
list of positions to operate, count the number of islands after each addLand operation.
An island is surrounded by water and is formed by connecting adjacent lands hori-
zontally or vertically. You may assume all four edges of the grid are all surrounded by
water.
int[] p = positions[k];
int index = p[0]*n+p[1];
rootArray[index]=index;//set root to be itself for each node
for(int r=0;r<4;r++){
int i=p[0]+directions[r][0];
int j=p[1]+directions[r][1];
if(i>=0&&j>=0&&i<m&&j<n&&rootArray[i*n+j]!=-1){
//get neighbor’s root
int thisRoot = getRoot(rootArray, i*n+j);
if(thisRoot!=index){
rootArray[thisRoot]=index;//set previous root’s root
count--;
}
}
}
217 | 531
211 of 246
180 288
89 Number of Islands II
result.add(count);
}
return result;
}
212 of 246
181 288
90 Surrounded Regions
Given a 2D board containing ’X’ and ’O’, capture all regions surrounded by ’X’. A
region is captured by flipping all ’O’s into ’X’s in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
90.1 Analysis
This problem is similar to Number of Islands. In this problem, only the cells on the
boarders can not be surrounded. So we can first merge those O’s on the boarders like
in Number of Islands and replace O’s with ’#’, and then scan the board and replace all
O’s left (if any).
int m = board.length;
int n = board[0].length;
if(board[i][n-1] == ’O’){
219 | 531
213 of 246
182 288
90 Surrounded Regions
merge(board, i,n-1);
}
}
if(board[m-1][j] == ’O’){
merge(board, m-1,j);
}
}
if(board[i][j] != ’O’)
return;
board[i][j] = ’#’;
214 of 246
183 288
90 Surrounded Regions
int m = board.length;
int n = board[0].length;
if (board[i][n - 1] == ’O’) {
bfs(board, i, n - 1);
}
}
215 of 246
184 288
90 Surrounded Regions
while (!queue.isEmpty()) {
int cur = queue.poll();
int x = cur / n;
int y = cur % n;
fillCell(board, x - 1, y);
fillCell(board, x + 1, y);
fillCell(board, x, y - 1);
fillCell(board, x, y + 1);
}
}
// add current cell is queue & then process its neighbors in bfs
queue.offer(i * n + j);
board[i][j] = ’#’;
}
}
216 of 246
185 288
91 Maximal Rectangle
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing
all ones and return its area.
91.1 Analysis
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == ’0’) {
height[i][j] = 0;
} else {
height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
}
}
}
return maxArea;
}
int i = 0;
int max = 0;
223 | 531
217 of 246
186 288
91 Maximal Rectangle
return max;
}
218 of 246
187 288
92 Maximal Square
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all
1’s and return its area.
For example, given the following matrix:
1101
1101
1111
Return 4.
92.1 Analysis
This problem can be solved by dynamic programming. The changing condition is:
t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1. It means the square formed before this
point.
int m = matrix.length;
int n = matrix[0].length;
//top row
for (int i = 0; i < m; i++) {
t[i][0] = Character.getNumericValue(matrix[i][0]);
}
//left column
for (int j = 0; j < n; j++) {
t[0][j] = Character.getNumericValue(matrix[0][j]);
}
//cells inside
for (int i = 1; i < m; i++) {
225 | 531
219 of 246
188 288
92 Maximal Square
int max = 0;
//get maximal length
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (t[i][j] > max) {
max = t[i][j];
}
}
}
220 of 246
189 288
93 Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "ad-
jacent" cells are those horizontally or vertically neighboring. The same letter cell may
not be used more than once.
For example, given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", ->returns true, word = "SEE", ->returns true, word = "ABCB",
->returns false.
93.1 Analysis
return result;
}
public boolean dfs(char[][] board, String word, int i, int j, int k){
int m = board.length;
227 | 531
221 of 246
190 288
93 Word Search
int n = board[0].length;
if(board[i][j] == word.charAt(k)){
char temp = board[i][j];
board[i][j]=’#’;
if(k==word.length()-1){
return true;
}else if(dfs(board, word, i-1, j, k+1)
||dfs(board, word, i+1, j, k+1)
||dfs(board, word, i, j-1, k+1)
||dfs(board, word, i, j+1, k+1)){
return true;
}
board[i][j]=temp;
}
return false;
}
222 of 246
191 288
94 Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where
"adjacent" cells are those horizontally or vertically neighboring. The same letter cell
may not be used more than once in a word.
For example, given words = ["oath","pea","eat","rain"] and board =
[
[’o’,’a’,’a’,’n’],
[’e’,’t’,’a’,’e’],
[’i’,’h’,’k’,’r’],
[’i’,’f’,’l’,’v’]
]
Return ["eat","oath"].
Similar to Word Search, this problem can be solved by DFS. However, this solution
exceeds time limit.
public List<String> findWords(char[][] board, String[] words) {
ArrayList<String> result = new ArrayList<String>();
int m = board.length;
int n = board[0].length;
229 | 531
223 of 246
192 288
94 Word Search II
result.add(word);
}
}
return result;
}
if (board[i][j] == word.charAt(k)) {
char temp = board[i][j];
board[i][j] = ’#’;
if (k == word.length() - 1) {
return true;
} else if (dfs(board, word, i - 1, j, k + 1)
|| dfs(board, word, i + 1, j, k + 1)
|| dfs(board, word, i, j - 1, k + 1)
|| dfs(board, word, i, j + 1, k + 1)) {
board[i][j] = temp;
return true;
}
} else {
return false;
}
return false;
}
If the current candidate does not exist in all words’ prefix, we can stop backtracking
immediately. This can be done by using a trie structure.
public class Solution {
Set<String> result = new HashSet<String>();
224 of 246
193 288
94 Word Search II
int m=board.length;
int n=board[0].length;
if(i<0 || j<0||i>=m||j>=n){
return;
}
if(visited[i][j])
return;
if(!trie.startsWith(str))
return;
if(trie.search(str)){
result.add(str);
}
visited[i][j]=true;
dfs(board, visited, str, i-1, j, trie);
dfs(board, visited, str, i+1, j, trie);
dfs(board, visited, str, i, j-1, trie);
dfs(board, visited, str, i, j+1, trie);
visited[i][j]=false;
}
}
//Trie Node
225 of 246
194 288
94 Word Search II
class TrieNode{
public TrieNode[] children = new TrieNode[26];
public String item = "";
}
//Trie
class Trie{
public TrieNode root = new TrieNode();
226 of 246
195 288
95 Integer Break
Given a positive integer n, break it into the sum of at least two positive integers and
maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 +
4).
Let dp[i] to be the max production value for breaking the number i. Since dp[i+j] can
be i*j, dp[i+j] = max(max(dp[i], i) * max(dp[j], j)), dp[i+j]).
public int integerBreak(int n) {
int[] dp = new int[n+1];
return dp[n];
}
If we see the breaking result for some numbers, we can see repeated pattern like the
following:
2 -> 1*1
3 -> 1*2
4 -> 2*2
5 -> 3*2
6 -> 3*3
7 -> 3*4
8 -> 3*3*2
9 -> 3*3*3
10 -> 3*3*4
11 -> 3*3*3*2
233 | 531
227 of 246
196 288
95 Integer Break
We only need to find how many 3’s we can get when n>4. If n
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;
int result=1;
if(n%3==0){
int m = n/3;
result = (int) Math.pow(3, m);
}else if(n%3==2){
int m=n/3;
result = (int) Math.pow(3, m) * 2;
}else if(n%3==1){
int m=(n-4)/3;
result = (int) Math.pow(3, m) *4;
}
return result;
}
228 of 246
197 288
96 Range Sum Query 2D Immutable
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined
by its upper left corner (row1, col1) and lower right corner (row2, col2).
96.1 Analysis
Since the assumption is that there are many calls to sumRegion method, we should
use some extra space to store the intermediate results. Here we define an array sum[][]
which stores the sum value from (0,0) to the current cell.
int m = matrix.length;
int n = matrix[0].length;
sum = new int[m][n];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
if(this.sum==null)
235 | 531
229 of 246
198 288
96 Range Sum Query 2D Immutable
return 0;
int bottomLeftX=row2;
int bottomLeftY= col1;
int result=0;
}else if(col1==0){
result = sum[row2][col2]
-sum[topRightX-1][topRightY];
}else{
result = sum[row2][col2]
-sum[topRightX-1][topRightY]
-sum[bottomLeftX][bottomLeftY-1]
+sum[row1-1][col1-1];
}
return result;
}
}
230 of 246
199 288
97 Longest Increasing Path in a Matrix
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You
may NOT move diagonally or move outside of the boundary
return longest;
}
237 | 531
231 of 246
200 288
97 Longest Increasing Path in a Matrix
}
}
return longest;
}
if(x>=0&&y>=0&&x<matrix.length&&y<matrix[0].length&&matrix[x][y]>matrix[i][j]){
mem[i][j]=Math.max(mem[i][j], dfs(matrix, x, y, mem));
}
}
return ++mem[i][j];
}
}
232 of 246
201 288
98 Implement a Stack Using an Array in
Java
@SuppressWarnings("unchecked")
public Stack(int cap) {
this.CAP = cap;
this.arr = (E[]) new Object[cap];
}
public E pop() {
if(this.size == 0){
return null;
}
this.size--;
E result = this.arr[top];
this.arr[top] = null;//prevent memory leaking
this.top--;
return result;
}
239 | 531
233 of 246
202 288
98 Implement a Stack Using an Array in Java
this.size++;
this.arr[++top] = e;
return false;
}
sb.setLength(sb.length()-2);
return sb.toString();
}
System.out.println(stack);
stack.pop();
System.out.println(stack);
stack.pop();
System.out.println(stack);
}
}
Output:
hello, world
hello
null
234 of 246
203 288
98 Implement a Stack Using an Array in Java
It turns out I don’t need to improve anything. There are some naming differences but
overall my method is ok.
This example occurs twice in "Effective Java". In the first place, the stack example is
used to illustrate memory leak. In the second place, the example is used to illustrate
when we can suppress unchecked warnings.
Do you wonder how to implement a queue by using an array?
235 of 246
204 288
99 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
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
}
}
What if 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.
243 | 531
237 of 246
205 288
100 Reorder List
Given a singly linked list L: L0→L1→ ... →Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-
1→L2→Ln-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.
100.1 Analysis
• 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;
}
}
245 | 531
239 of 246
206 288
100 Reorder List
n3.next = n4;
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;
}
}
}
240 of 246
207 288
100 Reorder List
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:
241 of 246
208 288
100 Reorder List
Merge List:
242 of 246
209 288
100 Reorder List
243 of 246
210 288
101 Linked List Cycle
101.1 Analysis
If we have 2 pointers - fast and slow. It is guaranteed that the fast one will meet the
slow one if there exists a circle.
if(slow == fast)
return true;
}
return false;
}
}
251 | 531
245 of 246
211 288
102 Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which
could point to any node in the list or null.
Return a deep copy of the list.
• 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
if (head == null)
return null;
RandomListNode p = head;
253 | 531
247 of 246
212 288
102 Copy List with Random Pointer
p.next = temp.next;
if (temp.next != null)
temp.next = temp.next.next;
p = p.next;
}
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 Xiaomeng’s 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
248 of 246
213 288
102 Copy List with Random Pointer
q.random = null;
p = p.next;
q = q.next;
}
return newHead;
}
249 of 246
214 288
103 Merge Two Sorted Lists
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.
103.1 Analysis
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;
257 | 531
251 of 246
215 288
103 Merge Two Sorted Lists
p = p.next;
}
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}
}
252 of 246
216 288
104 Odd Even Linked List
104.1 Problem
Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
104.2 Analysis
This problem can be solved by using two pointers. We iterate over the link and move
the two pointers.
259 | 531
253 of 246
217 288
104 Odd Even Linked List
p1.next = p2.next;
p1 = p1.next;
p2.next = p1.next;
p2 = p2.next;
}
p1.next = connectNode;
return result;
}
254 of 246
218 288
105 Remove Duplicates from Sorted List
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.
105.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
solutions.
105.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
261 | 531
255 of 246
219 288
105 Remove Duplicates from Sorted List
}else{
prev = p;
p = p.next;
}
}
return head;
}
}
105.3 Solution 2
ListNode p = head;
return head;
}
}
256 of 246
220 288
106 Remove Duplicates from Sorted List
II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only
distinct numbers from the original list.
For example, given 1->1->1->2->3, return 2->3.
ListNode p = t;
while(p.next!=null&&p.next.next!=null){
if(p.next.val == p.next.next.val){
int dup = p.next.val;
while(p.next!=null&&p.next.val==dup){
p.next = p.next.next;
}
}else{
p=p.next;
}
return t.next;
}
263 | 531
257 of 246
221 288
107 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.
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;
p = prev.next;
p2 = p2.next;
}
}
prev.next = fakeHead2.next;
return fakeHead1.next;
265 | 531
259 of 246
222 288
107 Partition List
}
}
260 of 246
223 288
108 LRU Cache
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.
108.1 Analysis
The key to solve this problem is using a double linked list which enables us to quickly
move nodes.
The LRU cache is a hash table of keys and double linked nodes. The hash table
makes the time of get() to be O(1). The list of double linked nodes make the nodes
adding/removal operations O(1).
267 | 531
261 of 246
224 288
108 LRU Cache
return -1;
}
if(n.next!=null){
n.next.pre = n.pre;
}else{
end = n.pre;
}
if(head!=null)
head.pre = n;
262 of 246
225 288
108 LRU Cache
head = n;
if(end ==null)
end = head;
}
}else{
setHead(created);
}
map.put(key, created);
}
}
}
263 of 246
226 288
109 Intersection of Two Linked Lists
109.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 {
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;
271 | 531
265 of 246
227 288
109 Intersection of Two Linked Lists
}
while(p2 !=null){
len2++;
p2 = p2.next;
}
int diff = 0;
p1=headA;
p2=headB;
}
p1 = p1.next;
p2 = p2.next;
}
return null;
}
}
266 of 246
228 288
110 Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
The key to solve this problem is using a helper node to track the head of the list.
public ListNode removeElements(ListNode head, int val) {
ListNode helper = new ListNode(0);
helper.next = head;
ListNode p = helper;
while(p.next != null){
if(p.next.val == val){
ListNode next = p.next;
p.next = next.next;
}else{
p = p.next;
}
}
return helper.next;
}
273 | 531
267 of 246
229 288
111 Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example, given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in
the list, only nodes itself can be changed.
Use two template variable to track the previous and next node of each pair.
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
return h.next;
}
275 | 531
269 of 246
230 288
112 Reverse Linked List
ListNode p1 = head;
ListNode p2 = head.next;
head.next = null;
while(p1!= null && p2!= null){
ListNode t = p2.next;
p2.next = p1;
p1 = p2;
if (t!=null){
p2 = t;
}else{
break;
}
}
return p2;
}
277 | 531
271 of 246
231 288
112 Reverse Linked List
second.next = head;
return rest;
}
272 of 246
232 288
113 Reverse Linked List II
113.1 Analysis
int i=0;
ListNode p = head;
while(p!=null){
i++;
if(i==m-1){
prev = p;
}
if(i==m){
first.next = p;
}
if(i==n){
second.next = p.next;
p.next = null;
}
p= p.next;
}
if(first.next == null)
return head;
279 | 531
273 of 246
233 288
113 Reverse Linked List II
p1.next = second.next;
return head;
}
274 of 246
234 288
114 Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example, given linked list 1->2->3->4->5 and n = 2, the result is 1->2->3->5.
Calculate the length first, and then remove the nth from the beginning.
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;
return head;
}
281 | 531
275 of 246
235 288
114 Remove Nth Node From End of List
Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When
the fast reaches the end, the slow pointer points at the previous element of the target
element.
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
276 of 246
236 288
115 Implement Stack using Queues
Implement the following operations of a stack using queues. push(x) – Push element
x onto stack. pop() – Removes the element on top of the stack. top() – Get the top
element. empty() – Return whether the stack is empty.
Note: only standard queue operations are allowed, i.e., poll(), offer(), peek(), size()
and isEmpty() in Java.
115.1 Analysis
class MyStack {
LinkedList<Integer> queue1 = new LinkedList<Integer>();
LinkedList<Integer> queue2 = new LinkedList<Integer>();
283 | 531
277 of 246
237 288
115 Implement Stack using Queues
278 of 246
238 288
116 Implement Queue using Stacks
class MyQueue {
value.push(x);
while(!temp.isEmpty()){
value.push(temp.pop());
}
}
}
285 | 531
279 of 246
239 288
116 Implement Queue using Stacks
280 of 246
240 288
117 Palindrome Linked List
We can create a new list in reversed order and then compare each node. The time and
space are O(n).
public boolean isPalindrome(ListNode head) {
if(head == null)
return true;
ListNode p = head;
ListNode prev = new ListNode(head.val);
while(p.next != null){
ListNode temp = new ListNode(p.next.val);
temp.next = prev;
prev = temp;
p = p.next;
}
ListNode p1 = head;
ListNode p2 = prev;
while(p1!=null){
if(p1.val != p2.val)
return false;
p1 = p1.next;
p2 = p2.next;
}
return true;
}
We can use a fast and slow pointer to get the center of the list, then reverse the second
list and compare two sublists. The time is O(n) and space is O(1).
287 | 531
281 of 246
241 288
117 Palindrome Linked List
secondHead.next = null;
p = p.next;
q = q.next;
return true;
}
282 of 246
242 288
118 Implement a Queue using an Array
in Java
There following Java code shows how to implement a queue without using any extra
data structures in Java. We can implement a queue by using an array.
import java.lang.reflect.Array;
import java.util.Arrays;
E[] arr;
int head = -1;
int tail = -1;
int size;
boolean push(E e) {
if (size == arr.length)
return false;
if(tail == -1){
tail = head;
}
289 | 531
283 of 246
243 288
118 Implement a Queue using an Array in Java
return true;
}
boolean pop() {
if (size == 0) {
return false;
}
E result = arr[tail];
arr[tail] = null;
size--;
tail = (tail+1)%arr.length;
if (size == 0) {
head = -1;
tail = -1;
}
return true;
}
E peek(){
if(size==0)
return null;
return arr[tail];
}
284 of 246
244 288
119 Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only
access to that node.
Supposed the linked list is 1 ->2 ->3 ->4 and you are given the third node with value
3, the linked list should become 1 ->2 ->4 after calling your function.
291 | 531
285 of 246
245 288
120 Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all
integers in the sliding window.
LinkedList<Integer> queue;
int size;
return (double)sum/queue.size();
}
}
293 | 531
287 of 246
246 288