Mar 19, 2022

Length of longest common subsequence of two strings

#include <iostream>

#include <cstring>

using namespace std;

int mem[100][100];

int max(int a, int b)

{

    return (a>b)?a:b;

}


int lcs(char* s, char* t, int i, int j)

{

    if(i<0 || j<0)

        return 0;


    if(mem[i][j] != -1)

        return mem[i][j];

        

    if(s[i] != t[j])

    {

        mem[i][j] = max(lcs(s,t,i-1,j), lcs(s,t,i,j-1));

    }

    else

    {

        mem[i][j] = 1 + lcs(s,t,i-1,j-1);

    }


    return mem[i][j];

}




int main() {

// your code goes here

char s[] = "thsi is a bir senrence to find eit distance";

char t[] = "this is a big sentence to find edit distance";

    memset(mem, -1, sizeof(mem));

int len = lcs(s,t,strlen(s)-1, strlen(t)-1);

cout << "length of longest common subsequence between <"<<s<<"> and <" << t << "> is " << len;

return 0;

}


Output:

length of longest common subsequence between <thsi is a bir senrence to find eit distance> and <this is a big sentence to find edit distance> is 40



+++++++++++++++++++++++

using dynamic programming

+++++++++++++++++++++++


#include <iostream>

#include <cstring>


using namespace std;


//longest common subsequence between 2 strings


int mem[20][20];


int max(int a, int b) { return a>b?a:b; }


int lcs(char s1[], int l1, char s2[], int l2)

{

    

    int len = 0;

    

    if(mem[l1][l2] != -1)

        return mem[l1][l2];

        

    for(int i=0; i<l1; i++)

    {

        for(int j=0; j<l2; j++)

        {

            if(s1[i] == s2[j])

            {

                mem[i][j] = (i>0 && j>0)?1+ mem[i-1][j-1]:1;

            }

            else

            {

                mem[i][j] = max((j>0)?mem[i][j-1]:0, (i>0)?mem[i-1][j]:0);

            }

        }

        

    }

    

    return mem[l1-1][l2-1];

}



int main() {

// your code goes here

memset(mem, -1, sizeof(mem));

char a[] = "subsequence";

char b[] = "queue";

int len = lcs(a,strlen(a), b, strlen(b));

cout << "LCS between " << a << " and " << b << " is=" << len;

return 0;

}



output:
LCS between subsequence and queue is=4

Edit distance between two strings

 #include <iostream>

#include <climits>

#include <cstring>

using namespace std;


int min(int a, int b, int c)

{

    return (a<b)? (a<c?a:c):(b<c?b:c);

}

int editDistance(char* s, char* t, int i, int j)

{  

    if(i==0)

        return j;

    if(j==0)

        return i;

        

        

    if(s[i]!=t[j])

    {

        //either s[0, i-1] = t[j] or s[0, i-1] = t[0, j-1] or s[0, i] = t[0,j-1]

        return 1+min(editDistance(s,t,i-1,j), editDistance(s,t,i-1,j-1), editDistance(s,t,i,j-1));

    }

    else

        return editDistance(s, t, i-1, j-1); //it is same as the ed(s[0,i-1], t[0,j-1]

}


int main() {

// your code goes here

char s[] = "organisation";

char t[] = "organisaton";

int dist = editDistance(s, t, strlen(s)-1, strlen(t)-1);

cout << "edit distance of " << s << " and " << t << " is " << dist;

return 0;

}


Output:
edit distance of organisation and organisaton is 1

---------------------------------------------------------------------------------------------

#include <iostream>
#include <climits>
#include <cstring>
using namespace std;

int min(int a, int b, int c)
{
    return (a<b)? (a<c?a:c):(b<c?b:c);
}
int editDistance(char* s, char* t, int i, int j, int mem[100][100])
{
    if(i <0 || j<0)
        return 1;
    
    if(mem[i][j] != -1)
        return mem[i][j];
        
    if(i==0)
        return j;
    if(j==0)
        return i;
        
        
    if(s[i]!=t[j])
    {
        //either s[0, i-1] = t[j] or s[0, i-1] = t[0, j-1] or s[0, i] = t[0,j-1]
        mem[i][j] = 1+min(editDistance(s,t,i-1,j, mem), editDistance(s,t,i-1,j-1, mem), editDistance(s,t,i,j-1, mem)); 
    }
    else
        mem[i][j] = editDistance(s, t, i-1, j-1, mem); //it is same as the ed(s[0,i-1], t[0,j-1]
        
    return mem[i][j];
}

