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

DS Questions

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

DS Questions

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

ARRAYS

Short Questions:

Q1) Define array.


A) An array refers to an orderly arrangement of data elements/items. It stores
data elements in adjacent locations. It is a linear data structure that stores
elements of the same data type. It is a linear homogeneous data structure.

h
Q2) List out applications of arrays.

ab
A) Some key applications of arrays in a concise format:

ur
- Data Storage: Store collections of elements of the same type.

Sa
- Lists and Collections: Implement lists, stacks, queues, and linked lists.

- Matrices and Multidimensional Arrays: Represent multidimensional data like


matrices.
d
an
- Image and Audio Processing: Store pixel or audio samples for processing.

- Graphs and Trees: Represent adjacency matrices or lists for graphs and
it

trees.
oh

- Dynamic Programming: Store intermediate results in optimization algorithms.


M

- Sorting and Searching: Implement sorting and searching algorithms


efficiently.
by

- Hash Tables: Used for fast retrieval and storage in key-value pairs.

- Simulation and Modeling: Manipulate large datasets for simulations and


e

modeling.
ad

- Game Development: Manage game state, sprites, collision detection, etc.


M

- Signal Processing: Analyze and process signals in telecommunications and


media.

- Database Management: Process query results and manage indexes


efficiently.
- Artificial Intelligence and Machine Learning: Store and manipulate datasets
for machine learning tasks.

Q3) Which operation is supported by array ADT?


A) The Array Abstract Data Type (ADT) supports operations such as
accessing, inserting, deleting, updating elements, searching for elements,
sorting, merging arrays, splitting arrays, and retrieving the array size.

h
Q4) What will happen in a C++ program when you assign a value to an

ab
array element whose subscripts exceed the size of the array?
A) In C++, accessing an array element with an out-of-bounds index results in
undefined behaviour. This means anything can happen:

ur
● Crash: Most likely scenario, program crashes due to memory corruption.
● Unexpected behaviour: Program might appear to work for a while but

Sa
produce incorrect results.
● No effect (rare): In some rare cases, no immediate issue might occur.

d
Q5) What is the index number of the last element of an array of 20
an
elements?
A)19
it

Q6) List out the operations performed on arrays.


oh

A) Accessing, inserting, deleting, updating, searching, sorting, merging,


splitting, copying, iterating, finding max/min, calculating sum/average, resizing,
rotating, and mapping/transforming elements.
M

Q7) Give the number of elements in array[1:5].


by

A) 5

Q8) Give the number of elements in the array[1:5,1:4,1:3].


e

A) The expression [1:5, 1:4, 1:3] represents a multi-dimensional array or a


ad

slice of an array. Let's break it down:


● [1:5] represents elements from index 1 to index 5 (inclusive), so there are
M

5−1+1=5 elements in this dimension.


● [1:4] represents elements from index 1 to index 4 (inclusive), so there are
4−1+1=4 elements in this dimension.
● [1:3] represents elements from index 1 to index 3 (inclusive), so there are
3−1+1=3 elements in this dimension.
To find the total number of elements in this multi-dimensional array, we multiply
the number of elements in each dimension:
Total elements = elements in dimension 1 × elements in dimension 2 ×
elements in dimension 3
Total elements = 5 × 4 × 3 = 60
Therefore, there are a total of 60 elements in the array [1:5, 1:4, 1:3]

Q9) Give the number of elements in array A[3][2].


A) 6

h
Q 10) What is the row major order?

ab
A) Row-major order is a way of
arranging multidimensional arrays in
memory where elements of each row

ur
are stored contiguously, meaning
elements of the same row are adjacent in memory.

Sa
Q 11) What is column major order?
A) Column-major order is a way of
arranging multidimensional arrays in d
an
memory where elements of each
column are stored contiguously,
meaning elements of the same column are adjacent in memory.
it
oh

Q12) Write a formula to calculate the address of elements in a


one-dimensional array.
A) Address of A[i] = BaseAddress + S * (i – LB)
M

Where:
● Address of element: The memory address where the desired element is
by

located.
● B = Base address: The memory address of the first element of the array.
● S = Storage size of one element store in any array(in byte).
e

● LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).


ad

Q13) Write a formula to calculate the address of elements in a


M

three-dimensional array.
A)
● n1 as the size of the first dimension (number of elements along dimension
1).
● n2 as the size of the second dimension (number of elements along
dimension 2).
● n3 as the size of the third dimension (number of elements along dimension
3).
● s is the size of each element in bytes.
● i as the index along the first dimension (0-based index).
● j as the index along the second dimension (0-based index).
● k as the index along the third dimension (0-based index).
The formula to calculate the address of the element at indices (i,j,k) in a
row-major order 3-dimensional array is given by:

h
Address = BaseAddress + ((i∗n2∗n3)+(j∗n3)+k)∗s

ab
Where:
● BaseAddress is the starting address of the array in memory.
● (i∗n2∗n3)+(j∗n3)+k calculates the offset of the element from the base

ur
address based on its indices.
● s is the size of each element in bytes, which helps in calculating the

Sa
correct byte offset

Q 14) Define sparse matrix.


d
A) A sparse matrix is a matrix where most elements are zero. Sparse matrices
an
save memory in computations involving large datasets with mostly zero
values, such as in scientific simulations, graph algorithms, and machine
learning tasks.
it
oh

Q 15) Define order-list matrix.


A) An "order-list matrix" is like a grid of numbers or symbols. But instead of
just putting them randomly, we arrange them in a specific order. This order is
M

decided by a list we have. So, each row or column in the matrix follows the
sequence given in that list. It's like organizing things neatly according to a set
by

plan.

Q 16) If the starting address of array a[-2,23] is 100 then what will be the
e

address of the 16th element?


ad

A) Address of 16th element=Starting address+(Index of 16th element×Size of


each element)]=100+15*4=160(consider this array of integer type i.e:- size of
M

each element is 4)

