I did a few mock interview questions with my roommate today. Here’s some of what we went through.
#1 Find the height of a tree
#1 Find the height of a tree struct Node { Node* left; Node* right; int data; } int FindHeight(Node* head, int depth) { if( head == NULL ) reutrn depth; return max(FindHeight(head->left, depth + 1), FindHeight(head->right, depth + 1)); }
#2 Find the largest palindrome product of three digits [100, 999].
//#2 Find the largest palindrome product of 3 digits // bool IsPalindrome(int value) { string stringVal; atoi(value, stringVal); for(int a = 0, b = stringVal.size(); a != b; ++a, --b) { if(stringVal[a] != stringVal[b]) return false; } return true; } int FindLargestPalindrome() { // [100, 999] for(int a = 999; a > 0; --a) { for(int b = 999; b > 0; --b) { int result = a*b; if(IsPalindrome(result)) reutrn result; } } return -1; }
# Detect rectangle overlap in one check.
// #3 Detect rectangle overlap in one check struct Point { int x; int y; }; struct Rect { Point TopLeft; Point BottomRight; }; bool IsOverlapped(Rect r1, Rect r2) { // r1 intersects with r2 if(r1.BottomRight.x > r2.TopLeft.x && r1.TopLeft.x < r2.BottomRight.x && r1.BottomRight.y < r2.TopLeft.y && r1.TopLeft.y > r2.BottomRight.y) return true; }
#4 Return the middle element of a singly linked list in one pass
#4 Return the middle element of a singly linked list in one pass Node* MiddleElement(Node* head) { Node* step1 = head; Node* step2 = head; while(step2 != NULL) { step1 = step1->next; if(step2->next) // This check is to avoid over stepping the null termination step2 = step2->next->next; else step2 = step2->next; { return step1; }