int main() {
// your code goes here
char s[] = "thsi is a bir senrence to find eit distance";
char t[] = "this is a big sentence to find edit distance";
int mem[100][100];
memset(mem, -1, sizeof(mem));
int dist = editDistance(s, t, strlen(s)-1, strlen(t)-1, mem);
cout << "edit distance of <" << s << "> and <" << t << "> is " << dist;
return 0;
}


Output:
edit distance of <thsi is a bir senrence to find eit distance> and <this is a big sentence to find edit distance> is 5


----------------------------------------------
3.5ms 5.5KB memory  (with memorisation)
5s 5.4KB memory (without memorisation)

Mar 18, 2022

Find missing number in 0 to n

Problem -

An array A contains all the integers from Oto n, except for one number which

is missing. In this problem, we cannot access an entire integer in A with a single operation. The

elements of A are represented in binary, and the only operation we can use to access them is "fetch

the jth bit of A[ i ],"which takes constant time. Write code to find the missing integer. Can you do

it in O(n) time?



Solution -


        BITWISE XOR

00000000 0

00000001 1

00000010 11

00000011 0

00000100 100

00000101 1

00000110 111

00000111 0

00001000 1000

00001001 1

00001010 1011

00001011 0

00001100 1100

00001101 1

00001110 1111

00001111 0

00010000 10000


If BITWISE XOR is performed on all numbers from 0 to n then

- if n%4 == 0   then BITWISE_XOR(0,n) = n

- if n%4 == 1   then BITWISE_XOR(0,n) = 1

- if n%4 == 2   then BITWISE_XOR(0,n) = n+1

- if n%4 == 3   then BITWISE_XOR(0,n) = 0



Hence the missing number can be calculated by performing BITWISE_XOR on the computed BITWISE_XOR(0,n)


missing number = BITWISE_XOR ( BITWISE_XOR(given numbers),  BITWISE_XOR(0,n))


BITWISE_XOR(0,n)            - O(1)

BITWISE_XOR(given numbers)  - O(n)


Hence the overall time complexity is O(n)


Mar 17, 2022

Random set

 #include <iostream>

using namespace std;


//Write a method to randomly generate a set of m integers from an array of size n. Each

// element must have equal probability of being chosen.


void printArray(int a[], int n)

{

    for(int i=0; i<n; i++)

    {

        cout << a[i] << " ";

    }  

    cout << endl;

}


void shuffle(int a[], int n)

{

    for(int i=n-1; i>=1; i--)

    {

        swap(a[i], a[rand()%(i)]);

    }

}


void randomSet(int a[], int n, int b[], int m)

{

    if(m>n)

        return;

        

    for(int i=n-1, j=0; i>=1 && j<m; i--, j++)

    {

        int k = rand()%(i);

        b[j] = a[k];

        swap(a[i], a[k]);

    }

}


int main() {

// your code goes here

int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

int b[100];

printArray(a, sizeof(a)/sizeof(a[0]));

// shuffle(a, sizeof(a)/sizeof(a[0]));

printArray(a, sizeof(a)/sizeof(a[0]));

randomSet(a, sizeof(a)/sizeof(a[0]), b, sizeof(a)/sizeof(a[0]) - 4);

printArray(b, sizeof(a)/sizeof(a[0]) - 4);

return 0;

}


Output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
2 10 14 3 4 8 12 9 11 15 13 

Shuffle a deck of cards

 #include <iostream>

using namespace std;


//Write a method to shuffle a deck of cards.


void printArray(int a[], int n)

{

    for(int i=0; i<n; i++)

    {

        cout << a[i] << " ";

    }  

    cout << endl;

}

void shuffle(int a[], int n)