Q 17) If the starting address of array a[1:5,1:6] is 100, then, what will be
the address of a[3,4] element?
A) 160
Q 18) If the starting address of array a[1:5,1:6,1:4] is 100 then what will
be the address of a[3,4,5] element?
A) 286[Address = 100 + ((3∗6∗4)+(4∗4)+5)∗2]
[Address = BaseAddress + ((i∗n2∗n3)+(j∗n3)+k)∗s]

Q19) Write any one difference between row major and column major.
A) In row-major order, the consecutive elements of the rows of the array are
stored next to each other in memory.

h
Column-major order stores the consecutive elements of the columns of the

ab
array next to each other in memory.

Q 20) What are the disadvantages of arrays?

ur
A) Here are the disadvantages of arrays:

Sa
➢ Fixed Size: Arrays have a fixed size, making it difficult to resize
dynamically.
➢ Contiguous Memory: Requires contiguous memory allocation, limiting
d
flexibility and leading to memory fragmentation.
an
➢ Inefficient Insertions/Deletions: Inserting or deleting elements in the middle
requires shifting elements, which can be inefficient for large arrays.
➢ Homogeneous Data: Arrays store elements of the same data type, limiting
it

flexibility for heterogeneous data storage.


oh

➢ Lack of Dynamic Behavior: Arrays do not inherently support dynamic


behaviour like adding or removing elements without manual adjustments.
M

These limitations necessitate the use of more complex data structures in


certain scenarios to overcome these drawbacks.
by
e
ad
M
Long Questions:
Q1) Explain the classification of data structure.
A)

h
ab
ur
Sa
d
an
it
oh

Q2) Explain various operations performed on data structures.


M

A) Various operations performed on data structures include:


by

1. Insertion: Adding new elements or nodes to the data structure.


2. Deletion: Removing existing elements or nodes from the data structure.
3. Traversal: Accessing and processing all elements or nodes in a structured
e

manner.
4. Search: Finding a specific element or node within the data structure.
ad

5. Sorting: Arranging elements or nodes in a specific order (e.g., ascending or


descending).
M

6. Update: Modifying the value or properties of existing elements or nodes.


7. Merge: Combining two or more data structures into a single data structure.
8. Split: Dividing a data structure into smaller segments based on certain
criteria.
9. Access: Retrieving or modifying elements or nodes at specific positions.
10. Comparison: Comparing data structures for equality or based on certain
criteria.
11. Copying: Creating a duplicate or shallow copy of a data structure.
12. Memory Management: Allocating and deallocating memory efficiently,
especially in dynamic data structures.

Q3) Write a short note on abstract data type.


A)
➔ Operations in DS involve tasks like adding or deleting items, accessing
elements based on priority, or sorting/searching within the structure.

h
➔ When a DS offers such operations, it is termed as ADT.

ab
➔ The word ‘abstract’ refers to the fact that the data and the basic operations
defined on it are being studied independently of how they are implemented.
It involves what can be done with data, not how it has to be done.

ur
Q4) Explain the properties of algorithms.

Sa
A) The properties of algorithms define their characteristics and behaviours.
Here are the fundamental properties of algorithms:

d
1. Input: Every algorithm must have zero or more inputs. These inputs are the
an
data upon which the algorithm operates to produce the desired output.

2. Output: For each valid input, an algorithm must produce one or more
it

outputs. The output represents the result or solution to the problem.


oh

3. Definiteness: Each step of the algorithm must be precisely and


unambiguously defined. There should be no ambiguity or uncertainty about
M

what actions to take at each step.


by

4. Finiteness: An algorithm must terminate after a finite number of steps. It


should not run indefinitely or enter an infinite loop.
e

5. Effectiveness: An algorithm should be practical and efficient in solving the


ad

problem. It should use a reasonable amount of resources (such as time,


memory, and processing power) relative to the size of the input.
M

6. Correctness: An algorithm is correct if it produces the correct output for all


possible valid inputs. It solves the problem it was designed to solve.

7. Generalization: An algorithm should be applicable to a wide range of inputs


and scenarios, not just specific instances of the problem. It should be able to
handle different cases and variations of the problem, providing a general
solution.

8. Optimality: An optimal algorithm achieves the best possible performance or


resource usage among all possible algorithms for a given problem. It
minimizes time complexity, space complexity, or other relevant metrics.

9. Robustness: An algorithm should be resilient to errors, invalid inputs, or

h
unexpected conditions. It should handle exceptional cases gracefully, such as

ab
by providing meaningful error messages or recovering from errors without
crashing.

ur
10. Independence: An algorithm should be independent of the programming
language, hardware platform, or specific environment in which it is

Sa
implemented. It should be portable and adaptable to different computing
environments.

d
These properties ensure that algorithms provide a reliable and systematic
an
approach to problem-solving, enabling the development of efficient and
scalable software solutions across various domains.
it

Q5) Explain the steps for the development of algorithm


oh

A) To develop an algorithm:

1. Understand the Problem:


M

- Define the problem, inputs, outputs, and constraints.


- Consider special and edge cases.
by

2. Plan the Approach:


- Choose a strategy and necessary data structures.
e

- Break down the problem into smaller tasks.


ad

3. Design the Algorithm:


M

- Outline the algorithm's steps and logic.


- Develop pseudocode or a flowchart.

4. Implement the Algorithm:


- Translate the algorithm into code.
- Follow coding best practices and test incrementally.
5. Test and Debug:
- Develop test cases and evaluate correctness and efficiency.
- Debug any errors encountered.

6. Optimize if Necessary:
- Analyze time and space complexity.
- Optimize code logic and data structures.

h
7. Document and Maintain:

ab
- Document purpose, inputs, outputs, and usage.
- Include comments in code and update as needed.

ur
These steps ensure correctness, efficiency, and maintainability of the
algorithm.

Sa
Q6) Differentiate Between linear and non-linear data structure.
A) Linear and non-linear data structures are two fundamental types of data
d
structures used in computer science. They differ in terms of how the elements
an
or nodes are organized and connected within the structure. Here's a
differentiation between linear and non-linear data structures:
it

