SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
10 Important Classical Programming Interview Questions 
Classical Programming Interview Questions 
Powered by –
Contents 
Q. How can we sum the digits of a given number in single statement? ....................................... 3 
Q. Solve the Rat In A Maze problem using backtracking. ................................................................ 3 
Q. Write C code to solve the Tower of Hanoi problem. ..................................................................... 6 
Q. Write C code to check if an integer is a power of 2 or not in a single line? .............................. 6 
Q. How to compare two linked lists? Write a C program to compare two linked lists. .............. 6 
Q. How would you detect a loop in a linked list? Write a C program to do the same ................. 7 
Q. Write a C program to return the nth node from the end of a linked list. ................................... 8 
Q. How do you find the middle of a linked list? Write a C program to find the same ................. 9 
Q. Write a C program to find the depth or height of a tree. ............................................................ 10 
Q. Write a C program to delete a node from a Binary Search Tree? ............................................ 11
Q. How can we sum the digits of a given number in single statement? 
Answer: 
Q. Solve the Rat In A Maze problem using backtracking. 
Answer: 
This is one of the classical problems of computer science. There is a rat trapped in a maze. There are multiple paths in the maze from the starting point to the ending point. There is some cheese at the exit. The rat starts from the entrance of the maze and wants to get to the cheese. 
This problem can be attacked as follows: 
 Have a m*m matrix which represents the maze. 
 For the sake of simplifying the implementation, have a boundary around your matrix and fill it up with all ones. This is so that you know when the rat is trying to go out of the boundary of the maze. In the real world, the rat would know not to go out of the maze, but hey! So, initially the matrix (I mean, the maze) would be something like (the ones represent the "extra" boundary we have added). The ones inside specify the obstacles. 111111111111111111111 100000000000000000001 100000010000000000001 100000010000000000001 100000000100001000001 100001000010000000001 100000000100000000001 100000000000000000001 111111111111111111111 
#include<stdio.h> 
void main() { 
int num = 123456; 
int sum = 0; 
for (; num > 0; sum += num % 10, num /= 10); 
// This is the "single line". 
printf("nsum = [%d]n", sum); 
}
 The rat can move in four directions at any point in time (well, right, left, up, down). Please note that the rat can't move diagonally. Imagine a real maze and not a matrix. In matrix language 
o Moving right means adding {0,1} to the current coordinates. 
o Moving left means adding {0,-1} to the current coordinates. 
o Moving up means adding {-1,0} to the current coordinates. 
o Moving right means adding {1,0} to the current coordinates. 
 The rat can start off at the first row and the first column as the entrance point. 
 From there, it tries to move to a cell which is currently free. A cell is free if it has a zero in it. 
 It tries all the 4 options one-by-one, till it finds an empty cell. If it finds one, it moves to that cell and marks it with a 1 (saying it has visited it once). Then it continues to move ahead from that cell to other cells. 
 If at a particular cell, it runs out of all the 4 options (that is it can’t move either right, left, up or down), then it needs to backtrack. It backtracks till a point where it can move ahead and be closer to the exit. 
 If it reaches the exit point, it gets the cheese, of course. 
 The complexity is O(m*m). 