{

    for(int i=n-1; i>=1; i--)

    {

        swap(a[i], a[rand()%(i)]);

    }

}

int main() {

// your code goes here

int a[] = {1, 2, 3, 4, 5, 6};

printArray(a, sizeof(a)/sizeof(a[0]));

shuffle(a, sizeof(a)/sizeof(a[0]));

printArray(a, sizeof(a)/sizeof(a[0]));

return 0;

}


Output:
1 2 3 4 5 6 
5 6 2 1 3 4 

Mar 16, 2022

Find pair of a given sum in an array

 #include <iostream>

using namespace std;


void sumOfPair(int a[], int n, int sum)

{

    int left =0, right=n-1;

    while(left<right)

    {

        if(a[left]+a[right]==sum)

        {

            cout << "left="<<left << ", right=" << right;

            return;

        }

        else if(a[left]+a[right]>=sum)

            right--;

        else

            left++;

    }

}


int main() {

// your code goes here

int sortedArray[] = {1, 2, 3, 4, 6, 8, 9, 13, 17, 21, 29, 31};

sumOfPair(sortedArray, sizeof(sortedArray)/sizeof(sortedArray[0]), 27);

return 0;

}


number of paths in a matrix from top left to bottom right

#include using namespace std; 

int numPathsInMatrix(int m, int n) 
{
 if(m==1 || n==1) return 1; 

return numPathsInMatrix(m-1, n) + numPathsInMatrix(m, n-1); 
}

 int main() { 
// your code goes here cout << numPathsInMatrix(4,4); 
return 0; 
}

Mar 15, 2022

Check if 2 line segments intersect and find point of intersection

 #include <iostream>

using namespace std;


// Given two straight line segments (represented as a start point and an end point),

// compute the point of intersection, if any.


//Logic - To be able to intersect the slopes should be opposite

bool doIntersect(int sx, int sy, int ex, int ey, int s1x, int s1y, int e1x, int e1y)

{

    float slope1 = (sy-s1y)/(sx-s1x);

    float slope2 = (e1y-sy)/(e1x-sx);

    float slope3 = (ey-s1y)/(ex-s1x);

    float slope4 = (e1y-ey)/(e1x-ex);

    

    if(slope1>=slope2 && slope3>=slope4)

        return false;

    if(slope1>=slope2 && slope3<=slope4)

        return true;

    if(slope1<=slope2 && slope3<=slope4)

        return false;

    if(slope1<=slope2 && slope3>=slope4)

        return true;


    

}


//point of intersect can be computed using slope formula

//say Ix. Iy is the intersection then slope(S,I) = slope(I,E) and slope(S1,I) = slope(I,E1)

//This will generate 2 equations with 2 unknowns and hence can be solved.

//special cases should be checked where either segments start or end lie on the other. In that case

// the distance formula can be used to verify.


int main() {

// your code goes here

bool res = doIntersect(1,2,3,4,2,6,2,-8);

if(res)

    cout << "intersect";

else

    cout << "don't intersect";

return 0;

}


Mar 12, 2022

Grid travel (find path by dynamic prog)

 #include <iostream>

#include <cstring>

using namespace std;

// Imagine a robot sitting on the upper left corner of grid with r rows and c columns.

// The robot can only move in two directions, right and down, but certain cells are "off limits" such that

// the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to

// the bottom right.


bool findPath(int r, int c, int currow, int curcol, int path[], int top)

{

    

    if(r<0 || c<0)

        return false;

        

    if(r ==1 && c == 1)

    {

        return true;

    }

    

    if(r == currow+1 && c == curcol+1)

        return true;

    

    if(currow+1 > r)

        return false;

        

    if(curcol+1 > c)

        return false;

        


    if(curcol ==0 && currow == 2)   // 1=off-limit cell, 0=ok

        return false;

    

    if(curcol ==1 && currow == 4)   // 1=off-limit cell, 0=ok

        return false;

        

    path[top] = 0; //down   

    bool b1 = findPath(r, c, currow+1, curcol, path, top+1);

    

    if(b1) return b1;

    

    path[top] = 1; //right

    bool b2 = findPath(r, c, currow, curcol+1, path, top+1);

    

    if(b2) return b2;

    

    return false;

}


