0% found this document useful (0 votes)
9 views19 pages

Recursion: Q.1 Explain With Example Three Different Types o

The document explains various concepts in computer science, including types of recursion (direct, indirect, and tail recursion), basic stack operations, searching techniques with their time complexities, and comparisons between different queue types. It also covers polynomial addition using linked lists, operations of double-ended queues, and dynamic data structures like circular linked lists. Additionally, it discusses Fibonacci search algorithm and its efficiency in searching sorted arrays.

Uploaded by

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

Recursion: Q.1 Explain With Example Three Different Types o

The document explains various concepts in computer science, including types of recursion (direct, indirect, and tail recursion), basic stack operations, searching techniques with their time complexities, and comparisons between different queue types. It also covers polynomial addition using linked lists, operations of double-ended queues, and dynamic data structures like circular linked lists. Additionally, it discusses Fibonacci search algorithm and its efficiency in searching sorted arrays.

Uploaded by

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

Q.

1 Explain with example three different types of


recursion.
Recursion is a programming technique where a function calls itself to
solve a problem. There are several types of recursion, but three
common types are:

1. Direct Recursion: In direct recursion, a function calls itself directly.


This is the most straightforward form of recursion .
Example: Calculating the factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
this example, the factorial function calls itself with a decremented argument (n-
1) until the base case n == 0 is reached, demonstrating direct recursion

 2. Indirect Recurs
: Definition: Function A calls function B, and function B eventually calls
function A, creating a circular call chain.
def even(n):
if n == 0:
return True
else:
return odd(n - 1)
def odd(n):
if n == 0:
return False
else:
return even(n - 1)
Here, even calls odd, and odd calls even, illustrating indirectrecursion.
Base Cases: Both even and odd need base cases (n=0) to terminate the
recursion.
Tail Recursion:
Tail recursion is a specific form of recursion where the
recursive call is the last operation in the function. This allows some
programming languages to optimize the recursion and avoid increasing
the call stack.
def tail_recursive_factorial(n, accumulator=1):
if n == 0:
return accumulator
else:
return tail_recursive_factorial(n - 1, n *
accumulator)

# Usage print(tail_recursive_factorial(5)) # Output: 120


In this example, the tail_recursive_factorial function uses an accumulator to
carry the result, and the recursive call is the last operation performed, making it
tail-recursive.
.
Q.2 Write a pseudo code for basic operation of stack.
CLASS Stack
INITIALIZE
items = EMPTY LIST

FUNCTION is_empty()
RETURN LENGTH(items) == 0

FUNCTION push(item)
APPEND item TO items

FUNCTION pop()
IF is_empty() THEN
THROW "Stack underflow: Attempt to pop from an empty stack."
ENDIF
RETURN LAST ITEM OF items
REMOVE LAST ITEM FROM items

FUNCTION peek()
IF is_empty() THEN
THROW "Stack underflow: Attempt to peek at an empty stack."
ENDIF
RETURN LAST ITEM OF items

FUNCTION size()
RETURN LENGTH(items)

END CLASS
Q.3 Explain in brief the different searching techniques. What is
the time complexity of each of them?
Searching techniques are algorithms used to find specific data within a data
structure. Here are
some common searching techniques along with their time complexities:
1. **Linear Search**: **Description**: This technique checks each element
in the list sequentially until the desired element is found or the list ends.
- **Time Complexity**:
- Worst-case: O(n)
- Best-case: O(1)

2. **Binary Search** : This technique is used on sorted arrays. It


repeatedly divides the search interval in half. If the value of the search key is less
than the item in the middle of the interval, it narrows the interval to the lower
half. Otherwise, it narrows it to the upper half.
- **Time Complexity**:
- Worst-case: O(log n)
- Best-case: O(1)

