Friday, October 18, 2013

Based on String Processing

1. KMP Algorithm ... A simple and efficient string matching algorithm Click here to see the code

2. Ternary Search Tree...For String Storing and Matching and Traversing.... An Efficient Approach  Click here to see the code

3. Tries-String Storing and matching Program Using C language click here to see the code

Based on Bitwise

1. Given a number having only one ’1′ and all other ’0′s in its binary representation, find position of the only set bit.

2.Find the position of the most significant set bit in a 64-bit signed long int.

3. Count the number of bits that are set to 1, in a 64-bit signed integer.

4. RangeOperation on A(m, n) = m & (m+1) & ... & (n-1) & n.

5. Bit Flooding outward and backward of a set Bit.

Based on programs of different coding challenges

1. Matrix rotation by 90 degree clockwise direction...for N*N matrix  Click here to see the code

2. program for finding Sqrt upto 3 decimal point  Click here to see the code

3. Game Of Thrones - I, Hackerank Challenge Question   Click here to see the code

4. Run Length Encoding and Decoding known as RLECompress  Click here to see the code

5. Inky Pinky Ponky, a Kids Game   Click here to see the code

6. BULLS and COWS... A guessing number game Click here to see the code

List of Linked list programs.

1. A program for reversing each k-nodes of blocks in the program   Click here to see the code.

2. program for Palindrome using Singly LinkedList   Click here to see the code.  Click here to see the code.

3.An efficient way to write a program for checking whether it is palindrome or not  Click here to see the code.

4.Merge k sorted linked lists with total of N elements and return it as one sorted list Click here to see the code

5.Addition of two number's using singly linked list  Click here to see the code

Quicksort using singly linked list  Click here to see the code

7. Circular linked list: A (corrupt) linked list in which a node's next pointer points 
to an earlier node, so as to make a loop in the linked list Click here to see the code                                                       

List of programs based on Graph

1. Given an undirected graph G having N (1<N<=1000) vertices and positive weights. Find the shortest path from vertex 1 to vertex N, or state that such path doesn't exist. 

2. You are given an unweighted, undirected graph. Write a program to check if it's a tree topology
  (I have faced this question in Amazon online test).

Wednesday, October 16, 2013

Find the shortest path from vertex 1 to vertex N

Given an undirected graph G having N (1<N<=1000) vertices and positive weights. Find the shortest path from vertex 1 to vertex N, or state that such path doesn't exist. 
Hint: At each step, among the vertices which weren't yet checked and for which a path from vertex 1 was found, take the one which has the shortest path, from vertex 1 to it, yet found. 

Uses Prims/Dijikstra Algorithms....

#include<iostream>
#include<cstdlib>
#include<limits.h>
using namespace std;
struct Graph
{
    int V;
    int E;
    int **Matrix;
};
struct Table
{
    int Dist;
    int Pvertex;
};

void Create_Matrix(Graph *G)
{
G->Matrix=new int*[G->V];
for(int i=0;i<G->V;i++)
G->Matrix[i]=new int[G->V];
for(int i=0;i<G->V;i++)
 for(int j=0;j<G->V;j++)
   G->Matrix[i][j]=-1;
int u,v,cost;
for(int i=0;i<G->E;i++)
{   
    cin>>u>>v>>cost;
    u--,v--;
    G->Matrix[u][v]=cost;
}
}
void Heapify(int PQ[], Table DT[],int size)
{
  if(size<2)return;
  int left=0,right=0,max=0;
  int parent=(size-1)/2;
  if(2*parent+2<=size)
  {right=2*parent+2;left=2*parent+1;}
  else if(2*parent+1<=size)
  left=2*parent+1;

  if(right)
    if(DT[PQ[left]].Dist<DT[PQ[right]].Dist)
      max=PQ[left];
     else
      max=PQ[right];
 else if(left)
     max=PQ[left];
     if(max)
     {
      size=PQ[parent];
      PQ[parent]=PQ[max];
      PQ[max]=size;     
     Heapify(PQ,DT,parent);     
     }  
}

