Add two big numbers represented as linked lists without reversing the linked lists - algorithm

Suppose you have 2 big numbers represented as linked lists, how do you add them and store the result in a separate linked list.
eg
a = 2 -> 1 -> 7
b = 3 -> 4
result = 2 -> 5 -> 1
Can you add them without reversing the linked lists

Pseudocode:
Step 1. Traverse the linked lists and push the elements in two different stacks
Step 2. Pop the top elements from both the stacks
Step 3. Add the elements (+ any carry from previous additions) and store the carry in a temp variable
Step 4. Create a node with the sum and insert it into beginning of the result list

I think this's something beyond context but can be very performance incentive for the person who originally posted this question.
So here's a recommendation:
instead of using every node as a single digit of the number, use each node to store a large number(close to the size of integer) and if the highest possible number you chose to store in each node be x(your case 9) then you can view your number as a representation in base x+1.
where each digit is a number between 0 and x.
This would give you significant performance gain as the algorithm would run in O(log n) time and require the same number of nodes as against O(n) in your case , n being the number of decimal digits of the larger of two addends.
Typically for the ease of your algorithm, you can choose a power of 10 as the base which fits in the range of your integer.
For example if your number be 1234567890987654321 and you want to store it in linked list choosing the base to be 10^8 then your representation should look like:
87654321-> 4567890 -> 123(little endian)

Here's my hacky attempt in Java that runs in about O(max(len(a),len(b))). I've provided a complete sample with a very simple singly linked list implementation. It's quite late here so the code is not as nice as I'd like - sorry!
This code assumes:
That the length of the lists is known
Singly linked list
Dealing with integer data
It uses recursion to propagate the sums and carry for each digit, and sums left to right. The lists are never reversed - sums are performed left to right, and carry propagates up the recursive stack. It could be unrolled in an iterative solution, but I won't worry about that.
public class LinkedListSum {
static class LLNode {
int value;
LLNode next;
public LLNode(int value){
this.value = value;
}
public int length(){
LLNode node = this;
int count = 0;
do {
count++;
} while((node = node.next) != null);
return count;
}
public List<Integer> toList(){
List<Integer> res = new ArrayList<Integer>();
LLNode node = this;
while(node != null){
res.add(node.value);
node = node.next;
}
return res;
}
}
public static void main(String[] argc){
LLNode list_a = fromArray(new int[]{4,7,4,7});
LLNode list_b = fromArray(new int[]{5,3,7,4,7,4});
System.out.println("Sum: " + sum(list_a, list_b).toList());
}
private static LLNode fromArray(int[] arr){
LLNode res = new LLNode(0);
LLNode current = res;
for(int i = 0; i < arr.length; i++){
LLNode node = new LLNode(arr[i]);
current.next = node;
current = node;
}
return res.next;
}
private static LLNode sum(LLNode list_1, LLNode list_2){
LLNode longer;
LLNode shorter;
if(list_1.length() >= list_2.length()){
longer = list_1;
shorter = list_2;
} else {
longer = list_2;
shorter = list_1;
}
// Pad short to same length as long
int diff = longer.length() - shorter.length();
for(int i = 0; i < diff; i++){
LLNode temp = new LLNode(0);
temp.next = shorter;
shorter = temp;
}
System.out.println("Longer: " + longer.toList());
System.out.println("Shorter: " + shorter.toList());
return sum_same_length(new LLNode(0), null, longer, shorter);
}
private static LLNode sum_same_length(LLNode current, LLNode previous, LLNode longerList, LLNode shorterList){
LLNode result = current;
if(longerList == null){
previous.next = null;
return result;
}
int sum = longerList.value + shorterList.value;
int first_value = sum % 10;
int first_carry = sum / 10;
current.value = first_value;
// Propagate the carry backwards - increase next multiple of 10 if necessary
LLNode root = propagateCarry(current,previous,first_carry);
current.next = new LLNode(0);
sum_same_length(current.next, current, longerList.next, shorterList.next);
// Propagate the carry backwards - increase next multiple of 10 if necessary:
// The current value could have been increased during the recursive call
int second_value = current.value % 10;
int second_carry = current.value / 10;
current.value = second_value;
root = propagateCarry(current,previous,second_carry);
if(root != null) result = root;
return result;
}
// Returns the new root of the linked list if one had to be added (due to carry)
private static LLNode propagateCarry(LLNode current, LLNode previous, int carry){
LLNode result = null;
if(carry != 0){
if(previous != null){
previous.value += carry;
} else {
LLNode first = new LLNode(carry);
first.next = current;
result = first;
}
}
return result;
}
}

Here is a pseudo code.
list *add (list *l1, list *l2)
{
node *l3, l3_old;
while (l1 != NULL)
{
stack1.push (l1);
l1 = l1->next;
}
while (l2 != NULL)
{
stack2.push (l2);
l2 = l2->next;
}
l3_old = NULL;
while (!stack1.isempty () && !stack2.isempty ()) // at least one stack is not empty
{
l3 = get_new_node ();
l1 = stack1.pop ();
l2 = stack2.pop ();
l3->val = l1->val + l2->val;
if (l3_old != NULL)
{
l3->val = l3->val + (int)l3_old/10;
l3_old->val %= 10;
}
l3->next = l3_old;
l3_old = l3;
}
while (!stack1.isempty ())
{
l1 = stack1.pop ();
l3 = get_new_node ();
l3->val = l1->val + (int)l3_old->val/10;
l3_old->val %= 10;
l3->next = l3_old;
l3_old = l3;
}
while (!stack2.isempty ())
{
l2 = stack2.pop ();
l3 = get_new_node ();
l3->val = l2->val + (int)l3_old->val/10;
l3_old->val %= 10;
l3->next = l3_old;
l3_old = l3;
}
return l3;
}

Here is my attempt, using the two linked lists and returning the sum as a new list using recursion.
public class SumList {
int[] a1= {7,3,2,8};
int[] a2= {4,6,8,4};
LinkedList l1= new LinkedList(a1);
LinkedList l2= new LinkedList(a2);
Node num1= l1.createList();
Node num2= l2.createList();
Node result;
public static void main(String[] args) {
SumList sl= new SumList();
int c= sl.sum(sl.num1, sl.num2);
if(c>0) {
Node temp= new Node(c);
temp.next= sl.result;
sl.result= temp;
}
while(sl.result != null){
System.out.print(sl.result.data);
sl.result= sl.result.next;
}
}
int sum(Node n1, Node n2) {
if(n1==null || n2==null)
return 0;
int a1= this.getSize(n1);
int a2= this.getSize(n2);
int carry, s= 0;
if(a1>a2) {
carry= sum(n1.next, n2);
s= n1.data+carry;
}
else if(a2>a1) {
carry= sum(n1, n2.next);
s= n2.data+carry;
}
else {
carry= sum(n1.next, n2.next);
s= n1.data+n2.data+carry;
}
carry= s/10;
s=s%10;
Node temp= new Node(s);
temp.next= result;
result= temp;
return carry;
}
int getSize(Node n) {
int count =0;
while(n!=null) {
n=n.next;
count++;
}
return count;
}
}

