Tuesday, April 12, 2011

WAP Create a singly linked list of Leaf nodes from a binary tree

include

struct node
{
struct node *left, *right;
int data;

};


void LeafLinked(struct node *t, struct node **prevLeaf, struct node **head)
{
if(t)
{

if(t->left == NULL && t->right == NULL)
{ //leaf

if(*head == NULL)
*head = t;

else if(*prevLeaf)
(*prevLeaf)->next = t;

*prevLeaf = t;
}
else { //at least one child
LeafLinked(t->left, prevLeaf, head);
LeafLinked(t->right, prevLeaf, head);
}
}
}


/*Utilities*/

struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

inline void printList(struct node *t)
{
while(t)
{
printf("%d ", t->data);
t = t->next;
}
printf("\n");
}

int main()
{
/*level 0*/
struct node *t = newNode(10);

/*level 1*/
t->left = newNode(20);
t->right = newNode(30);


/*level 2*/
t->left->left = newNode(40);
t->left->right = newNode(70);
t->right->left = newNode(50);
t->right->right = newNode(60);

/*level 3*/
t->left->left->left = newNode(70);
t->right->right->left = newNode(60);
t->right->right->right = newNode(160);

/*Empty List head*/
struct node *head = NULL, *prevLeaf = NULL;

/*Convert tree to list*/
LeafLinked(t, &prevLeaf, &head);

/*print list*/
printList(head);


return 0;
}

Rune Here https://ideone.com/UOakN

Project Euler problem 16 -What is the sum of the digits of the number 2^1000?

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?


The problem no. 16 in Project Euler required us to find the sum of all the digits of the number 2^{1000}. Well, a no brainer would be to use the BigInteger and find the number by multiplication. I wanted a better solution.

But my knowledge and wits failed me. I must accept taking help on this one. I googled up a bit and found a very neat way of exponentiation. The basic funda is this:

2^n = 2 * 2^{n-1}

=> 2^n = 2^{n-1} + 2^{n-1}

So at any given time, if we have an array of digits of say 2^p, then getting 2^{p+1} is as simple as doubling all the digits and adjusting the carry-overs. The same principle can be easily extended to deal with any base.

class Problem_16 {
public long sumOfDigits(int base, int exp) {
int numberOfDigits = (int) Math.ceil(exp * Math.log10(base));
System.out.println(numberOfDigits);
int[] digits = new int[numberOfDigits];
digits[0] = base;
int currentExp = 1;


while (currentExp < exp) {
currentExp++;
int carry = 0;
for (int i = 0; i < digits.length; i++) {
int num = base * digits[i] + carry;
digits[i] = num % 10;
carry = num / 10;
}
}

long sum = 0;
for (int digit : digits)
sum += digit;


return sum;
}

public static void main(String[] args) {
int base = 2;
int exp = 10;
System.out.println(new Problem_16().sumOfDigits(base, exp));
}
}


Run here https://ideone.com/pYciv

Project Euler Problem 8- Finding product of 5 Consecutive in 1000 Digit Number

Source http://projecteuler.net/index.php?section=problems&id=8

public class Problem_8 {
public int getMaxProductOfFiveConsequtiveDigits(String[] nums) {
int maxProduct = 0;


for (String num : nums) {
int length = num.length();
if (length < 5)
continue;
int[] n = new int[5];
for (int i = 0; i < 5; i++)
n[i] = num.charAt(i) - '0';
int cycle = 5;
while (cycle < length) {
int prod = n[0] * n[1] * n[2] * n[3] * n[4];
if (prod > maxProduct)
maxProduct = prod;
n[cycle % 5] = num.charAt(cycle) - '0';
cycle++;
}
}

return maxProduct;
}

public static void main(String[] args) {
String[] nums = ("73167176531330624919225119674426574742355349194934"
+ "96983520312774506326239578318016984801869478851843"
+ "85861560789112949495459501737958331952853208805511"
+ "12540698747158523863050715693290963295227443043557"
+ "66896648950445244523161731856403098711121722383113"
+ "62229893423380308135336276614282806444486645238749"
+ "30358907296290491560440772390713810515859307960866"
+ "70172427121883998797908792274921901699720888093776"
+ "65727333001053367881220235421809751254540594752243"
+ "52584907711670556013604839586446706324415722155397"
+ "53697817977846174064955149290862569321978468622482"
+ "83972241375657056057490261407972968652414535100474"
+ "82166370484403199890008895243450658541227588666881"
+ "16427171479924442928230863465674813919123162824586"
+ "17866458359124566529476545682848912883142607690042"
+ "24219022671055626321111109370544217506941658960408"
+ "07198403850962455444362981230987879927244284909188"
+ "84580156166097919133875499200524063689912560717606"
+ "05886116467109405077541002256983155200055935729725"
+ "71636269561882670428252483600823257530420752963450").split("0");
System.out.println((new Problem_8()).getMaxProductOfFiveConsequtiveDigits(nums));
}
}


Run herer for Smaller Input https://ideone.com/SLY30