void Prims(Graph *G,int s)
{
  int *PQ=new int[G->V];
  Table *DT=new Table[G->V];
  for(int i=0;i<G->V;i++)
  DT[i].Dist=DT[i].Pvertex=PQ[i]=INT_MAX;

  DT[s].Dist=DT[s].Pvertex=0;
  int top=-1,v,d;
  PQ[++top]=DT[s].Dist;
  while(top>=0)
  {
      v=PQ[top--];
      Heapify(PQ,DT,top);
      for(int j=0;j<G->V;j++)
      {
          if(G->Matrix[v][j]>0)
         { d=G->Matrix[v][j]+DT[v].Dist;
         if(d<DT[j].Dist)
          { PQ[++top]=j;
            DT[j].Dist=d;
            DT[j].Pvertex=v;
           Heapify(PQ,DT,top);
          }
         }
      }

  }
int src,dest;
cin>>src>>dest;
src--,dest--;
for(int i=0;i<G->V;i++)
PQ[i]=INT_MAX;
top=-1;
if(DT[dest].Pvertex!=INT_MAX)
{PQ[++top]=dest;
 while(PQ[top]!=src)
 {
 v=top;
 PQ[++top]=DT[PQ[v]].Pvertex;
 }
}
else
{cout<<"PATH DOES NOT EXIST";return;}
while(top>=0)
cout<<PQ[top--]+1<<" ";

}

main()
{
Graph *G=new Graph;
G->Matrix=NULL;
cin>>G->V>>G->E;
Create_Matrix(G);
Prims(G,0);
return 0;

}

Friday, October 11, 2013

You are given an unweighted, undirected graph. Write a program to check if it's a tree topology.

I have faced this question in Amazon online test.....
You are given an unweighted, undirected graph. Write a program to check if it's a tree topology.

Input

The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

Output

Print YES if the given graph is a tree, otherwise print NO.

Example

Input:
3 2
1 2
2 3


Output:
YES

Solution:-Things to consider:- 
a) Whether there is cycle or not.
b) Whether there is any connected component exist or not.


General solution Hints:-
Create an Adjacency List/Matrix and maintain an Vector to check out the back edges of the graph if it found return 0, it means it is creating a cycle so it can't be tree. Second thing to consider is whether there is component or not if there is component exist in this case too it can't be tree.

Best Solutions:- Surprisingly solution is very easy if you think hard.
a)First condition can be checked by vertices==edges+1 to be tree.
2)Connected component can be checked by using sets. All edges should be in a single set to be a tree

#include<iostream>
#include<cstdlib>
using namespace std;
void Makeset(int Set[],int N)
{
    for(int i=0;i<=N;i++)
 Set[i]=-1;
}
int Find(int Set[],int size)
{
 if(Set[size]<0)
 return size;
 return Find(Set,Set[size]);
}
bool Union(int Set[],int N)
{
 int u,v,c;
 for(int i=0;i<N;i++)
 { 
  cin>>u>>v;
  --u,--v; //Because values ranges from 1 to n and we have array 0 to n-1 ;)
  u=Find(Set,u);
  v=Find(Set,v);
  if(u==v)
  return false; // if making cycle 
  else if(Set[u]>Set[v])
  {
   c=Set[u];
   Set[u]=v;
   Set[v]+=c; 
  }
  else if(Set[u]<Set[v])
  {
   c=Set[v];
   Set[v]=u;
   Set[u]+=c;
  }
  else
  {
   c=Set[v];
   Set[v]=u;
   Set[u]+=c;
  }
 }
return true;
}
int main()
{   int *Set=NULL;
 int N,M;
 bool f=false;
 cin>>M>>N;
 if(M==N+1)
 {
 Set=new int[M];
  Makeset(Set,N);
 f=Union(Set,N);
 }
if(f)
cout<<"YES";
else
cout<<"NO";
return 0;
}


My solution using Adjacency list goes like this... Don't forget to check out my Adjacency Matrix solution below 
#include<iostream>
using namespace std;
struct Adlist
{
    int data;
    Adlist *next;
};

struct Graph
{
    int V;
    int E;
    Adlist *list;
};

