Java interview preparation guide
Java interview preparation guide
Program Creek
Contents
3 Remove Element 18
4 Move Zeroes 19
5 Candy 20
9 Summary Ranges 28
10 Missing Ranges 29
11 Merge Intervals 30
12 Insert Interval 31
13 Partition Labels 34
17 Is Subsequence 40
22 Valid Palindrome 46
2 | 568
Contents
30 3Sum 58
31 4Sum 60
32 3Sum Closest 62
33 Wiggle Sort 63
34 Wiggle Subsequence 64
36 Next Permutation 66
49 HIndex 93
50 HIndex II 95
51 Valid Anagram 96
169 Construct Binary Tree from Inorder and Postorder Traversal 327
170 Construct Binary Tree from Preorder and Inorder Traversal 329
218 Evaluate math expression with plus, minus and parentheses 423
232 Get Target Number Using Number List and Arithmetic Operations 450
279 Design a Data Structure with Insert, Delete and GetMostFrequent of O(1) 533
Every title in the PDF is linked back to the original blog. When it is clicked, it opens the original post in your
browser. If you want to discuss any problem, please go to the post and leave your comment there.
I’m not an expert and some solutions may not be optimal. So please leave your comment if you see any problem
or have a better solution. I will reply your comment as soon as I can.
This collection is updated from time to time. Please check out this link for the latest version: http://www.programcreek.com/
10-algorithms-for-coding-interview/
1.1 Analysis
The problem is pretty straightforward. It returns the length of the array with unique elements, but the original
array need to be changed also. This problem is similar to Remove Duplicates from Sorted Array II.
int j = 0;
int i = 1;
i++;
}
return j + 1;
}
14 | 568
1 Remove Duplicates from Sorted Array
Note that we only care about the first unique part of the original array. So it is ok if input array is 1, 2, 2, 3, 3,
the array is changed to 1, 2, 3, 3, 3.
int i=0;
int j=1;
/*
i, j 1 1 1 2 2 3
step1 0 1 i j
step2 1 2 i j
step3 1 3 i j
step4 2 4 i j
*/
while(j<nums.length){
if(nums[j]==nums[i]){
if(i==0){
i++;
j++;
}else if(nums[i]==nums[i-1]){
j++;
}else{
i++;
nums[i]=nums[j];
j++;
}
}else{
i++;
nums[i]=nums[j];
j++;
}
}
return i+1;
}
16 | 568
2 Remove Duplicates from Sorted Array II
The problem with this solution is that there are 4 cases to handle. If we shift our two points to right by 1
element, the solution can be simplified as the Solution 2.
return i + 1;
}
j++;
}
return i;
}
18 | 568
4 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].
while(j<nums.length){
if(nums[j]==0){
j++;
}else{
nums[i]=nums[j];
i++;
j++;
}
}
while(i<nums.length){
nums[i]=0;
i++;
}
}
19 | 568
5 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?
5.1 Analysis
This problem can be solved in O(n) time.
We can always assign a neighbor with 1 more if the neighbor has higher a rating value. However, to get the
minimum total number, we should always start adding 1s in the ascending order. We can solve this problem by
scanning the array from both sides. First, scan the array from left to right, and assign values for all the ascending
pairs. Then scan from right to left and assign values to descending pairs.
This problem is similar to Trapping Rain Water.
20 | 568
5 Candy
return result;
}
6.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;
22 | 568
6 Trapping Rain Water
}else{
left[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;
}
t1[0]=1;
t2[nums.length-1]=1;
//multiply
for(int i=0; i<nums.length; i++){
result[i] = t1[i] * t2[i];
}
return result;
}
result[nums.length-1]=1;
for(int i=nums.length-2; i>=0; i--){
result[i]=result[i+1]*nums[i+1];
}
24 | 568
7 Product of Array Except Self
int left=1;
for(int i=0; i<nums.length; i++){
result[i]=result[i]*left;
left = left*nums[i];
}
return result;
}
8.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;
sum = sum+nums[i];
i++;
}
}
if(exists)
return result;
else
return 0;
26 | 568
8 Minimum Size Subarray Sum
int i=0;
int j=0;
int sum=0;
while(j<nums.length){
if(sum<s){
sum += nums[j];
j++;
}else{
minLen = Math.min(minLen, j-i);
if(i==j-1)
return 1;
sum -=nums[i];
i++;
}
}
while(sum>=s){
minLen = Math.min(minLen, j-i);
sum -=nums[i++];
}
9.1 Analysis
When iterating over the array, two values need to be tracked: 1) the first value of a new range and 2) the previous
value in the range.
if(nums.length==1){
result.add(nums[0]+"");
}
if(i==nums.length-1){
result.add(nums[i]+"");
}
first = nums[i];
}
pre = nums[i];
}
return result;
}
28 | 568
10 Missing Ranges
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return
its missing ranges.
Example:
Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99, Output: ["2", "4->49", "51->74", "76->99"]
if(lower==Integer.MAX_VALUE){
return result;
}
if(nums[i] == start){
start++;
}else{
result.add(getRange(start, nums[i]-1));
if(nums[i]==Integer.MAX_VALUE){
return result;
}
start = nums[i]+1;
}
}
if(start<=upper){
result.add(getRange(start, upper));
}
return result;
}
29 | 568
11 Merge Intervals
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].
11.1 Analysis
The key to solve this problem is defining a Comparator first to sort the arraylist of Intevals.
result.add(t);
return result;
}
30 | 568
12 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].
/**
* 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; }
31 | 568
12 Insert Interval
* }
*/
public class Solution {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
result.add(newInterval);
return result;
}
}
if (intervals.size() == 0) {
result.add(newInterval);
return result;
}
result.add(newInterval);
return result;
}
if(arr == null){
arr = new int[]{i, i};
map.put(c, arr);
}else{
arr[1]=i;
}
}
34 | 568
13 Partition Labels
int[] t = list.get(0);
for(int i=1; i<list.size(); i++){
int[] range = list.get(i);
if(range[1]<=t[1]){
continue;
}else if(range[0]>t[1]){ //impossible be equal
result.add(t[1]-t[0]+1);
t = range;
}else{
t[1] = range[1];
}
}
result.add(t[1]-t[0]+1);
return result;
}
int prev = 0;
if (prev != startIndex) {
sb.append(S.substring(prev, startIndex));
}
return sb.toString();
}
36 | 568
15 One Edit Distance
Given two strings S and T, determine if they are both one edit distance apart.
int m = s.length();
int n = t.length();
if(Math.abs(m-n)>1){
return false;
}
int i=0;
int j=0;
int count=0;
while(i<m&&j<n){
if(s.charAt(i)==t.charAt(j)){
i++;
j++;
}else{
count++;
if(count>1)
return false;
if(m>n){
i++;
}else if(m<n){
j++;
}else{
i++;
j++;
}
}
}
if(i<m||j<n){
count++;
}
if(count==1)
return true;
return false;
}
37 | 568
16 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.
16.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.
while (k >= 0) {
if (j < 0 || (i >= 0 && A[i] > B[j]))
A[k--] = A[i--];
38 | 568
16 Merge Sorted Array
else
A[k--] = B[j--];
}
}
int i=0;
int j=0;
while(i<s.length() && j<t.length()){
if(s.charAt(i)==t.charAt(j)){
i++;
}
j++;
if(i==s.length())
return true;
}
return false;
}
40 | 568
18 Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a
backspace character.
Example 1:
Example 2:
while(i>=0 || j>=0){
int c1=0;
while(i>=0 && (c1>0 || S.charAt(i)==’#’)){
if(S.charAt(i)==’#’){
c1++;
}else{
c1--;
}
i--;
}
int c2=0;
while(j>=0 && (c2>0 || T.charAt(j)==’#’)){
if(T.charAt(j)==’#’){
c2++;
}else{
c2--;
}
j--;
}
41 | 568
18 Backspace String Compare
}else{
i--;
j--;
}
}else{
if(i>=0 || j>=0){
return false;
}
}
}
int result = 0;
int k = 0;
if (i == A.length()) {
i = 0;
result++;
}
} else {
k++;
if (k == A.length()) {
return -1;
}
i = k;
j = 0;
result = 0;
}
}
if (i > 0) {
result++;
}
return result;
}
43 | 568
20 Container With Most Water
20.1 Problem
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (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.
20.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;
return max;
}
44 | 568
21 Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
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--;
}
45 | 568
22 Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters 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.
s = s.toLowerCase();
int i=0;
int j=s.length()-1;
while(i<j){
while(i<j && !((s.charAt(i)>=’a’ && s.charAt(i)<=’z’)
|| (s.charAt(i)>=’0’&&s.charAt(i)<=’9’))){
i++;
}
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
46 | 568
23 Shortest Word Distance
Given a list of words and two words word1 and word2, return the shortest distance between these two words in
the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3. Given word1 = "makes", word2 = "coding", return 1.
return min;
}
47 | 568
24 Shortest Word Distance II
This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and
your method will be called repeatedly many times with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and implements a method that takes two words
word1 and word2 and return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3. Given word1 = "makes", word2 = "coding", return 1.
ArrayList<Integer> l1 = map.get(word1);
ArrayList<Integer> l2 = map.get(word2);
The time complexity for shortest method is O(M*N), where M is freqency of word1 and N is the frequency of
word2. This can be improved by the following:
ArrayList<Integer> l1 = map.get(word1);
ArrayList<Integer> l2 = map.get(word2);
48 | 568
24 Shortest Word Distance II
int i=0;
int j=0;
while(i<l1.size() && j<l2.size()){
result = Math.min(result, Math.abs(l1.get(i)-l2.get(j)));
if(l1.get(i)<l2.get(j)){
i++;
}else{
j++;
}
}
return result;
}
The time complexity of the shortest method is now O(M+N). Since M+N <size of word list, the time is O(K)
where k is the list size.
int m=-1;
int n=-1;
return min;
}
50 | 568