(Multiply Strings)

Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.

Thoughts:
This is not a hard question in the sense that there’s no “clever” algorithm to apply. We just do the intuitive way. Think about how we human being multiply two integers. We take each digit and multiply it with another digit, then the addition, taking care of the carry. So we just “mimic” that method in our code. The only catch is that we have to be busy travelling between integer and char. Another catch is how much space we should initialize our result string. Well, in my solution, I try to be conservative to find the upper bound – the number of digits of the products can be no more than the sum of the digits of the two multipliers. In the end, we might find we allocated more space than we need to, resulting some leading zeros. We can just clean it up.

Code (Java):

public class Solution {
public String multiply(String num1, String num2) {
char[] result = new char[num1.length() + num2.length()];
for(int i = 0; i < result.length; ++i)
result[i] = '0';
for(int i = num1.length() - 1; i >= 0; --i) {
int index = num1.length() + num2.length() - 1 - (num1.length() - 1 - i);
int digit1 = Character.getNumericValue(num1.charAt(i));
for(int j = num2.length() - 1; j >= 0; --j) {
int digit2 = Character.getNumericValue(num2.charAt(j));
int temp = digit1 * digit2;
int previous = Character.getNumericValue(result[index]);
result[index] = (char) ((previous + temp) % 10 + '0');
int carry = (previous + temp) / 10;
int m = index - 1;
while(carry != 0 && m >= 0) {
int rm = Character.getNumericValue(result[m]);
result[m] = (char)((rm + carry) % 10 + '0');
carry = (rm + carry) / 10;
m--;
}

index--;
}
}
return new String(result).replaceFirst("^0+(?!\$)", "");
}
}

Code (C++):
class Solution {
public:
string multiply(string num1, string num2) {
char result[num1.size() + num2.size()];
for(int i = 0; i < num1.size() + num2.size(); ++i)
result[i] = '0';
for(int i = num1.size() - 1; i >= 0; --i) {
int index = num1.size() + num2.size() - 1 - (num1.size() - 1 - i);
int digit1 = num1[i] - '0';
for(int j = num2.size() - 1; j >= 0; --j) {
int digit2 = num2[j] - '0';
int temp = digit1 * digit2;
int previous = result[index] - '0';
result[index] = (char) ((previous + temp) % 10 + '0');
int carry = (previous + temp) / 10;
int m = index - 1;
while(carry != 0 && m >= 0) {
int rm = result[m] - '0';
result[m] = (char)((rm + carry) % 10 + '0');
carry = (rm + carry) / 10;
m--;
}

index--;
}
}
string candidate = string(result, num1.size() + num2.size());
size_t i = candidate.find_first_not_of('0');
return i ==  string::npos ? "0" : candidate.substr(i);
}
};



