0% found this document useful (0 votes)
83 views22 pages

DS Interview Coding

1. The document discusses various algorithms related to data structures like stacks, queues, trees. It includes implementations of reversing a string using a stack, checking balanced parentheses using a stack, tree traversals, checking if a binary tree is a BST, converting a binary tree to a doubly linked list, and implementing a stack using two queues. The time complexity of most algorithms is O(n). 2. Some key algorithms discussed are reversing a string using a stack in O(n) time, checking balanced parentheses in a string using a stack, different tree traversal algorithms like inorder, preorder and postorder, checking if a given binary tree is a BST, and implementing a stack using two queues where push is a costly operation

Uploaded by

Manaswinee C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views22 pages

DS Interview Coding

1. The document discusses various algorithms related to data structures like stacks, queues, trees. It includes implementations of reversing a string using a stack, checking balanced parentheses using a stack, tree traversals, checking if a binary tree is a BST, converting a binary tree to a doubly linked list, and implementing a stack using two queues. The time complexity of most algorithms is O(n). 2. Some key algorithms discussed are reversing a string using a stack in O(n) time, checking balanced parentheses in a string using a stack, different tree traversal algorithms like inorder, preorder and postorder, checking if a given binary tree is a BST, and implementing a stack using two queues where push is a costly operation

Uploaded by

Manaswinee C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

REVERSING STRING USING STACK:

TIME COMPLEXITY O(n)


1)
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
#include <limits.h>
struct stack
{
int top;
unsigned capacity;
char* array;
};
struct stack* createstack(unsigned capacity)
{
struct stack * stack = (struct stack*)malloc(sizeof(struct stack));
stack->top =-1;
stack->capacity=capacity;
stack->array=(char*)malloc(stack->capacity*sizeof(char));
return stack;

};
int isfull(struct stack* stack)
{
return stack->top == stack->capacity-1;

}
int isempty(struct stack* stack)
{

return stack->top == -1;

}
void push(struct stack* stack,char item)
{

if(isfull(stack))
return;
stack->array[++stack->top]=item;
}
char pop(struct stack* stack)
{

if(isempty(stack))
return INT_MIN;
return stack->array[stack->top--];
}

void reverse(char str[])


{
int n =strlen(str);
struct stack* stack = createstack(n);
int i;
for(i=0;i<n;i++)
{
push(stack,str[i]);
}
for(i=0;i<n;i++)
{
str[i]=pop(stack);
}

int main()
{

char str[]="karupanar";
reverse(str);
printf("The reversed string is %s",str);
return 0;
}

2)REVERSE STRING GENERAL

# include <stdio.h>
# include <string.h>
void swap(char *a,char* b)
{

char temp=*a;
*a=*b;
*b=temp;;

}
void reverse(char str[])
{
int i;
int n =strlen(str);

for(i=0;i<n/2;i++)
{
swap(&str[i],&str[n-i-1]);

}
}
int main()
{
char str[] = "GAMA";
reverse(str);
printf("The reversed string is %s",str);
return 0;

}
3) BALANCED PARENTHESIS USING STACK
Time complexity O(n)

#include <stdio.h>
#include <stdlib.h>
#define bool int

struct sNode {
char data;
struct sNode* next;
};

void push(struct sNode** top_ref, int new_data);

int pop(struct sNode** top_ref);

bool isMatchingPair(char character1, char character2)


{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}

bool areParenthesisBalanced(char exp[])


{
int i = 0;

struct sNode* stack = NULL;

while (exp[i]) {

if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')


push(&stack, exp[i]);

if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') {

if (stack == NULL)
return 0;

else if (!isMatchingPair(pop(&stack), exp[i]))


return 0;
}
i++;
}

if (stack == NULL)
return 1;
else
return 0;
}
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}

void push(struct sNode** top_ref, int new_data)


{
struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode));

if (new_node == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}

new_node->data = new_data;

