Data structures-interview quest


                                      DATA STRUCTURES AND ALGORITHMS

1.What is data structure?
A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.
2.List out the areas in which data structures are applied extensively?
Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation
3.If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
4.What is the data structures used to perform recursion?
Stack. Because of its LIFO (Last In First Out) property it remembers its caller, so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.
5.What are the methods available in storing sequential files ?
Straight merging, Natural merging, Polyphase sort, Distribution of Initial runs.
6.List out few of the Application of tree data-structure?
The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis.
7.In RDBMS, what is the efficient data structure used in the internal storage representation?
B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes.
8.What is a spanning Tree?
A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized.
9.Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes?
Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesn't mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.
10.Whether Linked List is linear or Non-linear data structure?
According to Access strategies Linked list is a linear one. According to Storage Linked List is a Non-linear one.
11.What is the quickest sorting method to use?
The answer depends on what you mean by quickest. For most sorting problems, it just doesn't matter how quick the sort is because it is done infrequently or other operations take significantly more time anyway. Even in cases in which sorting speed is of the essence, there is no one answer. It depends on not only the size and nature of the data, but also the likely order. No algorithm is best in all cases. There are three sorting methods in this author's toolbox that are all very fast and that are useful in different situations. Those methods are quick sort, merge sort, and radix sort.

The Quick Sort
The quick sort algorithm is of the divide and conquer type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A dividing value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three sets the algorithm will still work properly.

The Merge Sort
The merge sort is a divide and conquer sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don't fit into memory. It also can be implemented as a stable sort.

The Radix Sort
The radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints.
12.How can I search for data in a linked list?
Unfortunately, the only way to search a linked list is with a linear search, because the only way a linked list's members can be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.
13.What is the heap?
The heap is where malloc(), calloc(), and realloc() get memory.

Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn't deallocated automatically; you have to call free().Recursive data structures are almost always implemented with memory from the heap.
14.What is the easiest sorting method to use?
The answer is the standard library function qsort(). It's the easiest sort by far for several reasons:
It is already written.
It is already debugged.
It has been optimized as much as possible (usually).
Void qsort(void *buf, size_tnum, size_t size, int (*comp)(const void *ele1, const void *ele2));
15.What is the bucket size, when the overlapping and collision occur at same time?
One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values.
16.In an AVL tree, at what condition the balancing is to be done?
If the pivotal value (or the Height factor) is greater than 1 or less than 1.
17.Minimum number of queues needed to implement the priority queue?
Two. One queue is used for actual storing of data and another for storing priorities.
18.How many different trees are possible with 10 nodes ?
1014 - For example, consider a tree with 3 nodes(n=3), it will have the maximum combination of 5 different (ie, 23 - 3 =? 5) trees.
19.What is a node class?
A node class is a class that, relies on the base class for services and implementation, provides a wider interface to users than its base class, relies primarily on virtual functions in its public interface depends on all its direct and indirect base class can be understood only in the context of the base class can be used as base for further derivation can be used to create objects. A node class is a class that has added new services or functionality beyond the services inherited from its base class.
20.When can you tell that a memory leak will occur?
A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory.
21.When do you use the  placement new?
When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that’s already been allocated, and you need to construct an object in the memory you have. Operator new’s special version placement new allows you to do it.
class Widget
{
public :
Widget(intwidgetsize);

Widget* Construct_widget_int_buffer(void *buffer,intwidgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that’s constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.
22.Tell how to check whether a linked list is circular ?
Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1)

{
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2)

? ? ? ? ? ? {
print (\”circular\n\”);
}
}
23.What is the difference between ARRAY and STACK?
STACK follows LIFO. Thus the item that is first entered would be the last removed.

In array the items can be entered or removed in any order. Basically each member access is done using index. No strict order is to be followed here to remove a particular element.
24.What is the difference between NULL AND VOID pointer?
NULL can be value for pointer type variables.
VOID is a type identifier which has not size.
NULL and void are not same. Example: void* ptr = NULL;
25.What is precision?
Precision refers the accuracy of the decimal portion of a value. Precision is the number of digits allowed after the decimal point.
26.What is impact of signed numbers on the memory?
Sign of the number is the first bit of the storage allocated for that number. So you get one bit less for storing the number. For example if you are storing an 8-bit number, without sign, the range is 0-255. If you decide to store sign you get 7 bits for the number plus one bit for the sign. So the range is -128 to +127
27.How memory is reserved using a declaration statement ?
Memory is reserved using data type in the variable declaration. A programming language implementation has predefined sizes for its data types.