Project Euler Problem 67-Finding Maximum Sum in Triangle

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)




The 18th and the 67th problems in Project Euler are one and the same. The only difference is in the input test case. The problem 18 has a smaller input and 67 has a large input. For the explanation purpose, I’ll consider problem 18. The code without any modification can be extended to 67th problem.

Given a triangle of numbers, the objective is to determine the maximum sum along paths descending from the apex of the triangle to the base. Consider the example:

3

7 4

2 4 6

8 5 9 3

The maximum sum occurs along the path 3-7-4-9.

The problem required us to determine the maximum sum for any given triangle. Also an interesting thing is mentioned about the problem, in case you were considering a brute force method of checking every path:

It is not possible to try every route to solve this problem (where the base of the triangle has 100 numbers), as there are 2^(99) altogether! If you could check one trillion (10^(12)) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

Being forewarned, I never once gave a thought to the brute force solution.

This problem was not as tricky as they tried to sound it. The solution is quite easy to see. I’ll run you through the idea as it formed in my mind. I used the top-to-bottom approach for forming the idea and coming up with the solution, and then implemented the solution in bottom-to-top sweep. I hope you have realized that a greedy solution will not work here.

Consider the triangle given above. I’ll work out the maximum path for it from top to bottom. We start with 3. We may choose either 7 or 4. To help make this choice, consider the two triangles with apex 7 and the other with 4. So we have two smaller triangles of height 3 each. Say the maximum length for the triangle with apex 7 is x and with apex 4 is y. If x > y, we choose 7 as the next on the path, else 4.

Thus, at every step we form two triangle of height 1 smaller, and choose the apex which has the larger sum. Implemented as it is will give us the recursive solution. To get an iterative solution to this problem, one could traverse from bottom-to-top. The bottom-to-top approach is also simple. It is greedy in approach.

Consider the penultimate row, specifically the triangle with 2 as apex and 8, 5 as the base. The maximum sum in this triangle is 2+8 = 10. Replace 2 with 10. Do the same for all the triangles formed with the penultimate layer as the apex. Thus our triangle reduces to

3

7 4

10 13 15

You know what to do next. Keep applying the same till the apex of the original triangle has the maximum sum.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Problem_18 {
private static int heightOfTree = 100;
private final String fileName = "problem_67.in";
private int[][] tree;

public int maxValue() throws IOException {
readTree();

for (int i = Problem_18.heightOfTree - 2; i >= 0; i--)
for (int j = 0; j <= i; j++)
tree[i][j] += tree[i + 1][j] > tree[i + 1][j + 1] ? tree[i + 1][j] : tree[i + 1][j + 1];

return tree[0][0];
}

private void readTree() throws IOException {
tree = new int[Problem_18.heightOfTree][];

BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < Problem_18.heightOfTree; i++) {
tree[i] = new int[i + 1];
String[] values = bufferedReader.readLine().split(" ");
for (int j = 0; j <= i; j++)
tree[i][j] = Integer.parseInt(values[j]);
}
}

public static void main(String[] args) throws IOException {
System.out.println(new Problem_18().maxValue());
}
}

Project Euler Problems Finding Maximum Sum In Triangle From Top to Bottom

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Problem_18 {
private static int heightOfTree = 100;
private final String fileName = "problem_67.in";
private int[][] tree;

public int maxValue() throws IOException {
readTree();

for (int i = Problem_18.heightOfTree - 2; i >= 0; i--)
for (int j = 0; j <= i; j++)
tree[i][j] += tree[i + 1][j] > tree[i + 1][j + 1] ? tree[i + 1][j] : tree[i + 1][j + 1];

return tree[0][0];
}

private void readTree() throws IOException {
tree = new int[Problem_18.heightOfTree][];

BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < Problem_18.heightOfTree; i++) {
tree[i] = new int[i + 1];
String[] values = bufferedReader.readLine().split(" ");
for (int j = 0; j <= i; j++)
tree[i][j] = Integer.parseInt(values[j]);
}
}

public static void main(String[] args) throws IOException {
System.out.println(new Problem_18().maxValue());
}
}

Monday, April 11, 2011

WAP to reorder linked list as even elements followed by odd elements or Vice versa

#include
#include

/* Link list node */
struct node
{
int data;
struct node* next;
};

void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */
(*head_ref) = new_node;
}

//struct node*
void even_odd(struct node *current)
{
struct node* even=NULL;
struct node* odd=NULL;
struct node* oddstart=NULL;
//struct node* current=*head;

while(current)//partition linked list in two part
{
if((current->data)&1)//%2!=0)
{
if(odd)
odd->next=current;
else
oddstart=current;

odd=current;
}
else
{
if(even)
even->next=current;
even=current;

}

current=current->next;
}


if(even)
even->next=oddstart;// append to odd-starting position

if(odd)
odd->next=NULL;////make odd last equal to null;


}

/* Utility function to print a linked list */
void printList(struct node *head)
{
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
printf("\n");
}

/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;

push(&head, 12);
push(&head, 4);
push(&head, 12);
push(&head, 3);
push(&head, 16);
push(&head, 13);
push(&head, 8);
push(&head, 16);
push(&head, 15);
push(&head, 5);