new_node->next = (*top_ref);

(*top_ref) = new_node;
}

int pop(struct sNode** top_ref)


{
char res;
struct sNode* top;

if (*top_ref == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
4) program to check whether given binary tree is BST OR NOT:
TIMECOMPLEXTIY = O(n)
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

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

int isBSTUtil(struct node* node, int min, int max);

int isBST(struct node* node)


{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}

int isBSTUtil(struct node* node, int min, int max)


{

if (node==NULL)
return 1;

if (node->data < min || node->data > max)


return 0;

return
isBSTUtil(node->left, min, node->data-1) &&
isBSTUtil(node->right, node->data+1, max);
}

struct node* newNode(int data)


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

return(node);
}

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

if(isBST(root))
printf("Is BST");
else
printf("Not a BST");

getchar();
return 0;
}
5) TREE TRAVERSAL
TIME COMPLEXITY O(n)
# include <stdio.h>
# include <stdlib.h>
struct node
{
char data;
struct node*left;
struct node*right;
};
struct node* newnode(int data)
{
struct node * node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);

}
void inorder(struct node* root)
{
if(root == NULL)
return;
inorder(root->left);
printf("%c ",root->data);
inorder(root->right);
}
void preorder(struct node* root)
{
if(root == NULL)
return;

printf("%c ",root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(struct node* root)
{
if(root == NULL)
return;
postorder(root->left);
postorder(root->right);
printf("%c ",root->data);
}
int main()
{
struct node * root = newnode('A');
root->left=newnode('B');
root->right=newnode('C');
root->left->right=newnode('D');
root->right->left=newnode('E');
root->right->right=newnode('F');
root->right->left->left=newnode('G');
root->right->right->left=newnode('H');
root->right->right->right=newnode('I');

printf("\nThe inorder traversal is \n");


inorder(root);
printf("\nThe preorder traversal is \n");
preorder(root);
printf("\nThe postorder traversal is \n");
postorder(root);

}
6) HEIGHT OF THE BINARY TREE
TIME COMPLEXITY O(n)
#include<stdio.h>
#include<stdlib.h>

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

int maxDepth(struct node* node)


{
if (node==NULL)
return 0;
else
{
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int main()
{
struct node *root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Height of tree is %d", maxDepth(root));

getchar();
return 0;
}
7) binary to DLL

# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;

};
struct node* head ,*tail=NULL;
struct node* root;

struct node* newnode(int data)


{
struct node * newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
return(newnode);
};
void BT_TO_DLL(struct node* node)
{
if(node == NULL)
{
return ;
}
BT_TO_DLL(node->left);
if(head==NULL)
{
head=tail=node;
}
else
{
tail->right=node;
node->left=tail;

}
tail=node;
BT_TO_DLL(node->right);

}
void display()
{
struct node*current = head;
if(head == NULL)
{
printf("The list is empty\n");
return;
}
else
{
printf("The elements in DDL are\n");
while(current!=NULL)
{
printf("%d ",current->data);
current=current->right;
}
}
}
int main()
{
struct node* root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right=newnode(5);
root->right->left = newnode(6);
root->right->right = newnode(7);

BT_TO_DLL(root);
display();
return 0;
}

8) STACK FROM QUEUE(PUSH COSTLY)

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

struct node
{
int data;
struct node * next;
};

struct queue
{
struct node *rear;
struct node *front;
};

void initial(struct queue *);


void qadd(struct queue *,int);
int qdel(struct queue *);
void dis(struct queue *);
void push(int);
void pop();

struct queue q1,q2;


int main()
{
initial(&q1);
initial(&q2);
push(5);
push(6);
push(7);
pop();
printf("\nelements now are:\n");
display(&q1);

return 0;
}

void initial(struct queue *q)


{
q->front=NULL;
q->rear=NULL;
}

void qadd(struct queue *q,int n)


{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node));

tmp->data=n;
tmp->next=NULL;