// A recursive program to add two linked lists
#include <stdio.h>
#include <stdlib.h>
// A linked List Node
struct node
{
int data;
struct node* next;
};
typedef struct node node;
/* A utility function to insert a node at the beginning of linked list */
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;
}
/* A utility function to print linked list */
void printList(struct node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// A utility function to swap two pointers
void swapPointer( node** a, node** b )
{
node* t = *a;
*a = *b;
*b = t;
}
/* A utility function to get size of linked list */
int getSize(struct node *node)
{
int size = 0;
while (node != NULL)
{
node = node->next;
size++;
}
return size;
}
// Adds two linked lists of same size represented by head1 and head2 and returns
// head of the resultant linked list. Carry is propagated while returning from
// the recursion
node* addSameSize(node* head1, node* head2, int* carry)
{
// Since the function assumes linked lists are of same size,
// check any of the two head pointers
if (head1 == NULL)
return NULL;
int sum;
// Allocate memory for sum node of current two nodes
node* result = (node *)malloc(sizeof(node));
// Recursively add remaining nodes and get the carry
result->next = addSameSize(head1->next, head2->next, carry);
// add digits of current nodes and propagated carry
sum = head1->data + head2->data + *carry;
*carry = sum / 10;
sum = sum % 10;
// Assigne the sum to current node of resultant list
result->data = sum;
return result;
}
// This function is called after the smaller list is added to the bigger
// lists's sublist of same size. Once the right sublist is added, the carry
// must be added toe left side of larger list to get the final result.
void addCarryToRemaining(node* head1, node* cur, int* carry, node** result)
{
int sum;
// If diff. number of nodes are not traversed, add carry
if (head1 != cur)
{
addCarryToRemaining(head1->next, cur, carry, result);
sum = head1->data + *carry;
*carry = sum/10;
sum %= 10;
// add this node to the front of the result
push(result, sum);
}
}
// The main function that adds two linked lists represented by head1 and head2.
// The sum of two lists is stored in a list referred by result
void addList(node* head1, node* head2, node** result)
{
node *cur;
// first list is empty
if (head1 == NULL)
{
*result = head2;
return;
}
// second list is empty
else if (head2 == NULL)
{
*result = head1;
return;
}
int size1 = getSize(head1);
int size2 = getSize(head2) ;
int carry = 0;
// Add same size lists
if (size1 == size2)
*result = addSameSize(head1, head2, &carry);
else
{
int diff = abs(size1 - size2);
// First list should always be larger than second list.
// If not, swap pointers
if (size1 < size2)
swapPointer(&head1, &head2);
// move diff. number of nodes in first list
for (cur = head1; diff--; cur = cur->next);
// get addition of same size lists
*result = addSameSize(cur, head2, &carry);
// get addition of remaining first list and carry
addCarryToRemaining(head1, cur, &carry, result);
}
// if some carry is still there, add a new node to the fron of
// the result list. e.g. 999 and 87
if (carry)
push(result, carry);
}
// Driver program to test above functions
int main()
{
node *head1 = NULL, *head2 = NULL, *result = NULL;
int arr1[] = {9, 9, 9};
int arr2[] = {1, 8};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
// Create first list as 9->9->9
int i;
for (i = size1-1; i >= 0; --i)
push(&head1, arr1[i]);
// Create second list as 1->8
for (i = size2-1; i >= 0; --i)
push(&head2, arr2[i]);
addList(head1, head2, &result);
printList(result);
return 0;
}

1.First traverse the two lists and find the lengths of the two lists(Let m,n be the lengths).
2.Traverse n-m nodes in the longer list and set 'prt1' to the current node and 'ptr2' to beginning of the other list.
3.Now call the following recursive function with flag set to zero:
void add(node* ptr1,node* ptr2){
if(ptr1==NULL)
return;
add(ptr1->next,ptr2->next);
insertAtBegin(ptr1->data+ptr2->data+flag);
flag=(ptr1->data+ptr2->data)%10;
}
4.Now you need to add the remaining n-m nodes at the beginning of your target list, you can do it directly using a loop. Please note that for the last element in the loop you need to add the flag returned by the add() function as there might be a carry.
If your question is without using recursion:
1.Repeat the first two steps, then create your target list initalising every elements with '0'(make sure that the length of the list is accurate).
2.Traverse the two lists along with your target list(a step behind).If you find sum of two nodes greater than 10, make the value in the target list as '1'.
3.With the above step you took care of the carry. Now in one more pass just add the two nodes modulo 10 and add this value in the corresponding node of the target list.

without using stack .....
simply store the content of link list in array and perform addition and and then again put addition into link list
code :
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int value;
struct node *next;
}node;
int main()
{
printf("\nEnter the number 1 : ");
int ch;
node *p=NULL;
node *k=NULL;
printf("\nEnter the number of digit : ");
scanf("%d",&ch);
int i=0;
while(ch!=i)
{
i++;
node *q=NULL;
int a=0;
q=(node *)malloc(sizeof(node));
printf("\nEnter value : ");
scanf("%d",&a);
q->value=a;
if(p==NULL)
{
q->next=NULL;
p=q;
k=p;
}
else
{
q->next=NULL;
p->next=q;
p=q;
}
}
printf("\nEnter the number 2 : ");
int ch1;
node *p1=NULL;
node *k1=NULL;
int i1=0;
printf("\nEnter the number of digit : ");
scanf("%d",&ch1);
while(ch1!=i1)
{
i1++;
node *q1=NULL;
int a1=0;
q1=(node *)malloc(sizeof(node));
printf("\nEnter value : ");
scanf("%d",&a1);
q1->value=a1;
if(p1==NULL)
{
q1->next=NULL;
p1=q1;
k1=p1;
}
else
{
q1->next=NULL;
p1->next=q1;
p1=q1;
}
}
printf("\n\t");
int arr1[100];
int arr1_ptr=0;
while(k != NULL )
{
printf("%d\t",k->value);
arr1[arr1_ptr++]=k->value;
k=k->next;
}
printf("\n\t");
int arr2[100];
int arr2_ptr=0;
while(k1 != NULL )
{
printf("%d\t",k1->value);
arr2[arr2_ptr++]=k1->value;
k1=k1->next;
}
//addition logic ...
int result[100]={0};
int result_ptr=0;
int loop_ptr=0;
int carry=0;
arr1_ptr--;
arr2_ptr--;
if(arr1_ptr>arr2_ptr)
loop_ptr=arr1_ptr+1;
else
loop_ptr=arr2_ptr+1;
for(int i = loop_ptr ; i >= 0;i--)
{
if(arr1_ptr >= 0 && arr2_ptr >= 0)
{
if( (arr1[arr1_ptr] + arr2[arr2_ptr] + carry ) > 9 )
{
result[i]=((arr1[arr1_ptr] + arr2[arr2_ptr]+carry) % 10 );
carry = ((arr1[arr1_ptr--] + arr2[arr2_ptr--]+carry ) / 10 ) ;
}
else
{
result[i]=(arr1[arr1_ptr--] + arr2[arr2_ptr--] + carry );
carry = 0 ;
}
}
else if( !(arr1_ptr < 0 ) || !( arr2_ptr < 0 ) )
{
if( arr1_ptr < 0)
result[i]=arr2[arr2_ptr--]+carry;
else
result[i]=arr1[arr1_ptr--]+carry;
}
else
result[i]=carry;
}
/*printf("\n");
for(int i=0;i<loop_ptr+1;i++)
printf("%d\t",result[i]);
*/
node *k2=NULL,*p2=NULL;
for(int i=0;i<loop_ptr+1;i++)
{
node *q2=NULL;
q2=(node *)malloc(sizeof(node));
q2->value=result[i];
if(p2==NULL)
{
q2->next=NULL;
p2=q2;
k2=p2;
}
else
{
q2->next=NULL;
p2->next=q2;
p2=q2;
}
}
printf("\n");
while(k2 != NULL )
{
printf("%d\t",k2->value);
k2=k2->next;
}
return 0;
}

We can add them by using recursion. Assume the question is defined as follows: we have lists l1 and l2 and we want to add them by storing the result in l1. For simplicity assume that both lists have the same length (the code can be easily modified to work for different lengths). Here is my working Java solution:
private static ListNode add(ListNode l1, ListNode l2){
if(l1 == null)
return l2;
if(l2 == null)
return l1;
int[] carry = new int[1];
add(l1, l2, carry);
if(carry[0] != 0){
ListNode newHead = new ListNode(carry[0]);
newHead.next = l1;
return newHead;
}
return l1;
}
private static void add(ListNode l1, ListNode l2, int[] carry) {
if(l1.next == null && l2.next == null){
carry[0] = l1.val + l2.val;
l1.val = carry[0]%10;
carry[0] /= 10;
return;
}
add(l1.next, l2.next, carry);
carry[0] += l1.val + l2.val;
l1.val = carry[0]%10;
carry[0] /= 10;
}