For example, in C# the declaration int i; will reserve 32 bits for variable i.

A pointer declaration reserves memory for the address or the pointer variable, but not for the data that it will point to. The memory for the data pointed by a pointer has to be allocated at runtime.

The memory reserved by the compiler for simple variables and for storing pointer address is allocated on the stack, while the memory allocated for pointer referenced data at runtime is allocated on the heap.
28.How many parts are there in a declaration statement?
There are two main parts, variable identifier and data type and the third type is optional which is type qualifier like signed/unsigned.
29.Is Pointer a variable?
Yes, a pointer is a variable and can be used as an element of a structure and as an attribute of a class in some programming languages such as C++, but not Java. However, the contents of a pointer is a memory address of another location of memory, which is usually the memory address of another variable, element of a structure, or attribute of a class.
30.What is Data Structure?
A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. Some are used to store the data of same type and some are used to store different types of data.
31.What is significance of ” * ” ?
The symbol “*” tells the computer that you are declaring a pointer.
Actually it depends on context.
In a statement like int *ptr; the ‘*’ tells that you are declaring a pointer.
In a statement like int i = *ptr; it tells that you want to assign value pointed to by ptr to variable i.

The symbol “*” is also called as Indirection Operator/ Dereferencing Operator.
32.Why do we Use a Multidimensional Array?
A multidimensional array can be useful to organize subgroups of data within an array. In addition to organizing data stored in elements of an array, a multidimensional array can store memory addresses of data in a pointer array and an array of pointers.

Multidimensional arrays are used to store information in a matrix form.
e.g. a railway timetable, schedule cannot be stored as a single dimensional array.
One can use a 3-D array for storing height, width and length of each room on each floor of a building.
33.How do you assign an address to an element of a pointer array ?
We can assign a memory address to an element of a pointer array by using the address operator, which is the ampersand (&), in an assignment statement such as ptemployee[0] = &projects[2];
34.Run Time Memory Allocation is known as ?
Allocating memory at runtime is called a dynamically allocating memory. In this, you dynamically allocate memory by using the new operator when declaring the array, for example :int grades[] = new int[10];
35.What method is used to place a value onto the top of a stack?
push() method, Push is the direction that data is being added to the stack. push() member method places a value onto the top of a stack.
36.What method removes the value from the top of a stack?
The pop() member method removes the value from the top of a stack, which is then returned by the pop() member method to the statement that calls the pop() member method.
37.What does isEmpty() member method determines?
isEmpty() checks if the stack has at least one element. This method is called by Pop() before retrieving and returning the top element.
38.What is a queue ?
A Queue is a sequential organization of data. A queue is a first in first out type of data structure. An element is inserted at the last position and an element is always taken out from the first position.
39.What is the relationship between a queue and its underlying array?
Data stored in a queue is actually stored in an array. Two indexes, front and end will be used to identify the start and end of the queue.

When an element is removed front will be incremented by 1. In case it reaches past the last index available it will be reset to 0. Then it will be checked with end. If it is greater than end queue is empty.

When an element is added end will be incremented by 1. In case it reaches past the last index available it will be reset to 0. After incrementing it will be checked with front. If they are equal queue is full.
40.Which process places data at the back of the queue?
Enqueue is the process that places data at the back of the queue
41.Why is the isEmpty() member method called?
The isEmpty() member method is called within the dequeue process to determine if there is an item in the queue to be removed i.e. isEmpty() is called to decide whether the queue has at least one element. This method is called by the dequeue() method before returning the front element.
42.How is the front of the queue calculated ?
The front of the queue is calculated by front = (front+1) % size.
43.What does each entry in the Link List called?
Each entry in a linked list is called a node. Think of a node as an entry that has three sub entries. One sub entry contains the data, which may be one attribute or many attributes. Another points to the previous node, and the last points to the next node. When you enter a new item on a linked list, you allocate the new node and then set the pointers to previous and next nodes.
44.What is Linked List ?
Linked List is one of the fundamental data structures. It consists of a sequence of? nodes, each containing arbitrary data fields and one or two (”links”) pointing to the next and/or previous nodes. A linked list is a self-referential datatype because it contains a pointer or link to another data of the same type. Linked lists permit insertion and removal of nodes at any point in the list in constant time, but do not allow random access.
45.What member function places a new node at the end of the linked list?
The appendNode() member function places a new node at the end of the linked list. The appendNode() requires an integer representing the current data of the node.
46.How is any Data Structure application is classified among files?
A linked list application can be organized into a header file, source file and main application file. The first file is the header file that contains the definition of the NODE structure and the LinkedList class definition. The second file is a source code file containing the implementation of member functions of the LinkedList class. The last file is the application file that contains code that creates and uses the LinkedList class.
47.Which file contains the definition of member functions?
Definitions of member functions for the Linked List class are contained in the LinkedList.cpp file.
48.What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model.
1. RDBMS Array (i.e. Array of structures)
2. Network data model Graph
3. Hierarchical data model Trees.
49.Difference between calloc and malloc ?
malloc: allocate n bytes
calloc: allocate m times n bytes initialized to 0
50.ADJACENCY MATRIX:
Graphs G = (V, E) can be represented by adjacency matricesG[v1..v|V |, v1..v|V |], where the rows and columns are indexed by the nodes, and the entries G[vi, vj] represent the edges. In the case of unlabeled graphs, the entries are just boolean values.

