Prepared By: Uday Shah
Ruparel Education Pvt. Ltd. - (HOD-IT)
Asst. Prof.,
Faculty of Computer Applications,
Nobile University
UNIT 1:
Foundations of Python Programming
Q1. Key Features and Applications of Python
Answer
- Python
is a high-level programming language, which means it is easy for humans to
read and write compared to low-level languages.
- Its
syntax is very simple and similar to English, so beginners can learn it
quickly without confusion.
- Python
is an interpreted language, so code runs line by line without needing
compilation.
- It is
platform independent, meaning the same program can run on Windows, Linux,
or Mac without changes.
- Python
supports multiple programming paradigms like object-oriented, functional,
and procedural programming.
- It
has a large community support, so students can easily find help and
resources online.
- Python
provides many built-in libraries such as NumPy and Pandas, which make
programming faster and easier.
- It is
very useful for beginners and students because of its simple structure and
readability.
- Python
is widely used in Data Science for data analysis and visualization.
- It is
also used in Artificial Intelligence and Machine Learning for building
smart systems.
- Python
is used in Web Development using frameworks like Django and Flask.
- It is
helpful in automation tasks, such as file handling and repetitive work.
- Python
is also used in game development, although less than other languages.
- It
supports database connectivity, so it can store and retrieve data easily.
- Python
allows faster development, as it requires fewer lines of code compared to
other languages.
Answer
- Indentation
means giving space at the beginning of a line, which is very important in
Python.
- Python
uses indentation instead of brackets {} to define blocks of code.
- It
helps the interpreter understand which code belongs to which block.
- Proper
indentation improves code readability for programmers.
- It
makes the program look clean and well-structured.
- Incorrect
indentation will give an IndentationError in Python.
- It is
mainly used in loops and conditional statements.
- For
example, all statements inside if must be indented.
- Comments
are written using the # symbol in Python.
- Comments
are used to explain the logic of the program.
- They
help other programmers understand the code easily.
- Comments
are ignored by the compiler, so they do not affect execution.
- They
are very useful for debugging and maintenance.
- Multi-line
comments can be written using triple quotes ''' '''.
- Writing
comments is considered a good programming practice.
Answer
- int
is used to store whole numbers like 10, 50, or -5 without decimals.
- float
is used to store decimal numbers like 10.5 or 3.14.
- bool
represents logical values, which are either True or False.
- string
is used to store text data, such as names or sentences.
- Integers
are used in calculations where no decimal value is needed.
- Floats
are used when precision and decimal values are required.
- Boolean
values are mostly used in conditions and decision-making.
- Strings
are used in printing messages and storing text information.
- int
consumes less memory compared to float.
- float
provides more accurate results for scientific calculations.
- Boolean
values are often the result of comparison operations.
- Strings
support operations like concatenation and indexing.
- Strings
are immutable, meaning they cannot be changed after creation.
- All
these are built-in data types provided by Python.
- Each
data type is used depending on the type of data required in the program.
Answer
- Type
Conversion is an automatic process where Python converts one data type to
another.
- Type
Casting is a manual process done by the programmer.
- Conversion
happens implicitly without user involvement.
- Casting
happens explicitly using functions like int(), float(), etc.
- Example
of conversion: adding int and float automatically gives float.
- Example
of casting: converting string to int using int("10").
- Conversion
is usually safe and error-free.
- Casting
can sometimes produce errors if data is invalid.
- Conversion
is handled by Python internally.
- Casting
gives more control to the programmer.
- Conversion
happens during expression evaluation.
- Casting
is used when user wants specific data type.
- Common
casting functions are int(), float(), str().
- Conversion
is not always visible to user.
- Both
are important for handling different data types.
Answer
- A
simple if statement checks only one condition.
- if-else
provides two possible outcomes (true or false).
- Nested
if means one if statement inside another if.
- Nested
conditions are used when multiple conditions need checking.
- Simple
if is easier to understand for beginners.
- Nested
if can become complex if not written properly.
- Nested
conditions allow detailed decision making.
- Example:
checking grades (A, B, C) based on marks.
- Simple
if requires less code.
- Nested
if increases code length and complexity.
- Proper
indentation is very important in nested conditions.
- Logical
thinking is required to write nested conditions correctly.
- Used
in real-world applications like login systems.
- Helps
in solving complex problems step by step.
- Both
are important for controlling program flow.
Q6. List and Tuple
Answer
- A
list is a collection of multiple values stored in one variable.
- A
tuple is also a collection but with some restrictions.
- Lists
are created using square brackets [].
- Tuples
are created using parentheses ().
- Lists
are mutable, meaning values can be changed.
- Tuples
are immutable, meaning values cannot be changed.
- Lists
allow adding and removing elements.
- Tuples
do not allow modification after creation.
- Lists
are slightly slower than tuples.
- Tuples
are faster because they are fixed.
- Lists
support many functions like append(), remove().
- Tuples
have limited functions.
- Lists
are used when data changes frequently.
- Tuples
are used for fixed data like coordinates.
- Both
are important for storing grouped data.
Answer
- A
dictionary stores data in key-value pairs.
- It is
created using curly braces {}.
- Each
key must be unique in a dictionary.
- Values
can be duplicated.
- Example:
{"name":"Uday", "age":20}.
- A set
stores unique values only.
- Sets
are also created using {}.
- Duplicate
values are automatically removed in sets.
- Sets
are unordered, so indexing is not possible.
- Dictionaries
are ordered (in latest Python versions).
- Dictionary
values are accessed using keys.
- Sets
are useful for mathematical operations like union.
- Dictionaries
are useful for mapping data.
- Sets
improve performance for uniqueness checking.
- Both
are important data structures in Python.
Answer
- The
pass statement is used when no action is required.
- It
acts as a placeholder in the code.
- It
prevents syntax errors when a block is empty.
- It is
commonly used in loops and conditions.
- It
can be used inside functions and classes.
- It
does not produce any output.
- It
does not affect program execution.
- Useful
during program development stage.
- Helps
in writing code step by step.
- It
improves code structure.
- It
indicates that code will be added later.
- It is
better than leaving block empty.
- It
avoids compilation errors.
- It is
a temporary statement.
Answer
- The
break statement is used to stop the loop completely.
- The
continue statement is used to skip the current iteration.
- When
break is executed, control comes out of loop.
- Continue
moves control to the next iteration.
- Break
is useful when a condition is satisfied.
- Continue
is useful for skipping unwanted values.
- Break
reduces number of loop executions.
- Continue
does not stop loop, it continues running.
- Break
is used in infinite loops to exit.
- Continue
is used in filtering data.
- Both
are used in loops like for and while.
- Break
improves efficiency.
- Continue
improves flexibility.
- They
help in better control of loops.
- Both
are important for logical programming.
Answer
- A
for loop is used when the number of iterations is known.
- A
while loop is used when the condition decides execution.
- For
loop uses range() function.
- While
loop depends on condition being true.
- For
loop is easy to use and understand.
- While
loop gives more control over execution.
- For
loop automatically ends after iterations.
- While
loop may run forever if condition is wrong.
- For
loop is commonly used with lists and arrays.
- While
loop is used in logical problems.
- For
loop syntax is simple.
- While
loop requires manual control (increment/decrement).
- Both
loops are used for repetition.
- Both
reduce code length.
- Both
are important for programming logic.
UNIT 2:
Introduction to Algorithms & Python Data Handling
Q1. What is Data Structure? Explain its Classification
Answer
- A
data structure is a way to store and organize data in a computer, so it
can be used efficiently.
- It
helps in performing operations like insertion, deletion, and searching
easily.
- Data
structures improve the performance of programs by managing data properly.
- They
are mainly divided into two types: Linear and Non-linear.
- Linear
data structures store data in a sequential manner.
- Examples
of linear structures are array, list, stack, and queue.
- Non-linear
data structures store data in a hierarchical or network form.
- Examples
include tree and graph.
- Another
classification is primitive and non-primitive data structures.
- Primitive
data structures include int, float, char, and boolean.
- Non-primitive
data structures include arrays, linked lists, trees, and graphs.
- Data
structures are used in real-life applications like databases and operating
systems.
- Choosing
the correct data structure improves efficiency and speed.
- They
help in better memory utilization.
- Data
structures are a basic concept in computer science and programming.
Answer
- A
user-defined function is a function created by the programmer to perform a
specific task.
- It
helps in reducing code repetition by reusing the same block of code.
- Functions
make programs more organized and readable.
- In
Python, functions are defined using the def keyword.
- Syntax
starts with def function_name():.
- Code
inside the function must be properly indented.
- Functions
can take parameters (inputs) from the user.
- They
can also return values using the return statement.
- Example:
def add(a, b): return a+b.
- Functions
can be called by using their name with arguments.
- They
help in modular programming, dividing large programs into small parts.
- Functions
improve debugging and maintenance.
- They
allow code reuse in different parts of program.
- Python
supports both built-in and user-defined functions.
- User-defined
functions are important for writing clean and efficient programs.
Answer
- A
module is a file that contains Python code like functions and variables.
- A
custom module is a module created by the user.
- It
helps in organizing code into separate files.
- Modules
improve code reuse and maintainability.
- To
create a module, save code in a .py file.
- Example:
create file maths.py with functions.
- Use
import maths to use the module.
- Functions
inside module can be called using module name.
- Example:
maths.add(2,3)
- Modules
reduce code duplication.
- They
make large programs easy to manage.
- Python
provides many built-in modules like math and random.
- Custom
modules are useful for team projects.
- They
help in separating logic into different parts.
- Modules
support structured programming approach.
Answer
- Python
lists are dynamic, meaning their size can change at runtime.
- You
can add elements using methods like append().
- You
can also remove elements using remove() or pop().
- Lists
do not require fixed size during declaration.
- They
can store different types of data (int, string, etc.).
- Lists
automatically increase or decrease memory when needed.
- This
makes lists very flexible compared to arrays.
- Lists
allow insertion at any position.
- They
support many built-in functions.
- Lists
can be modified anytime (mutable).
- Dynamic
nature reduces memory wastage.
- Lists
are widely used in real applications.
- They
allow easy data manipulation.
- Useful
in handling unknown size data.
- Makes
Python programming simple and powerful.
Answer
- Python
array is available using array module.
- Lists
are built-in data structures.
- Arrays
store same type of elements only.
- Lists
can store different data types.
- Arrays
are more memory efficient.
- Lists
are more flexible.
- Arrays
require importing module.
- Lists
do not need any import.
- Arrays
are faster for numerical operations.
- Lists
are easier to use.
- Arrays
are used in scientific applications.
- Lists
are used in general programming.
- Syntax
of arrays is more complex.
- Lists
support more built-in methods.
- Lists
are more commonly used than arrays.
Answer
- Data
refers to raw facts and figures.
- It
is unprocessed and has no meaning by itself.
- Example:
numbers like 10, 20, 30 are data.
- Information
is processed and meaningful data.
- It
is useful for decision making.
- Example:
average marks of students is information.
- Data
is input for processing.
- Information
is output after processing.
- Data
can be collected from various sources.
- Information
helps in understanding patterns.
- Data
alone is not useful without processing.
- Information
provides value and meaning.
- Computers
process data into information.
- Both
are important in computing.
- Information
is always more useful than raw data.
Answer
- Primitive
data structures are basic data types.
- Examples
include int, float, char, boolean.
- They
store single value only.
- They
are directly supported by programming language.
- Non-primitive
data structures are complex data types.
- Examples
include array, list, tree, graph.
- They
store multiple values.
- They
are derived from primitive types.
- Primitive
types are simple and fast.
- Non-primitive
types are flexible and powerful.
- Primitive
data is stored in fixed size memory.
- Non-primitive
data can be dynamic.
- Primitive
types are used for basic operations.
- Non-primitive
types are used for complex problems.
- Both
are essential in programming.
Q8. Static vs Dynamic Memory Allocation
Answer
- Static
memory allocation is done at compile time.
- Dynamic
memory allocation is done at runtime.
- Static
memory size is fixed.
- Dynamic
memory size can be changed.
- Static
allocation is faster.
- Dynamic
allocation is flexible.
- Static
memory cannot be resized.
- Dynamic
memory can grow or shrink.
- Static
memory may waste space.
- Dynamic
memory uses memory efficiently.
- Static
allocation is simple.
- Dynamic
allocation is complex.
- Example:
array (static), list (dynamic).
- Dynamic
memory is used in modern applications.
- Both
methods are important in programming.
Q9. Asymptotic Notation
Answer
- Asymptotic
notation is used to measure algorithm performance.
- It
shows how time or space grows with input size.
- It
helps compare different algorithms.
- Big-O
notation shows worst-case complexity.
- Example:
O(n), O(n²), O(log n).
- It
ignores constants and focuses on growth rate.
- Helps
in selecting efficient algorithms.
- Used
in computer science for analysis.
- Big-O
is most commonly used notation.
- Omega
shows best case.
- Theta
shows average case.
- Important
for large input data.
- Helps
optimize programs.
- Improves
performance understanding.
- Essential
concept in data structures.
Q10. Input and Output (input() and print())
Answer
- input()
is used to take input from user.
- It
always returns value as string.
- You
can convert input using int(), float().
- Example:
x = input("Enter number").
- print()
is used to display output.
- It
prints data on screen.
- Example:
print("Hello").
- It
supports multiple values.
- You
can format output using f-strings.
- Input
is used for user interaction.
- Output
is used to show results.
- Both
are basic functions in Python.
- Used
in almost every program.
- Helps
in communication between user and program.
- Essential
for learning programming.
Q11. Analysis of
Algorithm
Answer
- Analysis
of algorithm means evaluating efficiency of an algorithm.
- It
helps to know how much time and space is required.
- Two
types: time complexity and space complexity.
- Time
complexity measures execution time.
- Space
complexity measures memory usage.
- Helps
in comparing algorithms.
- Important
for large data handling.
- Uses
asymptotic notation.
- Example:
O(n), O(log n).
- Best
case, worst case, average case analysis.
- Helps
in optimization.
- Improves
program performance.
- Used
in real-world applications.
- Important
for interviews and exams.
- Essential
topic in data structures.
UNIT 3: Stack,
Queue & Linked List
Q1. Define Stack and Explain with Algorithm
Answer
- A
stack is a linear data structure that follows LIFO (Last In First Out)
principle.
- This
means the last element inserted is the first one to be removed.
- The
main operations of stack are push (insert) and pop (delete).
- Another
operation is peek, which shows the top element without removing it.
- Stack
uses a pointer called TOP to track the last inserted element.
- When
stack is full, it is called overflow condition.
- When
stack is empty, it is called underflow condition.
- Stack
can be implemented using array or linked list.
- Push
operation adds an element at the top.
- Pop
operation removes the top element.
- Algorithm
for PUSH: check overflow → increment TOP → insert element.
- Algorithm
for POP: check underflow → return element → decrement TOP.
- Stack
is used in expression evaluation and recursion.
- It
is easy to implement and understand.
- Stack
is widely used in programming and system design.
Q2. Stack Applications (Explain any three)
Answer
- Stack
is used in expression evaluation, such as postfix and prefix expressions.
- It
helps in checking balanced parentheses in expressions like ( ).
- Stack
is used in function calls and recursion, where each call is stored.
- It
is used in undo and redo operations in applications like text editors.
- Stack
is used in backtracking algorithms like maze solving.
- It
is helpful in syntax parsing in compilers.
- Used
in depth-first search (DFS) algorithm.
- Helps
in reversing data like strings.
- Used
in browser history navigation.
- Supports
memory management in programs.
- Used
in arithmetic expression conversion.
- Helps
in managing temporary data.
- Efficient
for last inserted element processing.
- Widely
used in software development.
- Important
for understanding recursion.
Q3. Stack in Recursion
Answer
- Recursion
is a process where a function calls itself repeatedly.
- Stack
is used internally to manage these function calls.
- Each
function call is stored as a stack frame.
- The
stack stores local variables and return address.
- When
a function is called, it is pushed onto the stack.
- When
a function completes, it is popped from the stack.
- This
follows LIFO principle.
- Recursive
calls create multiple stack entries.
- When
base condition is reached, stack starts unwinding.
- If
too many calls occur, it may cause stack overflow.
- Example:
factorial function uses recursion.
- Stack
helps maintain correct execution order.
- It
manages memory during recursion.
- Without
stack, recursion is not possible.
- Stack
is essential for recursive problem solving.
Q4. Prefix and Postfix Conversion
Answer
- Prefix
notation places operator before operands.
- Example:
+AB means A + B.
- Postfix
notation places operator after operands.
- Example:
AB+ means A + B.
- Infix
notation is the normal form (A + B).
- Conversion
is done using stack.
- Operators
have precedence like +, *, ^.
- Stack
stores operators temporarily.
- Parentheses
are handled carefully.
- Higher
precedence operators processed first.
- Prefix
and postfix avoid ambiguity.
- Used
in compilers and calculators.
- Postfix
is easier for evaluation.
- No
need for parentheses in postfix.
- Conversion
improves expression processing.
Q5. What is Queue? Difference from Stack
Answer
- A
queue is a linear data structure that follows FIFO (First In First Out).
- The
first element inserted is the first one to be removed.
- Queue
operations are enqueue (insert) and dequeue (delete).
- Stack
follows LIFO, queue follows FIFO.
- In
queue, insertion happens at rear.
- Deletion
happens from front.
- Queue
uses two pointers: front and rear.
- Stack
uses only one pointer (TOP).
- Queue
is used in scheduling tasks.
- Stack
is used in recursion.
- Queue
maintains order of arrival.
- Stack
reverses order of elements.
- Queue
is used in printers and buffers.
- Both
are linear data structures.
- Both
are important in programming.
Q6. Queue Implementation Algorithm
Answer
- Queue
uses FIFO principle.
- Two
pointers are used: front and rear.
- Initially,
both are set to -1.
- Enqueue
means inserting element at rear.
- Dequeue
means removing element from front.
- Before
inserting, check for overflow.
- Before
deleting, check for underflow.
- Enqueue
algorithm: increment rear → insert element.
- Dequeue
algorithm: return front element → increment front.
- If
queue is empty, front = rear = -1.
- Queue
can be implemented using array.
- Also
implemented using linked list.
- Efficient
for scheduling tasks.
- Maintains
proper order of data.
- Used
in real-time systems.
Q7. Circular Queue
Answer
- Circular
queue connects last position to first.
- It
solves problem of unused space in normal queue.
- Rear
moves in circular manner.
- When
rear reaches end, it goes to beginning.
- Uses
modulo operation for circular movement.
- Efficient
use of memory.
- Prevents
wastage of space.
- Overflow
occurs when queue is full.
- Underflow
occurs when queue is empty.
- Operations
are enqueue and dequeue.
- Used
in CPU scheduling.
- Also
used in buffering systems.
- Improves
performance over linear queue.
- Requires
careful pointer management.
- Important
concept in data structures.
Q8. Linked List and Types
Answer
- A
linked list is a collection of nodes connected by links.
- Each
node contains data and a pointer.
- It
does not require continuous memory.
- It
is a dynamic data structure.
- Easy
insertion and deletion.
- Types
of linked list include singly linked list.
- Doubly
linked list has two pointers.
- Circular
linked list connects last node to first.
- Linked
list is flexible.
- Used
in memory management.
- Efficient
for large data.
- No
fixed size required.
- Access
is sequential, not direct.
- More
memory required than array.
- Important
in dynamic applications.
Q9. Program for Singly Linked List
Answer
- Singly
linked list contains nodes with one pointer.
- Each
node points to next node.
- First
node is called head.
- Last
node points to NULL.
- Nodes
are created dynamically.
- Insertion
can be at beginning, middle, or end.
- Deletion
removes node from list.
- Traversal
means visiting all nodes.
- Example
in Python uses class Node.
- Each
node has data and next field.
- Linked
list grows dynamically.
- No
memory wastage.
- Useful
for dynamic data.
- Easy
insertion compared to array.
- Important
for data structure understanding.
Q10. Program to
Implement Stack
Answer
- Stack
can be implemented using list in Python.
- Use
append() for push operation.
- Use
pop() for pop operation.
- Stack
follows LIFO principle.
- Top
element is last element of list.
- Check
if stack is empty before pop.
- Use
len() to check size.
- Stack
operations are simple.
- Efficient
for small applications.
- Python
list acts as stack.
- No
need for separate implementation.
- Used
in expression evaluation.
- Easy
to implement.
- Useful
in real-world problems.
- Helps
understand stack concept.
Q11. Insert Node at Specific Position in Linked List
Answer
- First
create a new node.
- Assign
data to the node.
- Traverse
list to desired position.
- Keep
track of previous node.
- Adjust
pointers carefully.
- New
node points to next node.
- Previous
node points to new node.
- If
inserting at beginning, update head.
- If
inserting at end, set next to NULL.
- Check
for invalid position.
- Maintain
list structure.
- Avoid
losing existing nodes.
- Operation
takes O(n) time.
- Important
for dynamic data handling.
- Used
in real applications like memory management.
UNIT 4: Sorting,
Searching & Hashing
Q1. Bubble Sort Algorithm (Step-by-Step)
Answer
- Bubble
Sort is a simple sorting algorithm used to arrange elements in ascending
or descending order.
- It
works by repeatedly comparing adjacent elements in the list.
- If
two elements are in the wrong order, they are swapped.
- After
each pass, the largest element moves to the end of the list.
- This
process is repeated until the list is completely sorted.
- Number
of passes required is n-1 for n elements.
- It
is called “bubble” sort because elements bubble up to their correct
position.
- It
is easy to understand and implement.
- Algorithm
Step 1: Start from the first element.
- Step
2: Compare it with the next element.
- Step
3: Swap if needed.
- Step
4: Continue till the end of list.
- Step
5: Repeat passes until no swaps occur.
- Time
complexity is O(n²) in worst case.
- It
is not efficient for large datasets but useful for learning.
Answer
- Quick
Sort is a divide and conquer algorithm used for fast sorting.
- It
selects a pivot element from the list.
- All
elements smaller than pivot go to the left side.
- All
elements greater than pivot go to the right side.
- This
process is called partitioning.
- Then
Quick Sort is applied recursively on both sides.
- It
continues until the list is fully sorted.
- Example
list: [100,25,35,85,75,95,12,52,1,3]
- Choose
pivot (e.g., first or last element).
- Divide
list into smaller and larger elements.
- Recursively
apply same process.
- Combine
sorted sublists.
- Quick
sort is faster than bubble sort.
- Average
time complexity is O(n log n).
- It
is widely used in real-world applications.
Answer
- Selection
sort is a simple sorting technique.
- It
works by selecting the smallest element from the list.
- The
smallest element is placed at the correct position.
- This
process is repeated for all elements.
- First
pass: smallest element goes to first position.
- Second
pass: second smallest goes to second position.
- It
does not require swapping many times.
- It
performs fewer swaps compared to bubble sort.
- Algorithm
Step 1: Find minimum element.
- Step
2: Swap with first position.
- Step
3: Repeat for remaining elements.
- Time
complexity is O(n²).
- It is
easy to understand.
- Not
efficient for large datasets.
- Useful
for small lists.
Q4. Binary Search Program
Answer
- Binary
search is used to find an element in a sorted list.
- It
works by dividing the list into two halves.
- First,
find the middle element.
- Compare
middle element with target value.
- If
equal, element is found.
- If
target is smaller, search left half.
- If
target is larger, search right half.
- Repeat
process until element is found.
- It
reduces search space quickly.
- Requires
sorted data.
- Much
faster than linear search.
- Time
complexity is O(log n).
- Uses
low and high pointers.
- Efficient
for large datasets.
- Commonly
used in searching problems.
Answer
- Hashing
is a technique to store and retrieve data quickly.
- It
uses a function called hash function.
- Hash
function converts key into an index.
- Data
is stored at calculated index.
- It
provides fast access to data.
- Used
in hash tables.
- A
good hash function should be fast to compute.
- It
should distribute keys uniformly.
- It
should minimize collisions.
- It
should be deterministic (same input → same output).
- Should
use all parts of key.
- Avoid
clustering of values.
- Improve
search efficiency.
- Used
in databases and caching.
- Important
for fast data access.
Answer
- Collision
occurs when two keys map to same index.
- It
is a common problem in hashing.
- Happens
due to limited size of hash table.
- Different
keys may produce same hash value.
- Collisions
reduce efficiency.
- Needs
proper handling.
- Cannot
be completely avoided.
- Must
be minimized using good hash function.
- Example:
keys 10 and 20 giving same index.
- Causes
overwriting if not handled.
- Leads
to incorrect data retrieval.
- Increases
search time.
- Requires
resolution techniques.
- Important
concept in hashing.
- Must
be managed carefully.
Answer
- Collision
resolution is used to handle collisions in hashing.
- One
method is chaining.
- In
chaining, each index stores a linked list.
- Multiple
elements can be stored at same index.
- Another
method is open addressing.
- In
open addressing, find next empty slot.
- Linear
probing checks next index sequentially.
- Quadratic
probing uses square increments.
- Double
hashing uses another hash function.
- Helps
maintain efficiency.
- Prevents
data loss.
- Ensures
correct retrieval.
- Improves
performance.
- Required
in hash table design.
- Important
for real applications.
Answer
- Merge
sort is a divide and conquer algorithm.
- It
divides list into smaller parts.
- Each
part is sorted individually.
- Then
parts are merged together.
- Example:
[38,27,43,3,9,82,10]
- Divide
into two halves repeatedly.
- Continue
until single elements remain.
- Merge
sorted elements step by step.
- Maintain
order while merging.
- Produces
sorted list at end.
- Time
complexity is O(n log n).
- Stable
sorting algorithm.
- Requires
extra memory.
- Efficient
for large data.
- Widely
used in applications.
Answer
- Linear
search checks elements one by one.
- It
starts from first element.
- Compares
each element with target.
- Stops
when element is found.
- If
not found, returns failure.
- Works
on unsorted data.
- Easy
to implement.
- No
special requirement.
- Time
complexity is O(n).
- Not
efficient for large data.
- Suitable
for small lists.
- Used
in simple programs.
- Sequential
process.
- No
extra memory needed.
- Basic
searching technique.
Answer
- Given
list: [100,25,35,85,75,95,12,52,1,3]
- Compare
first two elements and swap if needed.
- Largest
element moves to end in first pass.
- Continue
comparing adjacent elements.
- After
first pass, largest element is fixed.
- Second
pass sorts next largest.
- Continue
passes until sorted.
- Total
passes = n-1.
- Each
pass reduces unsorted part.
- Repeated
swapping occurs.
- Easy
but slow method.
- Time
complexity is O(n²).
- Good
for understanding sorting.
- Not
suitable for large data.
- Demonstrates
working of algorithm clearly.
Answer
- Merge
sort divides list into halves.
- Uses
recursive approach.
- Each
half is sorted separately.
- Then
merged in sorted order.
- Combines
smaller lists into bigger list.
- Maintains
order while merging.
- Uses
extra memory.
- Time
complexity is O(n log n).
- Efficient
for large datasets.
- Stable
sorting algorithm.
- Works
well for linked lists.
- Suitable
for external sorting.
- Better
than bubble sort.
- Requires
divide and conquer strategy.
- Important
sorting algorithm.
UNIT 5: Nonlinear
Data Structures – Trees & Graphs
Q1. Tree Terminologies (Root, Parent, Child, Leaf,
Sibling)
Answer
- A tree
is a hierarchical data structure where data is arranged like a tree shape.
- The
topmost node of a tree is called the root node.
- Root
is the starting point of the tree.
- A parent
node is a node that has one or more child nodes.
- A child
node is a node that comes under another node.
- A node
can have multiple children depending on the tree type.
- A leaf
node is a node that has no children.
- Leaf
nodes are always present at the bottom of the tree.
- Sibling
nodes are nodes that share the same parent.
- Example:
children of same parent are siblings.
- Each
node may have a link to its children.
- Tree
structure represents real-life hierarchy like family tree.
- These
terms help understand tree structure clearly.
- Used
in file systems and databases.
- Important
for understanding advanced data structures.
Q2. Binary Tree and Its Types
Answer
- A
binary tree is a tree where each node has maximum two children.
- These
children are called left child and right child.
- Binary
tree is widely used in computer science.
- One
type is full binary tree, where each node has 0 or 2 children.
- Another
type is complete binary tree, where all levels are filled except last.
- In
complete tree, nodes are filled from left to right.
- Perfect
binary tree has all levels completely filled.
- Balanced
binary tree maintains minimum height.
- Balanced
tree improves search performance.
- Binary
trees are used in searching and sorting.
- Example:
Binary Search Tree (BST).
- Helps
in efficient data storage.
- Easy
to traverse using different methods.
- Important
in expression trees.
- Used
in many real-world applications.
Q3. BST Insertion and Deletion
Answer
- A
Binary Search Tree (BST) follows rule: left < root < right.
- During
insertion, compare value with root.
- If
smaller, go to left subtree.
- If
larger, go to right subtree.
- Repeat
until correct position is found.
- Insert
new node at leaf position.
- Example:
inserting 50, 30, 70 creates BST structure.
- Deletion
has three cases.
- Case
1: deleting leaf node (simple removal).
- Case
2: node with one child (replace node with child).
- Case
3: node with two children (replace with inorder successor).
- Inorder
successor is smallest node in right subtree.
- After
deletion, tree must maintain BST property.
- BST
allows efficient searching.
- Important
for database indexing.
Q4. Tree Traversals (Inorder, Preorder, Postorder)
Answer
- Tree
traversal means visiting all nodes in a specific order.
- Inorder
traversal follows Left → Root → Right.
- It
gives sorted output in BST.
- Preorder
traversal follows Root → Left → Right.
- Used
to create copy of tree.
- Postorder
traversal follows Left → Right → Root.
- Used
in deleting tree.
- Traversals
can be done using recursion.
- Each
traversal has its own use.
- Inorder
is most commonly used.
- Preorder
is useful in expression trees.
- Postorder
is useful in evaluation.
- Traversal
helps in accessing all nodes.
- Important
for tree operations.
- Basic
concept in tree data structure.
Q5. Graph Traversal Technique
Answer
- Graph
traversal means visiting all vertices of a graph.
- It is
used to explore all nodes.
- Two
main techniques are DFS and BFS.
- Traversal
ensures all nodes are visited once.
- It
uses data structures like stack or queue.
- Helps
in searching and path finding.
- Used
in networking and maps.
- Avoids
visiting same node again.
- Uses
visited array or list.
- Works
for both directed and undirected graphs.
- Important
for algorithm design.
- Helps
solve real-world problems.
- Efficient
for large graphs.
- Used
in AI and game development.
- Basic
concept in graph theory.
Q6. Adjacency Matrix vs Adjacency List
Answer
- Adjacency
matrix uses a 2D array to represent graph.
- Rows
and columns represent vertices.
- Value
1 means edge exists, 0 means no edge.
- Easy
to implement.
- Requires
more memory.
- Adjacency
list uses list of nodes.
- Each
vertex stores list of connected nodes.
- Uses
less memory than matrix.
- Efficient
for sparse graphs.
- Matrix
is good for dense graphs.
- List
is flexible and dynamic.
- Matrix
is faster for edge checking.
- List
is better for traversal.
- Both
represent graph differently.
- Choice
depends on application.
Q7. Depth First Search (DFS)
Answer
- DFS is
a graph traversal technique.
- It
explores as far as possible before backtracking.
- Uses stack
or recursion.
- Start
from a node and go deep.
- Visit
one node at a time.
- Mark
visited nodes.
- Avoid
revisiting nodes.
- Backtrack
when no more nodes available.
- Works
for all graph types.
- Used
in maze solving.
- Used
in cycle detection.
- Time
complexity is O(V+E).
- Efficient
for deep search.
- Easy
to implement recursively.
- Important
graph algorithm.
Q8. Deletion in Binary Search Tree
Answer
- Deletion
in BST must maintain BST property.
- First
find the node to delete.
- Case
1: node is a leaf → simply remove it.
- Case
2: node has one child → replace with child.
- Case
3: node has two children.
- Find
inorder successor or predecessor.
- Replace
node with successor value.
- Delete
successor node.
- Maintain
tree structure.
- Use
recursion for implementation.
- Ensure
tree remains balanced if possible.
- Important
for dynamic data.
- Efficient
operation.
- Used in databases.
- Important for tree operations.