1. Organization:
oh

- Linear Data Structure: In linear data structures, the elements are organized
sequentially or linearly. Each element has exactly one predecessor and one
successor, except for the first and last elements.
M

- Non-linear Data Structure: In non-linear data structures, the elements are


not organized sequentially. They can have multiple predecessors and/or
by

successors, forming complex relationships among elements.

2. Connectivity:
e

- Linear Data Structure: Elements in linear data structures are connected in a


ad

linear manner, meaning each element is connected to its immediate


predecessor and successor.
M

- Non-linear Data Structure: Elements in non-linear data structures may have


multiple connections, forming branching or hierarchical relationships among
elements.

3. Examples:
- Linear Data Structure: Examples of linear data structures include arrays,
linked lists, stacks, and queues, where elements are arranged in a linear
sequence.
- Non-linear Data Structure: Examples of non-linear data structures include
trees, graphs, and heaps, where elements can have multiple connections,
leading to more complex relationships.

4. Traversal:

h
- Linear Data Structure: Traversal of linear data structures is typically

ab
straightforward, involving sequential access to each element in the structure.
- Non-linear Data Structure: Traversal of non-linear data structures may
require specialized algorithms, as the relationships among elements can be

ur
more complex. Traversal methods like depth-first search (DFS) and
breadth-first search (BFS) are commonly used for non-linear structures like

Sa
trees and graphs.

5. Memory Allocation:
d
- Linear Data Structure: Linear data structures often have contiguous
an
memory allocation, making them efficient for access and traversal.
- Non-linear Data Structure: Non-linear data structures may require dynamic
memory allocation and pointers to represent relationships among elements,
it

which can be less memory-efficient compared to linear structures.


oh

6. Usage:
- Linear Data Structure: Linear data structures are suitable for representing
M

data with a simple sequential relationship, such as ordered lists or sequences


of elements.
by

- Non-linear Data Structure: Non-linear data structures are used for modeling
more complex relationships, such as hierarchical structures (trees), network
connections (graphs), or priority-based data (heaps).
e
ad

Q8) What do you mean by an algorithm? Give an example.


A) Algorithm is a step-by-step procedure, which defines a set of instructions to
M

be executed in a certain order to get the desired output. Algorithms are


generally created independent of underlying languages, i.e. an algorithm can
be implemented in more than one programming language.
Eg. : Add two numbers entered by the user
− Step 1: Start.
− Step 2: Declare variables num1, num2 and sum.
− Step 3: Read values num1 and num2.
− Step 4: Add num1 and num2 and assign the result to sum.
sum ← num1+num2
− Step 5: Display sum.
− Step 6: Stop.

Q9) Explain efficiency of an algorithm.


A) The efficiency of an algorithm refers to how well it manages time and space
resources as it solves a problem. Time complexity measures how the runtime

h
of the algorithm scales with input size, while space complexity measures its

ab
memory usage. Efficient algorithms have low time and space complexities,
performing well with larger inputs and minimal memory requirements.

ur
Q) Write a short note on asymptotic notations.
A) Asymptotic notations such as Big O (O), Omega (Ω), and Theta (Θ) are

Sa
used in computer science to describe the time or space complexity of
algorithms as input sizes grow.
- Big O (O) represents the upper bound or worst-case scenario.
d
- Omega (Ω) represents the lower bound or best-case scenario.
an
- Theta (Θ) represents both upper and lower bounds, providing a tight bound
on complexity.
it

These notations help in analyzing and comparing the efficiency and scalability
oh

of algorithms without getting into specific constant factors or lower-order terms.

Q) Distinguish between best, worst and average case complexities of an


M

algorithm.
A)
by

Q) What do you mean by time and space complexity and how to


represent these complexity?
e

A) Time Complexity: Measures the amount of time an algorithm takes to run


ad

based on input size.


- Represented using Big O (O), Omega (Ω), and Theta (Θ) notations.
M

- Focuses on the worst-case, best-case, and average case of algorithm


execution time.

Space Complexity: Measures the amount of memory space an algorithm uses


based on input size.
- Also represented using Big O (O), Omega (Ω), and Theta (Θ) notations.
- Analyzes worst-case, best-case, and average case of memory usage by the
algorithm.
These complexities help in understanding and comparing algorithm efficiency
and resource usage as input sizes grow.

Q) Explain the concept of data type.


A) In coding, a data type tells the computer what kind of information is stored
in a variable. It's like putting labels on boxes to show what's inside. Different

h
data types allow for different actions on the data, like adding numbers or

ab
joining words. They also set rules, like how big the number can be or how long
the word can get. Data types help programs understand and handle
information correctly. They include things like numbers, words, yes/no

ur
answers, lists, and more. Knowing how to use data types helps make sure
programs work right and don't mess up the data.

Sa
Q) Find the complexity of following code.
for (int i = 0; i < n; i++) {
for(int j=1;j<n;j++) d
an
cout<<j
}
A) O(n^2)
it
oh

Q). Find the total frequency count of the following code.


M
by
e
ad

A)
M

Q) Find the total frequency count of the following code.


i = 2n
A)

Data Structures questions unit 1

h
Q1) Define data structure.
A) A data structure is a way of organizing and storing data in a computer so that it

ab
can be accessed and used efficiently. It refers to the logical or mathematical
representation of data, as well as the implementation in a computer program.

ur
Examples include arrays, linked lists, and trees. Each type has its own strengths and
weaknesses, making them suitable for different tasks.

Sa
Q2) Define algorithm.
A) Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally
d
created independent of underlying languages, i.e. an algorithm can be implemented
an
in more than one programming language.

Q3) List out areas in which data structures are applied.


it

A) Database Systems: For efficient data retrieval and storage.


oh

Operating Systems: For managing jobs, files, and resources.

Compiler Design: For syntax checking and optimization.


M

Networking: For routing and traffic scheduling.


by

Artificial Intelligence: For decision-making processes.

Graphics: For storing objects, layers, and effects.