A
B
C
D
A
0
1
1
1
B
1
0
0
1
C
1
0
0
1
D
1
1
1
0
In case of labeled graphs, the labels themselves may be introduced into the entries.

A
B
C
D
A
10
4
1
B
15
C
9
D
Adjacency matrices require O(|V |2) space, and so they are space-efficient only when they are dense (that is, when the graphs have many edges). Time-wise, the adjacency matrices allow easy addition and deletion of edges.

51.Adjacency Lists

A representation of the graph consisting of a list of nodes, with each node containing a list of its neighbouring nodes.
This representation takes O(|V | + |E|) space

52. What do you mean by: Syntax Error, Logical Error, Run time Error?  

Syntax Error-Syntax Error is due to lack of knowledge in a specific language. It is due to somebody does not know how to use the features of a language.We can know the errors at the time of compilation.logical 
Error-It is due to the poor understanding of the requirement or problem.
Run time Error-The exceptions like divide a number by 0,overflow and underflow comes under this.


53 .What is the maximum total number of nodes in a tree that has N levels? Note that the root is level (zero).
2^(N+1)-1..

if N=0; it is 2-1=1,1 is the max no of node in the tree
if N=1; it is 4-1=3, 3 is the max no of nodes in the tree
if N=2; it is 8-1=7, 7 is the max.

54. Explain about the types of linked lists?
There are three linked lists1)linear or simple linked lists2)doubly linked lists3)circular linked lists
Simple linked list :This contains a node which has two parts, see that a node is a STRUCTURE. One is data and other one is a pointer which is called self reference pointers, so we must make it to point to the next location of second node created dynamically.
Double linked lists: A node will consists of previous node address, a data & next node address which can move backwards to the very first address.
Circular linked list: Here we will have the node consists of same thing but default when it finishes the last node and come to the first node.


55.What are the parts of root node?  
A root node contains data part and has link part. i.e links to its child. If it is binary tree it has two links i.e left child and right child.


56 .How will inorder, preorder and postorder traversals printthe elements of a tree?
voidinorder(node * tree)
{
 if(tree!=NULL)
 {
inorder(tree->leftchild);
printf("%d",tree->data);
inorder(tree->rightchild);
 }
else
return;
}
void postorder(node * tree)
{
if(tree!=NULL)
{
postorder(tree->leftchild);
postorder(tree->rightchild);
printf("%d",tree->data);
 }
else
return;
}
void preorder(node * tree)
 {
if(tree!=NULL)
{
printf("%d",tree->data);
preorder(tree->leftchild);
preorder(tree->rightchild);
}
else
return;
}

57.Create an singly linked lists and reverse the lists by interchanging the links and not the data?
                                            
struct node{ int data;
node * next;
};
node *pt1,*pt2=NULL:
while(root!=NULL)
{
pt1=root;
root=root->next;
pt1->next=pt2;
pt2=pt1;
}


58. How can one find a cycle in the linked list? IF found how to recognize the cycle and delete that cycle?

find_cycle(Node* head){
Node* ptr1 = head;
Node* ptr2 = head;
while(ptr1 != NULL && ptr2 != NULL && ptr2->next != NULL){
if(ptr1 == ptr2){
printf("\nClycle present in thrLinkList\n");
return true;
}
ptr1 = prt1->next;
ptr2 = ptr2->next->next;
}
return false;
}

59.What do you mean by Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion?
These terms are found in Recursion.
1.Base Case:it is the case in recursion where the answer is known,or we can say the termination condition for a recursion to unwind back.For example to find Factorial of num using recursion:

