0% found this document useful (0 votes)
70 views

Algorithms

The document discusses data structures and algorithms. It defines a data structure as a named location that can store and organize data, and an algorithm as a collection of steps to solve a problem. Learning data structures and algorithms allows for writing efficient computer programs. It provides examples of common data structures like arrays, linked lists, stacks, queues, trees and graphs.

Uploaded by

Usman Malik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Algorithms

The document discusses data structures and algorithms. It defines a data structure as a named location that can store and organize data, and an algorithm as a collection of steps to solve a problem. Learning data structures and algorithms allows for writing efficient computer programs. It provides examples of common data structures like arrays, linked lists, stacks, queues, trees and graphs.

Uploaded by

Usman Malik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

DATA STRUCTURES AND ALOGRITHMS

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.

Database Data Structure


It is a special format for storing data to serve a
It is an organized collection of data. particular purpose.
It is used for efficiency and to reduce the
It is used to access the data and manage it easily. complexities of the program.
Structured query language (SQL) is used to perform operations
on the data in a database. DataBase Management System Programming languages like C, C++, Java,
(DBMS) is used to manage the database.  Python are used to perform operations using
data Structures.
It is a Non-volatile memory. It is a volatile memory.
Relational database, NOSQL database, Centralized database, Linear data structure and non-linear data
Hierarchical database are some types of databases. structure are the types of data structures.
Example : Array, Linked List, Stack, Queue,
Example : MySQL, Oracle, MongoDB, Sybase etc. Tree, Graph.
Store Data in permanent Memory Store Data in Temporary Memory

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 −

In the above graph,


V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
Graph Data Structure
Mathematical graphs can be represented in data structure. We can represent a graph
using an array of vertices and a two-dimensional array of edges. Before we proceed
further, let's familiarize ourselves with some important terms −
 Vertex − Each node of the graph is represented as a vertex. In the following
example, the labeled circle represents vertices. Thus, A to G are vertices. We
can represent them using an array as shown in the following image. Here A can
be identified by index 0. B can be identified using index 1 and so on.
 Edge − Edge represents a path between two vertices or a line between two
vertices. In the following example, the lines from A to B, B to C, and so on
represents edges. We can use a two-dimensional array to represent an array as
shown in the following image. Here AB can be represented as 1 at row 0,
column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as
0.
 Adjacency − Two node or vertices are adjacent if they are connected to each
other through an edge. In the following example, B is adjacent to A, C is
adjacent to B, and so on.
 Path − Path represents a sequence of edges between the two vertices. In the
following example, ABCD represents a path from A to D.

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

1. Define data structure?

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.

2. Define full binary tree?


What is complete binary search tree?

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. 

3. What is perfect binary search tree?

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. 

7. What is a cycle in a graph?


Define acyclic graph with help of example?

Answer: Cycle Graph-


 A simple graph of ‘n’ vertices (n>=3) and n edges forming a cycle of length ‘n’ is called as
a cycle graph.
 In a cycle graph, all the vertices are of degree 2.
 

Examples-
 

In these graphs,

 Each vertex is having degree 2.


 Therefore, they are cycle graphs.
 

Cyclic Graph-
 

 A graph containing at least one cycle in it is called as a cyclic graph.


 

Example-
 
 

Here,

 This graph contains two cycles in it.


 Therefore, it is a cyclic graph.
 

Acyclic Graph-
 

 A graph not containing any cycle in it is called as an acyclic graph.


 

Example-
 

Here,

 This graph do not contain any cycle in it.


 Therefore, it is an acyclic graph.

8. How to find total number of nodes?


Answer: How you will find total number of nodes in a binary tree?

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.

9. What is adjacency list?

Answer: Adjacency List: 


An array of lists is used. The size of the array is equal to the number of vertices of graph.
Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to
the ith vertex. This representation can also be used to represent a weighted graph. The
weights of edges can be represented as lists of pairs.

10. When you should not use sequential search?

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.

What is worst case time for sequential search?

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.

11. What is circular queue? Why we use it?

Answer: A circular queue is the extended version of a regular queue where the last element is

connected to the first element and forming a circle-like structure.

Circular Queue is used for:

 CPU scheduling

 Memory management

 Traffic Management

12. How do you understand hash tables?

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: The Pointer in C, is a variable that stores address of another variable. A


pointer can also be used to refer to another pointer function. A pointer can be
incremented/decremented, i.e., to point to the next/ previous memory location.
The purpose of pointer is to save memory space and achieve faster execution
time.

14. Write different categories of strings?

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:

string lastName = "Smith";

string book = "Second Foundation";

string foo = "blah";

15. What is ADT? List its benefit?

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.

Benefits of using Abstract Data Types

 Code is easier to understand


 Implementations of ADTs can be changed (e.g., for efficiency) without requiring
changes to the program that uses the ADTs. 

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

17. What is need of pre-/postfix when we have infix?


Infix notation is easy to read for humans, whereas pre-/postfix notation is easier to parse for
a machine. The big advantage in pre-/postfix notation is that there never arise any questions
like operator precedence.

18. What is an AVL tree in data structure?

Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing


binary search tree. AVL tree checks the height of the left and the right sub-trees and assures
that the difference is not more than 1. This difference is called the Balance Factor.

19. What is dequeue?


Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is
open at both its ends. One end is always used to insert data (enqueue) and the other is used
to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item
stored first will be accessed first.

 enqueue() − add (store) an item to the queue.


 dequeue() − remove (access) an item from the queue.
A deque, also known as a double-ended queue, is an ordered collection of items similar to the
queue. It has two ends, a front and a rear, and the items remain positioned in the collection. It is
important to note that even though the deque can assume many of the characteristics of stacks
and queues, it does not require the LILO and FIFO orderings that are enforced by those data
structures.