3. **Jump Search**:
- **Description**: This technique works on sorted arrays. It divides the array
into blocks of a fixed size (jump size) and checks the last element of each block.
If the target is greater than the last element of a block, it jumps to the next blo
**Time comlexity - Worst-case: $O(\sqrt{n} - Best-case:
$O(1)
4. **Exponential Search**:
- **Description**: This technique is useful for unbounded or infinite lists. It finds
the range where the target may exist by repeatedly doubling the index until the
target is less than the current element, and then it performs a binary search
within that range.
- **Time Complexity**: Worst-case: $O(\log n)$ - Best-case: O(1)
5. **Interpolation Search**:
- **Description**: This technique is an improvement over binary search for
uniformly distributed sorted arrays. It estimates the position of the target based
on the value of the target relative to the values at the ends of the array segment.
- **Time Complexity**: - Worst-case: O(n)) - Best-case: O(\log \
log n)
6. **Ternary Search**:
- **Description**: This technique is similar to binary search but divides the
array into three parts instead of two. It checks two midpoints and narrows down
the search to one of the three segments
- **Time Complexity**: - Worst-case: O(\log_3 n) - Best-case: O(1)

Q.4 Write pseudo-C/C++ code to implement stack using


array with overflow and underflow conditions.
#define MAX 100
int stack[MAX];
int top = -1;
// Push operation
void push(int x) {
if (top == MAX - 1) {
cout << "Stack Overflow\n";
return; }
stack[++top] = x;
}
int pop() { // Pop operation
if (top == -1) {
cout << "Stack Underflow\n";
return -1; }
return stack[top--];
}
Q.21) Write a short note on sentinel search & Index sequential search
with suitable example Sentinel Search
Definition: A modified linear search that uses a sentinel (target value) at the end
of the array to avoid boundary checks.
 Advantage: Faster than standard linear search due to fewer comparisons.
 Example:
Array: [10, 30, 50, 20, 60], Key = 20
Place 20 as sentinel at end → [10, 30, 50, 20, 60, 20]
Search without checking array bounds.

Index Sequential Search


 Definition: Combines binary and linear search by first searching an
index table, then linearly searching a data block.
 Advantage: Faster than linear search on large sorted data.
 Example:
Index: [30 → 0, 60 → 3, 80 → 6]
To find 45, locate block via index, then do linear search in block [30,
40, 50].

Q.5 a) Write short note on : [8]


i) Comparison of Circular Queue with Linear queue
ii) Priority Queue Linear Queue:
linear queue
Structure: A linear queue follows a First-In, First-Out (FIFO) approach, with
elements added to the rear and removed from the front.
 Space Utilization: After elements are dequeued, the space they
occupied becomes unusable, leading to potential space wastage.
 Real-world Example: A printer queue, where jobs are processed in the
order they arrive.
 Time Complexity: Enqueue and dequeue operations are typically O(1),
but shifting elements might be required after dequeueing, potentially
impacting performance.
 Pros: Simple to implement and understand.
 Cons: Inefficient space utilization, can lead to wasted space if elements
are dequeued.
Circular Queue:
 Structure: The last element of the queue is connected to the first
element, creating a circular arrangement.
 Space Utilization: The rear pointer can wrap around to the front, reusing
previously occupied space.
 Real-world Example: CPU scheduling, where processes are managed in
a circular fashion.
 Time Complexity: Enqueue and dequeue operations are typically O(1).
 Pros: More efficient space utilization, eliminates wasted space, and allows
for continuous cyclic processing of data.

Priority Queue:
 Structure: Elements are arranged based on their priority, with higher
priority elements having precedence over lower priority elements.
 Dequeue Operation:
Elements are dequeued based on their priority, not the order they were
enqueued.
 Implementation:
Can be implemented using various data structures, such as binary heaps or
Fibonacci heaps.
 Real-world Example: Task scheduling in operating systems, where
tasks with higher priority are executed first.
Time Complexity: O(log n)

Q.6Write Pseudo C++ code for addition of two