Here is some pseudo code to chew upon 
findpath() 
{ 
Position offset[4]; 
Offset[0].row=0; offset[0].col=1; //right; 
Offset[1].row=1; offset[1].col=0;//down; 
Offset[2].row=0; offset[2].col=-1;//left; 
Offset[3].row=-1; offset[3].col=0;//up; 
// Initialize wall of obstacles around the maze 
for(int i=0; i<m+1;i++) 
maze[0][i] = maze[m+1][i]=1; maze[i][0] = maze[i][m+1]=1; 
Position here; 
Here.row=1; 
Here.col=1; 
maze[1][1]=1; 
int option = 0; 
int lastoption = 3; 
while(here.row!=m || here.col!=m) 
{ 
//Find a neighbor to move 
int r,c;
while (option<=LastOption) 
{ 
r=here.row + offset[position].row; 
c=here.col + offset[option].col; 
if(maze[r][c]==0)break; 
option++; 
} 
//Was a neighbor found? 
if(option<=LastOption) 
{ 
path->Add(here); 
here.row=r;here.col=c; 
maze[r][c]=1; 
option=0; 
} 
else 
{ 
if(path->Empty())return(False); 
Position next; 
Path->Delete(next); 
If(new.row==here.row) 
Option=2+next.col - here.col; 
Else {option = 3 + next.row - here.col;} 
Here=next; 
} 
return(TRUE); 
} 
}
Q. Write C code to solve the Tower of Hanoi problem. 
Answer: 
main() 
{ 
towers_of_hanio(n,'L','R','C'); 
} 
towers_of_hanio(int n, char from, char to, char temp) 
{ 
if(n>0) 
{ 
tower_of_hanio(n-1, from, temp, to); 
printf("nMove disk %d from %c to %cn", n, from, to); 
tower_of_hanio(n-1, temp, to, from); 
} 
} 
Q. Write C code to check if an integer is a power of 2 or not in a single line? 
Answer: 
Method1 
if(!(num & (num - 1)) && num) 
{ 
// Power of 2! 
} 
Method2 
if(((~i+1)&i)==i) 
{ 
//Power of 2! 
} 
Q. How to compare two linked lists? Write a C program to compare two linked lists. 
Answer: 
int compare_linked_lists(struct node *q, struct node *r) { 
static int flag;
if ((q == NULL) && (r == NULL)) { 
flag = 1; 
} else { 
if (q == NULL || r == NULL) { 
flag = 0; 
} 
if (q->data != r->data) { 
flag = 0; 
} else { 
compare_linked_lists(q->link, r->link); 
} 
} 
return (flag); 
} 
Another way is to do it on similar lines as strcmp() compares two strings, character by character (here each node is like a character). 
Q. How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list. 
Answer: 
Brute force method Have a double loop, where you check the node pointed to by the outer loop, with every node of the inner loop. 
typedef struct node { 
void *data; 
struct node *next; 
} mynode; 
mynode * find_loop(NODE * head) { 
mynode *current = head; 
while (current->next != NULL) { 
mynode *temp = head; 
while (temp->next != NULL && temp != current) { 
if (current->next == temp) { 
printf("nFound a loop."); 
return current; 
} 
temp = temp->next; 
} 
current = current->next; 
} 
return NULL;
} 
Visited flag Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked list. Fastest method Have 2 pointers to start of the linked list. Increment one pointer by 1 node and the other by 2 nodes. If there's a loop, the 2nd pointer will meet the 1st pointer somewhere. If it does, then you know there's one. Here is some code 
p=head; 
q=head->next; 
while(p!=NULL && q!=NULL) 
{ 
if(p==q) 
{ 
//Loop detected! 
exit(0); 
} 
p=p->next; 
q=(q->next)?(q->next->next):q->next; 
} 
// No loop. 
Q. Write a C program to return the nth node from the end of a linked list. 
Answer: 
Here is a solution which is often called as the solution that uses frames. Suppose one needs to get to the 6th node from the end in this LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case) STEP 1: 
1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 STEP 2:
1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10 
Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL. STEP 3: 
1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1) 
So here you have!, the 6th node from the end pointed to by ptr2! 
Here is some C code.. 
struct node { 
int data; 
struct node *next; 
} mynode; 
mynode * nthNode(mynode *head, int n /*pass 0 for last node*/) { 
mynode *ptr1, *ptr2; 
int count; 
if (!head) { 
return (NULL); 
} 
ptr1 = head; 
ptr2 = head; 
count = 0; 
while (count < n) { 
count++; 
if ((ptr1 = ptr1->next) == NULL) { 
//Length of the linked list less than n. Error. 
return (NULL); 
} 
} 
while ((ptr1 = ptr1->next) != NULL) { 
ptr2 = ptr2->next; 
} 
return (ptr2); 
}
Q. How do you find the middle of a linked list? Write a C program to return the middle of a linked list 
Answer: 
Method1 
p=head; 
q=head; 
if(q->next->next!=NULL) 
{ 
p=p->next; 
q=q->next->next; 
} 
printf("The middle element is %d",p->data); 
Here p moves one step, where as q moves two steps, when q reaches end, p will be at the middle of the linked list. 
Method 2 
struct node *middle(struct node *head) { 
struct node *middle = NULL; 
int i; 
for (i = 1; head; head = head->next, i++) { 
if (i == 1) 
middle = head; 
else if ((i % 2) == 1) 
middle = middle->next; 
} 
return middle; 
} 
In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to (i%3==1) and in the same way we can find nth node of list by changing (i%2==1) to (i%n==1) but make sure ur (n<=i). 
Q. Write a C program to find the depth or height of a tree. 
Answer: 
Here is some C code to get the height of the three 
tree_height(mynode *p) 
{
if(p==NULL)return(0); 
if(p->left) {h1=tree_height(p->left);} 
if(p=>right) {h2=tree_height(p->right);} 
return(max(h1,h2)+1); 
} 
The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of height n, h > 0, has at least h and at most (2^h -1) elements in it. The height of a binary tree that contains n, n>0, elements is at most n and atleast log(n+1) to the base 2. Log(n+1) to the base 2 = h n = (2^h - 1) 
Q. Write a C program to delete a node from a Binary Search Tree? 
Answer: 
The node to be deleted might be in the following states 
 The node does not exist in the tree - In this case you have nothing to delete. 
 The node to be deleted has no children - The memory occupied by this node must be freed and either the left link or the right link of the parent of this node must be set to NULL. 
 The node to be deleted has exactly one child - We have to adjust the pointer of the parent of the node to be deleted such that after deletion it points to the child of the node being deleted. 
 The node to be deleted has two children - We need to find the inorder successor of the node to be deleted. The data of the inorder successor must be copied into the node to be deleted and a pointer should be setup to the in order successor. This inorder successor would have one or zero children. This node should be deleted using the same procedure as for deleting a one child or a zero child node. Thus the whole logic of deleting a node with two children is to locate the inorder successor, copy its data and reduce the problem to a simple deletion of a node with one or zero children. 