if(q->front==NULL)
{
q->rear=tmp;
q->front=tmp;
return;
}

q->rear->next=tmp;
q->rear=tmp;
}

int qdel(struct queue *q)


{
struct node *tmp;
int itm;
if(q->front==NULL)
{
printf("\nqueue is empty");
return NULL;
}
tmp=q->front;
itm=tmp->data;
q->front=tmp->next;
free(tmp);
return itm;

void display(struct queue *q)


{
struct node *tmp;
tmp=q->front;
while((tmp)!=NULL)
{
printf("\n%d",(tmp->data));
tmp=tmp->next;
}
printf("\n");
}

void push(int val)


{
struct queue tmp;
int j;
qadd(&q2,val);

while(((&q1)->front)!=NULL)
{
j=qdel(&q1);
qadd(&q2,j);
}
tmp=q1;
q1=q2;
q2=tmp;
printf("\nelements after pushing are:\n");
display(&q1);

}
void pop()
{
printf("\n element deleted is %d",qdel(&q1));
}

9) CHECK WHETHER TREE IS BALANCED OR NOT

# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int height(struct node* root)
{
if(root == NULL)
{
return 0;
}
int lhgt=height(root->left);
int rhgt=height(root->right);
if(lhgt>rhgt)
{
return lhgt+1;
}
else
{
return rhgt+1;
}
}
int isbalanced(struct node* root)
{
int lh,rh;
if(root == NULL)
{
return 1;
}
lh = height(root->left);
rh = height(root->right);
if( (abs(lh-rh)<=1) && isbalanced(root->left) && isbalanced(root->right) )
return 1;
return 0;
}

int main()
{
struct node* root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
if(isbalanced(root))
{
printf("The tree is balanced\n");

}
else
{
printf("The tree is not balanced\n");
}

}
10) SORT STACK USING ANOTHER STACK(PYTHON)
TIME COMPLEXITY O(n^2)
SPACE COMPLEXITY O(n)
def sortStack ( stack ):
tmpStack = createStack()
while(isEmpty(stack) == False):
tmp = top(stack)
pop(stack)
while(isEmpty(tmpStack) == False and
int(top(tmpStack)) > int(tmp)):
push(stack,top(tmpStack))
pop(tmpStack)
push(tmpStack,tmp)

return tmpStack
def createStack():
stack = []
return stack
def isEmpty( stack ):
return len(stack) == 0
def push( stack, item ):
stack.append( item )
def top( stack ):
p = len(stack)
return stack[p-1]
def pop( stack ):
if(isEmpty( stack )):
print("Stack Underflow ")
exit(1)

return stack.pop()
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end = ' ')
print()
stack = createStack()
push( stack, str(34) )
push( stack, str(3) )
push( stack, str(31) )
push( stack, str(98) )
push( stack, str(92) )
push( stack, str(23) )

print("Sorted numbers are: ")


sortedst = sortStack ( stack )
prints(sortedst)

11) QUEUE FROM STACK(DEQUEUE COSTLY)


TIME COMPLEXITY O(n)

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

void push1(int);
void push2(int);
int pop1();
int pop2();
void enqueue();
void dequeue();
void display();
void create();
int st1[100], st2[100];
int top1 = -1, top2 = -1;
int count = 0;

void main()
{
int ch;

printf("\n1 - Enqueue element into queue");


printf("\n2 - Dequeue element from queue");
printf("\n3 - Display from queue");
printf("\n4 - Exit");
create();
while (1)
{
printf("\nEnter choice");
scanf("%d", &ch);
switch (ch)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choice");
}
}
}
void create()
{
top1 = top2 = -1;
}
void push1(int data)
{
st1[++top1] = data;
}
int pop1()
{
return(st1[top1--]);
}
void push2(int data)
{
st2[++top2] = data;
}
int pop2()
{
return(st2[top2--]);
}
void enqueue()
{
int data, i;

printf("Enter data into queue");


scanf("%d", &data);
push1(data);
count++;
}
void dequeue()
{
int i;

for (i = 0;i <= count;i++)


{
push2(pop1());
}
pop2();
count--;
for (i = 0;i <= count;i++)
{
push1(pop2());
}
}
void display()
{
int i;

for (i = 0;i <= top1;i++)


{
printf(" %d ", st1[i]);
}
}
12) DLL TO BINARY(BST)
TIME COMPLEXITY O(n)

