Algorithms
Algorithms
A data structure is a named location that can be used to store and organize data. And, an
algorithm is a collection of steps to solve a particular problem. Learning data structures and
algorithms allow us to write efficient and optimized computer programs.
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed
as vertices, and the links that connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set
of edges, connecting the pairs of vertices. Take a look at the following graph −
Basic Operations
Following are basic primary operations of a Graph −
Add Vertex − Adds a vertex to the graph.
Add Edge − Adds an edge between the two vertices of the graph.
Display Vertex − Displays a vertex of the graph
Answer: It is a special format for storing data to serve a particular purpose. It is used for
efficiency and to reduce the complexities of the program. Programming languages like C, C+
+, Java, Python are used to perform operations using data Structures. It is a volatile memory.
Store Data in Temporary Memory. Linear data structure and non-linear data structure are the
types of data structures. Array, Linked List, Stack, Queue, Tree, and Graph are examples of
data structure.
Answer: A binary tree in which each node has exactly zero or two children. In other words,
every node is either a leaf or has two children. It is Also known as proper binary tree.
Practical example of Complete Binary Tree is Binary Heap.
Answer: A Binary tree is a Perfect Binary Tree in which all the internal nodes have two
children and all leaf nodes are at the same level.
4. Which data structure is applied when we are dealing with recursive function?
Stack data structure is used to perform recursion. Recursion use system stack for
storing the return addresses of the function calls.
5. What is Recursion?
Answer: Recursion is the process of defining a problem (or the solution to a problem) in
terms of (a simpler version of) itself. In recursion we reduce steps to find solution. At final
redo the entire program. For example, linked lists and binary trees can be viewed as
recursive data structures.
6. What are different methods to represent a graph?
Answer: A graph can be represented using 3 data structures- adjacency matrix, adjacency
list and adjacency set.
Examples-
In these graphs,
Cyclic Graph-
Example-
Here,
Acyclic Graph-
Example-
Here,
If binary search tree has height h, maximum number of nodes will be when all levels are
completely full. Total number of nodes will be 20 + 21 + …. 2h = 2(h+1) -1.
Answer: If the data is ordered, binary search is almost always faster. If you’re using an
tree based index to pick out elements, then a sequential search is NOT preferred.
sequential search is preferred If any one of the following is associated with your list
a. Unsorted
b. Streaming data
c. Very small (say, length <= 7)
d. Linked List
e. Distribution of data is even, we can perform seq search from a specific
cut index
The two basic searches for arrays are the sequential search and the binary search. a) The
sequential search can be used to locate an item in any array. b) The binary search, on the
other hand, requires an ordered list. The sequential search is used whenever the list is not
ordered.
The worst case of sequential search is if either the last element was the target or if
the target was not even in the list. Both cases would take n comparisons, with n
being the size of the list in question. Thus the worst case complexity is O(n).
It is said that an example of a O(1) operation is that of accessing an element in an array.
According to one source, O(1) can be defined in the following manner: [Big-O of 1] means
that the execution time of the algorithm does not depend on the size of the input. Its
execution time is constant.
Answer: A circular queue is the extended version of a regular queue where the last element is
CPU scheduling
Memory management
Traffic Management
Answer: Hash Table is a data structure which stores data in an associative manner. In
a hash table, data is stored in an array format, where each data value has its own
unique index value. Access of data becomes very fast if we know the index of the
desired data.
Thus, it becomes a data structure in which insertion and search operations are very
fast irrespective of the size of the data. Hash Table uses an array as a storage medium
and uses hash technique to generate an index where an element is to be inserted or is
to be located from.
Hashing
Hashing is a technique to convert a range of key values into a range of indexes of an
array. We're going to use modulo operator to get a range of key values. Consider an
example of hash table of size 20, and the following items are to be stored. Item are in
the (key,value) format.
13. What are pointers?
Answer: A string is a data type used in programming, such as an integer and floating point
unit, but is used to represent text rather than numbers. It is comprised of a set of characters
that can also contain spaces and numbers. For example, the word "hamburger" and the phrase
"I ate 3 hamburgers" are both strings. Even "12345" could be considered a string, if specified
correctly. Typically, programmers must enclose strings in quotation marks for the data to
recognize as a string and not a number or variable name. Here are some more examples of
storing strings into variables:
Answer: Abstract Data type (ADT) is a data type for objects. The definition of ADT only
mentions what operations are to be performed but not how these operations will be
implemented. It does not specify how data will be organized in memory and what
algorithms will be used for implementing the operations. It is called “abstract” because it
gives an implementation-independent view. The process of providing only the essentials
and hiding the details is known as abstraction. There are three ADTs namely List ADT,
Stack ADT, Queue ADT.
16. What are tree traversal? How many traversal of binary tree possible?
Answer: Traversal is a process to visit all the nodes of a tree and may print their values too.
Because, all nodes are connected via edges (links) we always start from the root (head) node.
That is, we cannot randomly access a node in a tree. There are three ways which we use to
traverse a tree −
In-order Traversal
Pre-order Traversal
Post-order Traversal
Whenever an element is to be inserted, first locate its proper location. Start searching from the
root node, then if the data is less than the key value, search for the empty location in the left
sub-tree and insert the data. Otherwise, search for the empty location in the right sub-tree and
insert the data
22. There are 8, 15, 13 and 14 nodes in four trees which of the following number of nodes
can form a full binary tree?
Answer:
23. What is the minimum number of queues needed when implementing a priority queue?
Two queues are needed to implement priority queue, one to store data and another to
store priority.
24. What is the difference between Storage structure and file structure?
The main difference between file structure and storage structure is based on memory area
that is being accessed.
- Storage structure: It is the representation of the data structure in the computer memory.
- File structure: It is the representation of the storage structure in the auxiliary memory.
Secondary memory is known as a Backup memory or Additional memory or Auxiliary
memory.
25. What is the difference between Linear data structure and Non-linear data structure?
In computer science, a data structure is designed in such a way that it can work with various
algorithms. A data structure is classified into two categories:
Linear data structure
Non-linear data structure
Basic In this structure, the elements are In this structure, the elements are
arranged sequentially or linearly and arranged hierarchically or non-
attached to one another. linear manner.
Types Arrays, linked list, stack, queue are Trees and graphs are the types of a
the types of a linear data structure. non-linear data structure.
implemen Due to the linear organization, they Due to the non-linear organization,
tation are easy to implement. they are difficult to implement.
Traversal As linear data structure is a single The data items in a non-linear data
level, so it requires a single run to structure cannot be accessed in a
traverse each data item. single run. It requires multiple runs
to be traversed.
Linked list is basically a linear data Structure because it stores data in a linear fashion. A
linear data Structure is what which stores data in a linear format and the traversing is in
sequential manner and not in zigzag way. Linked list (both single and doubly) is a linear data
structure when we're talking about access strategy. However they're considered as non-linear data
structures on the basis of storage.
In general, algorithms that involve efficient data structure is applied in the following areas: numerical
analysis, operating system, A.I., compiler design, database management, graphics, and statistical
analysis, …
28. What is the minimum number of nodes that a binary tree can have?
If binary tree has height h, minimum number of nodes is h+1
Min-heap-Where the value of the root node is less than or equal to either of its children.
Max-Heap − Where the value of the root node is greater than or equal to either of its
children.
Implementation
Data structures such as stack and queues can be easily implemented using
linked list.
Stacks make excellent mechanisms for temporary storage of information within procedures. A
primary reason for this is that they allow recursive invocations of procedures without risk
of destroying data from previous invocations of the routine. Stacks are used to
implement functions, parsers, expression evaluation, and backtracking algorithms.
A stack, S of type T is a sequence of items of type T on which the following
operations are defined:
Divide and Conquer is a recursive problem-solving approach which break a problem into
smaller sub-problems, recursively solve the sub problems, and finally combines the
solutions to the sub problems to solve the original problem. This method usually allows us to
reduce the time complexity to a large extent.
38. What is doubly linked list? What is the use of doubly linked list?
Doubly Linked List is a variation of Linked list in which navigation is possible in both ways,
either forward or backward easily as compared to Single Linked List.
Doubly linked list can be used in navigation systems where both front and back navigation is
required. It is used by browsers to implement backward and forward navigation of visited web
pages i.e. back and forward button. It is also used by various applications to implement Undo
and Redo functionality.
39. Why do we use queue in data structure?
Queue is used when things don’t have to be processed immediately, but have to be processed in
First-In-First-Out order like Breadth First Search. This property of Queue makes it also useful
when a resource is shared among multiple consumers. Examples include CPU scheduling, Disk
scheduling and Handling of interrupts in real-time systems. The interrupts are handled in the
same order as they arrive i.e First come first served.
40. What is prefix of (a+b/c*(d*e))?
Answer: */+abc*de
2 (a + b) ∗ c ∗+abc ab+c∗
3 a ∗ (b + c) ∗a+bc abc+∗
5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗
These rings are of different sizes and stacked upon in an ascending order, i.e. the
smaller one sits over the larger one. There are other variations of the puzzle where the
number of disks increase, but the tower count remains the same.
Rules
The mission is to move all the disks to some another tower without violating the
sequence of arrangement. A few rules to be followed for Tower of Hanoi are −
Only one disk can be moved among the towers at any given time.
Only the "top" disk can be removed.
No large disk can sit over a small disk.
Following is an animated representation of solving a Tower of Hanoi puzzle with three
disks.
Shell Sort
This algorithm is quite efficient for medium-sized data sets as its average and worst-
case complexity of this algorithm depends on the gap sequence the best known is
Ο(n), where n is the number of items. And the worst case space complexity is O(n).
Then, we take interval of 1 and this gap generates two sub-lists - {14, 27, 35, 42}, {19,
10, 33, 44}
We compare and swap the values, if required, in the original array. After this step, the
array should look like this −
Finally, we sort the rest of the array using interval of value 1. Shell sort uses insertion
sort to sort the array.
Following is the step-by-step depiction −
We see that it required only four swaps to sort the rest of the array.
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and
uses a stack to remember to get the next vertex to start a search, when a dead end
occurs in any iteration.
As in the example given above, DFS algorithm traverses from S to A to D to G to E to
B first, then to F and lastly to C. It employs the following rules.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it
in a stack.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will
pop up all the vertices from the stack, which do not have adjacent vertices.)
Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
46. Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion
and uses a queue to remember to get the next vertex to start a search, when a
dead end occurs in any iteration.
As in the example given above, BFS algorithm traverses from A to B to E to F first then
to C and G lastly to D. It employs the following rules.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it
in a queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
Interpolation search is an improved variant of binary search. This search algorithm works
on the probing position of the required value. For this algorithm to work properly, the data
collection should be in a sorted form and equally distributed.
47. Interpolation search
Interpolation search is an improved variant of binary search. Interpolation search finds a
particular item by computing the probe position. Initially, the probe position is the position of
the middle most item of the collection.
For this algorithm to work properly, the data collection should be in a sorted form and equally
distributed.
Runtime complexity of interpolation search algorithm is Ο(log (log n)) as compared to Ο(log n)
of BST in favorable situations.
A B-tree is a tree data structure that keeps data sorted and allows searches, insertions, and deletions in
logarithmic amortized time. Unlike self-balancing binary search trees, it is optimized for systems that
read and write large blocks of data. It is most commonly used in database and file systems.