Here is some C code for these two situations 
Situation 1 100 (parent) 50 (cur == psuc) 20 80 (suc) 90
85 95 
Situation 2 100 (parent) 50 (cur) 20 90 80 
70 (suc) 
75 72 76 
mynode *delete(int item, mynode *head) 
{ 
mynode *cur, *parent, *suc, *psuc, q; 
if(head->left==NULL) {printf("nEmpty tree!n");return(head);} 
parent = head; 
cur = head->left; 
while(cur!=NULL && item != cur->value) 
{ 
parent = cur; 
cur = (item < cur->next)? cur->left:cur->right; 
} 
if(cur == NULL) 
{ 
printf("nItem to be deleted not found!n"); 
return(head); 
} 
// Item found, now delete it 
if(cur->left == NULL) 
q = cur->right; 
elseif(cur->right == NULL) 
q = cur->left; 
else 
{ 
// Obtain the inorder successor and its parent 
psuc = cur; 
cur = cur->left;
while(suc->left!=NULL) 
{ 
psuc = suc; 
suc = suc->left; 
} 
if(cur==psuc) 
{ 
// Situation 1 
suc->left = cur->right; 
} 
else 
{ 
// Situation 2 
suc->left = cur->left; 
psuc->left = suc->right; 
suc->right = cur->right; 
} 
q = suc; 
} 
// Attach q to the parent node 
if(parent->left == cur) 
parent->left=q; 
else 
parent->rlink=q; 
freeNode(cur); 
return(head); 
}
Study on the go; get high quality complete preparation courses now on your mobile!