Input : List a , List b
Output : List c
Most approaches here require extra space for List a and List b. This can be removed.
Reverse List a and List b so that they are represented in the reverse order (i.e., tail as head and all the links reversed) with constant space of O(1).
Then add the lists efficiently by traversing through both of them simultaneously and maintaining a carry.
Reverse List a and List b if required

Try this
/* No Recursion, No Reversal - Java */
import java.util.*;
class LinkedListAddMSB
{
static LinkedList<Integer> addList(LinkedList<Integer> num1, LinkedList<Integer> num2)
{
LinkedList<Integer> res = new LinkedList<Integer>();
LinkedList<Integer> shorter = new LinkedList<Integer>();
LinkedList<Integer> longer = new LinkedList<Integer>();
int carry = 0;
int maxlen,minlen;
if(num1.size() >= num2.size())
{
maxlen = num1.size();
minlen = num2.size();
shorter = num2;
longer = num1;
}
else
{
maxlen = num2.size();
minlen = num1.size();
shorter = num1;
longer = num2;
}
//Pad shorter list to same length by adding preceeding 0
int diff = maxlen - minlen;
for(int i=0; i<diff; i++)
{
shorter.addFirst(0);
}
for(int i=maxlen-1; i>=0; i--)
{
int temp1 = longer.get(i);
int temp2 = shorter.get(i);
int temp3 = temp1 + temp2 + carry;
carry = 0;
if(temp3 >= 10)
{
carry = (temp3/10)%10;
temp3 = temp3%10;
}
res.addFirst(temp3);
}
if(carry > 0)
res.addFirst(carry);
return res;
}
public static void main(String args[])
{
LinkedList<Integer> num1 = new LinkedList<Integer>();
LinkedList<Integer> num2 = new LinkedList<Integer>();
LinkedList<Integer> res = new LinkedList<Integer>();
//64957
num1.add(6);
num1.add(4);
num1.add(9);
num1.add(5);
num1.add(7);
System.out.println("First Number: " + num1);
//48
num2.add(4);
num2.add(8);
System.out.println("First Number: " + num2);
res = addList(num1,num2);
System.out.println("Result: " + res);
}
}

/* this baby does not reverse the list
** , it does use recursion, and it uses a scratch array */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list {
struct list *next;
unsigned value;
};
unsigned recurse( char target[], struct list *lp);
struct list * grab ( char buff[], size_t len);
unsigned recurse( char target[], struct list *lp)
{
unsigned pos;
if (!lp) return 0;
pos = recurse (target, lp->next);
/* We should do a bounds check target[] here */
target[pos] += lp->value;
if (target[pos] >= 10) {
target[pos+1] += target[pos] / 10;
target[pos] %= 10;
}
return 1+pos;
}
struct list * grab ( char *buff, size_t len)
{
size_t idx;
struct list *ret, **hnd;
/* Skip prefix of all zeros. */
for (idx=len; idx--; ) {
if (buff [idx] ) break;
}
if (idx >= len) return NULL;
/* Build the result chain. Buffer has it's LSB at index=0,
** but we just found the MSB at index=idx.
*/
ret = NULL; hnd = &ret;
do {
*hnd = malloc (sizeof **hnd);
(*hnd)->value = buff[idx];
(*hnd)->next = NULL;
hnd = &(*hnd)->next;
} while (idx--);
return ret;
}
int main (void)
{
char array[10];
struct list a[] = { {NULL, 2} , {NULL, 1} , {NULL, 7} };
struct list b[] = { {NULL, 3} , {NULL, 4} };
struct list *result;
a[0].next = &a[1]; a[1].next = &a[2];
b[0].next = &b[1];
memset(array, 0 , sizeof array );
(void) recurse ( array, a);
(void) recurse ( array, b);
result = grab ( array, sizeof array );
for ( ; result; result = result->next ) {
printf( "-> %u" , result->value );
}
printf( "\n" );
return 0;
}

Final version (no list reversal, no recursion):
#include <stdio.h>
#include <stdlib.h>
struct list {
struct list *nxt;
unsigned val;
};
struct list *sumlist(struct list *l, struct list *r);
int difflen(struct list *l, struct list *r);
struct list *sumlist(struct list *l, struct list *r)
{
int carry,diff;
struct list *result= NULL, **pp = &result;
/* If the lists have different lengths,
** the sum will start with the prefix of the longest list
*/
for (diff = difflen(l, r); diff; diff += (diff > 0) ? -1 : 1) {
*pp = malloc (sizeof **pp) ;
(*pp)->nxt = NULL;
if (diff > 0) { (*pp)->val = l->val; l= l->nxt; }
else { (*pp)->val = r->val; r= r->nxt; }
pp = &(*pp)->nxt ;
}
/* Do the summing.
** whenever the sum is ten or larger we increment a carry counter
*/
for (carry=0; l && r; l=l->nxt, r=r->nxt) {
*pp = malloc (sizeof **pp) ;
(*pp)->nxt = NULL;
(*pp)->val = l->val + r->val;
if ((*pp)->val > 9) carry++;
pp = &(*pp)->nxt ;
}
/* While there are any carries, we will need to propagate them.
** Because we cannot reverse the list (or walk it backward),
** this has to be done iteratively.
** Special case: if the first digit needs a carry,
** we have to insert a node in front of it
*/
for (diff =0 ;carry; carry = diff) {
struct list *tmp;
if (result && result->val > 9) {
tmp = malloc(sizeof *tmp);
tmp->nxt = result;
tmp->val = 0;
result = tmp;
}
diff=0;
for (tmp=result; tmp ; tmp= tmp->nxt) {
if (tmp->nxt && tmp->nxt->val > 9) {
tmp->val += tmp->nxt->val/10;
tmp->nxt->val %= 10; }
if (tmp->val > 9) diff++;
}
}
return result;
}
int difflen(struct list *l, struct list *r)
{
int diff;
for (diff=0; l || r; l = (l)?l->nxt:l, r = (r)?r->nxt:r ) {
if (l && r) continue;
if (l) diff++; else diff--;
}
return diff;
}
int main (void)
{
struct list one[] = { {one+1, 2} , {one+2, 6} , {NULL, 7} };
struct list two[] = { {two+1, 7} , {two+2, 3} , {NULL, 4} };
struct list *result;
result = sumlist(one, two);
for ( ; result; result = result->nxt ) {
printf( "-> %u" , result->val );
}
printf( ";\n" );
return 0;
}

In java i will do it this way
public class LLSum {
public static void main(String[] args) {
LinkedList<Integer> ll1 = new LinkedList<Integer>();
LinkedList<Integer> ll2 = new LinkedList<Integer>();
ll1.add(7);
ll1.add(5);
ll1.add(9);
ll1.add(4);
ll1.add(6);
ll2.add(8);
ll2.add(4);
System.out.println(addLists(ll1,ll2));
}
public static LinkedList<Integer> addLists(LinkedList<Integer> ll1, LinkedList<Integer> ll2){
LinkedList<Integer> finalList = null;
int num1 = makeNum(ll1);
int num2 = makeNum(ll2);
finalList = makeList(num1+num2);
return finalList;
}
private static LinkedList<Integer> makeList(int num) {
LinkedList<Integer> newList = new LinkedList<Integer>();
int temp=1;
while(num!=0){
temp = num%10;
newList.add(temp);
num = num/10;
}
return newList;
}
private static int makeNum(LinkedList<Integer> ll) {
int finalNum = 0;
for(int i=0;i<ll.size();i++){
finalNum += ll.get(i) * Math.pow(10,i);
}
return finalNum;
}
}

