This one is easy. Merge sort can solve this problem.
See the following code for the merge sort from bottom to top
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *loop_list(ListNode *head, int len){
// There are len nodes from head(inclusive) to ret(exclusive)
while(head != NULL && len-- > 0) head = head -> next;
return head;
}
ListNode *merge(ListNode *head, int len){
// Merge len nodes beginning from head->next(inclusive), and return the last node.
if(head == NULL || head -> next == NULL) return NULL;
ListNode *a_beg = head -> next;
ListNode *a_end = loop_list(a_beg, len/2 - 1);
if(!a_end) return NULL;
ListNode *b_beg = a_end -> next;
a_end -> next = NULL;
ListNode *b_end = loop_list(b_beg, len/2 - 1);
ListNode *new_end = b_end == NULL ? NULL : b_end -> next;
if(b_end != NULL) b_end -> next = NULL;
ListNode *loop = head;
ListNode *a_loop = a_beg;
ListNode *b_loop = b_beg;
while(a_loop || b_loop){
ListNode *next;
if(!a_loop) {
next = b_loop;
}
else if(!b_loop){
next = a_loop;
}
else next = (a_loop -> val < b_loop -> val) ? a_loop : b_loop;
loop -> next = next;
loop = loop -> next;
if(next == a_loop){
a_loop = a_loop -> next;
}
else if(next == b_loop){
b_loop = b_loop -> next;
}
}
loop -> next = new_end;
return loop;
}
ListNode *sortList(ListNode *head) {
ListNode *fake_head = new ListNode(0);
fake_head -> next = head;
int num_merge = 0;
for(int len = 2; true; len *= 2){
num_merge = 0;
ListNode *loop = fake_head;
while(loop && loop->next){
loop = merge(loop, len);
num_merge ++;
}
if(num_merge <= 1) break;
}
head = fake_head -> next;
delete fake_head;
return head;
}
};
Thursday, December 19, 2013
Leetcode: Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
The following is a O(n^2 lg n) algorithm because I use TreeMap instead of HashMap.
If I use HashMap, then the run time is O(n^2). But I did not find a way doing better than O(n^2).
Another question is that to use HashMap in java I need to define my own equals() and hashcode() functions, which is quite annoying. Especially hashcode() function, any one have a idea how to produce a good hashcode() function for this?
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.*;
class Slope implements Comparable<Slope>{
int x;
int y;
Slope(int a, int b){
if(b<0){
a *= -1;
b *= -1;
}
x = a; y = b;
}
public int compareTo(Slope other){
return this.x * other.y - this.y * other.x;
}
}
public class Solution {
int numPointsCentered(Point[] points, int id){
Map<Slope, Integer> counts = new TreeMap<Slope, Integer>();
int num_same_point = 0;
int return_max = 1;
for(int i = 0; i < points.length; i++){
if (i==id) continue;
if (points[i].x==points[id].x && points[i].y==points[id].y){
num_same_point++;
continue;
}
Slope slope = new Slope(points[i].x - points[id].x, points[i].y - points[id].y);
if(counts.containsKey(slope)){
counts.put(slope, counts.get(slope) + 1);
}else{
counts.put(slope, 2);
}
return_max = Math.max(return_max, counts.get(slope));
}
return return_max + num_same_point;
}
public int maxPoints(Point[] points) {
int num_points = 0;
for(int i = 0; i < points.length; i++){
int new_center_points = numPointsCentered(points, i);
num_points = Math.max(num_points, new_center_points);
}
return num_points;
}
}
The following is a O(n^2 lg n) algorithm because I use TreeMap instead of HashMap.
If I use HashMap, then the run time is O(n^2). But I did not find a way doing better than O(n^2).
Another question is that to use HashMap in java I need to define my own equals() and hashcode() functions, which is quite annoying. Especially hashcode() function, any one have a idea how to produce a good hashcode() function for this?
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.*;
class Slope implements Comparable<Slope>{
int x;
int y;
Slope(int a, int b){
if(b<0){
a *= -1;
b *= -1;
}
x = a; y = b;
}
public int compareTo(Slope other){
return this.x * other.y - this.y * other.x;
}
}
public class Solution {
int numPointsCentered(Point[] points, int id){
Map<Slope, Integer> counts = new TreeMap<Slope, Integer>();
int num_same_point = 0;
int return_max = 1;
for(int i = 0; i < points.length; i++){
if (i==id) continue;
if (points[i].x==points[id].x && points[i].y==points[id].y){
num_same_point++;
continue;
}
Slope slope = new Slope(points[i].x - points[id].x, points[i].y - points[id].y);
if(counts.containsKey(slope)){
counts.put(slope, counts.get(slope) + 1);
}else{
counts.put(slope, 2);
}
return_max = Math.max(return_max, counts.get(slope));
}
return return_max + num_same_point;
}
public int maxPoints(Point[] points) {
int num_points = 0;
for(int i = 0; i < points.length; i++){
int new_center_points = numPointsCentered(points, i);
num_points = Math.max(num_points, new_center_points);
}
return num_points;
}
}
Friday, October 11, 2013
Interview : a strategy to stop flipping the poker and win
Question:
You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top to bottom. You can stop me during this whole process, based on your memory of the previous cards you have seen. If you stop me, and there are still cards left in the deck, if the next unshown card is red, you get one dollar from me, otherwise if the next unshown card is black, you give me one dollar; if no cards left in the deck, you get one dollar if the last card is red, and you give one dollar if the last card is black.
Is there a strategy for you to win with probability larger than 50%?
Sol:
There is not strategy for that. Think the game in a different way: when you stop me, suppose instead of deciding whether you win or lose based on the next unshown card, we decide whether you win or lose based on the last card in the deck: if the last card is red you get one dollar, otherwise if it is black I get one dollar. The two games are the same. But for the latter, whatever strategies you choose the probability for you to win is always 50%, and so does the former.
You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top to bottom. You can stop me during this whole process, based on your memory of the previous cards you have seen. If you stop me, and there are still cards left in the deck, if the next unshown card is red, you get one dollar from me, otherwise if the next unshown card is black, you give me one dollar; if no cards left in the deck, you get one dollar if the last card is red, and you give one dollar if the last card is black.
Is there a strategy for you to win with probability larger than 50%?
Sol:
There is not strategy for that. Think the game in a different way: when you stop me, suppose instead of deciding whether you win or lose based on the next unshown card, we decide whether you win or lose based on the last card in the deck: if the last card is red you get one dollar, otherwise if it is black I get one dollar. The two games are the same. But for the latter, whatever strategies you choose the probability for you to win is always 50%, and so does the former.
Interview : Expected time to see a bus
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly random time. What is the expected bus waiting time?
Sol: image uniformly put a point at a line with length 10, so the expected waiting time is 5.
Now suppose there is a ice cream shop at the bus loop. Whenever the bus is close to the ice cream shop, the driver will flip a coin and decide whether to go eating an ice cream or not. It takes 10 mins for the driver to eat the ice cream. What is the expected bus waiting time if a guy arrives at a bus stop uniformly.
Sol: the key is to consider what uniform arriving time means. The bus is running either on a 10min-loop or a 20min-loop, each with probability 1/2. The bus keeps running, and the guy can arrive at any time between 0am - 24pm, uniformly. The time for the bus to be in a 20min-loop is two times larger than the time for a 10min-loop. So each day 2/3 of the time the bus is in a 20min-loop, and 1/3 of the time the bus is in a 10min-loop.
Thus, the probability for the guy to arrive when the bus is in a 20min-loop is 2/3. Expected waiting time is 10 for the 20min-loop and 5 for the 10min-loop. So the combined expected waiting time is
2/3 * 10 + 1/3 * 5
Sol: image uniformly put a point at a line with length 10, so the expected waiting time is 5.
Now suppose there is a ice cream shop at the bus loop. Whenever the bus is close to the ice cream shop, the driver will flip a coin and decide whether to go eating an ice cream or not. It takes 10 mins for the driver to eat the ice cream. What is the expected bus waiting time if a guy arrives at a bus stop uniformly.
Sol: the key is to consider what uniform arriving time means. The bus is running either on a 10min-loop or a 20min-loop, each with probability 1/2. The bus keeps running, and the guy can arrive at any time between 0am - 24pm, uniformly. The time for the bus to be in a 20min-loop is two times larger than the time for a 10min-loop. So each day 2/3 of the time the bus is in a 20min-loop, and 1/3 of the time the bus is in a 10min-loop.
Thus, the probability for the guy to arrive when the bus is in a 20min-loop is 2/3. Expected waiting time is 10 for the 20min-loop and 5 for the 10min-loop. So the combined expected waiting time is
2/3 * 10 + 1/3 * 5
Thursday, October 10, 2013
understand pure virtual function, abstract class, and virtual function.
See the following program:
#include <iostream>
using namespace std;
class MathSymbol {
public:
virtual void doOperation() = 0; // pure virtual class, so MathSymbol is a abstract class
virtual void print(){
cout<<"print MathSymbol"<<endl;
}
void move(){
cout<<"move MathSymbol"<<endl;
}
};
class B : public MathSymbol {
public:
void doOperation(){
cout<<"Operation in B"<<endl;
}
void print(){
cout<<"print B"<<endl;
}
void move(){
cout<<"move B"<<endl;
}
};
class C : public MathSymbol {
public:
void doOperation(){
cout<<"Operation in C"<<endl;
}
void print(){
cout<<"print C"<<endl;
}
void move(){
cout<<"move C"<<endl;
}
};
int main(){
// MathSymbol a; // this is error. because MathSymbol is abstract.
MathSymbol *pa = NULL;
B b, *pb = &b;
C c, *pc = &c;
MathSymbol* array[] = {pb,pc};
int len = 2;
for(int i = 0; i < len; i++){
array[i] -> doOperation();
}
for(int i = 0; i < len; i++){
array[i] -> print();
}
for(int i = 0; i < len; i++){
array[i] -> move();
}
return 0;
}
Its running result is:
Operation in B
Operation in C
print B
print C
move MathSymbol
move MathSymbol
#include <iostream>
using namespace std;
class MathSymbol {
public:
virtual void doOperation() = 0; // pure virtual class, so MathSymbol is a abstract class
virtual void print(){
cout<<"print MathSymbol"<<endl;
}
void move(){
cout<<"move MathSymbol"<<endl;
}
};
class B : public MathSymbol {
public:
void doOperation(){
cout<<"Operation in B"<<endl;
}
void print(){
cout<<"print B"<<endl;
}
void move(){
cout<<"move B"<<endl;
}
};
class C : public MathSymbol {
public:
void doOperation(){
cout<<"Operation in C"<<endl;
}
void print(){
cout<<"print C"<<endl;
}
void move(){
cout<<"move C"<<endl;
}
};
int main(){
// MathSymbol a; // this is error. because MathSymbol is abstract.
MathSymbol *pa = NULL;
B b, *pb = &b;
C c, *pc = &c;
MathSymbol* array[] = {pb,pc};
int len = 2;
for(int i = 0; i < len; i++){
array[i] -> doOperation();
}
for(int i = 0; i < len; i++){
array[i] -> print();
}
for(int i = 0; i < len; i++){
array[i] -> move();
}
return 0;
}
Its running result is:
Operation in B
Operation in C
print B
print C
move MathSymbol
move MathSymbol
One example explaining the virtual function
Virtual function will be realized after the it is called according to the object associated with it
Non virtual function will be realized by the compiler before the function is called.
See the program below:
#include <iostream>
using namespace std;
class A {
public:
void move(){
cout<<"move A"<<endl;
}
virtual void print(){
cout<<"I am A"<<endl;
};
};
class B : public A {
public:
void move(){
cout<< "move B"<< endl;
}
void print(){
cout<<"I am B"<<endl;
}
};
class C : public A {
public:
void move(){
cout<<"move C"<<endl;
}
void print(){
cout<<"I am C"<<endl;
}
};
int main(){
A a, *pa = &a;;
pa->print();
B b, *pb = &b;
C c, *pc = &c;
cout<<endl;
pb->move();
((A*)pb)->move();
cout<<endl;
pb->print();
((A*)pb)->print();
cout<<endl;
pc->print();
((A*)pc)->print();
cout<<endl;
A* array[] = {&a,&b,&c};
int len = 3;
for(int i = 0; i < len; i++){
array[i]->print();
}
cout<<endl;
for(int i = 0; i < len; i++){
array[i]->move();
}
return 0;
}
The running result is listed as:
I am A
move B
move A
I am B
I am B
I am C
I am C
I am A
I am B
I am C
move A
move A
move A
Non virtual function will be realized by the compiler before the function is called.
See the program below:
#include <iostream>
using namespace std;
class A {
public:
void move(){
cout<<"move A"<<endl;
}
virtual void print(){
cout<<"I am A"<<endl;
};
};
class B : public A {
public:
void move(){
cout<< "move B"<< endl;
}
void print(){
cout<<"I am B"<<endl;
}
};
class C : public A {
public:
void move(){
cout<<"move C"<<endl;
}
void print(){
cout<<"I am C"<<endl;
}
};
int main(){
A a, *pa = &a;;
pa->print();
B b, *pb = &b;
C c, *pc = &c;
cout<<endl;
pb->move();
((A*)pb)->move();
cout<<endl;
pb->print();
((A*)pb)->print();
cout<<endl;
pc->print();
((A*)pc)->print();
cout<<endl;
A* array[] = {&a,&b,&c};
int len = 3;
for(int i = 0; i < len; i++){
array[i]->print();
}
cout<<endl;
for(int i = 0; i < len; i++){
array[i]->move();
}
return 0;
}
The running result is listed as:
I am A
move B
move A
I am B
I am B
I am C
I am C
I am A
I am B
I am C
move A
move A
move A
Find the second largest element in an array with the minimum number of comparisons
I meet this question in an interview. It is actually a famous problem, whose solution is available here .
Here my thinking is provided.
1, The simplest case, suppose there are four elements, a,b,c,d, the minimum number of comparisons is 4:
a < b, c < d -> b < d -> max(b,c) is the second largest element.
That is, we compare (a,b), (c,d) to get the largest values b,d, then find the largest value d, the second largest value is in the set of all elements that have been compared with d, that is, b or c.
2, Suppose we have 2n elements: (a,b), (c,d), (e,f), ....... We have n pairs, so select the larger element in each pair to form an n-array: b,d,f....In total n comparison is needed.
Suppose our algorithm can find the largest two values from b,d,f,...., which is (b,d) with b < d, for example.
The second largest element can either be b or c, compare b vs c we get the second largest element.
Thus, if x(2n) is the number of comparisons needed for an 2n-array, we have x(2n) = n + x(n) + 1
Solve this recursive function with x(4) = 4, we get x(n) = n + log2(n) - 2.
Here my thinking is provided.
1, The simplest case, suppose there are four elements, a,b,c,d, the minimum number of comparisons is 4:
a < b, c < d -> b < d -> max(b,c) is the second largest element.
That is, we compare (a,b), (c,d) to get the largest values b,d, then find the largest value d, the second largest value is in the set of all elements that have been compared with d, that is, b or c.
2, Suppose we have 2n elements: (a,b), (c,d), (e,f), ....... We have n pairs, so select the larger element in each pair to form an n-array: b,d,f....In total n comparison is needed.
Suppose our algorithm can find the largest two values from b,d,f,...., which is (b,d) with b < d, for example.
The second largest element can either be b or c, compare b vs c we get the second largest element.
Thus, if x(2n) is the number of comparisons needed for an 2n-array, we have x(2n) = n + x(n) + 1
Solve this recursive function with x(4) = 4, we get x(n) = n + log2(n) - 2.
Thursday, March 21, 2013
Interleaving String
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
Two dimentional dynamic programming
map[i][j] = true if s1[0,i-1] and s2[0,j-1] interleaves into s3[0,i+j-1].
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
// Start typing your Java solution below
// DO NOT write main() function
if(s3.length() != s1.length() + s2.length())
return false;
boolean[][] mat = new boolean[s1.length() +1][s2.length()+1];
for(int i = 0; i < mat.length; i++){
for(int j = 0; j < mat[i].length; j++)
mat[i][j] = false;
}
mat[0][0] = true;
for(int i = 1; i <= s1.length(); i++){
if(s1.charAt(i-1) == s3.charAt(i-1)){
mat[i][0] = true;
}
else break;
}
for(int i = 1; i <= s2.length(); i++){
if(s2.charAt(i-1) == s3.charAt(i-1)){
mat[0][i] = true;
}
else break;
}
for(int i = 1; i <= s1.length(); i++){
for(int j = 1; j <= s2.length(); j++){
char c1 = s1.charAt(i-1);
char c2 = s2.charAt(j-1);
char c3 = s3.charAt(i+j-1);
if(c1 == c3) mat[i][j] |= mat[i-1][j];
if(c2 == c3) mat[i][j] |= mat[i][j-1];
}
}
return mat[s1.length()][s2.length()];
}
}
Wednesday, March 20, 2013
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.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given height = [2,1,5,6,2,3],
return 10.
using a stack, when the next height is larger, push its position into the stack, otherwise, pop a position and calculate the area of the maximum rectangle that can be formed using the height at the position.
remember: the bar right next to the top position at the stack after pop is always larger or equal to the bar at the poped position.
public class Solution {
public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
if(height==null || height.length == 0) return 0;
LinkedList<Integer> stack = new LinkedList<Integer>();
stack.add(0);
int i = 1;
int ret = height[0];
while( i < height.length + 1){
int nextv = i < height.length? height[i] : 0;
if(stack.isEmpty() || height[stack.getLast()] <= nextv)
{
stack.add(i++);
}
else{
int t = stack.removeLast();
ret = Math.max(ret, height[t] * (stack.isEmpty() ? i : i-1-stack.getLast()) );
}
}
return ret;
}
}
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.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
public class Solution {
public int trap(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A.length==0) return 0;
int i = 0; int j = A.length-1;
int lm = A[i]; int rm = A[j];
int sum = 0;
while(i<j){
if(lm <= rm){
if(A[++i] < lm) sum += lm - A[i];
else lm = A[i];
}
else{
if(A[--j] < rm) sum += rm - A[j];
else rm = A[j];
}
}
return sum;
}
}
Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
make an inorder traversal, if the value is increasing, it is a BST.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode pre;
private boolean ret;
void inorder(TreeNode root){
if(ret == false) return;
if(root==null) return;
inorder(root.left);
if(pre == null){ pre = root;}
else{
if(pre.val >= root.val){
ret = false;
return;
}
pre = root;
}
if(ret) inorder(root.right);
}
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
pre = null;
ret = true;
inorder(root);
return ret;
}
}
Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
firstorder the value will increase, so we can find the first error
backorder the value will decrease, so we can find the second error.
change it
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode first;
TreeNode second;
private TreeNode pre;
void inorder(TreeNode root){
if(first != null) return;
if(root == null) return;
inorder(root.left);
if(pre == null) pre=root;
else{
if(pre.val > root.val) {
first = pre; return;
}
pre = root;
}
if(first == null)
inorder(root.right);
}
void backorder(TreeNode root){
if(second != null) return;
if(root == null) return;
backorder(root.right);
if(pre == null) pre = root;
else{
if(pre.val < root.val) {
second = pre;
return;
}
pre = root;
}
if(second == null)
backorder(root.left);
}
public void recoverTree(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
first = null;
second = null;
pre = null;
inorder(root);
pre = null;
backorder(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Find the root, using recursive.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode buildTree(int[] a, int a1, int a2, int[] b, int b1, int b2){
if(a1 > a2 || b1 > b2) return null;
int rootval = b[b2];
int posA = a1;
while(posA <= a2){
if(a[posA] == rootval) break;
posA++;
}
TreeNode root = new TreeNode(rootval);
int posB = b1 + posA - 1 - a1;
TreeNode.left = buildTree(a,a1,posA-1,b, b1, posB);
TreeNode.right = buildTree(a,posA+1,a2,b, posB+1,b2-1);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
// Start typing your Java solution below
// DO NOT write main() function
if(inorder.length == 0) return null;
//return null;
return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
}
Subscribe to:
Posts (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Move Objects There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want ...
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/