void printPath(int a[])

{

    for(int i=0; i<50 && a[i]!=-1; i++)

        cout << ((a[i] == 0) ? 'd':'r')  << "-->";

}


int main() {

// your code goes here

int path[50];

memset(path, -1, 50*sizeof(int));

findPath(5, 5, 0, 0, path, 0);

printPath(path);

return 0;

}


output:
d-->r-->d-->d-->r-->d-->r-->r-->

Count steps using Dynamic prog

 #include <iostream>

#include <cstring>

using namespace std;

// A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3

// steps at a time. Implement a method to count how many possible ways the child can run up the

// stairs.


int countSteps(int n, int mem[])

{

    if(n<0)

        return 0;

        

    

    if(n==0 || n==1)

        return 1;

    

    if(mem[n]) return mem[n];

    

    mem[n] = countSteps(n-1, mem) + countSteps(n-2, mem) + countSteps(n-3, mem);

    return mem[n];

}

int main() {

// your code goes here

int mem[50];

memset(mem, 0, 50*sizeof(int));

cout << countSteps(10, mem) << endl;

return 0;

}


Mar 10, 2022

Fibonacci using DP

 #include <iostream>

#include <cstring>

using namespace std;


int fib(int n, int mem[])

{

    if(mem[n] != 0)

    {

        return mem[n];

    }

    if(n <= 2)

        return 1;

        

    mem[n] = fib(n-1, mem) + fib(n-2, mem);

    return mem[n];

}


int main() {

// your code goes here

int mem[50];

memset(mem, 0, 50*sizeof(int));

    

    cout << fib(30, mem) ;

return 0;

}


Mar 9, 2022

Check if list is a palindrome

 #include <iostream>

using namespace std;


class node{

    public:

    char e;

    node* next;

} ;


void printList(node* t)

{

    while(t)

    {

        cout << t->e << "->";

        t=t->next;

    }

    cout << endl;

}

node* buildList(char a[], int n)

{

    node* root = NULL;

    node* prev = NULL;

    for(int i=0; i<n; i++)

    {

        node* iter = new node();

        if(i==0)

        {

         root = iter;

        }

        

        iter->e = a[i];

        iter->next = NULL;

        if(prev)

            prev->next = iter;

        prev = iter;

    }

    


    printList(root);

    return root;

}


bool checkPalindromeRec(node** fwIter, node* revIter)

{

    if(!revIter)

        return true;

    

    bool res = checkPalindromeRec(fwIter, revIter->next);

    if(res && (*fwIter)->e == revIter->e)

    {

        *fwIter = (*fwIter)->next;

        return true;

    }

    

    return false;

}


void checkPalindrome(node* t)

{

    if(checkPalindromeRec(&t, t))

        cout << "it is a palindrome";

    else

        cout << "it is not a palindrome";

}

int main() {

// your code goes here

char a[] = {'a', 'r', 't', 'r', 'a'};

node* root = buildList(a, sizeof(a)/sizeof(a[0]));

checkPalindrome(root);

return 0;

}


Mar 8, 2022

Rotate matrix in place

 #include <iostream>

using namespace std;


void printMatrix(int a[4][4])

{

    for(int i=0;i<4;i++)

    {

        for(int j=0;j<4;j++)

        {

            cout << a[i][j] << " ";

        }

        cout << endl;

    }

}

void rotateMatrixInPlace(int a[4][4])

{

    cout << "before rotation\n";

    printMatrix(a);

    

// Transpose 

    for(int i=0;i<4; i++)

    {

        for(int j=i+1;j<4;j++)

        {

            int t = a[i][j];

            a[i][j] = a[j][i];

            a[j][i] = t;

        }

        

    }


// Mirror    

    for(int i=0;i<4; i++)

    {

        for(int j=0;j<2;j++)

        {

            int t = a[i][j];

            a[i][j] = a[i][3-j];

            a[i][3-j] = t;

        }

    }

    

    cout << "after rotation\n";

    printMatrix(a);

}