(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,
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Thoughts:
The idea is from here. I try to rephrase it a little bit here. The general idea is that we find a window first, not necessarily the minimum, but it’s the first one we could find, traveling from the beginning of S. We could easily do this by keeping a count of the target characters we have found. After finding an candidate solution, we try to optimize it. We do this by going forward in S and trying to see if we could replace the first character of our candidate. If we find one, we then find a new candidate and we update our knowledge about the minimum. We keep doing this until we reach the end of S. For the giving example:

1. We start with our very first window: “ADOBEC”, windowSize = 6. We now have “A”:1, “B”:1, “C”:1
2. We skip the following character “ODE” since none of them is in our target T. We then see another “B” so we update “B”:2. Our candidate solution starts with an “A” so getting another “B” cannot make us a “trade”.
3. We then see another “A” so we update “A”:2. Now we have two “A”s and we know we only need 1. If we keep the new position of this “A” and disregard the old one, we could move forward of our starting position of window. We move from A->D->O->B. Can we keep moving? Yes, since we know we have 2 “B”s so we can also disregard this one. So keep moving until we hit “C”: we only have 1 “C” so we have to stop. Therefore, we have a new candidate solution, “CODEBA”. Our new map is updated to “A”:1, “B”:1, “C”:1.
4. We skip the next “N” and we arrive at “C”. Now we have two “C”s so we can move forward the starting position of last candidate: we move along this path C->O->D->E until we hit “B”. We only have one “B” so we have to stop. We have yet another new candidate, “BANC”.
5. We have hit the end of S so we just output our best candidate, which is “BANC”.

Code (Java):

public class Solution {
public String minWindow(String S, String T) {
int[] needToFind = new int[256];
int[] hasFound = new int[256];

for(int i = 0; i < T.length(); ++i) {
needToFind[T.charAt(i)]++;
}

int count = 0;
int minWindowSize = Integer.MAX_VALUE;
int start = 0, end = 0;
String window = "";

for(; end < S.length(); end++) {
if(needToFind[S.charAt(end)] == 0) continue;
char c = S.charAt(end);
hasFound[c]++;

if(hasFound[c] <= needToFind[c]) {
count++;
}

if(count == T.length()) {
while(needToFind[S.charAt(start)] == 0 ||
hasFound[S.charAt(start)] > needToFind[S.charAt(start)]) {
if(hasFound[S.charAt(start)] > needToFind[S.charAt(start)])
hasFound[S.charAt(start)]--;
start++;
}

if(end - start + 1 < minWindowSize) {
minWindowSize = end - start + 1;
window = S.substring(start, end + 1);
}
}
}

return window;
}
}

Code (C++):
class Solution {
public:
string minWindow(string S, string T) {
int needToFind[256] = {0};
int hasFound[256] = {0};

for(int i = 0; i < T.size(); ++i) {
needToFind[T[i]]++;
}

int count = 0;
int minWindowSize = INT_MAX;
int start = 0, end = 0;
string window;

for(; end < S.size(); end++) {
if(needToFind[S[end]] == 0) continue;
hasFound[S[end]]++;

if(hasFound[S[end]] <= needToFind[S[end]]) {
count++;
}

if(count == T.size()) {
while(needToFind[S[start]] == 0 ||
hasFound[S[start]] > needToFind[S[start]]) {
if(hasFound[S[start]] > needToFind[S[start]])
hasFound[S[start]]--;
start++;
}

if(end - start + 1 < minWindowSize) {
minWindowSize = end - start + 1;
window = S.substr(start, minWindowSize);
}
}
}

return window;
}
};



(Minimum Path Sum)

Given a $m \times 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.
Note: You can only move either down or right at any point in time.

Thoughts:
Because the grid is filled with non-negative numbers. Standing at any position ($i, j$), the minimum sum we can get is $\text{grid}[i,j] + \min$(minimum sum starting from$[i+1,j]$, minimum sum starting from $[i,j+1]$). Hence we find the recursive structure of this problem. The base case would be one element only, one row only and one column only. Notice that we could end up with repeating computations a lot (e.g., right->down and down->right), hence we should employ dynamic programming, in which we introduce a hashmap to cache the partial result.

Code (Java):

public class Solution {

private Map<List<Integer>, Integer> map =
new HashMap<List<Integer>, Integer>();

public int minPathSum(int[][] grid) {
map.clear();
return minPathSumRec(grid, 0, 0);
}

private int minPathSumRec(int[][] grid, int i, int j) {
List<Integer> pair = new ArrayList<Integer>();
if(map.get(pair) != null)
return map.get(pair);
else {
int r = grid[i][j];;
if(i == grid.length-1 && j == grid[0].length - 1)
r += 0;
else if(i == grid.length - 1)
r += minPathSumRec(grid, i, j + 1);
else if(j == grid[0].length - 1)
r += minPathSumRec(grid, i + 1, j);
else
r += Math.min(minPathSumRec(grid, i + 1, j),
minPathSumRec(grid, i, j + 1));
map.put(pair, r);
return r;
}
}
}


Code (C++):

class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
cache.clear();
return minPathSumRec(grid, 0, 0);
}

private:
map<vector<int>, int> cache;

int minPathSumRec(vector<vector<int> > &grid, int i, int j) {
vector<int> pair(2);
pair[0] = i;
pair[1] = j;
if(cache.find(pair) != cache.end())
return cache[pair];
else {
int r = grid[i][j];
if(i == grid.size() -1 && j == grid[0].size() - 1)
r += 0;
else if(i == grid.size() - 1)
r += minPathSumRec(grid, i, j + 1);
else if(j == grid[0].size() - 1)
r += minPathSumRec(grid, i + 1, j);
else
r += min(minPathSumRec(grid, i, j + 1),
minPathSumRec(grid, i + 1, j));
cache[pair] = r;
return r;
}
}
};


(Minimum Depth of Binary Tree)

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Thoughts:
Sense of recursion should be came out now.
What is the base case or edge case? Empty tree. What is the minimum depth of an empty tree? 0.
In the recursion step, the passed in TreeNode “root” is been looked at. “root” is not null, which was covered in the base case. Then there are four sub-cases or combinations, if you like:

1. root is a leaf node. In other word, root.left == null && root.right == null. Return 1 at this case.
2. root.left == null && root.right != null. Then we just need to recurse on the right, so we return 1 + minDepth(root.right).
3. root.left != null && root.right == null. Similarly, we return 1 + minDepth(root.left).
4. root.left != null && root.right != null. This is rather interesting case. We don’t know which branch of the case has shorter path, so we should return the minimum of these two.

In the code, we can actually combine the four cases into two!

Code (Java):

public class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
else {
if(root.left != null && root.right != null)
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
else
return 1 + minDepth(root.right) + minDepth(root.left);
}

}
}

Code (C++):
class Solution {
public:
int minDepth(TreeNode *root) {
if(root == NULL)
return 0;
else if(root -> left != NULL && root -> right != NULL)
return 1 + min(minDepth(root -> left), minDepth(root -> right));
else
return 1 + minDepth(root -> right) + minDepth(root -> left);
}
};