Weitere ähnliche Inhalte

Was ist angesagt?

01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms NotesAndres Mendez-Vazquez
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribdAmit Kapoor
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)Thai Pangsakulyanont
 
Programming in Java: Recursion
Programming in Java: RecursionProgramming in Java: Recursion
Programming in Java: RecursionMartin Chapman
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
 
conditional statements
conditional statementsconditional statements
conditional statementsJames Brotsos
 
03 truncation errors
03 truncation errors03 truncation errors
03 truncation errorsmaheej
 
POST’s CORRESPONDENCE PROBLEM
POST’s CORRESPONDENCE PROBLEMPOST’s CORRESPONDENCE PROBLEM
POST’s CORRESPONDENCE PROBLEMRajendran
 
Assignment week0 c++
Assignment  week0 c++Assignment  week0 c++
Assignment week0 c++Netaji Gandi
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 

Was ist angesagt? (20)

02 Notes Divide and Conquer
02 Notes Divide and Conquer02 Notes Divide and Conquer
02 Notes Divide and Conquer
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 
03 notes
03 notes03 notes
03 notes
 
Network security CS6
Network security   CS6Network security   CS6
Network security CS6
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Programming in Java: Recursion
Programming in Java: RecursionProgramming in Java: Recursion
Programming in Java: Recursion
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
conditional statements
conditional statementsconditional statements
conditional statements
 
Ntewrok secuirty cs7
Ntewrok secuirty cs7Ntewrok secuirty cs7
Ntewrok secuirty cs7
 
Dynamic programing
Dynamic programingDynamic programing
Dynamic programing
 
03 truncation errors
03 truncation errors03 truncation errors
03 truncation errors
 
POST’s CORRESPONDENCE PROBLEM
POST’s CORRESPONDENCE PROBLEMPOST’s CORRESPONDENCE PROBLEM
POST’s CORRESPONDENCE PROBLEM
 
Matlab Assignment Help
Matlab Assignment HelpMatlab Assignment Help
Matlab Assignment Help
 
Assignment week0 c++
Assignment  week0 c++Assignment  week0 c++
Assignment week0 c++
 
internal assement 3
internal assement 3internal assement 3
internal assement 3
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 

Andere mochten auch

Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)sunilbhaisora1
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questionsDhivyashree Selvarajtnkpm
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questionsGradeup
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 

Andere mochten auch (11)

Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questions
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java codes
Java codesJava codes
Java codes
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java practical
Java practicalJava practical
Java practical
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 

Ähnlich wie Classical programming interview questions

Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureNurjahan Nipa
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptxKokilaK25
 
Design and Analysis of algorithms
Design and Analysis of algorithmsDesign and Analysis of algorithms
Design and Analysis of algorithmsDr. Rupa Ch
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode CompilerDonal Fellows
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfN Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfakashreddy966699
 
Will th ebelow code work andif not please help me fix it. Basically .pdf
Will th ebelow code work andif not please help me fix it. Basically .pdfWill th ebelow code work andif not please help me fix it. Basically .pdf
Will th ebelow code work andif not please help me fix it. Basically .pdfmichaelazach6427
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfezonesolutions
 
HW 5-RSAascii2str.mfunction str = ascii2str(ascii) .docx
HW 5-RSAascii2str.mfunction str = ascii2str(ascii)        .docxHW 5-RSAascii2str.mfunction str = ascii2str(ascii)        .docx
HW 5-RSAascii2str.mfunction str = ascii2str(ascii) .docxwellesleyterresa
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptxMrhaider4
 
Theoryofcomp science
Theoryofcomp scienceTheoryofcomp science
Theoryofcomp scienceRaghu nath
 
Amcat automata questions
Amcat   automata questionsAmcat   automata questions
Amcat automata questionsESWARANM92
 
Amcat automata questions
Amcat   automata questionsAmcat   automata questions
Amcat automata questionsESWARANM92
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxSALU18
 