int main() {

// your code goes here

int a[4][4] = 

{

    1, 2, 3, 4,

    5, 6, 7, 8,

    9, 0, 1, 2,

    3, 4, 5, 6

};

rotateMatrixInPlace(a);

return 0;

}


one away string

 #include <iostream>

#include <cstring>


using namespace std;


const int maxsize = 128;


void oneAway(char a[], char b[])

{

    int dist = strlen(a) - strlen(b);

    if(dist  > 1 || dist  < -1 )

    {

        cout << "false";

        return;

    }

    

    

    

    if(dist == 0)

    {

        //check for 1 replace

        int p=0;

        for(int i=0; i< strlen(a); i++)

        {

            if(a[i] != b[i])

            {

                ++p;

                if(p>1)

                {

                    cout << "false";

                    return;

                }

            }

        }

    }

    else

    {

        //check for 1 insert or remove :  (ab, a | b), (b, ab | ba)

        int p=0;

        int index = strlen(a) > strlen(b) ? 1 : 0;

        int len =  (index == 1) ? strlen(a) : strlen(b);

        int change=0;

        for(int i=0, j=0; i<len; i++, j++)

        {

            if(a[i] != b[j])

            {

                if(index == 1)

                {

                    i++;

                    change++;

                }

                else

                {

                    j++;

                    change++;

                }

            }

            

            if(change >1)

            {

                cout << false;

                return;

            }

            

        }

    }

    

    cout << "true";

}


int main() {

// your code goes here

char *a = "pale";

char *b = "pale";

oneAway(a, b);

return 0;

}


Permutation palindrome

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

const int maxsize = 128;

void is_permutationPalindrome(char s[])
{
    char r[maxsize];
    memset(r, 0, maxsize);

    for(int i=0; i<strlen(s); i++)
    {
        r[s[i]] ++;
    }
    
    int num_evens = 0, num_odds = 0;
    
    for(int i=0; i<maxsize; i++)
    {
        if(r[i] %2 == 0)
            num_evens++;
        else
            num_odds++;
    }
    
    if(num_odds == 1 || num_odds == 0)
        cout << "it is a palindrome permutation";
    else
        cout << "it is not a palindrome permutation";
}

int main() {
// your code goes here
char *s = "defer";
is_permutationPalindrome(s);
return 0;
}

Mar 7, 2022

Find maximum average subarray of k length

#include using namespace std; int maxAverageSubarray(int a[], int alen, int k) { if(alen < k) return -1; int max_sum = 0; for(int i=0;i max_sum) { max_sum = sum; index = i; } } return index-k+1; } int main() { // your code goes here int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << "The maximum average subarray of " "length "<< k << " begins at index " << maxAverageSubarray(arr, n, k); return 0; }

Substring in a given string

#include #include using namespace std; int substrpos(char s[], char t[]) { if(( (!s) || (!t) || strlen(s) < strlen(t)) ) return -1; for(int i=0; i<(strlen(s)-strlen(t))+1; i++) { int j=0; for(;j

Segregate 0s and 1s in an array

#include using namespace std; void groupZeroOne(int a[], int len) { int left = 0; int right = len-1; while(left < right) { if(a[left] == 1) { while(right > left && a[right] == 1) right--; int t=a[left]; a[left] = a[right]; a[right] = t; left++; right--; } else left++; } } void printArray(int a[], int len) { for(int i=0;i

Sort an array of 0s, 1s and 2s

#include using namespace std; void printArray(int a[], int len) { for(int i=0;i left && a[right] == val) right--; int t=a[left]; a[left] = a[right]; a[right] = t; left++; right--; } else left++; } if(a[right] == val) right--; return right; } int main() { // your code goes here int a[] = {1,0,2,0,1,2,1,2,0,1,1}; cout << "before arrangement- "; printArray(a, sizeof(a)/sizeof(int)); int twoIndex = groupZeroOneTwo(a, sizeof(a)/sizeof(int) - 1, 2); cout << "after arrangement1- "; printArray(a, sizeof(a)/sizeof(int)); groupZeroOneTwo(a, twoIndex, 1); cout << "after arrangement2- "; printArray(a, sizeof(a)/sizeof(int)); return 0; }