int Fact(intnum){

if(num==1 || num==0)//base case
return 1;
else // recursive case:
return num*Fact(num-1);
}

2.Recursive case:It is the case whcih brings us to the
closer answer.

3.Run Time Stack:It is a system stack us to save the frame stack of a function every recursion or every call.This frame stack consists of the return address,local variables and return value if any.

4.TailRecursion:The case where the function consist of single recursive call and it is the last statement to be executed.A tail Recursion can be replace by iteration. The above funtion consists of tail recursion case.where as the below function does not.

void binary(intstart,intend,int el){
int mid;
if(end>start){
mid=(start+end)/2;
if(el==ar[mid])
return mid;
else{
if(el>ar[mid])
binary(mid+1,end,ele);
else
binary(start,mid-11,ele);
}
}
}

60. What is NP completeness problem?
NP may be equivalently defined as the set of decision problems that can be solved in polynomial time on a nondeterministic Turing machine.
NP-complete problems are studied because the ability to quickly verify solutions to a problem (NP) seems to correlate with the ability to quickly solve that problem (P). It is not known whether every problem in NP can be quickly solved—this is called the P = NP problem. But if any single problem in NP-complete can be solved quickly, then every problem in NP can also be quickly solved, because the definition of an NP-complete problem states that every problem in NP must be quickly reducible to every problem in NP-complete
61. What is Hamiltonian cycle?
Given a undirected graph G, there exists a Hamiltonian cycle, if and only if there exists a cycle, in which every vertex is visited exactly once. Note that, one node can be allowed to close the cycle, so that node would visit twice.
The Hamiltonian cycle problem is a special case of the travelling salesman problem, obtained by setting the distance between two cities to a finite constant if they are adjacent and infinity otherwise
62. Types of Data structures:
The data structures can be of the following types:
1. Linear Data structures 2. Non-Linear Data Structures
1. Linear Data structures- In these data structures the elements form a sequence. Such as Arrays, Linked Lists Stacks and Queues are linear data structures.
2. Non-Linear Data Structures- In these data structures the elements do not form a sequence. Such as Trees and Graphs are non-linear data structures.
63. Define stack and its operations
Stacks hold objects, usually all of the same type. Most stacks support just the simple set of operations we introduced above; and thus, the main property of a stack is that objects go on and come off of thetop of the stack.
Here are the minimal operations we'd need for an abstract stack (and their typical names):
·         Push( ): Places an object on the top of the stack.
·         Pop( ): Removes an object from the top of the stack and produces that object.
·         Is Empty( ): Reports is whether the stack empty or not.
64. What is an abstract data type?
An Abstract Data Type (ADT) is more a way of looking at a data structure: focusing on what it does and ignoring how it does its job. A stack or a queue is an example of an ADT. It is important to understand that both stacks and queues can be implemented using an array. It is also possible to implement stacks and queues using a linked list. This demonstrates the "abstract" nature of stacks and queues: how they can be considered separately from their implementation
Consider for example the stack class. The end user knows that push() and pop() (amoung other similar methods) exist and how they work. The user doesn't and shouldn't have to know how push() and pop() work, or whether data is stored in an array, a linked list, or some other data structure like a tree.

65.CHARACTERISTICS OF DATA STRUCTURES:
Data Structure
Advantages
Disadvantages
Array
Quick inserts
Fast access if index known
Slow search
Slow deletes
Fixed size
Ordered Array
Faster search than unsorted array
Slow inserts
Slow deletes
Fixed size
Stack
Last-in, first-out acces
Slow access to other items
Queue
First-in, first-out access
Slow access to other items
Linked List
Quick inserts
Quick deletes
Slow search
Binary Tree
Quick search
Quick inserts
Quick deletes
(If the tree remains balanced)
Deletion algorithm is complex
Red-Black Tree
Quick search
Quick inserts
Quick deletes
(Tree always remains balanced)
Complex to implement
2-3-4 Tree
Quick search
Quick inserts
Quick deletes
(Tree always remains balanced)
(Similar trees good for disk storage)
Complex to implement
Hash Table
Very fast access if key is known
Quick inserts
Slow deletes
Access slow if key is not known
Inefficient memory usage
Heap
Quick inserts
Quick deletes
Access to largest item
Slow access to other items
Graph
Best models real-world situations
Some algorithms are slow and very complex

                                                      








ALGORITHMS