e

Statistical Analysis: For data organization and pattern extraction.


ad

Game Development: For storing game states, player data, and in-game assets.
M

Q4) List out structure of algorithm.


A) The structure of an algorithm typically consists of:

1. Initialization: Set up initial conditions or variables.


2. Input: Receive input data or parameters.
3. Processing: Perform computations or operations to solve the problem.
4. Output: Generate the final result or output.
5. Termination: End the algorithm and release any resources.
Q5) List out the properties of algorithms.
A) Clear and Unambiguous Well-Defined Inputs
Well-Defined Outputs Finite-ness
Feasible Language Independent

Q6) List out the steps involved in the development of an algorithm.


A)

h
Q7) Define Abstract Data Type.

ab
A)
➔ Operations in DS involve tasks like adding or deleting items, accessing

ur
elements based on priority, or sorting/searching within the structure.
➔ When a DS offers such operations, it is termed as ADT.

Sa
➔ The word ‘abstract’ refers to the fact that the data and the basic operations
defined on it are being studied independently of how they are implemented.
It involves what can be done with data, not how it has to be done.

d
Q8) List out the classification of data structure
an
A)
it
oh
M
by
e
ad
M

Q9) What is linear/primitive data structure?


A)
● Primitive data structures consist of the numbers and the characters which are
built in programs.
● These can be manipulated or operated directly by the machine level instructions.
● Basic data types such as integer, real, character, and Boolean come under
primitive data structures.
● These data types are also known as simple data types because they consist of
characters that cannot be divided.

Q10) What is non-linear/non-primitive data structure?


A)
● Non-primitive data structures are those that are derived from primitive data
structures.
● These data structures cannot be operated or manipulated directly by the machine

h
level instructions.
● They focus on formation of a set of data elements that is either homogeneous

ab
(same data type) or heterogeneous (different data type).
● These are further divided into linear and non-linear data structures based on the

ur
structure and arrangement of data.

Q11) Gives the names of linear data structures.

Sa
A) Arrays, linked lists, stacks, queues.

Q12) Gives the names of non-linear data structures.


A) Graphs, trees. d
an
Q13) Which are the operations performed on data structure?
A) Traversing Insertion Deletion Sorting Merging
it

Q14) How to measure the performance of an algorithm?


oh

A)

Q15) What is time complexity?


M

A) Time complexity can be defined as the amount of time taken by an algorithm to


execute each statement of code of an algorithm till its completion with respect to the
by

function of the length of the input.


OR
In computer science, the time complexity is the computational complexity that
e

describes the amount of time it takes to run an algorithm.


In simple words, Time complexity of a program is a simple measurement of how fast
ad

the time taken by a program grows, if the input increases.


M

Q16) Define space complexity.


A) Space complexity is the amount of memory space that an algorithm takes/requires
during the execution.
OR
In computer science, the space complexity of an algorithm or a computer program is
the amount of memory space required to solve an instance of the computational
problem as a function of the size of the input.
In simple words, Space complexity of a program is a simple measurement of how
fast the space taken by a program grows, if the input increases.

Q17) When empirical testing is used?


A) Empirical testing is used when practical experimentation and real-world data are
employed to evaluate the performance, efficiency, or effectiveness of algorithms,
systems, or processes.

h
Q18) What is the use of theoretical testing?
A) Theoretical testing is used to analyze and predict the performance, efficiency, and

ab
correctness of algorithms or systems based on mathematical analysis rather than
practical experimentation.

ur
Q19) What is average, best and worst case complexity?

Sa
A)
BEST CASE
If an algorithm takes the least amount of time to execute a specific set of input,
then it is called the best case time complexity. The best case efficiency of an
d
algorithm is the efficiency for the best case input of size n. Because of this
an
input, the algorithm runs the fastest among all the possible inputs of the same
size.
AVERAGE CASE
it

If the time complexity of an algorithm for certain sets of inputs are on an


oh

average, then such a time complexity is called average case time complexity.
Average case analysis provides necessary information about an algorithm’s
behavior on a typical or random input.
M

WORST CASE
If an algorithm takes a maximum amount of time to execute for a specific set of
by

input, then it is called the worst case time complexity. The worst case
efficiency of an algorithm is the efficiency for the worst case input of size n.
The algorithm runs the longest among all the possible inputs of the similar size
e

because of this input of size n.


ad

Q20) Define O notation of time complexity.


A)
M

➔ Big O is the method used to express the upper bound of the running time of an
algorithm.
➔ It is used to describe the performance or time complexity of the algorithm.
➔ Big O specifically describes the worst-case scenario and can be used to describe
the execution time required or the space used by the algorithm.
➔ This notation helps in calculating the maximum amount of time taken by an
algorithm to compute a problem. Big O is defined as: f(n) ≤ c ∗ g(n)
Q21) List out the notation that is used to express the time complexity of the
algorithm.
A) The notations used to express the time complexity of algorithms are:

1. Big O Notation (O): Upper bound or worst-case time complexity.


2. Omega Notation (Ω): Lower bound or best-case time complexity.
3. Theta Notation (Θ): Tight bound representing both upper and lower bounds.

h
4. Little O Notation (o): Strict upper bound.
5. Little Omega Notation (ω): Strict lower bound.

ab
These notations help in understanding how an algorithm's performance scales with

ur
input size and provide valuable insights into algorithm efficiency and scalability.

Sa
Long questions:-0.
2535
2 d
an
0Q1) Explain the classification of data structure.
A)
it
oh
M
by
e
ad
M

2. Explain various operations performed on data structures.


A) Various operations performed on data structures include:
- Insertion: Adding new elements/data.
- Deletion: Removing elements/data.
- Traversal: Accessing and visiting elements/data.
- Search: Finding specific elements/data.
- Update/Modification: Modifying existing elements/data.
- Sorting: Arranging elements/data in order.
- Merging/Combining: Combining data structures.
- Splitting: Dividing data structures.

