Interview Question


Country: India




Comment hidden because of low score. Click to expand.
1
of 1 vote

1-2-3 and 4-5-6 , just traverse thru linked list as ((1*10+2)*10+3)+((4*10+5)*10+6) this should give correct result . O(n+m) where n and m are the length of linked list.

- Anonymous January 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

All the answers that are converting the list to numbers or the result to a number are false if the numbers are very large.

- Rayden January 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Another solution could be

Create reverse of the two linked lists(rev1, rev2)
Now we can easily run through these lists rev1, rev2 element by element and do additions of their corresponding values to create a new list rev3.
Also make sure to pass the carries to next element. In the end if we have carry but both lists have exhausted, we will need to create a new element for the carry also in rev3.
Reverse this new list rev3 to get the final answer.

This solution does require additional space to store the intermediate reverse lists.

- amitvyasg January 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

You are thinking both list has the same size!! and if you look and the second example you gonna see that can have a list with different sizes!! the solutions are wrong if you only think and sum all the numbers on each list!

My solution
1. traverse the nodes and store each node in a seperate stack for each list.
2. for each element from each stack, put the sum in a diferent stack if one of the stack is empty continue with the other one until you have both stacks empty
3. then remove each element from the stack and add to a Linked list using the AddElement totail.

- danielpiedrahita January 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I am not assuming lists are equal, probably didn't communicate properly. If one of the will be added to next element and we will carry on with the single list for creating the new one.

I see both danielpiedrahita's and my last solution as the same in nature. Just that for me stack is implemented as a reverse linked list. How are you planning to implement the stack?

- amitvyasg January 23, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@amitvyasg, yes both solutions are in nature the same!! I didn't see your solution when I was writing mine.

the stack can be implement with reverse linked list!! but I assume that I have access to basic data structures. but if I need to build some special structure your solution can be tailored better to used the same structure as a stack and result list.
All depends of what you can used or what you need to built

- danielpiedrahita January 23, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Reverse the both lists and then send them as argument of the below function. Again reverse the list for the final result. The function handles every case.

struct node* addTwoLists (struct node* first, struct node* second)
{
    struct node* res = NULL; 
    struct node *temp, *prev = NULL;
    int carry = 0, sum;
 
    while (first != NULL || second != NULL) //while both lists exist
    {
        
        sum = carry + (first? first->data: 0) + (second? second->data: 0);        
        carry = (sum >= 10)? 1 : 0;        
        sum = sum % 10; 
      
        temp = newNode(sum);
        
        if(res == NULL)
            res = temp;
        else
            prev->next = temp;       
        prev  = temp; 
        if (first) first = first->next;
        if (second) second = second->next;
    }
 
    if (carry > 0)    // when additional carry generated, make a new node with data as carry value.
      temp->next = newNode(carry); 
  
    return res;
}

struct node *newNode(int data)
{
    struct node *new_node = (struct node *) malloc(sizeof(struct node));
    new_node->data = data;
    new_node->next = NULL;
    return new_node;
}

- nihaldps February 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. traverse the nodes and store each node in a seperate stack for each list.
2. pop nodes from two stacks, add them, and make it point to the previous added node.
3. repeat the step 2 till there are nodes in both the stacks.
4. pop non empty stack and point it to previous node. do this untill the stack has a node.

- Anonymous January 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Adding two integers may overflow. Converting the list to an integer may overflow too if the list is very long.

- Anonymous January 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Convert first list to a number
Convert second list to a number
sum the numbers
create and return new list representing the sum

#include <stdio.h>
#include <stdlib.h>

typedef struct node_type {
struct node_type *next;
int value;

} node;

int sum_of_list (node *curnode) {
int sum = 0;


while (curnode) {
sum *= 10;
sum += curnode->value;
curnode = curnode->next;
}

return sum;

}

void free_list (node *head) {
node *next = NULL;

while (head) {
next = head->next;
free (head);
head = next;
}
}

node* create_list (int value) {
node *head = NULL, *new = NULL;
int cur_value = 0;


while (value) {

cur_value = value % 10;
new = (node*) malloc(sizeof(node));
if (!new) {
printf("Not enough memory\n");
free_list(head);
return NULL;
}

new->value = cur_value;
new->next = head;
head = new;
value /= 10;
}

return head;
}


node * sum_list (node* list1, node* list2) {


int sum1 = 0, sum2 = 0;

if (!list1 && !list2) {
return NULL;
}

sum1 = sum_of_list(list1);
sum2 = sum_of_list(list2);

return create_list(sum1 + sum2);

}


main () {
char q[10];
int number1;
int number2;
node *head1 = NULL, *head2 = NULL, *sum_head = NULL;
int sum;

do {
printf("\nNumber1:");
scanf("%d", &number1);
head1 = create_list(number1);

printf("\nNumber2:");
scanf("%d", &number2);
head2 = create_list(number2);

sum_head = sum_list(head1, head2);
printf ("\nsum: %d", sum_of_list(sum_head));
free_list(head1);
free_list(head2);
free_list(sum_head);

printf("\nEnter quit or anything else to continue: ");
scanf("%s", q);
} while (strcmp(q, "quit") != 0);

- Amit Vyas January 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Adding two numbers may cause integer overflow.
Your logic will only work till 10 nodes.
We can save the numbers in strings if we were to go by your method and then add the numbers in the strings and store them in another string.

- ghantacoder January 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assumption is that they are the same length.

When you reach the end of the list (nil or null), return 0.
Otherwise, pass the remainder of the lists to the programs, adding the sum of the first two elements to each list into a new list called zs.

(defun sum-lists (xs ys zs)
    (if (= xs nil) 0
        (sum-lists (cdr xs) (cdr ys) (cons (+ (car xs) (car ys)) zs))))

- eek January 23, 2012 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More