void Create_Graph(Graph *G)
{
  int u,v;
  Adlist *ptr=NULL;
  for(int i=0;i<G->E;i++)
  {   Adlist *node=new Adlist;
      cin>>u>>v;
      u=u-1;
      v=v-1;
      node->data=v;
      node->next=NULL;
   
      if(G->list[u].next==NULL)
      G->list[u].next=node;
      else
      {ptr=G->list[u].next;
      while(ptr->next)
      ptr=ptr->next;
      ptr->next=node;
      }
   
      Adlist *node1=new Adlist;
      node1->data=u;
      node1->next=NULL;
      if(G->list[v].next==NULL)
      G->list[v].next=node1;
      else
      {
          ptr=G->list[v].next;
          while(ptr->next)
          ptr=ptr->next;
          ptr->next=node1;
      }
 
  }
}

void DFS(Graph *G,int u,char *Visited)
{
    if(Visited[u]==49)
    return;
    Visited[u]=49;
 
    for(int v=0;v<G->V;v++)
    {
        DFS(G,v,Visited);
    }
 
}

int main(void)
{ int k=1;
    Graph *G=new Graph;
    if(!G)return 0;
    cin>>G->V>>G->E;
    G->list=new Adlist[G->V];
    if(!G->list)return 0;
   char *Visited=new char[G->V];
   for(int v=0;v<G->V;v++)
    {
        G->list[v].data=0;
        G->list[v].next=NULL;
        Visited[v]=48;
    }
Create_Graph(G);
DFS(G,0,Visited);
for(int i=0;i<G->V;i++)
if(Visited[i]!=49)
{
    k=0;break;
}
if(G->V==G->E+1&&k)
cout<<"YES";
else
cout<<"NO";
}
//By using Adjacency Matrix


#include<iostream>
#include<cstdlib>
using namespace std;

struct Graph
{
int V;
int E;
int **Matrix;
};

Graph *Create(Graph *G)
{
int u,v;
G->Matrix=new int*[G->V];
for(int i=0;i<G->V;i++)
G->Matrix[i]=new int[G->V];
for(int i=0;i<G->E;i++)
{
    cin>>u>>v;
    G->Matrix[u-1][v-1]=1;
    G->Matrix[v-1][u-1]=1;
}
return G;
}

int DFS(Graph *G,int u,int *Visited)
{
    if(Visited[u]!=-1)
    return 0;
    Visited[u]=1;
for(int v=0;v<G->V;v++)
{
    if(G->Matrix[u][v])
       DFS(G,v,Visited);
}
return 1;  
}

int main(void)
{   int *Visited=NULL;
    Graph *G=new Graph;
    cin>>G->V>>G->E;
    G->Matrix=NULL;
    G=Create(G);
    Visited=new int[G->V];
    for(int i=0;i<G->V;i++)
    Visited[i]=-1;
  int k=DFS(G,0,Visited);
  if(k==0)
  cout<<"NO";
  else
  {
      for(int v=0;v<G->V;v++)
      {
          if(Visited[v]==-1)
          {cout<<"NO"; return 0;}
      }
  cout<<"YES";
  }
}



Friday, September 13, 2013

Merge k sorted linked lists and return it as one sorted list

Merge k sorted linked lists with total of N elements and return it as one sorted list...
Sol:- Well, this is very well known problem, and has many solutions.
Naive Approach:-
1. By Merging one list with other and resultant of previous with next lists
2. By Merging lists with pair there will be K/2 lists and now repeat the rest lists untill it became a single         list.

Optimal Approach:-
3. Keeping in mind the list are already sorted so we can use it's benefit. Use Heap which will work in following ways.
a) Take first elements of each lists and Min-Heapify it(least element).
b) Take out root element(least element) from the heap and put it into end of the resultant lists.
c) For step b if there is enough element in that list you have to put next element of the corresponding list to which root belongs.
d)if there is no next element of the corresponding list to which root belongs then replace First position element(Root) of the Heap with last position element and reduce Heap size by 1.
e)Follow the above operation upto N you are done.

//My running code in C++.....