(Merge k Sorted Lists)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Thoughts:
We start with the first list and then merge it with the second list, then the third list, so on and the so forth. For merging two sorted linked list, we use the linear merging algorithm borrowed from Merge Sort. The total complexity is $O(kn)$.

Code (Java):

public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode head = null;
for (ListNode node : lists)
}

private ListNode mergeTwoLists(ListNode head1, ListNode head2) {
if (head1 == null || head2 == null)

} else {
}
}
}

Code (C++):
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode *head = NULL;
for(int i = 0; i < lists.size(); ++i)
}

private:
if (head1 == NULL || head2 == NULL)

if (head1 -> val < head2 -> val) {
} else {
}
}
};



(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].

Thoughts:
We first sort the list according to the start-time. Then for any interval $i$ in the middle, it has overlap with the next interval $j$ iff $j$.start <= $i$.end. If so, we know we are about to merge them into a new interval $k$. And $k$.start = $i$.start && $k$.end = $\max(i$.end, $j$.end).

Code (Java):

public class Solution {
public class MyComparator implements Comparator{
public int compare(Object o1, Object o2) {
Interval i1 = (Interval)o1;
Interval i2 = (Interval)o2;
return i1.start - i2.start;
}
}

public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if(intervals == null)
return null;
ArrayList<Interval> result = new ArrayList<Interval>();
if(intervals.size() == 0)
return result;
if(intervals.size() == 1) {
return result;
}
Collections.sort(intervals, new MyComparator());
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for(int i = 1; i < intervals.size(); ++i) {
Interval curr = intervals.get(i);
if(curr.start <= end) {
end = Math.max(end, curr.end);
} else {
start = curr.start;
end = curr.end;
}
}
return result;
}
}


Code (C++):
Thanks to this post:

class Solution {
class Solution {
public:
struct MyComparatorClass {
bool operator() (Interval i, Interval j) { return (i.start < j.start);}
} myComparator;

vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> result;
if(intervals.size() == 0)
return result;
if(intervals.size() == 1) {
result.push_back(intervals[0]);
return result;
}
sort(intervals.begin(), intervals.end(), myComparator);
vector<Interval>::iterator it = intervals.begin();
Interval current = *(it)++;
while (it != intervals.end()){
if (current.end >= it -> start) {
current.end = std::max(current.end, it -> end);
} else {
result.push_back(current);
current = *(it);
}
it++;
}
result.push_back(current);
return result;
}
};


(String to Integer (atoi))

Implement atoi to convert a string to an integer.

Thoughts:
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Code (Java):

	public int atoi(String number) {
if (number == null || number.trim().length() == 0) {
return 0;
}

int result = 0;
number = number.trim();

boolean negate = false;
char sign = number.charAt(0);

if (sign == '+' || sign == '-') {
if (sign == '-') {
negate = true;
}
number = number.substring(1);
}

int length = number.length();
int start = -1;
int index = 0;
for (; index < length; index++) {
char a = number.charAt(index);
if (a >= '0' && a <= '9') {
if (start == -1)
start = index;
} else {
break;
}
}
int end = index - 1;

if (start == -1)
return 0;

for (int i = start; i <= end; ++i) {
char a = number.charAt(i);
int digit = a - '0';
if (!negate) {
if (result + digit * (int) Math.pow(10, end - i) >= result)
result += digit * (int) Math.pow(10, end - i);
else
result = Integer.MAX_VALUE;
} else {
if (result - digit * (int) Math.pow(10, end - i) <= result)
result -= digit * (int) Math.pow(10, end - i);
else
result = Integer.MIN_VALUE;
}
}

return result;
}

Code (C++):
class Solution {
public:
int atoi(const char *str) {
if (str == NULL) {
return 0;
}
string number(str);
if(number.size() == 0)
return 0;

int i = 0;
for(; i < number.size(); ++i) {
if(!isspace(number[i])) {
break;
}
}
number = number.substr(i);
int result = 0;

bool negate = false;
char sign = number[0];

if (sign == '+' || sign == '-') {
if (sign == '-') {
negate = true;
}
number = number.substr(1);
}

int length = number.size();
int start = -1;
int index = 0;
for (; index < length; index++) {
char a = number[index];
if (a >= '0' && a <= '9') {
if(start == -1)
start = index;
} else {
break;
}
}
int end = index - 1;

if (start == -1)
return 0;

for (int i = start; i <= end; ++i) {
char a = number[i];
int digit = a - '0';
if (!negate) {
if (result + digit * (int) pow(10, end - i) >= result)
result += digit * (int) pow(10, end - i);
else
result = INT_MAX;
} else {
if (result - digit * (int) pow(10, end - i) <= result)
result -= digit * (int) pow(10, end - i);
else
result = INT_MIN;
}
}

return result;
}
};