Count all distinct pairs with difference equal to k

#include #include using namespace std; void printArray(int a[], int len) { for(int i=0;i k) l++; } cout << "count =" << count; } int main() { // your code goes here int a[] = {8, 12, 16, 4, 0, 20}; cout << "array - "; printArray(a, sizeof(a)/sizeof(a[0])); countPairsWithDiffK(a, sizeof(a)/sizeof(a[0]), 4); return 0; }

sort an array using quicksort

#include #include using namespace std; void printArray(int a[], int len) { for(int i=0;i=r) return; //choose pivot int m = l; //this loop brings all elements < a[l] within m and > a[l] from m+1 to r for(int i=l+1; i<=r; i++) { if(a[i] < a[l]) { m++; int t=a[i]; a[i] = a[m]; a[m] = t; } } //move a[l] to pivot position which will make it rightly positioned in the array int t = a[m]; a[m] = a[l]; a[l] = t; qksort(a, l, m-1); qksort(a, m+1, r); } int main() { // your code goes here int a[] = {8, 12, 16, 4, 0}; cout << "before sorting - "; printArray(a, sizeof(a)/sizeof(a[0])); qksort(a, 0, sizeof(a)/ sizeof(a[0]) - 1); cout << "after sorting - "; printArray(a, sizeof(a)/sizeof(a[0])); return 0; }

Minimum length unsorted array

#include using namespace std; void printArray(int a[], int len) { for(int i=0;i a[i+1]) { left = i; break; } } if(left == -1) { cout << "arary is sorted"; return; } for(int i=n-1; i>left; i--) { if(a[i] < a[i-1]) { right = i; break; } } int min=a[left]; int max=a[left]; for(int i=left+1; i<=right; i++) { if(a[i] < min) min = a[i]; if(a[i] > max) max = a[i]; } for(int i=0;i min) { left = i; break; } } for(int i=n; i>right-1; i--) { if(a[i] < max) { right = i; break; } } cout << "left =" << left << " right=" << right << endl; } int main() { // your code goes here int a[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60}; cout << "array - "; printArray(a, sizeof(a)/sizeof(int)); minLengthUnsortedSubArray(a, sizeof(a)/sizeof(int)); return 0; }

Maximum sum sub matrix

 #include <iostream>

using namespace std;



void resetArray(int a[], int row)

{

    for(int i=0; i<row; i++)

    {

        a[i] = 0;

    }

}


void printMatrix(int a[4][4], int maxleft, int maxright, int maxup, int maxdown)

{

    cout << "\n";

    for(int i=maxup; i<=maxdown; i++)

    {

        for(int j=maxleft; j<= maxright; j++)

        {

            cout << a[i][j] << " ";

        }

        cout << endl;

    }

}


void maxSumSubMatrix(int a[4][4], int row, int col)

{

    int sum = 0, maxSum = 0;

    

    int sumColumn[row];


    int maxleft = 0, maxright = 0,  maxup = 0, maxdown = 0;

    int curup = 0;

    

    for(int i=0; i<col; i++)

    {

        resetArray(sumColumn, row);

        for(int j=i; j<col; j++)

        {

            sum = 0;

            curup = 0;

            for(int k=0; k<row; k++)

            {

                // cout << endl << sumColumn[k] << " + " << a[k][j] << "=";

                sumColumn[k] += a[k][j];

                // cout << sumColumn[k];

                sum += sumColumn[k];

                // cout << "  sumsofar=" << sum ;

                if(sum > maxSum)

                {

                    maxSum = sum;

                    maxleft = i;

                    maxright = j;

                    maxdown = k;

                    maxup = curup;

                    

                    // cout << " i:" << i << " j:" << j;

                    // cout << " maxsum:" << maxSum << " sum:" << sum;

                    // cout << " maxleft:" << maxleft << " maxright:" << maxright;

                    // cout << " maxup:" << maxup << " maxdown:" << maxdown << endl;

                }

                else if(sum <= 0)

                {

                    sum = 0;

                    curup = k+1;

                }                

            }

        }

    }

    

    printMatrix(a, maxleft, maxright, maxup, maxdown);

}