#include<iostream>
#include<cstdlib>
using namespace std;
#define N 25
#define K 5     // so N/K=5 which is no. of possible lists in this case

//List structure
typedef struct List_Structure
{
int data;
struct List_Structure *next;
}List;

// List creation and data insertion  
void Insertion(List **Head,int data)
{
List *Node=(List*)malloc(sizeof(List));
if(!Node){cout<<"Memory Error";return;}
Node->data=data;
Node->next=NULL;
if(!*Head)
{
*Head=Node;
}
else
{
List *temp=*Head;
while(temp->next)
temp=temp->next;
temp->next=Node;
}
}
// Function for list Traversal.
void Traverse(List *Head)
{
if(!Head)return;
cout<<Head->data<<" ";
Traverse(Head->next);
}

//Heapify(min) to get least element out of K elements where K is the no. of lists.
void Heapify(List *a[],int p,int size)
{
int lchild=0,max=0,rchild=0;
List *temp;
lchild=2*p+1;
rchild=2*p+2;
if(rchild>size)
{
rchild=0;
if(lchild>size)
lchild=0;
}
if(rchild)
{
if(a[lchild]->data<a[rchild]->data)
{
if(a[lchild]->data<a[p]->data)
max=lchild;
}
else
{
if(a[rchild]->data<a[p]->data)
max=rchild;
}
}
else if(lchild&&rchild==0)
{
if(a[lchild]->data<a[p]->data)
max=lchild;
}

if(max)
{
temp=a[p];
a[p]=a[max];
a[max]=temp;
}
}

//Heap function goes here.....It's managing function for the problem
List *Heap(List *Head[],int size)
{ List *Root=NULL,*temp=NULL,*ptr=NULL;
List *arr[N/K];
for(int i=0;i<N/K;i++)
arr[i]=Head[i];

for(int i=(size-1)/2;i>=0;i--)
Heapify(arr,i,size);

int i=0;
while(i<N)
{
if(!Root)
{
temp=Root=arr[0];
}
else
{
temp->next=arr[0];
temp=arr[0];

}

if(arr[0]->next!=NULL)
arr[0]=arr[0]->next;
else
{
arr[0]=arr[size];
--size;
}
Heapify(arr,0,size);
i++;
}

return Root;
}

int main(void)
{ List *Head[N/K]={NULL};
for(int i=0;i<N/K;i++)
Head[i]=NULL;
int k=5,j,value;
for(int i=0;i<N/K;i++)
{
for(j=0;j<N/K;j++)
{
cin>>value;
Insertion(&Head[i],value);
}
}
//you lists are as  
for(int i=0;i<N/K;i++)
{
Traverse(Head[i]);
cout<<endl;
}
//Merged list...
List *Start=Heap(Head,N/K-1);
Traverse(Start);
return 0;

}

Sunday, August 18, 2013

Matrix Rotation by 90 Degree Clockwise direction

// Matrix rotation by 90 degree clockwise direction...for N*N matrix.

solution 1:- No extra space.(with extra space see below solution).
#include <stdio.h>
#include <string.h>
#include <math.h>
#define N 4   // for row and column (square matrix).
void Display(int arr[N][N])
{
int i=0,j=0;
for(i=0;i<N;i++)
{ for(j=0;j<N;j++)
  printf("%d ",arr[i][j]);
printf("\n");
}
}
//Rotation goes here
void Rotate(int arr[N][N])
{
int i,j,k,p,temp;  

for(i=0;i<sqrt(N);i++)
{
  k=N-1-i;p=N-1-i;
  for(j=i;j<N-i-1;j++)
  {
      temp=arr[i][j];
      arr[i][j]=arr[k][i];
      arr[k][i]=arr[p][k];
      arr[p][k]=arr[j][p];
      arr[j][p]=temp;
     k--;
  }
}
}
main()
{
    int arr[N][N];
    int i=0,j=0;
    for(i=0;i<N;i++)
     for(j=0;j<N;j++)
       scanf("%d",&arr[i][j]);
      Rotate(arr);
       Display(arr);
      return 0;
}

solution2:- with O(N) extra space