even_odd(head);

printList(head);


}


Run Here

WAP to Fine Min Distance between two Number in Different List , Each Word May Occur at Differnt Position

You have two lists, each containing position of a word in some document. Write a program that returns minimum distance between the words in the document.
For example: Suppose X occurs at places {2, 3, 5, 10, 12, 16, 19, 20} and Y occurs at {8, 14, 27, 29}, then the minimum distance between X and Y is 1 (X=12,Y=14 OR X=16,Y=14).


#include
#include
#include

int min_Dist(int a[], int m, int b[], int n)
{

int i = 0,j= 0,min = INT_MAX,cur;

while(i < m && j < n)
{
cur = abs(a[i] - b[j]);

if(cur min=cur;
else
min=min;

if(a[i] < b[j])
i++;
else
j++;
}

return min;
}

int main() {

int a[] ={2, 3, 5, 10, 12, 16, 19, 20};//{2, 3, 5, 11, 18, 19, 20};
int b[]= {8, 14, 27, 29};//{15, 24, 27, 29};
int a_size=sizeof(a)/sizeof(int);
int b_size=sizeof(b)/sizeof(int);

printf("%d\n", min_Dist(a,a_size,b,b_size));

return 0;
}


Run Here https://ideone.com/5qIcB

Design A DS That Support Insert, delete, Get Operation in O(1) e.g Consant Time

Design a Data Structure with following operations
1.Insert(X) -> insert X if X not present
2.Delete(X) -> delete X if X present
3.Get() -> return any element if it is present

all operations in O(1).
No memory constraint.

Init:

k=0

Insert X:

k = k+1 mod m;
A[X] = k;
B[k] = X;

Search X:

return (A[X] < m) and (B[A[X]] == X)

Delete X:

A[X] = 0;
B[k] = 0;
k = k-1;

Sunday, April 10, 2011

WAP to Calculate The Next Palindrom of Given Number Need not to be a Palindrome

#include
#include
#include

using namespace std;

//result = s + 1
void SumOne (string &s, string &result)
{
int sum, carry = 1;
for (string::reverse_iterator p = s.rbegin(); p != s.rend(); p++)
{
sum = carry + (*p - '0') ;
carry = sum / 10;
result.push_back ('0' + sum%10 );
}
if (carry) result.push_back ('1') ;
reverse (result.begin(), result.end() );
}

int main()
{

string number, left, right, revLeft ;
int tcase=0;
cin >>tcase;

int i=0;

for(i=0;i {

cin >> number ;
int n = number.size();

left = n/2 > 0 ? number.substr (0, n/2) : "0" ;
right = n/2 > 0 ? number.substr ((n+1)/2, n/2): "0" ;

revLeft = left;
reverse (revLeft.begin(), revLeft.end() );

if ( revLeft.compare (right) > 0 )
{
number.replace ((n+1)/2, n/2, revLeft );
}
else
{
if ( number[(n-1)/2] != '9' )
{
number[(n-1)/2]++; //for number of even digits this modifies "left"
revLeft = number.substr (0, n/2) ;
reverse (revLeft.begin(), revLeft.end() );
number.replace ((n+1)/2, n/2, revLeft);
}
else
{
string nextSum ;
SumOne ( left, nextSum);

if ( nextSum.size() > left.size() ) { //for special pattern: "99999" or "999999"
number = "11";
number.insert (1, n-1, '0');
}
else {
if ( n % 2 ) number [(n-1)/2] = '0'; //for number like 52960
number.replace (0, nextSum.size(), nextSum);
reverse (nextSum.begin(), nextSum.end());
number.replace ( (n+1)/2, nextSum.size(), nextSum );
}
}
}

cout << number << endl;

}

return 0;
}

TC O(n)
Sc O(1)
Run Here http://ideone.com/sOkFE

WAP to Print New Binary Tree in which each njode has sum of its left & right subtree , from Given BT

#include
#include

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}


struct node* sumSubTree(struct node** root)
{
int LeftOld,RightOld;
struct node *l,*r;
if((*root) == NULL || ((*root) -> left== NULL && (*root)->right == NULL))
return NULL;
else
{
LeftOld = (*root)->left->data;
RightOld = (*root)->right->data;
l = sumSubTree(&(*root )->left);
r = sumSubTree(&(*root)->right);
(*root)->data = LeftOld + RightOld;
if(!l)
(*root)->data += l->data;
if(!r)
(*root)->data += r->data;
return *root;
}

}

/* Given a binary tree, print its nodes in inorder*/
void printPreorder(struct node* node)
{
if (node == NULL)
return;

/* first print data of node */
printf("%d ", node->data);

/* then recur on left sutree */
printPreorder(node->left);

/* now recur on right subtree */
printPreorder(node->right);
}

int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

root=sumSubTree(&root);

printf("\n Preorder traversal of binary tree is \n");
printPreorder(root);



getchar();
return 0;
}

Run Here https://ideone.com/irlOz