1.KRUSKAL’S ALGORITHM
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connectedweighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. If the graph is not connected, then it finds a minimum spanning forest (a minimum spanning tree for each connected component). Kruskal's algorithm is an example of a greedy algorithm.
Algorithm
·         create a forest F (a set of trees), where each vertex in the graph is a separate tree
·         create a set S containing all the edges in the graph
·         while S is nonempty and F is not yet spanning
·         remove an edge with minimum weight from S
·         if that edge connects two different trees, then add it to the forest, combining two trees into a single tree
·         otherwise discard that edge.
At the termination of the algorithm, the forest has only one component and forms a minimum spanning tree of the graph

2.PRIM’S ALGORITHM:
In computer science, Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connectedweightedundirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm was developed in 1930 by Czech mathematician VojtěchJarník and later independently by computer scientistRobert C. Prim in 1957 and rediscovered by EdsgerDijkstra in 1959. Therefore it is also sometimes called the DJP algorithm, the Jarník algorithm, or the Prim–Jarník algorithm.
The only spanning tree of the empty graph (with an empty vertex set) is again the empty graph. The following description assumes that this special case is handled separately.The algorithm continuously increases the size of a tree, one edge at a time, starting with a tree consisting of a single vertex, until it spans all vertices.
·         Input: A non-empty connected weighted graph with vertices V and edges E (the weights can be negative).
·         Initialize: Vnew = {x}, where x is an arbitrary node (starting point) from V, Enew = {}
·         Repeat until Vnew = V:
o    Choose an edge (u, v) with minimal weight such that u is in Vnew and v is not (if there are multiple edges with the same weight, any of them may be picked)
o    Add v to Vnew, and (u, v) to Enew
·         Output: Vnew and Enew describe a minimal spanning tree
3.DIJIKSTRA’S ALGORITHM:
Dijkstra's algorithm, conceived by Dutch computer scientistEdsgerDijkstra in 1956 and published in 1959,[1][2] is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably IS-IS and OSPF (Open Shortest Path First).

Algorithm

Let the node at which we are starting be called the initial node. Let the distance of node Ybe the distance from the initial node to Y. Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step.

  1. Assign to every node a distance value: set it to zero for our initial node and to infinity for all other nodes.
  2. Mark all nodes as unvisited. Set initial node as current.
  3. For current node, consider all its unvisited neighbors and calculate their tentative distance. For example, if current node (A) has distance of 6, and an edge connecting it with another node (B) is 2, the distance to B through A will be 6+2=8. If this distance is less than the previously recorded distance, overwrite the distance. All unvisited neighbors are added to an unvisited set.
  4. When we are done considering all neighbors of the current node, mark it as visited. A visited node will not be checked ever again; its distance recorded now is final and minimal.
  5. The next current node will be the node with the lowest distance in the unvisited set.
  6. If all nodes have been visited, finish. Otherwise, set the unvisited node with the smallest distance (from the initial node, considering all nodes in graph) as the next "current node" and continue from step 3.



4.DEPTH -FIRST SEARCH:
Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.

Example

For the following graph:

a depth-first search starting at A, assuming that the left edges in the shown graph are chosen before right edges, and assuming the search remembers previously-visited nodes and will not repeat them (since this is a small graph), will visit the nodes in the following order: A, B, D, F, E, C, G. The edges traversed in this search form a Trémaux tree, a structure with important applications in graph theory.
Performing the same search without remembering previously visited nodes results in visiting nodes in the order A, B, D, F, E, A, B, D, F, E, etc. forever, caught in the A, B, D, F, E cycle and never reaching C or G.
Iterative deepening is one technique to avoid this infinite loop and would reach all nodes.

Output of a depth-first search


The four types of edges defined by a spanning tree
The most natural result of a depth first search of a graph (if it is considered as a function rather than a procedure) is a spanning tree of the vertices reached during the search. Based on this spanning tree, the edges of the original graph can be divided into three classes: forward edges (or "discovery edges"), which point from a node of the tree to one of its descendants, back edges, which point from a node to one of its ancestors, and cross edges, which do neither. Sometimes tree edges, edges which belong to the spanning tree itself, are classified separately from forward edges. It can be shown that if the original graph is undirected then all of its edges are tree edges or back edges.

Vertex orderings