#include <stdio.h>
#include <string.h>
#define N 3
void Display(int arr[N][N])
{
int i=0,j=0;
for(i=0;i<N;i++)
{ for(j=0;j<N;j++)
  printf("%d ",arr[i][j]);
printf("\n");
}
}
//Rotation goes here
void Rotate(int arr[N][N])
{
int i,j,k,p,temp;  
int T[N];
for(i=0;i<2;i++)
{
    for(j=i;j<N-i;j++)
    {
    T[j]=arr[i][j];  
    }
    j--;
    for(k=i;k<N-i;k++)
    {
        temp=arr[k][j];
        arr[k][j]=T[k];
        T[k]=temp;
    }
    k=k--;
    p=i+1;
    for(k--;k>=i;k--)
    {
        temp=arr[j][k];
        arr[j][k]=T[p];
        T[p++]=temp;
    }
    p=i+1;//
    k++;
    for(--j;j>=i;j--)
    {
        temp=arr[j][k];
   
       arr[j][k]=T[p];
        T[p++]=temp;
    }
    j=i;p=i+1;
    for(k=p;k<N-p;k++)
    arr[j][k]=T[k];
}
}
main()
{
    int arr[N][N];
    int i=0,j=0;
    for(i=0;i<N;i++)
     for(j=0;j<N;j++)
       scanf("%d",&arr[i][j]);
      Rotate(arr);
       Display(arr);
      return 0;
}

Saturday, August 17, 2013

Given a circular linked list, implement an algorithm which returns the node at the beginning of the loop

DEFINITION 
Circular linked list: A (corrupt) linked list in which a node's next pointer points 
to an earlier node, so as to make a loop in the linked list. 
EXAMPLE 
Input: A - > B - > C - > D - > E - > C [the same C as earlier] 
Output: C 

#include <stdio.h>
#include <stdlib.h>
 
typedef struct LinkList
{
    int data;
    struct LinkList *next;
}List;
 
void CreateList(List **Head,int value)
{
    List *ptr=NULL,*node=(List*)malloc(sizeof(List));
    node->data=value;
    node->next=NULL;
    if(*Head==NULL)
    *Head=node;
    else
     {ptr=*Head;
      while(ptr->next)
      ptr=ptr->next;
      ptr->next=node;
         
     }
}
 
List *CorruptNode(List *Head)
{
    List *sptr=Head,*fptr=Head;
    if(!Head)return NULL;
    
    while(fptr->next!=NULL)
    {
        fptr=fptr->next;
        if(fptr->next!=NULL)
        fptr=fptr->next;
        else
        break;
        sptr=sptr->next;
        if(fptr==sptr)
        {
            fptr=Head;
            while(fptr!=sptr)
            {
                fptr=fptr->next;
                sptr=sptr->next;
            }
        return fptr;
        }
    }
return NULL;
}
 
 
main()
{  
List *Head=NULL,*Head1=NULL,*Head2=NULL;
int i=0,value,n=3;
printf("Enter the no. of elements in 2nd list ");
scanf("%d",&n);
for(i=0;i<n;i++) {  scanf("%d",&value);  CreateList(&Head1,value); }
printf("Enter the no. of elements in 2nd list ");
scanf("%d",&n);
for(i=0;i<n;i++)                     
{
 scanf("%d",&value);
 CreateList(&Head2,value);
}
 
Head=Head1;
while(Head1->next!=NULL)
Head1=Head1->next;
List *temp;
temp=Head1;
Head1->next=Head2;
while(Head2->next!=NULL)
Head2=Head2->next;
Head2->next=temp;   //creating corrupt node as List1 last node 
temp=CorruptNode(Head);
if(temp)
printf("corrupt one is= %d",temp->data);
else
printf("No corrupt node");
return 0;
}

Friday, August 16, 2013

Adding two numbers using Singly Linked List

This program has asked many times in Amazon written..... Addition of two number's using singly linked list.
// A simple solution would be ..... easy to follow the below program.
Example:- n1=1 2 3
                n2=5 6 7 8
              ouptut would be  5 8 0 1

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

typedef struct LinkList
{
    int data;
    struct LinkList *next;
}List;