h
- Access/Retrieval: Retrieving elements/data.
- Traversal Algorithms: Algorithms for exploring data structures.

ab
- Comparison: Comparing data structures.
- Memory Management: Efficient memory allocation/deallocation.

ur
- Serialization/Deserialization: Converting data for storage/transmission.
- Hashing: Using hash functions for efficient data retrieval.
- Split/Joint Operations: Operations specific to certain data structures.

Sa
These operations are crucial for manipulating and managing data efficiently within
data structures.

d
Q3) Write a short note on abstract data type.
an
A) Abstract Data Type (ADT) is a model that defines data and operations without
specifying implementation. It encapsulates data and operations, providing a clear
interface. ADTs promote implementation independence, data abstraction, and are
used widely in programming for code organization and reusability. Examples include
it

Stack, Queue, List, Set, Map, Tree, and Graph.


oh

Q4) Explain the properties of algorithms.


A)The properties of algorithms are:
M

- Input: Takes zero or more inputs.


- Output: Produces at least one output.
by

- Definiteness: Each step is precisely defined.


- Finiteness: Terminates after a finite number of steps.
- Effectiveness: Executes using finite resources.
e

- Feasibility: Solves the problem within reasonable time and resources.


- Uniqueness: Unique and optimal among possible solutions.
ad

- Correctness: Produces correct results for valid inputs.


- Optimality: Achieves best possible performance.
M

- Ease of Understanding: Clear and easy to implement and understand.

Q5) Explain the steps for the development of the algorithm.


A)The steps for developing an algorithm are:

1. Understand the Problem:


- Define the problem and its requirements.
2. Plan the Approach:
- Choose a strategy to solve the problem.

3. Design the Algorithm:


- Break down the problem into steps.
- Develop pseudocode or flowchart.

h
4. Implement the Algorithm:
- Translate algorithms into code.

ab
5. Test and Debug:

ur
- Test with various inputs and fix errors.

6. Optimize if Needed:

Sa
- Analyze and improve efficiency.

7. Document and Maintain:


- Document purpose, inputs, and usage. d
an
- Update as needed over time.

Q6) Differentiate between linear and non-linear data structure.


it

A)
oh

Certainly, here are some points to differentiate between linear and non-linear data
structures:
M

Linear Data Structure:


1. Elements are stored and accessed in a linear or sequential manner.
by

2. Each element has a unique predecessor and successor, except for the first and
last elements.
3. Linear data structures are suitable for simple storage and retrieval operations.
e

4. Examples include arrays, linked lists, stacks, and queues.


5. Traversal in linear structures is straightforward, usually involving iteration from one
ad

end to another.
M

Non-linear Data Structure:


1. Elements are not stored in a sequential manner; they may have hierarchical or
interconnected relationships.
2. Elements can have multiple predecessors and successors, forming complex data
relationships.
3. Non-linear data structures are suitable for representing hierarchical relationships,
networks, and interconnected data.
4. Examples include trees, graphs, and hash tables.
5. Traversal in non-linear structures requires specialized algorithms such as
depth-first search (DFS) or breadth-first search (BFS) due to complex relationships
among elements.
6. Non-linear structures can model real-world scenarios more accurately, such as
family trees, organizational hierarchies, and network connections.
Q7) What do you mean by an algorithm? Give an example.
A) An algorithm is a step-by-step procedure or set of rules used to solve a problem or
perform a specific task. It is a sequence of well-defined instructions that take input,

h
process it, and produce the desired output. Algorithms are fundamental in computer
science and are used in programming, mathematics, and problem-solving.

ab
Example of an Algorithm:

ur
Let's consider an algorithm to find the maximum number in an array of integers.

1. Input: An array of integers

Sa
2. Output: The maximum number in the array..

Q8) Explain efficiency of algorithms.


d
A) The efficiency of algorithms refers to how well they use computational resources
an
(such as time and memory) to solve a problem. Efficient algorithms:
1. Complete tasks quickly (less time complexity).
2. Use minimal memory (less space complexity).
3. Scale well with increasing input size without significantly increasing resource
it

usage.
oh

4. Minimize redundant or unnecessary operations.


5. Optimize resource utilization for better performance.
M

Q9) Write a short note on asymptotic notations.


A) Mentioned Above
by

Q10) Distinguish between best, worst and average case complexities of an


algorithm.
e

A) Mentioned Above
ad

Q11) What do you mean by Time and Space complexity and how to represent
these complexity?
M

A) Mentioned Above

Q12) Explain the concept of data type.


A) Data Type:
- A data type is a classification that specifies the type of data that a variable can hold
in programming.
- It determines the size, format, and range of values that can be stored in a variable.
- Examples of data types include integers, floating-point numbers, characters, strings,
boolean values, arrays, and custom-defined structures/classes.
- Data types help in efficient memory allocation and ensure proper data handling and
manipulation during program execution.
- They also define the operations that can be performed on variables of that type
(e.g., arithmetic operations for numeric types, concatenation for strings).
- Different programming languages may have their own set of built-in data types and
allow users to define custom data types.

h
Q13) Find the complexity of the following code.

ab
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {

ur
cout << j << " ";
}
cout << endl;

Sa
}
A)Let's analyze the time complexity of the given code snippet:

d
an
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
cout << j << " ";
}
it

cout << endl;


oh

Here, we have two nested loops:


M

- The outer loop runs from 0 to n-1.


- The inner loop runs from the current value of i to n-1.
by

Let's break it down:


- When i = 0, the inner loop runs n times.
e

- When i = 1, the inner loop runs n-1 times.


- When i = 2, the inner loop runs n-2 times.
ad

- ...
- When i = n-1, the inner loop runs 1 time.
M

The total number of iterations can be calculated as follows:


n + (n-1) + (n-2) + ... + 1 = (n*(n+1))/2

Therefore, the time complexity of the given code is O(n^2) because the nested loops
result in quadratic time complexity in terms of input size 'n'.

Q14) Find The Total Frequency Count Of Following code.


