CODING
INTERVIEW
Scanned with CamScannerContents
1 Rotate Array in Java 7
2 Evaluate Reverse Polish Notation 9
3. Solution of Longest Palindromic Substring in Java a
4 Solution Word Break 45
5 Word Break I! 18
6 Word Ladder 20
7 Median of Two Sorted Arrays Java 23
8 Regular Expression Matching in Java 25
9 Merge Intervals 27
10 Insert Interval 29
11 Two Sum 34
12 Two Sum II Input array is sorted 32
13 Two Sum III Data structure design 33
14 3Sum 34
15 4sum 36
16 3Sum Closest 38
17 String to Integer (atol) 39
18 Merge Sorted Array 4o
19 Valid Parentheses ae
20 Implement strstr() 43
2 181
Scanned with CamScanner21
22
23
24
25
26
27
28
29
31
32
33
34
35
36
37
41
42
43
45
Set Matrix Zeroes
Search Insert Position
Longest Consecutive Sequence Java
Valid Palindrome
Spiral Matrix
Search a 2D Matrix
Rotate Image
Triangle
Distinct Subsequences Total
Maximum Subarray
Maximum Product Subarray
Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array I
Longest Substring Without Repeating Characters
Longest Substring Which Cont:
6 2 Unique Characters
Palindrome Partitioning
Reverse Words in a String
Find Minimum in Rotated Sorted Array
Find Minimum in Rotated Sorted Array I!
Find Peak Element
Min stack
Majority Element
Combination Sum
Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock I!
Program Creek
Contents
4
46
v7
49
52
35
56
58
60
e
6
3 | 181
Scanned with CamScannerContents
46 Best Time to Buy and Sell Stock II! 85
47. Best Time to Buy and Sell Stock IV 86
8 Longest Common Prefix 88
49. Largest Number 89
50 Combinations 90
51 Compare Version Numbers 92.
52 Gas Station 93
53 Candy 5
54 Jump Game 96
55 Pascal's Triangle 97
56 Container With Most Water 98
57 Count and Say 99
58 Repeated DNA Sequences 100
59. Add Two Numbers 01
60 Reorder List 105
61 Linked List Cycle 109
62 Copy List with Random Pointer mt
63 Merge Two Sorted Lists 4
64 Merge k Sorted Lists 116
65 Remove Duplicates from Sorted List 417
66 Partition List 119
67 LRU Cache wat
68 Intersection of Two Linked Lists 324
69 Java PriorityQueue Class Example 325
70 Solution for Binary Tree Preorder Traversal in Java 327
4 | 181 Program Creek
Scanned with CamScannerce
2
73
74
75
76
7
78
79
81
82
83
85
87
90
91
93
94
95
Solution of Binary Tree Inorder Traversal in Java
Solution of Iterative Binary Tree Postorder Traversal in Java
val
jate Binary Search Tree
Flatten Binary Tree to Linked List
Path Sum
Construct Binary Tree from Inorder and Postorder Traversal
Convert Sorted Array to
lary Search Tree
Convert Sorted List to Binary Search Tree
Minimum Depth of Binary Tree
Binary Tree Maximum Path Sum
Balanced Binary Tree
Symmetric Tree
Clone Graph Java
How Developers Sort in Java?
Solution Merge Sort LinkedList in Java
Quicksort Array in Java
Solution Sort a linked list using insertion sort in Java
um Gap
Iteration vs. Recursion in Java
Edit Distance in Java
Single Number
Single Number |!
‘Twitter Codility Problem Max Binary Gap
Number of 1 Bits
Reverse Bits
Program Creek
Scanned with CamScanner
Contents
228
330
33
133
134
136
=z
138
x40
42
43
45
146
49
351
354
156
158
160
163
165
166
166
167
5 | 181Contents
97
Permutations
Permutations II
Permutation Sequence
Generate Parentheses
100 Reverse Integer
101 Palindrome Number
102 Pow(x, n)
6 | 381
Program Creek
169
7
173
Scanned with CamScanner1 Rotate Array in Java
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
= 7and 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?
1.1 Solution 1 - Intermediate Array
Ina straightforward way, we can create a new array and then copy elements to the
new array. Then change the original array by using Systemarraycopy()
public void rotate(int{] nums, int k) {
if( k > nuns. length)
keksnums. length;
int{] result = new int (nuns. length] ;
for(int i=; i < ky ine)
result[i] = nums[nums.length-kei];
d
int j=;
for(int isk; ienums.length; i+4){
result(i] = nums{j];
iets
»
System.arraycopy( result, @, nums, 6, nums.length ):
Space is O(n) and time is O(n).
1.2 Solution 2 - Bubble Rotate
Can we do this in O(2) space?
This solution is like a bubble sort.
public static void retate(int{] arr, int order) {
if (arr == null || order < 0) {
throw new TltegalargunentException( "Illegal argunent!
7 | 181
Scanned with CamScanner1 Rotate Array in Java
y
for (int = 0; i 6;
int temp = arrljli
art] = arrtj - Ui
arrl) - 1] = temp;
}
}
}
However, the time is O(n*k).
1.3 Solution 3 - Reversal
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:
Divide the array two parts: 1,2,3,4 and 5, 6
Rotate first part: 4,3,2,1,5,6
Rotate second part: 4,3,2,1,6,5
Rotate the whole array: 5,6,1,2,3,4
public static void rotate(int{] arr, int order) {
order = order % arr.tength;
if (arr == nuit || order < 0) {
‘throw new TLLegalArgumentException(*ILLegal argument! ");
y
/Nength of first part
int a= arr.length - order;
reverse(arr, 8, 2-1):
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr,length-1);
}
public static void reverse(int{] arr, int left, int right)
if(are == null | arr.tength = 1)
while(Lleft < right){
ant temp = arr([left];
arr[left] = arr[right];
arr{right] = temp;
lefts;
right
8 | 381 Program Creek
Scanned with CamScanner2 Evaluate Reverse Polish Notation
The problem:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +,
expression.
J. Each operand may be an integer or another
Sone examples:
> ((2+1) +3) 29
1, 8] > (4+ (13 /5)) > 6
2.1 Naive Approach
This problem is simple. After understanding the problem, we should quickly realize
that this problem can be solved by using a stack. We can loop through each element
in the given array. When it is a number, push it to the stack. When it is an operator,
pop two numbers from the stack, do the calculation, and push back the result.
op
—_ s
\ dA out
1, 2 are poped ou
= and thea 3 are pushed in
Zales
The following is the code. It runs great by feeding a small test. However, this code
9 | 181
Scanned with CamScanner2 Evaluate Reverse Polish Notation
contains compilation errors in leetcode. Why?
public class Test {
public static void main(string[] args) throws TOException {
Stringl] tokens = new Stringl] { "2", "1", "#", "3", "=" }
System.out.printin(evalRPN( tokens) );
+
public static int evalRPN(String(] tokens) {
int returnValue = 6;
String operators
aff;
StacksString> stack = new StacksString>();
for (String t : tokens) {
if (loperators.contains(t)) {
stack.push(t);
} else ¢
int a = Integer. valueOf(stack.pop());
int b = Integer. valueOf(stack.pop());
switch (t) {
stack. push (String. valueof(a + b));
break;
stack.push (String. valueof(b - a);
break;
case *
stack.push(String.valuedf(a + b));
break;
case
stack.push(String.valueof(b / a));
break;
}
?
?
returnValue = Integer.value0f (stack. pop());
return returnValue;
+
}
‘The problem is that switch string statement is only available from JDK 1.7. Leetcode
apparently use versions below that.
10 | 181 Program Creek
Scanned with CamScanner2.2 Accepted Solution
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 = 6;
String operators = “+
Stack stack = new Stack();
for(String t : tokens){
if(loperators.contains(t)){
stack.push(t) ;
Jetset
int @ = Integer.valuedf (stack.pop());
int b = Integer.valuef (stack. pop());
int index = operators. indexor (t);
switch(index) {
case 6:
stack.push (String. valueOt(a+b)) ;
break:
case 1:
stack.push(String. valuedt(b-a));
break;
case 2:
stack.push(String. valuedt (a+b) );
break;
case 3:
stack.push(String. valueot (b/a) );
break:
}
returnValue = Integer. valuedf(stack.pop());
return returnValue;
a1 | 181
Scanned with CamScanner3 Solution of Longest Palindromic Substring in Java
3 Solution of Longest Palindromic
Substring in Java
Finding the longest palindromic substring is a classic problem of coding interview. In
this post, I will summarize 3 different solutions for this problem.
3.1 Naive Approach
Naively, we can simply examine every substring and check if it is palindromic. The
time complexity is O(n3). If this is submitted to LeetCode onlinejudge, an error mes-
sage will be returned - "Time Limit Exceeded’. Therefore, this approach is just a start,
we need a better algorithm.
public static String longestPalindronel(String s) {
ant maxPalinLength = @;
String LongestPalindrom
int length = s.length();
// check all possible sub strings
for (int i = 0; i < Length; itt) {
for (int j = i+ 1; j < length; jo+) {
int len =j - iy
String curr = s.substring(i, j + 1);
if (isPalindrone(curr)) {
if (len > maxPalinLength) {
longestPalindrome = curr;
maxPalinLength = len;
y
?
?
}
return longestPalindrone;
}
public static boolean isPalindrome(String s) {
for (int 4 = 0; i s.charAt(i) == s.charAt(ie1)
Changing condition:
table[i+l][j-2]
table[illj] == 1
1 GG s.charat(i) == s.charat(j)
Time O(n3) Space O(n3)
public static String longestPalindrome2(String s) {
if (s == null)
return null;
if(s-length() <=1)
return 5;
int maxLen = 0;
String longestStr = nul
Ant Length = s.length();
int{1{] table = new int{Length] [length];
Jrevery single letter is palindrome
for (int i = 0; i < length; i++) {
table[il[i] = 1;
,
printTable(table) ;
/ie.g. beba
//two consecutive same letters are palindrome
for (int i = 0; i <= Length - 2; i++) {
if (s.charat(i) == s.charat(i + 1)){
table(i}[i + 1)
LongestStr = s.substring(i, i + 2);
»
,
printTable(table) ;
//condition for calculate whole table
for (int L= 3; L = Length; Lr) {
for (int i i <= Length-t; is) {
Program Creek 43 | 181
Scanned with CamScanner3 Solution of Longest Palindromic Substring in Java
int j}2i4-a;
if (s.charAt(i) == s.charAt(j)) {
table[il{j] = tableli + UU - 1;
if (table[il[j] == 1 6% L > maxten)
LongestStr = s.substring(i, j + 1);
} else {
tablelil [i]
}
PrintTable(table) ;
?
+
return longestStr;
}
public static void printTable(int{]() x){
for(int (1 y + x)
for(int 2: yt
System.cut.print(z +" ");
,
System.out.printtn();
y
System. out. printtn(" “13
d
Given an input, we can use printTable method to examine the table after each itera-
tion. For example, if input string is “dabcba’, the final matrix would be the following:
From the table, we can clear see that the longest string is in cell table[s][5].
3.3
imple Algorithm
From Yifan’s comment below.
‘Time O(n3), Space O(1)
public String longestPalindrone(String s) {
if (s.istmpty()) {
return null;
+
Af (s.Length() == 1) {
return s;
y
1g | 181 Program Creek
Scanned with CamScannerString longest = s.substring(9, 1);
for (int i = 0; i < s.length(); i++) ¢
// get longest palindrome with center of 4
String tmp = helper(s, i, i):
if (tmp.length() > longest.length()) {
longest = tmp;
}
// get longest palindrome with center of i, i#1
tmp = helper(s, i, i + 1);
if (tmp.length() > longest. tength()) {
Longest = tmp;
}
,
return longest;
y
// Given a center, either one letter or two letter,
11 Find Longest palindrome
public String helper(String s, int begin, int end) {
while (begin == 6 && end <= s.length() - 1 6& s.charat(begin) =
s.charAt(end)) {
begin-
end++;
,
return s.substring(begin + 1, end);
y
3.4 Manacher’s Algorithm
Manacher’s algorithm is much more complicated to figure out, even though it will
bring benefit of time complexity of O(n).
Since it is not typical, there is no need to waste time on that.
4 Solution Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into
2 space-separated sequence of one or more dictionary words. For example, given s
“Teetcode”, dict = ["leet", "code”]. Return true because "leetcode” can be segmented as
“eet code”.
415 | 181
Scanned with CamScanner4 Solution Word Break
4.1 Naive Approach
This problem can be solve by using a naive approach, which is trivial. A discussion
can always start from that though.
public class Solution {
public boolean wordBreak(String s, Set dict) {
return wordBreakHelper(s, dict, @);
+
public boolean wordBreakHelper(String s, Set dict, int start){
if(start == s.length())
return true;
for(String a: dict){
int len = a.length();
int end = startelen;
//end index should be <= string Length
if(end > s.length())
‘continue;
if(s.substring(start, start+len) .equals(a))
if(wordBreakHelper(s, dict, start+len))
return true;
}
return false;
‘Time: O(n3)
‘This solution exceeds the time limit.
4.2 Dynamic Programming
‘The key to solve this problem by using dynamic programming approach:
public class Solution {
public boolean wardBreak(String s, Set dict) {
boolean{] t = new doclean{s.length()+1];
t[0] = true; //set first te be true, why?
//Because we need initial state
for(int i=0; ies.Length(); i+4){
36 | 181 Program Creek
Scanned with CamScanner4 Solution Word Break
should continue from match position
af(1t)
continue;
for(String a: dict){
int len = a.length();
int end = i + len;
if(end > s.length())
continue;
if(tlend]) continue;
if(s-substring(i, end) equats(a)){
‘t[end] = true;
}
}
return tls.length()]i
Time: O(string length * dict size)
‘One tricky part of this solution is the case:
INPUT: “prograncreek*, [*prograncree”, “program”, "creek™]
We should get all possible matches, not stop at "programcree
4.3 Regular Expression
The problem is supposed to be equivalent to matching the regexp (leet! code)*, which
‘means that it can be solved by building a DFA in O(ath) and executing it in O(n)
(Thanks to hdanie.) Leetcode online judge does not allow using Pattern class though.
public static void main(String[] args) {
HashSet dict = new HashSeteString>();
dict.add("g0");
dict.add("goal");
dict-add(*goals");
dict-add("special");
StringBuilder sb = new StringBuilder();
for(String s: dict){
sb.append(s + "|");
,
String pattern = sb.toString() .substring(@, sb.Length()-1);
Program Creek 47 | 181
Scanned with CamScannerpattern = "("#pattern+")*";
Pattern p = Pattern. compile(pattern)
Matcher m= p.matcher("goalspecial”);
if (m.matches()){
System.out.printin("match") ;
}
}
4.4 The More Interesting Problem
‘The dynamic solution can tell us whether the string can be broken to words, but can
not tell us what words the string is broken to. So how to get those words?
Check out Word Break IL
5 Word Break II
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence
where each word is a valid dictionary word. Return all such possible sentences.
"dog'l, the
feat’, “cats”,
For example, given s = “catsanddog", dict
solution is ["cats and dog’, "cat sand dog"].
‘and’, "san
5.1 Java Solution - Dynamic Programming
This problem is very similar to Word Break. Instead of using a boolean array to track
the match positions, we need to track the actual words. Then we can use depth first
search to get all the possible paths, i., the list of strings.
‘The following diagram shows the structure of the tracking array.
18 | 181
Scanned with CamScanner5 Word Break II
index | Words
« | o
a | a
t | 2
s | 3 eat
a | 4 eats
» | 5
a | 6
a | 7 and, sand
° | @
o | 9
10 dog
public static ListeString> wordBreak(String s, Set dict) {
//create an array of ArrayList
List dp[] = new ArrayList[s.length()+1];
dp[@] = new ArrayList();
for(int 1-8; i s.length())
continue:
if (s. subst ring(4,end) .equals (word) ){
if (dplend) == null)
‘dplend] = new ArrayList();
+
dp lend) -add(word)
+
}
}
List result = new LinkedList();
Af(dpls.Length()] == nutty
return result;
Program Creek 19 | 181
Scanned with CamScannerArrayList temp = new ArrayListString>();
dfs(dp, s.length(), result, temp);
return result;
?
public static void dfs(ListeString> dpl],int end, List result,
ArrayList tmp) {
iffend <= 0){
String path get (tmp.size()-1);
for(int istmp.size()-2; i>=@; i--){
path 4=" "+ tmp.get(i) j
+
result.add (path) ;
return;
»
for(String str : dplend]){
tmp.add(str) ;
dfs(dp, end-str.length(), result, tmp);
‘tmp. remove (tmp .size()-1
6 Word Ladder
‘The problem:
Given two words (start and end), and a dictionary, find the length of shortest trans-
formation sequence from start to end, such that:
Only one letter can be changed at a time Each intermediate word must exist in the
dictionary For example,
Given:
start = “hit”
end = "cog"
dict = [*hot™ "dot",
Jog" ,"Let*,"Log"]
As one shortest transformation
should return its length 5.
Note: Return o if there is no such transformation sequence. All words have the same
length. All words contain only lowercase alphabetic characters.
‘This problem is a classic problem that has been asked frequently during interviews.
it" ->"hot” ->"dot” ->"dog" ->"cog", the program
20 | 381
Scanned with CamScanner6 Word Ladder
The following are two Java solutions.
6.1 Naive Approach
Ina simplest way, we can start from start word, change one character each time, if it
is in the dictionary, we continue with the replaced word, until start == end.
public class Solution {
public int ladderLength(String start, String end, HashSet dict) {
int len=0;
HashSet visited = new HashSet();
for(int icstart.length(); i++){
char[] startArr = start.toChararray();
for(char c='a'; ce='z'; cH)
if (c=estart. techarArray() [4]){
continue;
}
startarrlil = ¢;
String temp = new String(startAarr) ;
if (dict.contains (temp) ){
Lents
start = temp;
if (temp. equals (end) ){
return len;
}
y
y
return len;
Apparently, this is not good enough. The following example exactly shows the
problem. It can not find optimal path. The output is 3, but it actually only takes 2
1
a", rc, [rans "bY,
6.2 Breath First Search
So we quickly realize that this looks like a tree searching problem for which breath
first guarantees the optimal solution,
Program Creek an | 481
Scanned with CamScanner6 Word Ladder
Assuming we have some words in the
the diagram below.
ictionary, and the start is “hit” as shown in
We can use two queues to traverse the tree, one stores the nodes, the other stores the
step numbers.
Updated on 2/27/2015.
public int ladderLength(String start, String end, HashSet dict) {
if (dict-size() == 0)
return @;
dict-add(end) ;
LinkedList wordQueue = new LinkedList();
LinkedListeInteger> distancequeue = new LinkedList();
wordQueve. add (start)
distanceQueue.add(1);
//track the shortest path
int result = Integer.MAX VALUE;
while (!wordQueve.istmpty()) {
String currWord = wordQueue.pop();
Integer currDistance = distanceQueue.pop();
if (currWord.equats(end)) {
result = Math.min(result, currDistance) ;
+
for (int 1 = @; 4 < currWord.tength(); it) {
char[] cureCharArr = currWord.techararray() ;
for (char c= 'a';
}
public static int findkth(int AL], int B[], int k,
int aStart, int and, int bStart, int bend) {
int aLen
int bLen
aEnd - aStart +1;
bend - bStart +1;
// Handle special cases
if (alen == 0)
return B[bStart + kl;
if (blen == 6)
return AlaStart + kl;
if (k == 0)
return AlaStart] < B[bStart] 7 AlaStart] : B[bStart];
int aMid = alen » k / (alen + blen); // a's middle count
int bMid = k - aMlid - 1; // b's middle count
// wake aMid and bMid to be array index
aMid = altid + aStart;
bMid = bMid + bStart;
if (AlaMid] > B{bMid}) {
k =k - (bMid - bStart + 1);
End = aMid;
bStart = bMid +1;
pelse {
k =k - (aMid - aStert +1);
bend = bMid;
aStart = aMid +1;
}
return findkth(A, B, k, aStart, and, bStart, bend);
7.2 The Steps of the Algorithm
‘Thanks to Gunner86. The description of the algorithm is awesome!
1) Calculate the medians m1 and mz of the input arrays ari{] and ara[] respectively.
2) If m1 and mz both are equal then we are done, and return m1 (or ma) 3) If m1
2g | 181
Scanned with CamScanner8 Regular Expression Matching in Java
is greater than m2, then median is present in one of the below two subarrays. a)
From first element of art to mt (arz[o...|_n/2_|]) b) From m2 to last element of ar2
{ar2[|_n/2_|...n-1]) 4) If m2 is greater than mz, then median is present in one of the
below two subarrays. a) From mz to last element of art (ari{ |_n/2_|..1-1]) b) From
first element of ar2 to m2 (ar2[o...|_n/2_l]) 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(ars[o], ar2[o]) + min(ars[1], ar2[1]))/2
8 Regular Expression Matching in Java
Problem:
Implement regular expression matching with support for.’ and “*".
".) Watches 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)
Sone example:
isMatch("aa","a") return false
isMatch("aa","aa") return true
istatch("2aa","aa") return false
isMatch("aa", “as") return true
istatch("aa", “.*") return true
AsHatch("ab", *.=") return true
isMatch("zab", "ceasb") return true
8.1 Analysis
First of all, this is one of the most difficulty problems. It is hard to handle many cases.
‘The problem should be simplified to handle 2 basic cases:
‘= the second char of pattern is"
‘the second char of pattern is not "**
For the ist case, if the first char of pattern is not ".", the first char of pattern and
string should be the same. Then continue to match the left part.
For the 2nd case, if the first char of pattern is "." or first char of pattern == the first i
char of string, continue to match the left
Be careful about the offset.
Program Creek 25 | 181
Scanned with CamScanner8 Regular Expression Matching in Java
8.2 Java Solution 1 (Short)
The following Java solution is accepted
public class Solution {
public boolean isMatch(String s, String p) {
if(p-length() == @)
return s.length() == 6;
//p"s Length 1 is special case
if(pelength() == 1 || p.charat(1) = "*7)£
4f(s.length() <1 || (p.charat(a) != *.
p.charAt(9)))
return false;
return isMatch(s.substring(1), p-substring(1));
&& s.charat(o)
yelsef
int len = s.length();
int i= -1;
while(iclen & (i <0 || p-charat(e) == '.' |] p-charat(o) ==
s.charat(i)))£
if (isMatch(s.substring(i+1), p-substring(2)))
return true;
int;
}
return false;
8.3 Java Solution 2 (More Readable)
public boolean isMatch(String s, String p) «
// base case
if (p.length() == 0) {
return s.length() == 8;
+
// special case
if (p.length() == 1) {
// Af the length of s is @, return false
if (s.length() < 1) {
return false;
,
26 | 181 Program Creek
Scanned with CamScanner//# the first does not
else if ((p.charat(e)
return false;
itch, return false
s.charAt(8)) 6& (p.charat(a) !
ol €
y
// otherwise, compare the rest of the string of s and p.
else {
return isMatch(s.substring(1), p-substring(1));
}
,
71 case 1: when the second char of p is not '"
if (p.charat(1) != '=") {
if (s.length() <1) {
return false;
y
if ((p.charat(@) !=
return false;
} else {
return isMatch(s.substring(1), p.substring(1));
-charat(@)) && (p.charat(a) !
d
»
11 case 2: when the second char of p is
else {
//case 2.1: a char & '*' can stand for @ element
if (isMatch(s, p.substring(2))) {
return true;
+ complex case.
}
//case 2.2: a char & '«' can stand for 1 or more preceding element,
//s0 try every sub string
int i = 0;
while (i merge(ArrayList intervals) {
if (intervals == null || intervals.size() <= 1)
return intervals;
// sort intervals by using self-defined Comparator
Collections.sort (intervals, new IntervalComparator());
ArrayListeInterval> result = new ArrayList();
Interval prev = intervals.get(®);
28 | 181 Program Creek
Scanned with CamScannerfor (int i= 1; i < intervals.size(); is) {
Interval curr = intervals.get(i);
if (prev.end >= curr.start) {
U1 merged case
Interval merged = new Interval(prev.start, Math.max(prev.end,
curr.end)
prev = merged;
y else {
result.add (prev) ;
prev = curr;
}
}
result.add(prev) ;
return result;
,
>
class IntervalComparator implements Conparator (
public int compare(Interval il, Interval i2) {
return il.start - i2.start;
»
y
10 Insert Interval
Problem:
Given a set of non-overlapping & sorted intervals, insert a new intercal into the intervals
(merge if necessary).
Example 1:
Given intervals [1,3], [6,9], insert and merge [2,5] in as (1,51, 16,9].
Example 2:
Given [1,2], (3,51,[6,7], [8,10], [12,16], insert and merge [4,9] in as
(2,21, (3,10), 122,16] -
This is because the new interval [4,9] overlaps with (3,5],[6,71,[8,16].
29 | 181
Scanned with CamScanner10 Insert interval
10.1 Thoughts of This Problem
Quickly summarize 3 cases. Whenever there is intersection, created a new interval
Current
case 1 New
Case 2
10.2 Java Solution
i
+ Definition for an interval
+ public class Interval {
= int start;
int end;
+ Interval() { start = 0; end = 6; }
+ Interval (int s, int e) { start = 5; end »
“)
7
public class Solution {
public ArrayList insert(ArrayList intervals, Interval
newInterval) {
ArrayList result = new ArrayListeInterval>();
for(Interval interval: intervals){
if(interval.end < newInterval.start){
result add (interval) ;
}else if(interval.start > newInterval.end){
result .add(newInterval) ;
newinterval = interval;
Jelse if(interval.end >= newInterval.start || interval.start <
newInterval.end){
30 | 181 Program Creek
Scanned with CamScannernewinterval = new Interval (Math.nin(interval.start,
newInterval.start), Nath.max(newInterval.end, interval.end));
y
result.add(newInterval) ;
return result;
11 Two Sum
Given an array of integers, find two numbers such that they add up to a specific target
nnuntber.
‘The function twoSum should return indices of the two numbers such that they add
up to the target, where index 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: indexi=1, index2=2
11.1 Naive Approach
This problem is pretty straightforward. We can simply examine every possible pair of
numbers in this integer array.
Time complexity in worst case: O(n3).
public static int{] twoSum(int[] numbers, int target) {
int[] ret = new int (21;
for (int i = 9; i < mumbers.length; i++) {
for (int j= 441; 1 < mumbers.length; J++) {
if (nunbers{i] + numbers{j] == target) {
ret(o] =i +2;
ret() = +15
y
y
y
return ret;
+
31 | 181
Scanned with CamScannerCan we do better?
11.2 Better Solution
Use HashMap to store the target value.
public class Solution {
public int{] twoSum(int{] numbers, int target) ¢
HashMap map = new HashMapeInteger, Integer>();
int[] result = new int(2];
for (int 4 = 0; i < numbers.length; i++) {
if (map. containskey(numbers{i]}) {
int index = map.get(numbers[i]);
result(@] = index+l ;
resutt(1] = 1+1;
break;
}else {
map.put(terget - numbers[il, i);
+
+
return result;
}
‘Time complexity depends on the put and get operations of HashMap which is nor-
mally O(2).
‘Time complexity of this solution: O(n)
12 Two Sum II Input array is sorted
This problem is similar to Two Sum.
To solve this problem, we can use two points to scan the array from both sides. See
Java solution below:
public int] twoSum(int(] numbers, int target) {
if (numbers == null || numbers. length == 6)
return nut
int i
int j= numbers. length - 1;
while (i target) {
i
} else (
return new int{] 4+, 5 +1};
,
,
return nulls
y
13 Two Sum Ill 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
13.1 Java Solution
Since the desired class need add and get operations, HashMap is a good option for
this purpose.
public class TwoSum {
private HashMap elements = new HashMap();
public void add(int number) {
if (elements.containsKey(number)) {
elenents.put(nunber, elements.get(number) + 1);
} else {
elements. put (number, 1);
r
,
33 | 181
Scanned with CamScannerpublic boolean find(int value) {
for (Integer i : elements. keySet()) {
int target = value -
if (eLenents.containsKey(target)) {
if (i = target & elements.get(terget) <2) {
continue:
d
return true;
}
}
return false;
+
}
14 3Sum
Problem:
Given an array $ of n integers, are there elements a, b, ¢ in $ such that a +b + ¢=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 < ¢)
The solution set must not contain duplicate triplets.
For example, given array § = {1012-1 -A},
A solution set is:
(1,6, 1)
(1, -1,.2)
14.1 Naive Solution
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> threeSum(int[] num) {
Wsort array
Arrays. sort(num) ;
ArrayList> result = new
ArrayListcArrayList();
ArrayListeInteger> each = new ArrayList();
34 | 181
Scanned with CamScanner14 3Sum
for(int i=; icnum.tength; it+){
if (num{i] > @) break;
for(int jit; j @ && num{j} > 6) break;
+1; kenum-length; k++) {
8) ¢
for(int
if(num[i} + num(j] + num{k)
each. add(num{i}) ;
each. add (num{j]) ;
each. add(num{k]) ;
result.add(each) ;
each.clear();
y
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
14.2 Better Solution
A better solution is using two pointers instead of one. This makes time complexity of
Omn3),
To avoid duplicate, we can take advantage of sorted arrays, ie., move pointers by >1
to use same element only once.
public ArrayList> threeSum(int(] num) {
ArrayList> result = new ArrayListArrayList>();
if (num.length < 3)
return result;
11 sort array
Arrays.sort (num);
for (int i= 0; 4 < num.length - 2; itt) {
// /avoid duplicate solutions
if (2 == 6 || nunfi} > numti - 11)
Program Creek 35 | 181
Scanned with CamScannerint negate = -num{i};
int start =i +1;
int end = num.length - 1;
while (start < end) {
//case 1
if (num[start] + num{end] == negate) {
ArrayList temp = new ArrayList();
‘temp .add(num{i]);
‘temp.add(num[start]) ;
‘temp .add(num{end]);
result.add (temp);
startes;
end
(avoid duplicate solutions
while (start < end && numfend] == numfend + 1])
end--j
while (start < end && num[start] = nun{start - 1])
startet:
dcase 2
} else if (num[start] + numfend] < negate) {
startet:
Mcase 3
F else {
end--;
}
}
+
}
return result;
15 4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a+b +e
+d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <
b > fourSum(int{] num, int target) {
Arrays.sort (num) ;
HashSet> hashSet = new HashSet>();
Arraylist> result = new ArrayList>();
for (int i= 0; i < num.tength; iss) {
for (int j = i +1; j < num.length; j++) {
int k=j +1;
int U= num.length - 1;
while (k< 0 {
Aint sum = num{i] + num{j] + num(k] + num(U];
if (sum > target) {
Les
} else if (sum < target) {
kee
} else if (sum == target) {
ArrayListeInteger> temp = new ArrayList();
‘temp.add(num{i}) ;
‘temp.add (num j}) ;
‘temp..add(num{ i] );
‘temp.add(num{t}));
if
jashSet. contains(temp)) {
hashSet .add (temp) ;
result.add( temp) ;
,
kets
Lest
Program Creek 37 | 181
Scanned with CamScannery
?
+
return result;
}
Here is the hashCode method of ArrayList. It makes sure that if all elements of two
sts 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 i = list.iterator();
while (AshasNext()) {
E obj = i-next();
hashCode = 31shashCode + (obj==null ? @ : obj -hashCode());
16 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to
a given number, target. Return the sum of the three integers. You may assume that
‘each input would have exactly one solution. For example, given array $ = -1 2 1-4,
and target = 1. The sum that is closest to the target is 2. (-1 +2 +1=2)
16.1 Thoughts
‘This problem is similar with 2 Sum. This kind of problem can be solve by using similar
approach, ie., two pointers from both left and right.
16.2 Java Solution
public class Solution {
public int threeSumClosest(int{(] num, int target) {
int min = Integer.MAX_VALUE;
int result
Arrays.sort (num) ;
for (int i = 0; i < num.tength; i++) {
int j2i+ds
38 | 181
Scanned with CamScannerint k = num.length - 1;
while (j< k) {
int sum = num[i] + num(j] + num{k];
int diff = Math.abs(sum - target);
if (diff = 4) return @;
if (diff < min) {
min = diff;
result = sum;
+
if (sum <= target) {
jet
}else {
ken
>
y
y
return result;
?
+
Time Complexity is O(n3).
17 String to Integer (atoi)
Problem:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do
not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input
specs). You are responsible to gather all the input requirements up front.
17.1 Thoughts for This Problem
The vague description give us space to consider different cases.
+ null or empty string
. white spaces
> sign!
+ calculate real value
handle min & max
39 | 181
Scanned with CamScanner17.2 Java Solution
public int atoi (String str) {
if (str == null |] strslength() < 1)
return @;
// trim white spact
str = str.trim()
char flag =
// check negative or positive
int i= 0;
if (str.charat(a) = '-") {
flag = '-';
itt
} else if (str.charat (0)
+
// use double to store result
double result = @;
at
// calculate value
while (str.length() > 4 && str.charat(i) >= °6" 6& str.charAt(i) <= ‘9") {
result = result + 16 + (str.charat(i) - '0");
r
if (flag == *-")
result = -result;
7 handle max and min
if (result > Integer.MAX.VALUE)
return Integer.MAX.VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
‘Thanks to the comment below. The solution above passes LeetCode online judge,
but it haven't considered other characters. I will update this later.
4o | 181
Scanned with CamScanner18 Merge Sorted Array
18 Merge Sorted Array
Problem:
Given to 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.
18.1 Thoughts for This Problem
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.
18.2 Java Solution 1
public class Solution {
public void merge(int Al], int m, int B{], int n) {
while(m > @ 66 n> 6){
Sf (Alm-1] > Bln-1]){
Almen-1] = Alm-1];
ne
Jetset
Alm+n-2] = B{n-2];
neo:
y
wnile(n > 6){
Almen-1) = B{n-1];
18.3 Java Solution 2
The loop condition also can use men like the following,
public void merge(int AL], int m, int B[}, int n) {
inti=m- 1;
int j=n- 4;
intk=m+n
Program Creek
Scanned with CamScanner
41 | 181while (k >= 0) {
if (J <@ |] (i >= @ 88 ALi] > BIj]))
Alk--] = Ali--Is
else
Alke-] = BL
19 Valid Parentheses
Problem:
Given a string containing just the characters ‘(,,‘,",", 'U’ and ‘I’, determine if the
input string is valid. The brackets must close in the correct order, “()” and "(l]” are all
valid but "(" and “(D1" are not.
19.1 Thoughts about This Problem
Character is not a frequently used class, so need to know how to use it.
19.2 Java Solution
public static boolean isValid(String 5) {
HashMap map = new HashMap();
map.put("(", ')");
map.put("[’, '1");
map.put((’, "PD;
Stack stack = new Stack();
for (int i= 0; i
42 | 181
Scanned with CamScanner,
return stack.empty();
+
19.3 Simplified Java Solution
Almost identical, but convert string to char array at the beginning.
public static boolean isvalid(string s) {
chart] charArray = s.toCharArray();
HashMapsCharacter, Character> map = new HashMap();
map.put("(", *))5
map.put("[", “]")
map.put("(", “})5
Stack stack = new Stack();
for (Character ¢ : charArray) {
if (map.keySet() .contains(c)) {
stack.push(c);
} else if (map.values().contains(c)) {
if (Istack.istmpty() && map.get (stack.peek())
stack.pop();
y else {
return false;
y
}
,
return stack.isEmpty();
y
20 Implement strStr()
Problem:
Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or
null if needle is not part of haystack.
43 | 181
Scanned with CamScanner20.1 Thoughts
First, need to understand the problem correctly, the pointer simply means a sub string.
Second, make sure the loop does not exceed the boundaries of two strings.
20.2 Java Solution
public String strStr(String haystack, String needle) {
int needleLen = needle. Length();
int haystackLen = haystack. Length();
if (needleLen =
return
jaystackLen 6& needleLen == 0)
if (needleLen
return haystac
for (int 1 = 0; i 2
(1,3,5,6], 2 > 1
(1,3,5,6], 7 > 4
11,3,5,6], 8 > @
22.1 Solution 1
Naively, we can just iterate the array and compare target with ith and (i+1)th element.
Time complexity is O(n)
public class Solution {
public int searchInsert(int{] A, int target) {
46 | 181
Scanned with CamScannerAf (Acsnull) return 6;
if(target <= A[@]) return 0;
for(int i=@; i Ali] && target <= ALi+i}){
return i+];
+
}
return A. length;
22.2 Solution 2
This also looks like a binary search problem. We should try to make the complexity to
be O(nlogn).
public class Solution {
public int searchInsert(int{] A, int target) {
if (Aesnull| |A.length==6)
return @;
return searchInsert(A,target,@,A.ength-1) ;
>
public int searchinsert(int[] A, int target, int start, int end){
int mid=(starteend) /2;
if(target==A{mid])
return mid;
else if(targetmid?searchInsert(A, target midel,end) : (end+1) ;
47 | 181
Scanned with CamScanner23 Longest Consecutive Sequence Java
23 Longest Consecutive Sequence Java
Given an unsorted array of integers, find the length of the longest consecutive elements
sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence
should be [1, 2, 3, 4]- Its length is 4
Your algorithm should run in O(n) complexity.
23.1 Thoughts
Because it requires O(n) complexity, we can not solve the problem by sorting the array
first. Sorting takes at least O(nlogn) time.
23.2 Java Solution
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) {
// Xf array is empty, return @
if (num.length == 0) {
return ;
+
Set set = new HashSet();
int max = 1;
for (int e : num)
set.add(e);
for (int e + num) {
int left =e -
int right =e +
int count = 1;
while (set.contains(left)) {
count++;
set.remove(left) ;
left--;
+
while (set-contains(right)) {
count++;
set. remove(right);
right++s
y
48 | 181 Program Creek
Scanned with CamScannermax = Math.max(count, max);
»
return max;
+
After an element is checked, it should be removed from the set. Otherwise, time
complexity would be O(mn) in which m is the average length of all consecutive se-
quences.
To clearly see the time complexity, I suggest you use some simple examples and
manually execute the program. For example, given an array 1,2,4,5,3, the program
time is m. m is the length of longest consecutive sequence.
We do have an extreme case here: If n is number of elements, m is average length
of consecutive sequence, and m==n, then the time complexity is O(n3). The reason is
that in this case, no element is removed from the set each time. You can use this array
to get the point: 1,3,5,7,9.
24 Valid Palindrome
Given a string, determine if itis a palindrome, considering only alphanumeric charac-
ters and ignoring cases.
For example, "Red rum, sir, is murder" is a palindrome, while "Programcreek is
awesome’ is not.
Note: Have you consider that the string might be empty? This is a good question to
ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
24.1 Thoughts
From start and end loop though the string, ie, 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.
24.2 Java Solution 1 - Naive
public class Solution {
public boolean isPalindrone(String s) {
f(s == null) return false;
if(s.Length() <2) return true;
4g | 181
Scanned with CamScanner24 Valid Palindrome
char{] charArray = s.toCharArray();
int len = s.length();
int i=6;
int j=ten-1;
while(ici){
char left, right
while(iclen-1 66 lisAlpha(left) 66 !istium(Left))
int;
Left = charArraylil;
?
while(j>0 66 LisAtpha( right) 6&6 LisNum(right))«
joni
right = charArray(j};
>
afi)
break:
Left = charArray[il:
right = charArray(j];
Af (issame(left, right)){
return false:
y
iss
je
+
return true:
}
public boolean isAlpha(char a){
Af ((a >= ‘a Gace '2") || (a 22 AT a ZN
return true;
yelset
return false;
r
,
public boolean isNum(char a){
ifla >= "0" Sa ce '9'){
return true;
yelset
return false;
}
50 | 181 Program Creek
Scanned with CamScanner24 Valid Palindrome
?
public boolean isSame(char a, char b){
if (isNum(a) 66 isNum(b)){
return a == b;
Jelse if(Character.toLowerCase(a)
return true;
Jelsef
return false;
Character.toLowerCase(b)){
}
24.3 Java Solution 2 - Using Stack
This solution removes the special characters first. (Thanks to Tia)
public boclean isPalindrone(String s) {
5 = s.replaceall("[~a-zA-Z0-9]", "").toLowercase();
int len = s.tength();
if (len < 2)
return true;
StackeCharacter> stack = new StackeCharacter>();
int index =
while (index < len / 2) {
stack. push(s.charAt index) );
index++;
,
if (len % 2 == 1)
index++;
white (index < len) {
if (stack.empty(})
return false;
char temp = stack.pop();
Af (s.charAt(index) != temp)
return false;
else
indexes
y
return true;
Program Creek 51 | 181
Scanned with CamScanner24.4 Java Solution 3 - Using Two Pointers
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(se=null| |[s-length()==8) return false;
5 = s.replaceatl(” [*a-2A-20-9]", *").toLowerCase()
System.out.printtn(s);
for(int i < s.length() ; i++){
Af(s.charat(i) t= s.charat(s.length() - 1 - i)){
return false;
}
}
return true;
y
public static void main(String[] args) {
String str = "A man, a plan, a canal: Panama";
System.out. printtn(isValidPalindrome(str)) ;
y
25 Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the
matrix in spiral order.
For example, given the following matrix:
You should return [1,2,3,6,9.8,7.4,5].
52 | 181
Scanned with CamScanner25 Spiral Matrix
25.1 Java Solution 1
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 spiraOrder(int{]{] matrix) {
ArrayList result = new ArrayList();
if(matrix == null || matrix.length == 9) return result;
int
int
matrix.length;
matrix(@] length;
int
int
while(m8 66 >a) {
//4f one row/colunn left, no circle can be formed
if(m==1){
for(int fen; G44)
result.add(matrix(x] [y+#]);
+
brea
}else if(n==1){
for(int i=8; i