Here is my first try:
public class addTwo {
public static void main(String args[]){
LinkedListNode m =new LinkedListNode(3);
LinkedListNode n = new LinkedListNode(5);
m.appendNew(1);
m.appendNew(5);
m.appendNew(5);
n.appendNew(9);
n.appendNew(2);
n.appendNew(5);
n.appendNew(9);
n.appendNew(9 );
m.print();
n.print();
LinkedListNode add=addTwo(m,n);
add.print();
}
static LinkedListNode addTwo(LinkedListNode m,LinkedListNode n){
LinkedListNode result;
boolean flag =false;
int num;
num=m.data+n.data+(flag?1:0);
flag=false;
if(num>9){
flag=true;
}
result = new LinkedListNode(num%10);
while(m.link!=null && n.link!=null){
m=m.link;
n=n.link;
num=m.data+n.data+(flag?1:0);
flag=false;
if(num>9){
flag=true;
}
result.appendNew(num%10);
}
if(m.link==null && n.link==null){
if(flag)
result.appendNew(1);
flag=false;
}else if(m.link!=null){
while(m.link !=null){
m=m.link;
num=m.data;
num=m.data+(flag?1:0);
flag=false;
if(num>9){
flag=true;
}
result.appendNew(num%10);
}
}else{
while(n.link !=null){
n=n.link;
num=n.data;
num=n.data+(flag?1:0);
flag=false;
if(num>9){
flag=true;
}
result.appendNew(num%10);
}
}
if(flag){
result.appendNew(1);
}
return result;
}
class LinkedListNode {
public int data;
public LinkedListNode link;
public LinkedListNode(){System.out.println(this+":"+this.link+":"+this.data);}
public LinkedListNode(int data){
this.data=data;
}
void appendNew(int data){
if(this==null){
System.out.println("this is null");
LinkedListNode newNode = new LinkedListNode(data);
}
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode prev =this;
while(prev.link!=null){
prev = prev.link;
}
prev.link=newNode;
}
void print(){
LinkedListNode n=this;
while(n.link!=null){
System.out.print(n.data +"->");
n = n.link;
}
System.out.println(n.data);
}
}
result is:
3->1->5->5
5->9->2->5->9->9
8->0->8->0->0->0->1

My recursive Java implementation:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addTwoNumbers(l1, l2, 0);
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2, int carryOver) {
int result;
ListNode next = null;
if (l1 == null && l2 == null) {
if (carryOver > 0) {
return new ListNode(carryOver);
} else {
return null;
}
} else if (l1 == null && l2 != null) {
result = l2.val + carryOver;
next = addTwoNumbers(null, l2.next, result / 10);
} else if (l1 != null && l2 == null){
result = l1.val + carryOver;
next = addTwoNumbers(l1.next, null, result / 10);
} else {
result = l1.val + l2.val + carryOver;
next = addTwoNumbers(l1.next, l2.next, result / 10);
}
ListNode node = new ListNode(result % 10);
node.next = next;
return node;
}
}
Hope that helps.

/* spoiler: just plain recursion will do */
#include <stdio.h>
struct list {
struct list *next;
unsigned value;
};
struct list a[] = { {NULL, 2} , {NULL, 1} , {NULL, 7} };
struct list b[] = { {NULL, 3} , {NULL, 4} };
unsigned recurse( unsigned * target, struct list *lp);
unsigned recurse( unsigned * target, struct list *lp)
{
unsigned fact;
if (!lp) return 1;
fact = recurse (target, lp->next);
*target += fact * lp->value;
return 10*fact;
}
int main (void)
{
unsigned result=0;
/* set up the links */
a[0].next = &a[1];
a[1].next = &a[2];
b[0].next = &b[1];
(void) recurse ( &result, a);
(void) recurse ( &result, b);
printf( "Result = %u\n" , result );
return 0;
}

Related

Knight on Chess Board - Shortest Path

I'm trying to solve this problem: https://www.interviewbit.com/problems/knight-on-chess-board/#
Basically, you're given a board, a start point and an end point and have to find the shortest path. I'm trying to do BFS on the the board using the 8 possible moves a knight can make and returning the number of moves it took, or -1 if there was no solution. I'm getting a run time out of memory error. I'm not sure where the error (or potential errors) are occurring.
Edit: Previously I was getting an error because I forgot got to mark nodes as visited. I've added that in but I'm still not getting the right answer.
public class Solution {
private class Node {
int row;
int col;
int count;
public Node() {
this.row = 0;
this.col = 0;
this.count = 0;
}
public Node(int row, int col, int count) {
this.row = row;
this.col = col;
this.count = count;
}
}
public int knight(int A, int B, int sr, int sc, int er, int ec) {
int[][] matrix = new int[A][B];
Queue<Node> q = new LinkedList<>(); //linkedlist??
Node n = new Node(sr, sc, 0);
q.add(n);
matrix[sr][sc] = -1;
final int[][] SHIFTS = {
{-2,1},
{-2,-1},
{2,1},
{2,-1},
{-1,2},
{-1,-2},
{1,2},
{1,-2}
};
int count = 0;
while(!q.isEmpty()) {
Node cur = q.remove();
if(cur.row == er && cur.col == ec) {
return cur.count;
}
for(int[] i : SHIFTS) {
if(canTraverse(matrix, cur.row + i[0], cur.col + i[1])) {
matrix[cur.row + i[0]][cur.col + i[1]] = -1;
q.add(new Node(cur.row + i[0], cur.col + i[1], cur.count + 1));
}
}
}
return -1;
}
public static boolean canTraverse(int[][] matrix, int sr, int sc) {
if(sr < 0 || sr >= matrix.length || sc < 0 || sc >= matrix[sr].length || matrix[sr][sc] == -1) {
return false;
}
return true;
}
}
BFS algorithm needs to mark every visited position (node) to work properly. Else, such code could cause (almost certainly) runtime error or memory limit exceded (in short terms: A calls B and B calls A).
Solution: Create a boolean array and mark the nodes at the time they enter to the queue and you are done.

Reversing singly linked list using recursion

I have written code to reverse singly linked list using recursion. It is working fine on lists of length less than or equal to 174725. But on lists of length greater than 174725 it gives a segmentation fault(Segmentation fault: 11) while reversing it via reverse() call. Can someone please explain this to me ?
#include <iostream>
using namespace std;
class Node
{
public:
int val;
Node *next;
};
class Sll
{
public:
Node *head;
private:
void reverse(Node *node);
public:
Sll();
void insert_front(int key);
void reverse();
void print();
};
void Sll::reverse(Node *node)
{
if (node == NULL) return;
Node *rest = node->next;
if (rest == NULL)
{
head = node;
return;
}
reverse(rest);
rest->next = node;
node->next = NULL;
return;
}
Sll::Sll()
{
head = NULL;
}
void Sll::insert_front(int key)
{
Node *newnode = new Node;
newnode->val = key;
newnode->next = head;
head = newnode;
return;
}
void Sll::print()
{
Node *temp = head;
while (temp)
{
temp = temp->next;
}
cout << endl;
return;
}
void Sll::reverse()
{
reverse(head);
return;
}
int main()
{
Sll newList = Sll();
int n;
cin >> n;
for (int i = 0; i < n; i++) newList.insert_front(i + 1);
newList.reverse();
// newList.print();
return 0;
}
List reversing function must be tail-recursive, otherwise it is going to overflow the stack when recursing over a long list, like you observe. Also, it needs to be compiled with optimisations enabled or with -foptimize-sibling-calls gcc option.
Tail-recursive version:
Node* reverse(Node* n, Node* prev = nullptr) {
if(!n)
return prev;
Node* next = n->next;
n->next = prev;
return reverse(next, n);
}
An iterative list reversion can be more easily inlined though and it does not require any optimization options:
inline Node* reverse(Node* n) {
Node* prev = nullptr;
while(n) {
Node* next = n->next;
n->next = prev;
prev = n;
n = next;
}
return prev;
}

Sub-sequence of Vowels