polynomials using singly linked list.
Node* addPolynomials(Node* poly1, Node* poly2) {
Node* result = nullptr;
Node** lastPtrRef = &result;
while (poly1 || poly2) {
int coeff = 0, exp = 0;
if (poly1 && (! poly2 || poly1->exponent > poly2->exponent)) {
coeff = poly1->coefficient;
exp = poly1->exponent;
poly1 = poly1->next;
} else if (poly2 && (!poly1 || poly2->exponent > poly1->exponent)) {
coeff = poly2->coefficient;
exp = poly2->exponent;
poly2 = poly2->next;
} else {
coeff = poly1->coefficient + poly2->coefficient;
exp = poly1->exponent;
poly1 = poly1->next;
poly2 = poly2->next;
}
if (coeff != 0) {
*lastPtrRef = new Node(coeff, exp);
lastPtrRef = &((*lastPtrRef)->next);
}
}
return result;
}
Q.7) Explain with example primitive operations of
Double ended Queue
A Doubly Ended Queue (Deque) allows insertion and
deletion of elements from both the front and rear ends. Here
are the primitive operations associated with a deque, along
with examples
1. Insert Front (addFront):
 Adds an element to the front.
 Example:
 Initial: | 2 | 3 | 4 |
 After addFront(1): | 1 | 2 | 3 | 4 |
2. Insert Rear (addRear):
 Adds an element to the rear.
 Example:
 Initial: | 1 | 2 | 3 |
 After addRear(4): | 1 | 2 | 3 | 4 |
3. Delete Front (removeFront):
 Removes and returns the front element.
 Example:
 Initial: | 1 | 2 | 3 | 4 |
 After removeFront(): | 2 | 3 | 4 | (returns 1)
4. Delete Rear (removeRear):
 Removes and returns the rear element.
 Initial: | 2 | 3 | 4 |
 After removeRear(): | 2 | 3 | (returns 4)
5. Get Front (getFront):
 Returns the front element without removing it.
 Example:
 Initial: | 2 | 3 |
 After getFront(): returns 2
6. isEmpty:
 Checks if the deque is empty.
 Example:
 Initial: | | (empty)
 After isEmpty(): returns true
7. isFull (for bounded deques):
 Checks if the deque is full.
 Example Initial: | 1 | 2 | 3 | 4 | (max
size 4)
 After isFull(): returns true

Q.8) Write pseudocode for Linear Queue Implementation


using array.
Initialize QUEUE_SIZE
Create array queue[QUEUE_SIZE]
Set front = -1, rear = -1

Function isFull():
Return (rear == QUEUE_SIZE - 1)

Function isEmpty():
Return (front == -1)

Function enqueue(value):
If isFull():
Print "Queue is full"
Return
If isEmpty():
front = 0
rear = rear + 1
queue[rear] = value

Function dequeue():
If isEmpty():
Print "Queue is empty"
Return
value = queue[front]
If front == rear:
front = rear = -1
Else:
front = front + 1
Return value
Function displayQueue():
If isEmpty():
Print "Queue is empty"
Return
For i from front to rear:
Print queue[si]

Q10) What is dynamic data structure. Explain with


circular linked list with it’s basic operation
basic operation.Dynamic Data Structure:
A dynamic data structure is a data structure that can grow or
shrink at runtime, allowing efficient memory usage. Unlike
static data structures (e.g., arrays), where the size is fixed at
compile-time, dynamic data structures use pointers to allocate
and deallocate memory as needed during execution.
Circular Linked List:
A circular linked list is a type of linked list where the last node
points back to the first node, forming a circle. This means you
can traverse the list from any point and eventually return to
that point. Structure of a
Node:
In a singly circular linked list:
struct Node {
int data;
struct Node* next;
};
Basic Operations:
Insertion:
o Beginning: New node → head; last node → new node.
o End: New node → head; last node → new node.
o Position: Insert between two nodes.
Deletion:
o Beginning: Head → next; last node → new head.
o End: Second-last node → head.
o Position: Skip and free the node.
Traversal:
o Start from head, loop until you reach the head again
. Example: Singly Circular Linked List
o Nodes: [10] → [20] → [30] → back to [10]
Insertion at end (40):
[10] → [20] → [30] → [40] → back to [10]
Traversal Output: 10 20 30 40

Q.11) What are the variants of recursion. Explain with