int main() {

// your code goes here

int a[4][4] = {

        1, -2,-1, 3,

        3,-6, 7, -4,

   -5, 3, 0, 2,

    -4, 5,-2, 1

};

printMatrix(a, 0, 3, 0, 3);

cout << "Maximum sum sub matrix is: " << endl;

maxSumSubMatrix(a, 4, 4);

return 0;

}


Mar 4, 2022

Alternate recursive implementation to reverse a list

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

class node {
    public:
    int e;
    node* next;
};

void printList(node* r)
{
    while(r)
    {
        cout << "[" << r->e << "]->";
        r = r->next;
    }
    cout << endl;
}

node* buildList()
{
    int size = 5;
    node* prev=NULL;
    node* root;
    node* cur;
    for(int i=0; i<size; i++)
    {
        cur = new node();
        cur->e = rand() % 100;
        if(prev)
        {
            prev->next = cur;
            prev = cur;
        }
        else
        {
            prev = cur;
            root = cur;
        }
    }
    
    cur->next = NULL;
    
    return root;
}
node* reverseList(node* r, node** newRoot)
{
    if(!r->next)
    {
        *newRoot = r;
        return r;
    }
    
    node* last = reverseList(r->next, newRoot);
    //A->1->2->B => A->2->1->B
    //r=1, r->next =2, last=2, last->next=B
    r->next = last->next;
    last->next = r;
    return r;
}

int main() {
// your code goes here
node* root=buildList();
cout<< "before reversing: ";
printList(root);
node* newRoot;
reverseList(root, &newRoot);
cout<< "after reversing: ";
printList(newRoot);
return 0;
}

  ------------------------
  output
  
  before reversing: [83]->[86]->[77]->[15]->[93]->
  after reversing: [93]->[15]->[77]->[86]->[83]->

Mar 2, 2022

Print all permutations of a string

#include <iostream>
#include <cstring>
#include <string>
#define MAXSIZE 256
#define PATSIZE 10
using namespace std;

void permute(char str[], int l, int r)
{
    
    if(l==r)
    {
        cout&lt;&lt; str &lt;&lt; endl;
        return;
    }    
   
    
    for(int i=l;i&lt;=r;i++)
    {
        swap(str[l], str[i]);

        permute(str, l+1, r);
        
        swap(str[l], str[i]);      
    }

}

int main() {
// your code goes here
char txt[] = "abcd";
permute(txt, 0, strlen(txt)-1);
return 0;
}

Mar 1, 2022

Pattern searching using finite automata

#include <iostream>
#include <cstring>
#include <string>
#define MAXSIZE 256
#define PATSIZE 10
using namespace std;

// pat = 'ABCAD' ==> 
// state | A | B | C | D |
//   0   | 1 | 0 | 0 | 0 |
//   1   | 1 | 2 | 0 | 0 |
//   2   | 1 | 0 | 3 | 0 |
//   3   | 4 | 0 | 0 | 0 |
//   4   | 1 | 0 | 0 | 5 |
//
void constructFA(char pat[], int m, int FA[][MAXSIZE])
{
    for(int i=0; i<m; i++)
    {
        FA[i][pat[0]] = 1;
        FA[i][pat[i]] = i+1;
    }
}

void findMatch(char txt[], int n, char pat[], int m, int FA[][MAXSIZE])
{
    int state=0;
    for(int i=0; i<n; i++)
    {
        state = FA[state][txt[i]];
        if(state == m)
        {
            cout << "index=" << i << ": " << string(txt).substr(i,n-i+1)<< endl;
            state = 0;
        }
    }
}
int main() {
// your code goes here
char txt[] = "This is a test. It is new.";
char pat[] = "is";
int FA[PATSIZE][MAXSIZE];
constructFA(pat, strlen(pat)-1, FA);
findMatch(txt, strlen(txt)-1, pat, strlen(pat)-1, FA);
return 0;
}

--------------------------------
  output:
index=2: is is a test. It is new.
index=5: is a test. It is new.
index=19: is new.