Monthly Archives: October 2012

Minimum matrix multiplication

Given 2 arrays A,B, where x(A.length) < y(B.length), we want to insert (y – x) 0’s to A at various places such that A*B is minimum. For instance, if A = (1, -1) and B = (1,2, 3, 4), then inserting two … Continue reading

Posted in Array and linked list, Dynamic programming | Leave a comment

String rotation

String rotate by k position. For example, “abcdefg” and k=2. The result should be “cdefgab”.  C++: 01 void reverse(char* start, char* end) 02 { 03     while(start<end){ 04         char tmp=*start; 05         *start=*end; 06        … Continue reading

Posted in String | Leave a comment

Reverse a sentence.

Reverse a sentence. For example: “I am a student.”==>”student. a am I”.  C++: 01 void reverse(char* start, char* end) 02 { 03     while(start<end){ 04         char tmp=*start; 05         *start=*end; 06         *end=tmp; 07    … Continue reading

Posted in String | Leave a comment

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced. An example of a height-balanced tree. A height-balanced tree is a tree whose subtrees differ in height by no more than one and the subtrees are height-balanced, too. C++: 01 bool isBalan(TreeNode … Continue reading

Posted in Recursive, Tree | Leave a comment

Quick sort

C++: 01 void quicksort(int A[], int l, int u) 02 { 03   int i, m; 04   if(l>=u) return; 05   swap(A, l, randint(l,u)); 06   m=l; 07   for(i=l+1;i<=u;i++) 08     if(A[i]<A[l]) 09       swap(A,++m,i); 10   swap(A,l,m); 11   quicksort(l,m–1); 12   quicksort(m+1,u); 13 }

Posted in Divide and Conquer | Leave a comment