Ähnlich wie Classical programming interview questions (20)

Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Design and Analysis of algorithms
Design and Analysis of algorithmsDesign and Analysis of algorithms
Design and Analysis of algorithms
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfN Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
 
Will th ebelow code work andif not please help me fix it. Basically .pdf
Will th ebelow code work andif not please help me fix it. Basically .pdfWill th ebelow code work andif not please help me fix it. Basically .pdf
Will th ebelow code work andif not please help me fix it. Basically .pdf
 
algorithm unit 1
algorithm unit 1algorithm unit 1
algorithm unit 1
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
HW 5-RSAascii2str.mfunction str = ascii2str(ascii) .docx
HW 5-RSAascii2str.mfunction str = ascii2str(ascii)        .docxHW 5-RSAascii2str.mfunction str = ascii2str(ascii)        .docx
HW 5-RSAascii2str.mfunction str = ascii2str(ascii) .docx
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Theoryofcomp science
Theoryofcomp scienceTheoryofcomp science
Theoryofcomp science
 
Amcat automata questions
Amcat   automata questionsAmcat   automata questions
Amcat automata questions
 
Amcat automata questions
Amcat   automata questionsAmcat   automata questions
Amcat automata questions
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 

Kürzlich hochgeladen

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 

Kürzlich hochgeladen (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

Classical programming interview questions

  • 1. 10 Important Classical Programming Interview Questions Classical Programming Interview Questions Powered by –
  • 2. Contents Q. How can we sum the digits of a given number in single statement? ....................................... 3 Q. Solve the Rat In A Maze problem using backtracking. ................................................................ 3 Q. Write C code to solve the Tower of Hanoi problem. ..................................................................... 6 Q. Write C code to check if an integer is a power of 2 or not in a single line? .............................. 6 Q. How to compare two linked lists? Write a C program to compare two linked lists. .............. 6 Q. How would you detect a loop in a linked list? Write a C program to do the same ................. 7 Q. Write a C program to return the nth node from the end of a linked list. ................................... 8 Q. How do you find the middle of a linked list? Write a C program to find the same ................. 9 Q. Write a C program to find the depth or height of a tree. ............................................................ 10 Q. Write a C program to delete a node from a Binary Search Tree? ............................................ 11
  • 3. Q. How can we sum the digits of a given number in single statement? Answer: Q. Solve the Rat In A Maze problem using backtracking. Answer: This is one of the classical problems of computer science. There is a rat trapped in a maze. There are multiple paths in the maze from the starting point to the ending point. There is some cheese at the exit. The rat starts from the entrance of the maze and wants to get to the cheese. This problem can be attacked as follows:  Have a m*m matrix which represents the maze.  For the sake of simplifying the implementation, have a boundary around your matrix and fill it up with all ones. This is so that you know when the rat is trying to go out of the boundary of the maze. In the real world, the rat would know not to go out of the maze, but hey! So, initially the matrix (I mean, the maze) would be something like (the ones represent the "extra" boundary we have added). The ones inside specify the obstacles. 111111111111111111111 100000000000000000001 100000010000000000001 100000010000000000001 100000000100001000001 100001000010000000001 100000000100000000001 100000000000000000001 111111111111111111111 #include<stdio.h> void main() { int num = 123456; int sum = 0; for (; num > 0; sum += num % 10, num /= 10); // This is the "single line". printf("nsum = [%d]n", sum); }
  • 4.  The rat can move in four directions at any point in time (well, right, left, up, down). Please note that the rat can't move diagonally. Imagine a real maze and not a matrix. In matrix language o Moving right means adding {0,1} to the current coordinates. o Moving left means adding {0,-1} to the current coordinates. o Moving up means adding {-1,0} to the current coordinates. o Moving right means adding {1,0} to the current coordinates.  The rat can start off at the first row and the first column as the entrance point.  From there, it tries to move to a cell which is currently free. A cell is free if it has a zero in it.  It tries all the 4 options one-by-one, till it finds an empty cell. If it finds one, it moves to that cell and marks it with a 1 (saying it has visited it once). Then it continues to move ahead from that cell to other cells.  If at a particular cell, it runs out of all the 4 options (that is it can’t move either right, left, up or down), then it needs to backtrack. It backtracks till a point where it can move ahead and be closer to the exit.  If it reaches the exit point, it gets the cheese, of course.  The complexity is O(m*m). Here is some pseudo code to chew upon findpath() { Position offset[4]; Offset[0].row=0; offset[0].col=1; //right; Offset[1].row=1; offset[1].col=0;//down; Offset[2].row=0; offset[2].col=-1;//left; Offset[3].row=-1; offset[3].col=0;//up; // Initialize wall of obstacles around the maze for(int i=0; i<m+1;i++) maze[0][i] = maze[m+1][i]=1; maze[i][0] = maze[i][m+1]=1; Position here; Here.row=1; Here.col=1; maze[1][1]=1; int option = 0; int lastoption = 3; while(here.row!=m || here.col!=m) { //Find a neighbor to move int r,c;
  • 5. while (option<=LastOption) { r=here.row + offset[position].row; c=here.col + offset[option].col; if(maze[r][c]==0)break; option++; } //Was a neighbor found? if(option<=LastOption) { path->Add(here); here.row=r;here.col=c; maze[r][c]=1; option=0; } else { if(path->Empty())return(False); Position next; Path->Delete(next); If(new.row==here.row) Option=2+next.col - here.col; Else {option = 3 + next.row - here.col;} Here=next; } return(TRUE); } }
  • 6. Q. Write C code to solve the Tower of Hanoi problem. Answer: main() { towers_of_hanio(n,'L','R','C'); } towers_of_hanio(int n, char from, char to, char temp) { if(n>0) { tower_of_hanio(n-1, from, temp, to); printf("nMove disk %d from %c to %cn", n, from, to); tower_of_hanio(n-1, temp, to, from); } } Q. Write C code to check if an integer is a power of 2 or not in a single line? Answer: Method1 if(!(num & (num - 1)) && num) { // Power of 2! } Method2 if(((~i+1)&i)==i) { //Power of 2! } Q. How to compare two linked lists? Write a C program to compare two linked lists. Answer: int compare_linked_lists(struct node *q, struct node *r) { static int flag;
  • 7. if ((q == NULL) && (r == NULL)) { flag = 1; } else { if (q == NULL || r == NULL) { flag = 0; } if (q->data != r->data) { flag = 0; } else { compare_linked_lists(q->link, r->link); } } return (flag); } Another way is to do it on similar lines as strcmp() compares two strings, character by character (here each node is like a character). Q. How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list. Answer: Brute force method Have a double loop, where you check the node pointed to by the outer loop, with every node of the inner loop. typedef struct node { void *data; struct node *next; } mynode; mynode * find_loop(NODE * head) { mynode *current = head; while (current->next != NULL) { mynode *temp = head; while (temp->next != NULL && temp != current) { if (current->next == temp) { printf("nFound a loop."); return current; } temp = temp->next; } current = current->next; } return NULL;
  • 8. } Visited flag Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked list. Fastest method Have 2 pointers to start of the linked list. Increment one pointer by 1 node and the other by 2 nodes. If there's a loop, the 2nd pointer will meet the 1st pointer somewhere. If it does, then you know there's one. Here is some code p=head; q=head->next; while(p!=NULL && q!=NULL) { if(p==q) { //Loop detected! exit(0); } p=p->next; q=(q->next)?(q->next->next):q->next; } // No loop. Q. Write a C program to return the nth node from the end of a linked list. Answer: Here is a solution which is often called as the solution that uses frames. Suppose one needs to get to the 6th node from the end in this LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case) STEP 1: 1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 STEP 2:
  • 9. 1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10 Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL. STEP 3: 1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1) So here you have!, the 6th node from the end pointed to by ptr2! Here is some C code.. struct node { int data; struct node *next; } mynode; mynode * nthNode(mynode *head, int n /*pass 0 for last node*/) { mynode *ptr1, *ptr2; int count; if (!head) { return (NULL); } ptr1 = head; ptr2 = head; count = 0; while (count < n) { count++; if ((ptr1 = ptr1->next) == NULL) { //Length of the linked list less than n. Error. return (NULL); } } while ((ptr1 = ptr1->next) != NULL) { ptr2 = ptr2->next; } return (ptr2); }
  • 10. Q. How do you find the middle of a linked list? Write a C program to return the middle of a linked list Answer: Method1 p=head; q=head; if(q->next->next!=NULL) { p=p->next; q=q->next->next; } printf("The middle element is %d",p->data); Here p moves one step, where as q moves two steps, when q reaches end, p will be at the middle of the linked list. Method 2 struct node *middle(struct node *head) { struct node *middle = NULL; int i; for (i = 1; head; head = head->next, i++) { if (i == 1) middle = head; else if ((i % 2) == 1) middle = middle->next; } return middle; } In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to (i%3==1) and in the same way we can find nth node of list by changing (i%2==1) to (i%n==1) but make sure ur (n<=i). Q. Write a C program to find the depth or height of a tree. Answer: Here is some C code to get the height of the three tree_height(mynode *p) {
  • 11. if(p==NULL)return(0); if(p->left) {h1=tree_height(p->left);} if(p=>right) {h2=tree_height(p->right);} return(max(h1,h2)+1); } The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of height n, h > 0, has at least h and at most (2^h -1) elements in it. The height of a binary tree that contains n, n>0, elements is at most n and atleast log(n+1) to the base 2. Log(n+1) to the base 2 = h n = (2^h - 1) Q. Write a C program to delete a node from a Binary Search Tree? Answer: The node to be deleted might be in the following states  The node does not exist in the tree - In this case you have nothing to delete.  The node to be deleted has no children - The memory occupied by this node must be freed and either the left link or the right link of the parent of this node must be set to NULL.  The node to be deleted has exactly one child - We have to adjust the pointer of the parent of the node to be deleted such that after deletion it points to the child of the node being deleted.  The node to be deleted has two children - We need to find the inorder successor of the node to be deleted. The data of the inorder successor must be copied into the node to be deleted and a pointer should be setup to the in order successor. This inorder successor would have one or zero children. This node should be deleted using the same procedure as for deleting a one child or a zero child node. Thus the whole logic of deleting a node with two children is to locate the inorder successor, copy its data and reduce the problem to a simple deletion of a node with one or zero children. Here is some C code for these two situations Situation 1 100 (parent) 50 (cur == psuc) 20 80 (suc) 90
  • 12. 85 95 Situation 2 100 (parent) 50 (cur) 20 90 80 70 (suc) 75 72 76 mynode *delete(int item, mynode *head) { mynode *cur, *parent, *suc, *psuc, q; if(head->left==NULL) {printf("nEmpty tree!n");return(head);} parent = head; cur = head->left; while(cur!=NULL && item != cur->value) { parent = cur; cur = (item < cur->next)? cur->left:cur->right; } if(cur == NULL) { printf("nItem to be deleted not found!n"); return(head); } // Item found, now delete it if(cur->left == NULL) q = cur->right; elseif(cur->right == NULL) q = cur->left; else { // Obtain the inorder successor and its parent psuc = cur; cur = cur->left;
  • 13. while(suc->left!=NULL) { psuc = suc; suc = suc->left; } if(cur==psuc) { // Situation 1 suc->left = cur->right; } else { // Situation 2 suc->left = cur->left; psuc->left = suc->right; suc->right = cur->right; } q = suc; } // Attach q to the parent node if(parent->left == cur) parent->left=q; else parent->rlink=q; freeNode(cur); return(head); }
  • 14. Study on the go; get high quality complete preparation courses now on your mobile!