#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
struct Node* prev;
};
int countNodes(struct Node *head);

struct Node* sortedListToBSTRecur(struct Node **head_ref, int n);


struct Node* sortedListToBST(struct Node *head)
{
int n = countNodes(head);
return sortedListToBSTRecur(&head, n);
}
struct Node* sortedListToBSTRecur(struct Node **head_ref, int n)
{
if (n <= 0)
return NULL;
struct Node *left = sortedListToBSTRecur(head_ref, n/2);
struct Node *root = *head_ref;
root->prev = left;
*head_ref = (*head_ref)->next;
root->next = sortedListToBSTRecur(head_ref, n-n/2-1);

return root;
}
int countNodes(struct Node *head)
{
int count = 0;
struct Node *temp = head;
while(temp)
{
temp = temp->next;
count++;
}
return count;
}
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if((*head_ref) != NULL)
(*head_ref)->prev = new_node ;
(*head_ref) = new_node;
}
void printList(struct Node *node)
{
while (node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
void preOrder(struct Node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->prev);
preOrder(node->next);
}
int main()
{
struct Node* head = NULL;
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);

printf("Given Linked List\n");


printList(head);
struct Node *root = sortedListToBST(head);
printf("\n PreOrder Traversal of constructed BST \n ");
preOrder(root);

return 0;
}

13)MINIMUM NUMBER OF JUMPS TO REACH END OF THE ARRAY


TIME COMPLEXITY O(n^2)

#include <limits.h>
#include <stdio.h>

int min(int x, int y) { return (x < y) ? x : y; }


int minJumps(int arr[], int n)
{
int jumps[n];
int i, j;

if (n == 0 || arr[0] == 0)
return INT_MAX;

jumps[0] = 0;
for (i = 1; i < n; i++) {
jumps[i] = INT_MAX;
for (j = 0; j < i; j++) {
if (i <= j + arr[j] && jumps[j] != INT_MAX) {
jumps[i] = min(jumps[i], jumps[j] + 1);
break;
}
}
}
return jumps[n - 1];
}
int main()
{
int arr[] = { 2, 1, 3, 2, 3, 4, 5, 1, 2, 8 };
int size = sizeof(arr) / sizeof(int);
printf("Minimum number of jumps to reach end is %d ",
minJumps(arr, size));
return 0;
}

14)CUTTING ROD:
TIME COMPLEXITY O(n^2)
#include<stdio.h>
#include<limits.h>
int max(int a, int b) { return (a > b)? a : b;}
int cutRod(int price[], int n)
{
int val[n+1];
val[0] = 0;
int i, j;
for (i = 1; i<=n; i++)
{
int max_val = INT_MIN;
for (j = 0; j < i; j++)
max_val = max(max_val, price[j] + val[i-j-1]);
val[i] = max_val;
}

return val[n];
}
int main()
{
int arr[] = {1, 5, 8, 9, 10, 17, 17, 20};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %d\n", cutRod(arr, size));
getchar();
return 0;
}

15) SUBSET SUM PROBLEM


TIME COMPLEXITY O(sum*n)
#include <stdio.h>
#include <stdlib.h>
#define bool int
bool isSubsetSum(int set[], int n, int sum)
{

bool true;
bool false;
bool subset[n + 1][sum + 1];
for (int i = 0; i <= n; i++)
subset[i][0] = true;
for (int i = 1; i <= sum; i++)
subset[0][i] = false;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < set[i - 1])
subset[i][j] = subset[i - 1][j];
if (j >= set[i - 1])
subset[i][j] = subset[i - 1][j] ||
subset[i - 1][j - set[i - 1]];
}
}