20. What is big O notation in data structure?


A theoretical measure of the execution of an algorithm, usually the time or memory needed,
given the problem size n (which is usually the number of items), is called big O notation.

21. How you insert a new item in binary search tree?


BST is a collection of nodes arranged in a way where they maintain BST properties. Each node
has a key and an associated value. While searching, the desired key is compared to the keys in
BST and if found, the associated value is retrieved.
Following is a pictorial representation of BST-

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

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.

26. Linked list is linear or nonlinear data structure? Give reason.

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.

27. In what areas do data structures applied?


Data structure is important in almost every aspect where data is involved.

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

29. What is ordered list in data structure?


The structure of an ordered list is a collection of items where each item holds a relative
position that is based upon some underlying characteristic of the item. The ordering is
typically either ascending or descending and we assume that list items have a meaningful
comparison operation that is already defined

30. What are dynamic data structures?


A dynamic data structure (DDS) refers to an organization or collection of data in memory that
has the flexibility to grow or shrink in size, enabling a programmer to control exactly how
much memory is utilized. Typical examples are lists and trees that grow and shrink
dynamically.
31. What is max heap?
Heap is a special case of balanced binary tree data structure where the root-node key is
compared with its children and arranged accordingly.

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.

32. List the advantages of linked list?


Linked list is a dynamic data structure so it can grow and shrink at runtime by
allocating and de-allocating memory. So there is no need to give initial size of
linked list.
Insertion and Deletion: Insertion and deletion of nodes are really easier.
Unlike array here we don’t have to shift elements after insertion or deletion of
an element. In linked list we just have to update the address present in next
pointer of a node.

No Memory Wastage: As size of linked list can increase or decrease at run


time so there is no memory wastage. In case of array there is lot of memory
wastage, like if we declare an array of size 10 and store only 6 elements in it
then space of 4 elements are wasted. There is no such problem in linked list as
memory is allocated only when required.

Implementation

Data structures such as stack and queues can be easily implemented using
linked list.

33. What is FIFO?


In computing and in systems theory, FIFO (an acronym for first in, first out) is a method for
organizing the manipulation of a data structure (often, specifically a data buffer) where the
oldest (first) entry, or "head" of the queue, is processed first.

34. What is merge sort?


Merge sort is a sorting technique based on divide and conquer technique. With worst-
case time complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted
manner.
35. What is push and pop in data structure?
Pushing means putting an item onto a stack (data structure), so that it becomes the stack's top-
most item. Popping’ means removing the top-most item from a stack.
36. Why do we use stacks?

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:

1. Initialize the stack S to be the empty stack


2. Determine whether or not the stack S is empty()
3. Determine whether or not the stack S is full()
4. push() a new item of type T onto the top of the stack, S
5. If S in not empty, pop() remove an item from the top of the stack, S.

37. What is dividing and conquer approach?

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

Sr.No Infix Notation Prefix Notation Postfix


. Notation

1 a+b +ab ab+

2 (a + b) ∗ c ∗+abc ab+c∗

3 a ∗ (b + c) ∗a+bc abc+∗

4 a/b+c/d +/ab/cd ab/cd/+

5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗

6 ((a + b) ∗ c) - d -∗+abcd ab+c∗d-

41. What is spanning tree?


A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected..
By this definition, we can draw a conclusion that every connected and undirected Graph G has
at least one spanning tree. A disconnected graph does not have any spanning tree, as it
cannot be spanned to all its vertices.
We found three spanning trees off one complete graph. A complete undirected graph can have
maximum nn-2 number of spanning trees, where n is the number of nodes. In the above
addressed example, n is 3, hence 33−2 = 3 spanning trees are possible.
General Properties of Spanning Tree
We now understand that one graph can have more than one spanning tree. Following are a
few properties of the spanning tree connected to graph G −
 A connected graph G can have more than one spanning tree.
 All possible spanning trees of graph G, have the same number of edges and vertices.
 The spanning tree does not have any cycle (loops).
 Removing one edge from the spanning tree will make the graph disconnected, i.e. the
spanning tree is minimally connected.
 Adding one edge to the spanning tree will create a circuit or loop, i.e. the spanning tree
is maximally acyclic.

42. What is meant by Principle of optimality?


Definition: A problem is said to satisfy the Principle of Optimality if the sub-solutions of an
optimal solution of the problem are themselves optimal solutions for their sub-problems.
Examples: The shortest path problem satisfies the Principle of Optimality.

43. Why do we need to do algorithm analysis?


Algorithm analysis is important in practice because the accidental or unintentional use of an
inefficient algorithm can significantly impact system performance. In time-sensitive
applications, an algorithm taking too long to run can render its results outdated or useless.

44. What is Tower of Hanoi?


Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and
more than one rings is as depicted

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.

Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This


presentation shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.

45. What is Fibonacci series?


Fibonacci series generates the subsequent number by adding two previous numbers.
Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be
taken 0, 1 or 1, 1 respectively.
Fibonacci series satisfies the following conditions −
Fn = Fn-1 + Fn-2
Hence, a Fibonacci series can look like this −
F8 = 0 1 1 2 3 5 8 13
or, this −
F8 = 1 1 2 3 5 8 13 21

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).

How Shell Sort Works?


Let us consider the following example to have an idea of how shell sort works. We take
the same array we have used in our previous examples. For our example and ease of
understanding, we take the interval of 4. Make a virtual sub-list of all values located at
the interval of 4 positions. Here these values are {35, 14}, {33, 19}, {42, 27} and {10,
44}
We compare values in each sub-list and swap them (if necessary) in the original array.
After this step, the new array should look like this −

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.

You might also like