I was practicing for an interview and came across this question on a website:
A magical sub-sequence of a string S is a sub-sequence of S that
contains all five vowels in order. Find the length of largest magical sub-sequence of a string S.
For example, if S = aeeiooua, then aeiou and aeeioou are magical sub-sequences
but aeio and aeeioua are not.
I am a beginner in dynamic programming and am finding it hard to come up with a recursive formula for this.
I did it with an iterative approach rather than recursive one. I started building solution similar to LIS (Longest Increasing Subsequence) and then optimised it upto O(n).
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string vowel = "aeiou";
int vpos(char c)
{
for (int i = 0; i < 5; ++i)
if (c == vowel[i])
return i;
return -1;
}
int magical(string s)
{
int l = s.length();
int previndex[5] = {-1, -1, -1, -1, -1}; // for each vowel
vector<int> len (l, 0);
int i = 0, maxlen = 0;
// finding first 'a'
while (s[i] != 'a')
{
++i;
if (i == l)
return 0;
}
previndex[0] = i; //prev index of 'a'
len[i] = 1;
for ( ++i; i < l; ++i)
{
if (vpos(s[i]) >= 0) // a vowel
{
/* Need to append to longest subsequence on its left, only for this vowel (for any vowels) and
* its previous vowel (if it is not 'a')
This important observation makes it O(n) -- differnet from typical LIS
*/
if (previndex[vpos(s[i])] >= 0)
len[i] = 1+len[previndex[vpos(s[i])]];
previndex[vpos(s[i])] = i;
if (s[i] != 'a')
{
if (previndex[vpos(s[i])-1] >= 0)
len[i] = max(len[i], 1+len[previndex[vpos(s[i])-1]]);
}
maxlen = max(maxlen, len[i]);
}
}
return maxlen;
}
int main()
{
string s = "aaejkioou";
cout << magical(s);
return 0;
}
O(input string length) runtime
import java.util.*;
public class Main {
/*
algo:
keep map of runningLongestSubsequence that ends in each letter. loop through String s. for each char, try appending
to runningLongestSubsequence for that char, as well as to runningLongestSubsequence for preceding char.
update map with whichever results in longer subsequence.
for String s = "ieaeiouiaooeeeaaeiou", final map is:
terminal letter in longest running subsequence-> longest running subsequence
a -> aaaa
e -> aeeeee
i -> aeeeeei
o -> aeeeeeio
u -> aeeeeeiou
naming:
precCharMap - precedingCharMap
runningLongestSubMap - runningLongestSubsequenceMap
*/
public static int longestSubsequence(String s) {
if (s.length() <= 0) throw new IllegalArgumentException();
Map<Character, Character> precCharMap = new HashMap<>();
precCharMap.put('u', 'o');
precCharMap.put('o', 'i');
precCharMap.put('i', 'e');
precCharMap.put('e', 'a');
Map<Character, String> runningLongestSubMap = new HashMap<>();
for (char currChar : s.toCharArray()) {
//get longest subs
String currCharLongestSub;
String precCharLongestSub = null;
if (currChar == 'a') {
currCharLongestSub = runningLongestSubMap.getOrDefault(currChar, "");
} else {
currCharLongestSub = runningLongestSubMap.get(currChar);
char precChar = precCharMap.get(currChar);
precCharLongestSub = runningLongestSubMap.get(precChar);
}
//update running longest subsequence map
if (precCharLongestSub == null && currCharLongestSub != null) {
updateRunningLongestSubMap(currCharLongestSub, currChar, runningLongestSubMap);
} else if (currCharLongestSub == null && precCharLongestSub != null) {
updateRunningLongestSubMap(precCharLongestSub, currChar, runningLongestSubMap);
} else if (currCharLongestSub != null && precCharLongestSub != null) {
//pick longer
if (currCharLongestSub.length() < precCharLongestSub.length()) {
updateRunningLongestSubMap(precCharLongestSub, currChar, runningLongestSubMap);
} else {
updateRunningLongestSubMap(currCharLongestSub, currChar, runningLongestSubMap);
}
}
}
if (runningLongestSubMap.get('u') == null) {
return 0;
}
return runningLongestSubMap.get('u').length();
}
private static void updateRunningLongestSubMap(String longestSub, char currChar,
Map<Character, String> runningLongestSubMap) {
String currCharLongestSub = longestSub + currChar;
runningLongestSubMap.put(currChar, currCharLongestSub);
}
public static void main(String[] args) {
//String s = "aeeiooua"; //7
//String s = "aeiaaioooaauuaeiou"; //10
String s = "ieaeiouiaooeeeaaeiou"; //9
//String s = "ieaeou"; //0
//String s = "ieaeoooo"; //0
//String s = "aeiou"; //5
//if u have String s beginning in "ao", it'll do nothing with o and
//continue on to index 2.
System.out.println(longestSubsequence(s));
}
}
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
unsigned int getcount(string a, unsigned int l,unsigned int r );
int main()
{
std::string a("aaaaaeeeeaaaaiiioooeeeeuuuuuuiiiiiaaaaaaoo"
"oooeeeeiiioooouuuu");
//std::string a("aaaaaeeeeaaaaiiioooeeeeuuuuuuiiiiiaaaaaaoooooeeeeiiioooo");
//std::string a("aaaaaeeeeaaaaiiioooeeeeiiiiiaaaaaaoooooeeeeiiioooo"); //sol0
//std::string a{"aeiou"};
unsigned int len = a.length();
unsigned int i=0,cnt =0,countmax =0;
bool newstring = true;
while(i<len)
{
if(a.at(i) == 'a' && newstring == true)
{
newstring = false;
cnt = getcount(a,i,len);
if(cnt > countmax)
{
countmax = cnt;
cnt = 0;
}
}
else if(a.at(i)!='a')
{
newstring = true;
}
i++;
}
cout<<countmax;
return 0;
}
unsigned int getcount(string a, unsigned int l,unsigned int r )
{
std::string b("aeiou");
unsigned int seq=0,cnt =0;
unsigned int current =l;
bool compstr = false;
while(current<r)
{
if(a.at(current) == b.at(seq))
{
cnt++;
}
else if((seq <= (b.size()-2)) && (a.at(current) == b.at(seq+1)))
{
seq++;
cnt++;
if (seq == 4)
compstr =true;
}
current++;
}
if (compstr == true)
return cnt;
return 0;
}
you can use recursive approach here (this should work for string length upto max int (easily memorization can be used)
public class LMV {
static final int NOT_POSSIBLE = -1000000000;
// if out put is this i.e soln not possible
static int longestSubsequence(String s, char[] c) {
//exit conditions
if(s.length() ==0 || c.length ==0){
return 0;
}
if(s.length() < c.length){
return NOT_POSSIBLE;
}
if(s.length() == c.length){
for(int i=0; i<s.length(); i++){
if(s.charAt(i) !=c [i]){
return NOT_POSSIBLE;
}
}
return s.length();
}
if(s.charAt(0) < c[0]){
// ignore, go ahead with next item
return longestSubsequence(s.substring(1), c);
} else if (s.charAt(0) == c[0]){
// <case 1> include item and start search for next item in chars
// <case 2> include but search for same item again in chars
// <case 3> don't include item
return Math.max(
Math.max( ( 1+longestSubsequence(s.substring(1), Arrays.copyOfRange(c, 1, c.length) ) ),
( 1+longestSubsequence(s.substring(1), c ) ) ),
( longestSubsequence(s.substring(1), c )) );
} else {
//ignore
return longestSubsequence(s.substring(1), c);
}
}
public static void main(String[] args) {
char[] chars = {'a', 'e', 'i', 'o', 'u'};
String s1 = "aeio";
String s2 = "aaeeieou";
String s3 = "aaeeeieiioiiouu";
System.out.println(longestSubsequence(s1, chars));
System.out.println(longestSubsequence(s2, chars));
System.out.println(longestSubsequence(s3, chars));
}
}
int func( char *p)
{
char *temp = p;
char ae[] = {'a','e','i','o','u'};
int size = strlen(p), i = 0;
int chari = 0, count_aeiou=0;
for (i=0;i<=size; i++){
if (temp[i] == ae[chari]) {
count_aeiou++;
}
else if ( temp[i] == ae[chari+1]) {
count_aeiou++;
chari++;
}
}
if (chari == 4 ) {
printf ("Final count : %d ", count_aeiou);
} else {
count_aeiou = 0;
}
return count_aeiou;
}
The solution to retrun the VOWELS count as per the hackerrank challenge.
int findsubwithcontinuousvowel(string str){
int curr=0;
int start=0,len=0,maxlen=0,i=0;
for(i=0;i<str.size();i++){
if(str[i]=='u' && (current[curr]=='u' || (curr+1<5 && current[curr+1]=='u'))){
//len++;
maxlen=max(len+1,maxlen);
}
if(str[i]==current[curr]){
len++;
}
else if(curr+1<5 && str[i]==current[curr+1]){
len++;
curr++;
}
else{
len=0;
curr=0;
if(str[i]=='a'){
len=1;
}
}
}
return maxlen;
}
Check if vowels are available in sequence in isInSequence and process the result on processor.
public class one {
private char[] chars = {'a','e','i','o','u'};
private int a = 0;
private boolean isInSequence(char c){
// check if char is repeating
if (c == chars[a]){
return true;
}
// if vowels are in sequence and just passed by 'a' and so on...
if (c == 'e' && a == 0){
a++;
return true;
}
if (c == 'i' && a == 1){
a++;
return true;
}
if (c == 'o' && a == 2){
a++;
return true;
}
if (c == 'u' && a == 3){
a++;
return true;
}
return false;
}
private char[] processor(char[] arr){
int length = arr.length-1;
int start = 0;
// In case if all chars are vowels, keeping length == arr
char array[] = new char[length];
for (char a : arr){
if (isInSequence(a)){
array[start] = a;
start++;
}
}
return array;
}
public static void main(String args[]){
char[] arr = {'m','a','e','l','x','o','i','o','u','a'};
one o = new one();
System.out.print(o.processor(arr));
}
}
#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(NULL);cin.tie(NULL);cout.tie(NULL);
#define ll unsigned long long
using namespace std;
int main() {
// your code goes here
ios
string s;
cin>>s;
int n=s.length();
int dp[n+1][5]={0};
for(int i=1;i<=n;i++)
{
if(s[i-1]=='a')
{
dp[i][0]=1+dp[i-1][0];
dp[i][1]=dp[i-1][1];
dp[i][2]=dp[i-1][2];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='e')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][0]>0)
{dp[i][1]=1+max(dp[i-1][1],dp[i-1][0]);}
else
dp[i-1][1]=0;
dp[i][2]=dp[i-1][2];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='i')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][1]>0)
{dp[i][2]=1+max(dp[i-1][1],dp[i-1][2]);}
else
dp[i-1][2]=0;
dp[i][1]=dp[i-1][1];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='o')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][2]>0)
{dp[i][3]=1+max(dp[i-1][3],dp[i-1][2]);}
else
dp[i-1][3]=0;
dp[i][2]=dp[i-1][2];
dp[i][1]=dp[i-1][1];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='u')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][3]>0)
{dp[i][4]=1+max(dp[i-1][4],dp[i-1][3]);}
else
dp[i-1][4]=0;
dp[i][1]=dp[i-1][1];
dp[i][3]=dp[i-1][3];
dp[i][2]=dp[i-1][2];
}
else
{
dp[i][0]=dp[i-1][0];
dp[i][1]=dp[i-1][1];
dp[i][2]=dp[i-1][2];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
}
cout<<dp[n][4];
return 0;
}