return subset[n][sum];
}
int main()
{

int set[] = { 1,2,5,7};


int sum = 8;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == 1)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}
16) OVERLAPPING SUB PROBLEM
#include<stdio.h>
#define NIL -1
#define MAX 100

int lookup[MAX];
void _initialize()
{
int i;
for (i = 0; i < MAX; i++)
lookup[i] = NIL;
}
int fib(int n)
{
if (lookup[n] == NIL)
{
if (n <= 1)
lookup[n] = n;
else
lookup[n] = fib(n-1) + fib(n-2);
}

return lookup[n];
}

int main ()
{
int n = 2;
_initialize();
printf("Fibonacci number is %d ", fib(n));
return 0;
}
17) LONGEST PALINDROME SUBSEQUENCE:
TIME COMPLEXITY O(n^2)
#include<stdio.h>
#include<string.h>

int max (int x, int y) { return (x > y)? x : y; }


int lps(char *str)
{
int n = strlen(str);
int i, j, cl;
int L[n][n];
for (i = 0; i < n; i++)
L[i][i] = 1;
for (cl=2; cl<=n; cl++)
{
for (i=0; i<n-cl+1; i++)
{
j = i+cl-1;
if (str[i] == str[j] && cl == 2)
L[i][j] = 2;
else if (str[i] == str[j])
L[i][j] = L[i+1][j-1] + 2;
else
L[i][j] = max(L[i][j-1], L[i+1][j]);
}
}

return L[0][n-1];
}
int main()
{
char seq[] = "adbgcfbea";
int n = strlen(seq);
printf ("The length of the LPS is %d", lps(seq));
getchar();
return 0;
}
18) coin change problem:(PYTHON)
def getNumberOfWays(N, Coins):
ways = [0] * (N + 1);
ways[0] = 1;
for i in range(len(Coins)):
for j in range(len(ways)):
if (Coins[i] <= j):
ways[j] += ways[(int)(j - Coins[i])];
return ways[N];

def printArray(coins):
for i in coins:
print(i);

if __name__ == '__main__':
Coins = [1, 5, 10];

print("The Coins Array:");


printArray(Coins);

print("Solution:",end="");
print(getNumberOfWays(12, Coins));
19) LONGEST COMMON SUBSEQUENCE:
TIME COMPLEXITY O(mn)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int max(int a, int b);
int lcs( char *X, char *Y, int m, int n )
{
int L[m+1][n+1];
int i, j;
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;

else if (X[i-1] == Y[j-1])


L[i][j] = L[i-1][j-1] + 1;

else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
return L[m][n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";

int m = strlen(X);
int n = strlen(Y);

printf("Length of LCS is %d", lcs( X, Y, m, n ) );

return 0;
}
20) OPTIMAL BINARY SEARCH TREE
TIME COMPLEXITY:O(n^4)
#include <stdio.h>
#include <limits.h>
int sum(int freq[], int i, int j);
int optimalSearchTree(int keys[], int freq[], int n)
{
int cost[n][n];
for (int i = 0; i < n; i++)
cost[i][i] = freq[i];

for (int L=2; L<=n; L++)


{

for (int i=0; i<=n-L+1; i++)


{
int j = i+L-1;
cost[i][j] = INT_MAX;
for (int r=i; r<=j; r++)
{
int c = ((r > i)? cost[i][r-1]:0) +
((r < j)? cost[r+1][j]:0) +
sum(freq, i, j);
if (c < cost[i][j])
cost[i][j] = c;
}
}
}
return cost[0][n-1];
}
int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}
int main()
{
int keys[] = {12,15,20,25};
int freq[] = {4, 3,6,2};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ",
optimalSearchTree(keys, freq, n));
return 0;
}

You might also like