Thursday, June 2, 2016

interleavings of strings 
Void printRecursive(string str1, string str2, ref  string result, int m, int n, int index) 
If (m==0&& n==0) Console.Write(result); 
If (m != 0){ 
result[index] = str1[0]; 
printRecursive(str1.substring(1), str2, result, m-1, n, index+1); 
If ( n!= 0){ 
result[index] = str2[0]; 
printRecursive(str1, str2.substring(1), result, m. n-1, index+1); 

Given a linked list, reverse alternate nodes and append at theend 
Input 1->2->3->4->5->6 
Output 1->3->5->6->4->2 (evens are reversed) 
Void ReverseEven(Node odd) 
If (odd == null || odd.next == null || odd.next.next == null) return; 
Node even = odd.next; 
Odd.next= odd.next.next; 
Odd = odd.next; 
Even.next = null; 
While(odd && odd.next) 
Node temp = odd.next.next; 
Odd.next.next = even; 
Even = odd.next; 
Odd.next = temp; 
If (temp != null) 
  Odd = temp; 

Odd.next = even; 
}

Given a binary search tree, find the number of pairs whose sum of two nodes values equals to k
One method is to do an inorder traversal and serialize the tree to a sorted array
int GetCountPairs(List<int> num, int sum)
{
int count = 0;
int start = 0;
int end = nums.Count;
for (int i =0; i< num.Count; i++)
{
  int pair = find(num, sum-nums[i]); // binary chop
   if (pair != -1)
        count +=1 ;
}
return count;
}
or advance start and end as long as their sum is greater than target.
the same thing may be applied to tree with the following:
find inorder node as n1
find reverse of node as n2
if n1 != n2 and their sum is equal to target increment 1
else if sum < target take next inorder
else if sum > target take reverse of inorder
if inorder is exhausted then there are no more
Assuming no duplicates
int GetCountPairs(List<int> num, int sum)
{
int count = 0;
int start = 0;
int end = nums.Count - 1;
While (start < end){
Int total = nums [start] +nums [end]
If (Total == sum)
{
 Count+=1;
Start++;
End- -;
}
If (Total  < sum)
{
Start++;
}else {
End- -;
}
}
return count;
}

No comments:

Post a Comment