It is also possible to use the depth-first search to linearly order the vertices of the original graph (or tree). There are three common ways of doing this:
·         A preordering is a list of the vertices in the order that they were first visited by the depth-first search algorithm. A preordering of an expression tree is the expression in Polish notation.
·         A postordering is a list of the vertices in the order that they were last visited by the algorithm. A postordering of an expression tree is the expression in reverse Polish notation.
·         A reverse postordering is the reverse of a postordering, i.e. a list of the vertices in the opposite order of their last visit. When searching a tree, reverse postordering is the same as preordering, but in general they are different when searching a graph.
Thus the possible preorderings are A B D C and A C D B (order by node's leftmost occurrence in above list), while the possible reverse postorderings are A C B D and A B C D (order by node's rightmost occurrence in above list). Reverse postordering produces a topological sorting of any directed acyclic graph

5.BREADTH-FIRST SEARCH:
In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal.
Algorithm:
  1. Enqueue the root node.
  2. Dequeue a node and examine it.
o    If the element sought is found in this node, quit the search and return a result.
o    Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
  1. If the queue is empty, every node on the graph has been examined – quit the search and return "not found".
  2. If the queue is not empty, repeat from Step 2.

                       The result of breadth-first search is
a b c d e f g h


6. TRAVELLING SALESMAN PROBLEM:     

The travelling salesman problem (TSP) is an NP-hard problem in combinatorial optimization studied in operations research and theoretical computer science. Given a list of cities and their pairwise distances, the task is to find a shortest possible tour that visits each city exactly once

Description:

Symmetric TSP with four cities

As a graph problem:
TSP can be modeled as an undirected weighted graph, such that cities are the graph's vertices, paths are the graph's edges, and a path's distance is the edge's length. A TSP tour becomes a Hamiltonian cycle if and only if every edge has the same distance. Often, the model is a complete graph (i.e., an edge connects each pair of vertices). If no path exists between two cities, adding an arbitrarily long edge will complete the graph without affecting the optimal tour.
Asymmetric and symmetric
In the symmetric TSP, the distance between two cities is the same in each opposite direction, forming an undirected graph. This symmetry halves the number of possible solutions. In the asymmetric TSP, paths may not exist in both directions or the distances might be different, forming a directed graph. Traffic collisions, one-way streets, and airfares for cities with different departure and arrival fees are examples of how this symmetry could break down.


PAPER:TCS PLACEMENT PAPER ( DATA STRUCTURE QUESTIONS)
DATA STRUCTURE QUESTIONS:

1.What is a data structure?
2.What does abstract data type means?
3.Evaluate the following prefix expression " ++ 26 + - 1324" (Similar types can be asked)
4.Convert the following infix expression to post fix notation ((a+2)*(b+4)) -1 (Similar types can be asked)
5.How is it possible to insert different type of elements in stack?
6.Stack can be described as a pointer. Explain.
7.Write a Binary Search program
8.Write programs for Bubble Sort, Quick sort
9.Explain about the types of linked lists
10.How would you sort a linked list?
11.Write the programs for Linked List (Insertion and Deletion) operations
12.What data structure would you mostly likely see in a non recursive implementation of a recursive algorithm?
13.What do you mean by Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion?
14.Explain quick sort and merge sort algorithms and derive the time-constraint relation for these.
15.Explain binary searching, Fibinocci search.
16.What is the maximum total number of nodes in a tree that has N levels? Note that the root is level (zero)
17.How many different binary trees and binary search trees can be made from three nodes that contain the key values 1, 2 & 3?
18.A list is ordered from smaller to largest when a sort is called. Which sort would take the longest time to execute?
19.A list is ordered from smaller to largest when a sort is called. Which sort would take the shortest time to execute?
20When will you sort an array of pointers to list elements, rather than sorting the elements themselves?
21.The element being searched for is not found in an array of 100 elements. What is the average number of comparisons needed in a sequential 22.search to determine that the element is not there, if the elements are completely unordered?
23.What is the average number of comparisons needed in a sequential search to determine the position of an element in an array of 100 elements, if 24.the elements are ordered from largest to smallest?
25.Which sort show the best average behavior?
26.What is the average number of comparisons in a sequential search?
27.Which data structure is needed to convert infix notations to post fix notations?
28.What do you mean by:
Syntax Error
Logical Error
Runtime Error
29.How can you correct these errors?
30.In which data structure, elements can be added or removed at either end, but not in the middle?
31.How will in order, preorder and post order traversals print the elements of a tree?
32.Parenthesis are never needed in prefix or postfix expressions. Why?
33.Which one is faster? A binary search of an ordered set of elements in an array or a sequential search of the elements.





Top of Form