example
Recursion can be categorized into different types based on how
the recursive call is made within the function. These types
include tail recursion, head recursion, tree recursion, indirect
recursion, and nested recursion.
1. Tail Recursion:
 The recursive call is the last statement in the function.
 No computation is performed after the recursive call.
 Can be optimized by compilers.
2. Head Recursion:
 The recursive call is made first, before any other
operations in the function.
 Work is done after the recursive call.
3. Tree Recursion:
 A function calls itself more than once.
 Common in problems like the Fibonacci sequence, where
one call branches into two or more.
4. Indirect Recursion:
 Two or more functions call each other in a cycle.
 For example, functionA might call functionB,
and functionB calls functionA.
5. Nested Recursion:
 The recursive call's argument is itself a recursive call.
 For example, nested_recursion(nested_recursion(n + 11)).
Q.12 Explain Fibonacci Search algorithm with suitable
example. What is it’s time complexity?
✅ Fibonacci Search Algorithm
Fibonacci Search is a comparison-based search algorithm
similar to Binary Search, but it uses Fibonacci numbers to
divide the array into sections. It works on a
sorted array and is particularly efficient in scenarios where the
cost of accessing elements depends on proximity, such as in
memory hierarchies or specific hardware
1. Find the smallest Fibonacci number F(k) such that F(k) >= n
(where n is the size of the array).
2. Set offset = -1.
3. Compare the element at index i = min(offset + F(k-2), n-1):
 If key == arr[i]: element found.
 If key < arr[i]: move the range to the left (use F(k-2) and
F(k-3)).
 If key > arr[i]: move the range to the right (use F(k-1) and
adjust offset).
4.Repeat until the range is reduced.
Example:-
Array: [10, 22, 35, 40, 45, 50, 80, 82, 85, 90,
100]
Key to search: 85
Size (n) = 11
Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13 →
use F(7) = 13
Steps:
i = min(0 + F(5), 10) = 5 → arr[5] = 50
→ 85 > 50 → move right
i = 5 + F(3) = 8 → arr[8] = 85
Match found
O(log n)
Q,22) Write algorithm for posfix expression
evalution.
1. Initialization: Create an empty stack to store operands.
2. Scanning: Scan the postfix expression from left to right.
3. Operand: If you encounter an operand (a number),
convert it to an integer and push it onto the stack.
4. Operator: If you encounter an operator, pop the top two
operands from the stack. 5.Calculation: Perform the
operation using the popped operands.
6. Push Result: Push the result of the operation back onto
the stack.
7. Final Result: After processing the entire expression, the
final result will be on the top of the stack. Pop the stack
and return the value.

Q13 ) Write pseudo-C/C++ code to implement


stack using array with overflow and underflow
conditions.
#include <iostream>
using namespace std;
#define MAX 100
class Stack {
private:
int arr[MAX], top;
public:
Stack() { top = -1; }

void push(int value) {


if (top >= MAX - 1) cout << "Overflow\n";
else arr[++top] = value;
}
int pop() {
if (top < 0) { cout << "Underflow\n"; return -1; }
return arr[top--];
}

void display() {
if (top < 0) cout << "Empty\n";
else for (int i = top; i >= 0; i--) cout << arr[i] << "
";
cout << endl;
}
};
int main() {
Stack s;
s.push(10); s.push(20);
s.display(); // 20 10
s.pop(); // 20
s.display(); // 10
return 0; }
Q.14) Write an algorithm to delete intermediate
node from Doubly linked list
Algorithm: Delete Intermediate Node from Doubly
Linked List
1. Start with the head of the doubly linked list.
2. Check if the list is empty:
o If the list is empty (head == NULL), display a

message that the list is empty and return.


3. Traverse the list to find the node to be deleted:
o If you have the reference to the node

(nodeToDelete), proceed.
4. Ensure the node to be deleted is not the head or
tail:
o If the node to be deleted is neither the head

nor the tail, you can safely delete it by


modifying the pointers.
5. Adjust the pointers:
o Set the next pointer of the node before

nodeToDelete (nodeToDelete->prev->next =
nodeToDelete->next).
o Set the prev pointer of the node after

