Recursion: Q.1 Explain With Example Three Different Types o
Recursion: Q.1 Explain With Example Three Different Types o
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)
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)
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)
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)
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]
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
(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
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)