for send=1 to n do
for receive =1 to send do
for ack=2 to receive do
message=send-(receive+ack) ack=ack-1
send=send+1
end
end
A)To find the total frequency count of the given code, we will analyze the number of

h
times each loop is executed:

ab
for send = 1 to n do
for receive = 1 to send do

ur
for ack = 2 to receive do
message = send - (receive + ack)
ack = ack - 1

Sa
end
send = send + 1
end
end d
an
Let's break it down:
1. Outer Loop (`send`):
- It runs 'n' times because it starts from 1 and goes up to 'n'.
it
oh

2. Middle Loop (`receive`):


- For each iteration of the outer loop, it runs from 1 to the current value of `send`.
- In the first iteration, it runs 1 time.
M

- In the second iteration, it runs 2 times.


- In the third iteration, it runs 3 times.
by

- And so on, until it runs 'n' times in the last iteration.

3. Inner Loop (`ack`):


e

- For each iteration of the middle loop, it runs from 2 to the current value of
`receive`.
ad

- In the first iteration of the middle loop (when `receive` is 1), it doesn't run because
the condition `ack = 2 to receive` is not met.
M

- In the second iteration of the middle loop (when `receive` is 2), it runs 1 time
(when `ack` is 2).
- In the third iteration of the middle loop (when `receive` is 3), it runs 2 times (when
`ack` is 2 and 3).
- And so on, until it runs 'receive-1' times in each iteration of the middle loop.

Now, let's calculate the total frequency count:


- The innermost loop runs a total of (1 + 1 + 2 + 2 + 3 + 3 + ... + (n-1) + (n-1)) times.
- This sum is equal to 2 * (1 + 2 + 3 + ... + (n-1)), which is equal to 2 * (n * (n-1) / 2) =
n * (n-1).
- The total frequency count is the product of frequencies of all loops, so it is n * (n-1) *
n = n^2 * (n-1).

Therefore, the total frequency count of the given code is n^2 * (n-1).
Q15.) Find The Total Frequency Count Of Following Code.
i=2n

h
for j=1 to i
for k=3 to j

ab
n=n+1
end

ur
end
A) Let's analyze the total frequency count of the given code:

Sa
i = 2n
for j = 1 to i
for k = 3 to j
n=n+1 d
an
end
end

Let's break it down:


it

1. Outer Loop (`j`):


oh

- It runs from 1 to `i`.


- The number of iterations of the outer loop is equal to the value of `i`.
- So, the outer loop runs 2n times.
M

2. Inner Loop (`k`):


by

- For each iteration of the outer loop, the inner loop runs from 3 to the current value
of `j`.
- In the first iteration of the outer loop (when `j` is 1), the inner loop doesn't run
e

because the condition `k = 3 to j` is not met.


- In the second iteration of the outer loop (when `j` is 2), the inner loop runs 1 time
ad

(when `k` is 3).


- In the third iteration of the outer loop (when `j` is 3), the inner loop runs 2 times
M

(when `k` is 3 and 4).


- And so on, until it runs `(j - 3) + 1` times in each iteration of the outer loop.

3. Frequency Count (`n = n + 1`):


- This statement executes every time the inner loop runs.
- So, the frequency count is the total number of times the inner loop runs.

Let's calculate the total frequency count:


- For each value of `j`, the inner loop runs `(j - 3) + 1` times.
- So, the total frequency count is the sum of this count for all values of `j` from 2 to
2n.

Sum of integers from 1 to n = n * (n + 1) / 2

For our case, sum from 1 to (2n - 3) = (2n - 3) * (2n - 2) / 2

h
Total frequency count = Sum from 1 to (2n - 3) + Sum from 1 to (2n - 3) + Sum from 1
to (2n - 3) + ... (2n times)

ab
Total frequency count = 2n * [(2n - 3) * (2n - 2) / 2]

ur
Simplifying this expression gives the total frequency count.

Sa
Therefore, the total frequency count of the given code is 2n * [(2n - 3) * (2n - 2) / 2].

d
an
it
oh
M
by
e
ad
M
LINKED LIST
Short Questions

h
ab
Q) What is the limitation of sequential data structures?
A) Fixed Size: They have a set size, making it hard to handle changing

ur
amounts of data.
Linear Access: Finding data means searching through every piece one by
one, which can be slow for big sets.

Sa
Inefficient Insertions and Deletions: Adding or removing data from the middle
can be slow because it might mean moving a lot of other data around.
Limited Flexibility: They might not be great for handling different types of
d
data or complex relationships between pieces of data.
an
Slow for Dynamic Changes: Making lots of changes to the data, like adding
or removing items frequently, can be slow and inefficient.
No Quick Access: If you want to find something specific, you might need to
it

look through everything from the start, which can take a while.
oh

Limited Scalability: As the data gets bigger or changes more, these structures
might struggle to keep up and become less efficient.
M

Q) What is a linked list?


A)
by

➢ A linked list consists of nodes where each node contains a data field and a
reference(link) to the next node in the list. This allows for dynamic memory
allocation and efficient insertion and deletion operations compared to
e

arrays.
ad

➢ They are referred to as an array of connected objects where data is stored


in the pointer fields.
M

➢ Linked lists are useful when the number of elements to be stored in a list is
indefinite.

Q) Give a real world example of a linked list.


A) A real-world example of a linked list is a train. Each coach represents a
node, and the coupling that connects one coach to the next represents the
link. The engine is the head of the linked list, and the caboose is the tail. Just
like in a linked list, you can add or remove coaches (nodes) anywhere in the
train.

Q) Explain logical representation of linked lists.


A)

h
ab
ur
Sa
Q) What are the advantages of a singly linked list?
A)
Advantages:
d
Dynamic Size: The size of a linked list can be increased or decreased at
an
runtime.
Efficient Insertions/Deletions: Insertion or deletion of a node can be done
more efficiently compared to an array.
it

No Memory Wastage: Each node is created only when required, so there’s no


oh

memory waste.
Versatility: They support various operations like insertion, deletion, traversal,
and concatenation.
M