Puzzle: Find the order of n persons standing in a line (based on their heights)

Saw this question on Careercup.com:
Given heights of n persons standing in a line and a list of numbers corresponding to each person (p) that gives the number of persons who are taller than p and standing in front of p. For example,
Heights: 5 3 2 6 1 4
InFronts:0 1 2 0 3 2
Means that the actual actual order is: 5 3 2 1 6 4
The question gets the two lists of Heights and InFronts, and should generate the order standing in line.
My solution:
It could be solved by first sorting the list in descending order. Obviously, to sort, we need to define an object Person (with two attributes of Height and InFront) and then sort Persons based on their height. Then, I would use two stacks, a main stack and a temp one, to build up the order.
Starting from the tallest, put it in the main stack. If the next person had an InFront value of greater than the person on top of the stack, that means the new person should be added before the person on top. Therefore, we need to pop persons from the main stack, insert the new person, and then return the persons popped out in the first step (back to the main stack from temp one). I would use a temp stack to keep the order of the popped out persons. But how many should be popped out? Since the list is sorted, we need to pop exactly the number of persons in front of the new person, i.e. corresponding InFront.
I think this solution works. But the worst case order would be O(n^2) -- when putting a person in place needs popping out all previous ones.
Is there any other solutions? possibly in O(n)?
The O(nlogn) algoritm is possible.
First assume that all heights are different.
Sort people by heights. Then iterate from shortest to tallest. In each step you need an efficient way to put the next person to the correct position. Notice that people we've already placed are not taller that the current person. And the people we place after are taller than the current. So we have to find a place such that the number of empty positions in the front is equal to the inFronts value of this person. This task can be done using a data structure called interval tree in O(logn) time. So the total time of an algorithm is O(nlogn).
This algorithm works well in case where there's no ties. As it may be safely assumed that empty places up to front will be filled by taller people.
In case when ties are possible, we need to assure that people of the same height are placed in increasing order of their positions. It can be achieved if we will process people by non-decreasing inFronts value. So, in case of possible ties we should also consider inFronts values when sorting people.
And if at some step we can't find a position for next person then the answer it "it's impossible to satisfy problem constraints".
There exists an algorithm with O(nlogn) average complexity, however worst case complexity is still O(n²).
To achieve this you can use a variation of a binary tree. The idea is, in this tree, each node corresponds to a person and each node keeps track of how many people are in front of him (which is the size of the left subtree) as nodes are inserted.
Start iterating the persons array in decreasing height order and insert each person into the tree starting from the root. Insertion is as follows:
Compare the frontCount of the person with the current node's (root at the beginning) value.
If it is smaller than it insert the node to the left with value 1. Increase the current node's value by 1.
Else, descend to the right by decreasing the person's frontCount by current node's value. This enables the node to be placed in the correct location.
After all nodes finished, an inorder traversal gives the correct order of people.
Let the code speak for itself:
public static void arrange(int[] heights, int[] frontCounts) {
Person[] persons = new Person[heights.length];
for (int i = 0; i < persons.length; i++)
persons[i] = new Person(heights[i], frontCounts[i]);
Arrays.sort(persons, (p1, p2) -> {
return Integer.compare(p2.height, p1.height);
});
Node root = new Node(persons[0]);
for (int i = 1; i < persons.length; i++) {
insert(root, persons[i]);
}
inOrderPrint(root);
}
private static void insert(Node root, Person p) {
insert(root, p, p.frontCount);
}
private static void insert(Node root, Person p, int value) {
if (value < root.value) { // should insert to the left
if (root.left == null) {
root.left = new Node(p);
} else {
insert(root.left, p, value);
}
root.value++; // Increase the current node value while descending left!
} else { // insert to the right
if (root.right == null) {
root.right = new Node(p);
} else {
insert(root.right, p, value - root.value);
}
}
}
private static void inOrderPrint(Node root) {
if (root == null)
return;
inOrderPrint(root.left);
System.out.print(root.person.height);
inOrderPrint(root.right);
}
private static class Node {
Node left, right;
int value;
public final Person person;
public Node(Person person) {
this.value = 1;
this.person = person;
}
}
private static class Person {
public final int height;
public final int frontCount;
Person(int height, int frontCount) {
this.height = height;
this.frontCount = frontCount;
}
}
public static void main(String[] args) {
int[] heights = {5, 3, 2, 6, 1, 4};
int[] frontCounts = {0, 1, 2, 0, 3, 2};
arrange(heights, frontCounts);
}
I think one approach can be the following. Although it again seems to be O(n^2) at present.
Sort the Height array and corresponding 'p' array in ascending order of heights (in O(nlogn)). Pick the first element in the list. Put that element in the final array in the position given by the p index.
For example after sorting,
H - 1, 2, 3, 4, 5, 6
p - 3, 2, 1, 2, 0, 0.
1st element should go in position 3. Hence final array becomes:
---1--
2nd element shall go in position 2. Hence final array becomes:
--21--
3rd element should go in position 1. Hence final array becomes:
-321--
4th element shall go in position 2. This is the position among the empty ones. Hence final array becomes:
-321-4
5th element shall go in position 0. Hence final array becomes:
5321-4
6th element should go in position 0. Hence final array becomes:
532164
I think the approach indicated above is correct. However a critical piece missing in the solutions above are.
Infronts is the number of taller candidate before the current person. So after sorting the persons based on height(Ascending), when placing person 3 with infront=2, if person 1 and 2 was in front placed at 0, 1 position respectively, you need to discount their position and place 3 at position 4, I.E 2 taller candidates will take position 2,3.
As some indicated interval tree is the right structure. However a dynamic sized container, with available position will do the job.(code below)
struct Person{
int h, ct;
Person(int ht, int c){
h = ht;
ct = c;
}
};
struct comp{
bool operator()(const Person& lhs, const Person& rhs){
return (lhs.h < rhs.h);
}
};
vector<int> heightOrder(vector<int> &heights, vector<int> &infronts) {
if(heights.size() != infronts.size()){
return {};
}
vector<int> result(infronts.size(), -1);
vector<Person> persons;
vector<int> countSet;
for(int i= 0; i< heights.size(); i++){
persons.emplace_back(Person(heights[i], infronts[i]));
countSet.emplace_back(i);
}
sort(persons.begin(), persons.end(), comp());
for(size_t i=0; i<persons.size(); i++){
Person p = persons[i];
if(countSet.size() > p.ct){
int curr = countSet[p.ct];
//cout << "the index to place height=" << p.h << " , is at pos=" << curr << endl;
result[curr] = p.h;
countSet.erase(countSet.begin() + p.ct);
}
}
return result;
}
I'm using LinkedList for the this. Sort the tallCount[] in ascending order and accordingly re-position the items in heights[]. This is capable of handling the duplicate elements also.
public class FindHeightOrder {
public int[] findOrder(final int[] heights, final int[] tallCount) {
if (heights == null || heights.length == 0 || tallCount == null
|| tallCount.length == 0 || tallCount.length != heights.length) {
return null;
}
LinkedList list = new LinkedList();
list.insertAtStart(heights[0]);
for (int i = 1; i < heights.length; i++) {
if (tallCount[i] == 0) {
Link temp = list.getHead();
while (temp != null && temp.getData() <= heights[i]) {
temp = temp.getLink();
}
if (temp != null) {
if (temp.getData() <= heights[i]) {
list.insertAfterElement(temp.getData(), heights[i]);
} else {
list.insertAtStart(heights[i]);
}
} else {
list.insertAtEnd(heights[i]);
}
} else {
Link temp = list.getHead();
int pos = tallCount[i];
while (temp != null
&& (temp.getData() <= heights[i] || pos-- > 0)) {
temp = temp.getLink();
}
if (temp != null) {
if (temp.getData() <= heights[i]) {
list.insertAfterElement(temp.getData(), heights[i]);
} else {
list.insertBeforeElement(temp.getData(), heights[i]);
}
} else {
list.insertAtEnd(heights[i]);
}
}
}
Link fin = list.getHead();
int i = 0;
while (fin != null) {
heights[i++] = fin.getData();
fin = fin.getLink();
}
return heights;
}
public class Link {
private int data;
private Link link;
public Link(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Link getLink() {
return link;
}
public void setLink(Link link) {
this.link = link;
}
#Override
public String toString() {
return this.data + " -> "
+ (this.link != null ? this.link : "null");
}
}
public class LinkedList {
private Link head;
public Link getHead() {
return head;
}
public void insertAtStart(int data) {
if (head == null) {
head = new Link(data);
head.setLink(null);
} else {
Link link = new Link(data);
link.setLink(head);
head = link;
}
}
public void insertAtEnd(int data) {
if (head != null) {
Link temp = head;
while (temp != null && temp.getLink() != null) {
temp = temp.getLink();
}
temp.setLink(new Link(data));
} else {
head = new Link(data);
}
}
public void insertAfterElement(int after, int data) {
if (head != null) {
Link temp = head;
while (temp != null) {
if (temp.getData() == after) {
Link link = new Link(data);
link.setLink(temp.getLink());
temp.setLink(link);
break;
} else {
temp = temp.getLink();
}
}
}
}
public void insertBeforeElement(int before, int data) {
if (head != null) {
Link current = head;
Link previous = null;
Link ins = new Link(data);
while (current != null) {
if (current.getData() == before) {
ins.setLink(current);
break;
} else {
previous = current;
current = current.getLink();
if (current != null && current.getData() == before) {
previous.setLink(ins);
ins.setLink(current);
break;
}
}
}
}
}
#Override
public String toString() {
return "LinkedList [head=" + this.head + "]";
}
}
}
As people already corrected for original input:
Heights : A[] = { 5 3 2 6 1 4 }
InFronts: B[] = { 0 1 2 0 3 2 }
Output should look like: X[] = { 5 3 1 6 2 4 }
Here is the O(N*logN) way to approach solution (with assumption that there are no ties).
Iterate over array B and build chain of inequalities (by placing items into a right spot on each iteration, here we can use hashtable for O(1) lookups):
b0 > b1
b0 > b1 > b2
b3 > b0 > b1 > b2
b3 > b0 > b1 > b4 > b2
b3 > b0 > b5 > b1 > b4 > b2
Sort array A and reverse it
Initialize output array X, iterate over chain from #1 and fill array X by placing items from A into a position defined in a chain
Steps #1 and #3 are O(N), step #2 is the most expensive O(N*logN).
And obviously reversing sorted array A (in step #2) is not required.
This is the implementation for the idea provided by user1990169. Complexity being O(N^2).
public class Solution {
class Person implements Comparator<Person>{
int height;
int infront;
public Person(){
}
public Person(int height, int infront){
this.height = height;
this.infront = infront;
}
public int compare(Person p1, Person p2){
return p1.height - p2.height;
}
}
public ArrayList<Integer> order(ArrayList<Integer> heights, ArrayList<Integer> infronts) {
int n = heights.size();
Person[] people = new Person[n];
for(int i = 0; i < n; i++){
people[i] = new Person(heights.get(i), infronts.get(i));
}
Arrays.sort(people, new Person());
Person[] rst = new Person[n];
for(Person p : people){
int count = 0;
for(int i = 0; i < n ; i++){
if(count == p.infront){
while(rst[i] != null && i < n - 1){
i++;
}
rst[i] = p;
break;
}
if(rst[i] == null) count++;
}
}
ArrayList<Integer> heightrst = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
heightrst.add(rst[i].height);
}
return heightrst;
}
}
Was solving this problem today, here is what I came up with:
The idea is to sort the heights array in descending order. Once, we have this sorted array - pick up an element from this element and place it in the resultant array at the corresponding index (I am using an ArrayList for the same, it would be nice to use LinkedList) :
public class Solution {
public ArrayList<Integer> order(ArrayList<Integer> heights, ArrayList<Integer> infronts) {
Person[] persons = new Person[heights.size()];
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < persons.length; i++) {
persons[i] = new Person(heights.get(i), infronts.get(i));
}
Arrays.sort(persons, (p1, p2) -> {
return Integer.compare(p2.height, p1.height);
});
for (int i = 0; i < persons.length; i++) {
//System.out.println("adding "+persons[i].height+" "+persons[i].count);
res.add(persons[i].count, persons[i].height);
}
return res;
}
private static class Person {
public final int height;
public final int count;
public Person(int h, int c) {
height = h;
count = c;
}
}
}
I found this kind of problem on SPOJ. I created a binary tree with little variation. When a new height is inserted, if the front is smaller than the root's front then it goes to the left otherwise right.
Here is the C++ implementation:
#include<bits/stdc++.h>
using namespace std;
struct TreeNode1
{
int val;
int _front;
TreeNode1* left;
TreeNode1*right;
};
TreeNode1* Add(int x, int v)
{
TreeNode1* p= (TreeNode1*) malloc(sizeof(TreeNode1));
p->left=NULL;
p->right=NULL;
p->val=x;
p->_front=v;
return p;
}
TreeNode1* _insert(TreeNode1* root, int x, int _front)
{
if(root==NULL) return Add(x,_front);
if(root->_front >=_front)
{
root->left=_insert(root->left,x,_front);
root->_front+=1;
}
else
{
root->right=_insert(root->right,x,_front-root->_front);
}
return root;
}
bool comp(pair<int,int> a, pair<int,int> b)
{
return a.first>b.first;
}
void in_order(TreeNode1 * root, vector<int>&v)
{
if(root==NULL) return ;
in_order(root->left,v);
v.push_back(root->val);
in_order(root->right,v);
}
vector<int>soln(vector<int>h, vector<int>in )
{
vector<pair<int , int> >vc;
for(int i=0;i<h.size();i++) vc.push_back( make_pair( h[i],in[i] ) );
sort(vc.begin(),vc.end(),comp);
TreeNode1* root=NULL;
for(int i=0;i<vc.size();i++)
root=_insert(root,vc[i].first,vc[i].second);
vector<int>v;
in_order(root,v);
return v;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
vector<int>h;
vector<int>in;
for(int i=0;i<n;i++) {int x;
cin>>x;
h.push_back(x);}
for(int i=0;i<n;i++) {int x; cin>>x;
in.push_back(x);}
vector<int>v=soln(h,in);
for(int i=0;i<n-1;i++) cout<<v[i]<<" ";
cout<<v[n-1]<<endl;
h.clear();
in.clear();
}
}
Here is a Python solution that uses only elementary list functions and takes care of ties.
def solution(heights, infronts):
person = list(zip(heights, infronts))
person.sort(key=lambda x: (x[0] == 0, x[1], -x[0]))
output = []
for p in person:
extended_output = output + [p]
extended_output.sort(key=lambda x: (x[0], -x[1]))
output_position = [p for p in extended_output].index(p) + p[1]
output.insert(output_position, p)
for c, p in enumerate(output):
taller_infronts = [infront for infront in output[0:c] if infront[0] >= p[0]]
assert len(taller_infronts) == p[1]
return output
Simple O(n^2) solution for this in Java:
Algorith:
If the position of the shortest person is i, i-1 taller people will be in front of him.
We fix the position of shortest person and then move to second shortest person.
Sort people by heights. Then iterate from shortest to tallest. In each step you need an efficient way to put the next person to the correct position.
We can optimise this solution even more by using segment tree. See this link.
class Person implements Comparable<Person>{
int height;
int pos;
Person(int height, int pos) {
this.height = height;
this.pos = pos;
}
#Override
public int compareTo(Person person) {
return this.height - person.height;
}
}
public class Solution {
public int[] order(int[] heights, int[] positions) {
int n = heights.length;
int[] ans = new int[n];
PriorityQueue<Person> pq = new PriorityQueue<Person>();
for( int i=0; i<n; i++) {
pq.offer(new Person(heights[i], positions[i]) );
}
for(int i=0; i<n; i++) {
Person person = pq.poll();
int vacantTillNow = 0;
int index = 0;
while(index < n) {
if( ans[index] == 0) vacantTillNow++;
if( vacantTillNow > person.pos) break;
index++;
}
ans[index] = person.height;
}
return ans;
}
}
Segment tree can be used to solve this in O(nlog n) if there are no ties in heights.
Please look for approach 3 in this link for a clear explanation of this method.
https://www.codingninjas.com/codestudio/problem-details/order-of-people-heights_1170764
Below is my code for the same approach in python
def findEmptySlot(tree, root, left, right, K, result):
tree[root]-=1
if left==right:
return left
if tree[2*root+1] >= K:
return findEmptySlot(tree, 2*root+1, left, (left+right)//2, K, result)
else:
return findEmptySlot(tree, 2*root+2, (left+right)//2+1, right, K-tree[2*root+1], result)
def buildsegtree(tree, pos, start, end):
if start==end:
tree[pos]=1
return tree[pos]
mid=(start+end)//2
left = buildsegtree(tree, 2*pos+1,start, mid)
right = buildsegtree(tree,2*pos+2,mid+1, end)
tree[pos]=left+right
return tree[pos]
class Solution:
# #param A : list of integers
# #param B : list of integers
# #return a list of integers
def order(self, A, B):
n=len(A)
people=[(A[i],B[i]) for i in range(len(A))]
people.sort(key=lambda x: (x[0], x[1]))
result=[0]*n
tree=[0]*(4*n)
buildsegtree(tree,0, 0, n-1)
for i in range(n):
idx=findEmptySlot(tree, 0, 0, n-1, people[i][1]+1, result)
result[idx]=people[i][0]
return result

Finding and removing the last occurrence of an element in a (singly) linked list with only one traversal

Is it possible to find the last occurrence of an element (for example, an integer) and remove this node with only one (forward) traversal through the list?
Yes.
Simply remember the previous entry every time you find the value you're searching for on the traversal. When the traversal is complete, the last entry remembered will have a link to the entry to be removed, and that is sufficient to do the removal.
public void DeleteLastOccurenceOfKey(Node head, int key)
{
Node current=head;
Node prev=null;
Node temp=null;
while(current!=null)
{
if(current.next!=null && current.next.data==key)
{
prev=current;
temp=current.next;
}
current=current.next;
}
prev.next=temp.next;
}
DeleteLastOccurenceOfKey(head,25);
I/P:5 10 15 25 35 25 40
O/P:5 10 15 25 35 40
/*
* Delete last occurrence of an item from linked list
* Given a liked list and a key to be deleted. Delete last occurrence of key
* from linked. The list may have duplicates.
*
* Examples:
*
* Input: 1->2->3->5->2->10, key = 2`enter code here`
* Output: 1->2->3->5->10
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct list_ list;
struct list_ {
int d;
list *next;
};
void insert (list **head, int d) {
list *tmp = (list *)malloc(sizeof(list));
assert(tmp);
tmp->d = d;
tmp->next = *head;
*head = tmp;
}
void printL (list *p) {
while (p) {
printf (" %d ", p->d);
p = p->next;
}
printf ("\n");
}
void deletlastOccurence (list **head, int d) {
list *cur = *head;
list *prev = NULL;
list *match = NULL;
if (cur == NULL) {
printf ("list is empty\n");
return;
}
/*
* Special case when there only ONE NODE
* in the LIST
*/
if (cur->next == NULL) {
if (cur->d == d) {
printf ("Deleted one node %d\n", cur->d);
free(cur);
*head = NULL;
} else {
printf(" No match\n");
}
return;
}
/*
* Keep track of previous node
*/
while (cur && cur->next) {
if (cur->next->d == d) {
prev = cur;
match = cur->next;
}
cur = cur->next;
}
if (prev){
prev->next = match->next;
printf ("Delete %d\n", match->d);
free (match);
} else {
/*
* Special case when the last node is
* on the head itself
*/
if ((*head)->d == d) {
cur = *head;
*head = cur->next;
printf("element is at head Delete %d\n", cur->d);
free (cur);
} else {
printf ("No match\n");
}
}
printL(*head);
}
int main (int argc , char *argv) {
list *h = NULL;
insert(&h, 1);
insert(&h, 2);
insert(&h, 3);
insert(&h, 4);
insert(&h, 5);
insert(&h, 2);
insert(&h, 1);
insert(&h, 6);
printL(h);
deletlastOccurence(&h, 6);
deletlastOccurence(&h, 2);
}
public void deleteLastOccurence(int value) {
Element cur = this.head;
Element prev = null;
Element tmp = null;
if(this.head == null)
return;
if(this.head.data == value) {
this.head = null;
return;
}
while(cur != null) {
if(cur.next != null && cur.next.data == value) {
prev = cur;
tmp = cur.next;
}
cur = cur.next;
}
prev.next = tmp.next;
}

Resources