nodeToDelete (nodeToDelete->next->prev =
nodeToDelete->prev).
6. Delete the node:
o Free the memory allocated to nodeToDelete (if
needed, depending on language).
7. End.
Q.15)…Explain with example the following terms
related to sorting methods: i) Stability ii) Number
of Passes/Iterations iii) Sort order
i) Stability
Definition:
A stable sorting algorithm maintains the relative order
of records with equal keys (values). That means if two
elements are equal in value, their order in the original
list will be preserved after sorting.
Example;- Input: [(A, 2), (B, 1), (C, 2)]
Stable sort by number → [(B, 1), (A,
2), (C, 2)]
A stays before C (same number 2)
Q16.) What is stack? Write an ADT for stack
A stack is a linear data structure that follows the
Last In First Out (LIFO) principle, where the last
element added is the first one to be removed. It
supports operations
like push (add), pop (remove), and peek (retrieve
the top element).
ADT Stack
{
Stack() // Initializes an empty stack
void push(element) // Adds an element to the
top
element pop() // Removes and returns the
top element
element peek() // Returns the top element
without removing it
bool isEmpty() // Checks if the stack is
empty
bool isFull() // Checks if the stack is full (if
applicable)
}
Q.17) Draw and explain Priority Queue? State any
real lif application.
A priority queue is a data structure where each element
has a priority associated with it, and elements are
processed based on their priority. Higher priority
elements are processed before lower priority elements
Example of real life example
A hospital emergency room is a real-life example of a
priority queue, where patients are treated based on the
severity of their condition rather than the order they
arrived.
Q.18). Explain the use of backtracking in 4-
Queen’s problem3 What is recursion?
Q..Explain use of stack for undo operation in
word processor(MS office/ OpenOffice).
The 4-Queens problem involves placing four queens on a
4x4 chessboard so that no two queens threaten each
other. Backtracking is used to explore possible
placements:
 Place a Queen: Start placing queens row by row.
 Check Validity: Ensure no two queens threaten
each other.
 Recursive Call: If valid, recursively place the next
queen.
 Backtrack: If a conflict arises, remove the last
queen and try the next position.
Solution Found: Continue until all queens are
placed or all configurations are explored.
2. What is Recursion?
Recursion is a programming technique where a
function calls itself to solve a problem. It consists of:
 Base Case: A condition that stops further
recursive calls.
 Recursive Case: The part where the function calls
itself with modified arguments.
3. Use of Stack for Undo Operation in Word
Processors In word processors (e.g., MS
Office, Open Office), the undo operation is
implemented using a stack:
 Action Stack: Each user action (typing,
formatting) is pushed onto a stack.
 Undo Operation: The most recent action is
popped from the stack to revert the document
state.
 Redo Operation: Actions can be pushed onto a
redo stack for reapplication after an undo.
Q.19) Define the following term with suitable
example circular queue
A circular queue is a linear data structure that treats
the last position as if it's connected to the first position,
creating a circular arrangement. This allows for efficient
reuse of storage space that would otherwise be wasted
in a regular (linear) queue after elements are removed
and the queue is not yet full
Operations:
1. Enqueue – Add element at rear.
2. Dequeue – Remove element from front.
3. isFull – If next of rear is front.
4. isEmpty – If front = -1
Example:

Queue size = 5
Enqueue: 10 → 20 → 30
Queue: [10, 20, 30, _, _]
Dequeue: removes 10
Enqueue: 40 → 50 → 60 (wraps around)
Queue: [60, 20, 30, 40, 50] (rear wrapped to start)

Q.20) What is backtracking algorithmic strategy?


Explain the use of stack in backtracking strategy
with any one application.

Backtracking is a problem-solving algorithm that explores a solution


space by progressively building candidates for a solution, one piece at
a time, and discarding those that don't meet the problem's constraints
Application: Sudoku Solver

1. Start with an empty grid.


2. Try placing numbers in empty cells.
3. Backtrack if a number violates Sudoku rules.
4. Continue until the grid is filled without violations, then solution
found.

You might also like