Flexibility: Singly linked lists can hold elements of different types and sizes.
by

Q) What are the disadvantages of a singly linked list?


A)
Disadvantages:
e

Sequential Access: We have to access elements sequentially starting from


ad

the first node. So, direct access is not possible.


Extra Memory: Each node of the list requires extra storage for pointers, which
can be an overhead.
M

Backward Traversal: Singly linked lists are less flexible as they allow
movement in one direction only.

Q) Which are the operations performed on singly linked lists?


A) Insertion: Adding a new node to the list.
Deletion: Removing a node from the list.
Traversal: Moving through each node in the list.
Searching: Finding a node in the list.
Updating: Modifying the value of a node.
Sorting: Arranging the nodes in a specific order.
Q) What is the need for linked representation of lists?
A) itThe linked representation of lists is needed for efficient memory
management, dynamic size handling, fast insertion/deletion operations, ease
of implementation, support for various data structures, and memory efficiency

h
in certain scenarios.

ab
Q) Define circular linked list.
A) In a circular linked list, only one pointer is used to point to another node or

ur
next element. It is known as a circular list because the last node’s pointer
points to the HEAD node.

Sa
Q) What are the advantages of circular linked lists?
A) Circular Navigation: It provides a way to cyclically traverse the list since the last
node points to the first node. d
an
Efficient Operations: Operations like insertion and deletion at the beginning and
end are efficient as they require a single pointer update.
Infinite Looping: They are used in applications where the system needs to go
it

around the list again after reaching the end.


oh

Q) What are the disadvantages of circular linked lists?


A) Complex Implementation: The implementation of circular linked lists is complex
compared to singly or doubly linked lists.
M

Traversal Issues: If not traversed carefully, we could end up in an infinite loop.


Extra Memory: Like singly linked lists, each node requires extra storage for a pointer
by

which can be an overhead.

Q) What is the node structure for a circular linked list?


e

A)
ad
M
Q) Define doubly linked list.
A)
● A doubly linked list (DLL) is a special type of linked list in which each node
contains a pointer to the previous node as well as the next node of the linked list.
● The first pointer points to the next element and the second pointer points to the

h
previous element.
● The previous pointer for the HEAD node points to NULL and the next pointer for

ab
the last node points to NULL.
● Doubly-linked list is also known as a two-way list as both forward and backward

ur
traversal is possible.

Q) What are the advantages of doubly linked lists?

Sa
A) Advantages:
● A DLL can be traversed in both forward and backward directions.
● The delete operation in DLL is more efficient if a pointer to the node to be deleted
is given.
d
● We can quickly insert a new node before a given node.
an
● In a singly linked list, to delete a node, a pointer to the previous node is needed.
To get this previous node, sometimes the list is traversed. In DLL, we can get the
it

previous node using the previous pointer.


oh

Q) What are the disadvantages of doubly linked lists?


M

A) The disadvantages of doubly linked lists are:


- Higher memory usage per node.
- Increased complexity for operations like insertion and deletion.
by

- Requires additional space for previous pointers.


- More complex implementation and maintenance.
e

Q) List out operations performed on doubly linked lists.


ad

A) Insertion, Deletion, Traversal, Search, Update, Concatenation, Reverse, Length

Q) List application of linked list.


M

A) Applications of linked lists include:


- Implementing stacks and queues
- Memory management
- File systems
- Dynamic data structures like trees and graphs
- Representing sparse matrices
- Undo functionality
- Polynomial manipulation
- Job scheduling algorithms
- Music player playlists

Q) What is the difference between circular linked list and linear linked list?
A)

h
ab
ur
Sa
d
an
it
oh
M

Q) What is the difference between array and stack?


by
e
ad
M
h
ab
ur
Sa
d
an
A)
it
oh

Q) What do you mean by polynomials?


A) In data structures, polynomials refer to mathematical expressions consisting of
M

variables, coefficients, and exponents. They are typically represented using linked
lists or arrays, where each term in the polynomial is stored as a separate node or
by

element. Polynomials can be manipulated using various operations such as addition,


subtraction, multiplication, and division, making them an important concept in data
structures and mathematics.
e
ad

Q) Give node structure for the term of a polynomial having a single variable.
A) struct TermNode {
M

float coefficient; // Coefficient of the term


int exponent; // Exponent of the variable
struct TermNode* next; // Pointer to the next term node
};

Q) How singly linked list representation of polynomials?


A) #########################################################
Long Answers:-
Q1. Write a short note on the linked list.
A) A linked list is a linear data structure consisting of nodes where each node

h
contains data and a reference (or link) to the next node in the sequence. Key points
about linked lists include:

ab
1. Node Structure:

ur
Each node contains data and a pointer/reference to the next node.

Sa
2. Types of Linked Lists:
- Singly Linked List: Nodes have a pointer to the next node.

d
- Doubly Linked List: Nodes have pointers to both the next and previous nodes.
an
- Circular Linked List: Last node points back to the first node, forming a circle.

3. Dynamic Memory Allocation:


it

Linked lists allow dynamic memory allocation, enabling flexible memory usage.
oh

4. Insertion and Deletion:


M

Elements can be inserted/deleted easily at any position in the list, unlike arrays.

5. Traversal:
by

Traversal is typically sequential, starting from the head node and following links to
subsequent nodes.
e
ad

6. Memory Efficiency:
Each node only requires memory for data and pointers, leading to efficient memory
M

usage.

7. Size Flexibility:
Linked lists can grow or shrink dynamically based on operations.

8. Complexity:
While insertion and deletion are efficient at the beginning/end of the list, middle
operations may require traversal, impacting efficiency compared to arrays for random
access.

Overall, linked lists are versatile data structures suitable for scenarios requiring
dynamic memory allocation, flexible size management, and efficient insertion/deletion
operations.

h
ab
Q2. Explain Operation of singly linked list with algorithm.
A) Operations of Singly Linked List

ur
1. Insertion at Beginning:

Sa
- Create a new node, set it next to the current head, and update the head to the
new node.