void CreateList(List **Head,int value)
{
    List *ptr=NULL,*node=(List*)malloc(sizeof(List));
    node->data=value;
    node->next=NULL;
    if(*Head==NULL)
    *Head=node;
    else
     {ptr=*Head;
      while(ptr->next)
      ptr=ptr->next;
      ptr->next=node;
       
     }
}
void AddLL(List **Head,List *Head1,List *Head2)
{
    int sum=0,h1=0,h2=0;
    List *node=NULL,*ptr=NULL;
   Reverse(&Head1);Reverse(&Head2);
     while(Head1!=NULL||Head2!=NULL||sum>0)
     {   h1=0;h2=0;
         if(Head1!=NULL)
         {h1=Head1->data;Head1=Head1->next;}
         if(Head2!=NULL)
         {h2=Head2->data;Head2=Head2->next;}
         sum+=h1+h2;
         node=(List *)malloc(sizeof(List));
         node->data=sum%10;
         node->next=NULL;
         sum/=10;
         if(*Head==NULL)
         {
             *Head=node;
             ptr=*Head;
         }
         else
         {
             ptr->next=node;
             ptr=ptr->next;
         }
     }

Reverse(Head);
}

void Reverse(List **Head)
{
 List *temp=NULL,*ptr=*Head,*prev=NULL;
 if(!ptr)return;
 while(ptr->next!=NULL)
 {
     temp=ptr->next;
     ptr->next=prev;
     prev=ptr;
     ptr=temp;
 }
 ptr->next=prev;
 *Head=ptr;
}

void Display(List *ptr)
{
    if(!ptr)return;
    printf("%d ",ptr->data);
    Display(ptr->next);
}
main()
{
List *Head=NULL,*Head1=NULL,*Head2=NULL;
int i=0,value,n;
printf("Enter the length of digit of first no.\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
 scanf("%d",&value);
 CreateList(&Head1,value);
}
printf("\nEnter the length of digit of first no.\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
 scanf("%d",&value);
 CreateList(&Head2,value);
}
printf("\n");
AddLL(&Head,Head1,Head2);
Display(Head);
return 0;
}

Quicksort using singly linked list

//Quicksort using singly linked list.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct LinkList 
{
    int data;
    struct LinkList *next;
}List;
void Insert(List **Head,int value)
{
    List *ptr=*Head;
    List *newnode;
    newnode=(List*)malloc(sizeof(List));
    newnode->data=value;
    newnode->next=NULL;
    if(ptr==NULL)
    *Head=newnode;
    else
    {
        while(ptr->next!=NULL)
        ptr=ptr->next;
        ptr->next=newnode;
    }
    
}
void Quicksort(List *Head,List *end)
{  if(Head==end)return;
    int count=0,count1=0,count2=0,temp=0;
    List *front=Head,*back=end,pf,bf,*ptr=Head,*pivot=Head;
    while(ptr!=end)
    {
        count++;
        ptr=ptr->next;    
    }
 
    while(count>=0&&front->next!=back)
    {
        while(front->next&&front->next->data<pivot->data)
          front=front->next;
        while(count>0&&front->next!=back)
        {
            back=Head;
            count1=--count;
            while(count1)
            {
                back=back->next;
                count1--;
            }
            if(back->data<pivot->data)
            {
               temp=front->next->data;
               front->next->data=back->data;
               back->data=temp;
               front=front->next;
               count;
               break;
            }
        }
   
   }
    temp=front->data;
    front->data=pivot->data;
    pivot->data=temp;
   // Display(Head);
    Quicksort(Head,front);
   Quicksort(front->next,end);
}
void Display(List *Head)
{
    if(!Head)return ;
    printf("%d  ",Head->data);
    Display(Head->next);
}
int main(void)
{
List *Head=NULL;
int i,value;
for(i=0;i<10;i++) 
{
    scanf("%d",&value);
    Insert(&Head,value);
}
    Display(Head);printf("\n");
    Quicksort(Head,NULL);
    printf("\n");
   Display(Head);
return 0;    
}
// Input could be like... 9  8  11  2  15  4  13  1  17  5