2. Insertion at End: d
an
- Create new node, traverse to the end, set the last node's next to the new node.

3. Deletion at Beginning:
it

- Store reference to head, update head to next node, free stored node.
oh

4. Deletion at End:
M

- Traverse to second-to-last node, update its next pointer to NULL, free last node.
by

5. Traversal:
- Start at head, process the current node, move to next until the pointer points to
NULL.
e
ad

Q3. Explain a circular linked list.


A) A circular linked list is a type of linked list where the last node points back to the
M

first node, forming a circle. Traversal continues indefinitely in a loop, and it is


commonly used in applications such as round-robin scheduling and circular buffers.
Operations like insertion and deletion are similar to linear linked lists but require
careful handling to maintain the circular structure.

Q4. What are the advantages of circular linked lists over singly linked lists?
A) The advantages of circular linked lists over singly linked lists include:
- Efficient traversal for continuous looping operations.
- Support for circular operations like round-robin scheduling.
- Constant-time insertions and deletions at the beginning or end.
- Memory efficiency in certain scenarios.
- Avoidance of NULL checks for end of list, simplifying algorithms.
- Natural representation of looping structures or cyclic data patterns.

h
ab
Q5. Write pseudo code add node attending circular linked list.
A)Here is a short pseudo-code example for adding a node to a circular linked list:

ur
Sa
// Define the Node structure
struct Node {
int data;
struct Node* next; d
an
};

// Function to add a node to a circular linked list


it

void addNode(struct Node head, int newData) {


oh

struct Node* newNode = createNode(newData); // Create a new


node
M

if (*head == NULL) {
by

*head = newNode;
newNode->next = newNode; // Make it circular
e

} else {
ad

struct Node* temp = *head;


while (temp->next != *head) {
M

temp = temp->next;
}
temp->next = newNode;
newNode->next = *head; // Make it circular
}
}
```

This concise pseudo-code demonstrates adding a node to a circular linked list. It first
creates a new node with the given data and then adds it to the end of the list,
ensuring the circular structure is maintained. Adjustments can be made as needed
for specific implementations or error handling.

h
ab
Q6. Explain doubly linked list with advantages and disadvantages of it.

ur
A) Doubly Linked List:

Sa
Advantages:
1. Bidirectional Traversal: Allows traversal in both forward and backward directions,
enabling efficient operations like reverse traversal and deletion in both directions.
d
2. Efficient Insertions and Deletions: Insertions and deletions at the beginning, end,
an
or at known positions can be done in O(1) time complexity.
3. Improved Flexibility: Suitable for implementing undo/redo functionality, managing
sorted lists, and reverse operations efficiently.
it
oh

Disadvantages:
1. Higher Memory Overhead: Requires additional memory for storing the previous
M

pointer, leading to increased memory usage per node.


2. Complexity: Requires more complex code for managing both next and previous
by

pointers, increasing implementation complexity.


3. Memory Management: Requires careful handling to avoid memory leaks and
dangling pointers during node manipulations.
e

4. Space and Time Overhead: Extra pointers increase space overhead, and certain
ad

operations may have slightly higher time complexity compared to singly linked lists.
M

In short, doubly linked lists offer bidirectional traversal and efficient


insertions/deletions but come with higher memory overhead and complexity
compared to singly linked lists. Choose based on specific needs like traversal
patterns, insertion/deletion requirements, and memory constraints.
Q7. Write a pseudo code to delete a node from a doubly linked list.
A)Here's a pseudo code example to delete a node from a doubly linked list:

```plaintext
// Node structure for doubly linked list
struct Node {
int data;

h
struct Node* prev;

ab
struct Node* next;
};

ur
// Function to delete a node from a doubly linked list

Sa
void deleteNode(struct Node head, struct Node* delNode) {
// Base case: If list is empty or delNode is NULL, return
if (*head == NULL || delNode == NULL) {
return;
d
an
}
it

// Case 1: If delNode is the head node


oh

if (*head == delNode) {
*head = delNode->next; // Update head to next node
}
M
by

// Adjust pointers of previous and next nodes


if (delNode->prev != NULL) {
delNode->prev->next = delNode->next;
e

}
ad

if (delNode->next != NULL) {
delNode->next->prev = delNode->prev;
M

// Free memory of delNode


free(delNode);
}
```
Explanation:
- The `deleteNode` function takes the address of the head pointer (`head`) and the
node to be deleted (`delNode`).
- It first checks if the list is empty or `delNode` is NULL, in which case it returns.
- If `delNode` is the head node, it updates the head pointer to the next node.
- It adjusts the pointers of the previous and next nodes of `delNode` to maintain the

h
doubly linked list structure.

ab
- Finally, it frees the memory of the deleted node (`delNode`).

ur
This pseudo code demonstrates the basic logic for deleting a node from a doubly
linked list. Adjustments may be needed based on specific requirements or

Sa
optimizations, such as handling edge cases or maintaining list properties.

d
Q8. Explain operation of doubly linked list with algorithm.
an
A)

Q9. Write short notes on multiple linked lists.


it

A)
oh

Q10. Explain application of linked list.


M

A)
by

Q11. Write a short note on polynomial manipulation.


A)
e

Q12. Write a short note on a sparse matrix.


ad

A)
M

Q13. Explain operation of linked stack and linked queue.


A)

Q14. Write an algorithm for push/pop operation on a linked stack.


A)
Q15. What are the merits of linked stack and queues over their sequential
counterparts?
A)

Q 16. How are push and pop operations implemented on a linked stack?
A)

h
Q17. Write Algorithm for insertion/deletion operation on linked queue.

ab
A)

ur
Q18. Write Short note on Dynamic memory management.
A)

Sa
Q19. Explain Application Of Linked Stack and linked queue.
A)
d
an
Q20. Write a pseudo code for implementing stack using linked list.
A)
Q 21. Write a pseudo code for implementing a queue using a linked queue.
it

A
oh
M
by
e
ad
M

You might also like