SDOT 2024 Python, Java
SDOT 2024 Python, Java
The first line contains an integer n, the length of the first linked list.
The next line contain n integers, the elements of the linked list.
The next line contains an integer m , the length of the second linked list.
The next lines contain m integers, the elements of the second linked list.
Output Format
Output a single line of (n + m) integers consisting all elements of linked
lists in sorted order.
Example
Input
3
1 2 4
3
1 3 4
Output
1 1 2 3 4 4
LOGIC: Input:
Array 1: 1 2 4
Array 2: 1 3 4
Output:
Merged Array: 1 1 2 3 4 4
Logic:
1. Start with two sorted arrays.
2. Initialize pointers for each array, starting at the first element
Pointer for Array 1: 1
Pointer for Array 2: 1
3. Compare the elements at the pointers. Choose the smaller element and append
it to the merged array.
Merged Array: 1
Increment pointers for both arrays.
4. Repeat the comparison and appending process until one of the arrays is
exhausted
Merged Array: 1 1 2 3
5. Once one array is exhausted, append the remaining elements from the other
array to the merged array.
Merged Array: 1 1 2 3 4 4
PYTHON CODE
class ListNode: else:
def __init__(self, value=0, next=None): current.next = l2
self.value = value l2 = l2.next
self.next = next current = current.next
# Helper function to print the linked list # Merge the two lists
def print_linked_list(head): merged_list = merge_sorted_lists(list1,
while head is not None: list2)
print(head.value, end=" ")
head = head.next # Print the merged list
print() print("Merged List:")
print_linked_list(merged_list)
JAVA CODE
import java.io.*; Node current = head;
import java.util.*; while(current.next !=null){
class Node{ current = current.next;
int data; }
Node next; current.next = new_node;
Node(int data){ }
this.data = data; }
next = null; class Solution {
} static Node merge(Node head1, Node
} head2){
class LinkedList{ // Write your code here
Node head; if(head1==null)
void add(int data ){ {
Node new_node = new return head2;
Node(data); }
if(head == null){ if(head2==null)
head = new_node; {
return; return head1;
} }
Node ansHead; //NEW HEAD else{
if(head1.data<head2.data){ temp.next=head2;
ansHead=head1; head2=head2.next;
head1=head1.next; }
} temp=temp.next;
else{ }
ansHead=head2; if(head1!=null){
head2=head2.next; temp.next=head1;
} }
Node temp=ansHead; // after if(head2!=null){
doing all temp will be at last temp.next=head2;
position }
while(head1!=null && return ansHead;
head2!=null){
if(head1.data<head2.data){ }
temp.next=head1; // }
ansHead is already decided so we will public class Main {
traverse from //temp.next public static void main(String
head1=head1.next; args[]) {
Scanner sc = new Scanner(System.in); Solution Ob = new Solution();
int n = sc.nextInt(); Node head = Ob.merge(l1.head,
LinkedList l1= new l2.head);
LinkedList(); while(head != null){
for(int i=0;i<n;i++){ System.out.print(head.
l1.add(sc.nextInt()); data + " ");
} head = head.next;
int m = sc.nextInt(); }
LinkedList l2 = new }
LinkedList(); }
for(int i=0;i<m;i++){
l2.add(sc.nextInt());
}
PALINDROME LIST
Given a singly linked list of characters, write a function that returns
true if the given list is a palindrome, else false.
Input Format
You will be provided with the linked list''s head.
Output Format
Return true if the given list is a palindrome, else false..
Example 1
Input
5
1 2 3 2 1
Output
true
Example 2
Input
6
10 20 30 10 50 30
Output:
false
LOGIC
Example
Input
3
1 2 4
3
1 3 4
Output
1 1 2 3 4 4
PYTHON CODE
class ListNode: # Function to check if two lists are
def __init__(self, value=0, equal
next=None): def are_lists_equal(list1, list2):
self.value = value while list1 and list2:
self.next = next if list1.value !=
list2.value:
def is_palindrome(head): return False
# Function to reverse a linked list1 = list1.next
list list2 = list2.next
def reverse_list(node): return True
prev = None
while node: # Find the middle of the linked
next_node = node.next list
node.next = prev slow = fast = head
prev = node while fast and fast.next:
node = next_node slow = slow.next
return prev fast = fast.next.next
# Reverse the second half of the
linked list # Create a linked list
reversed_second_half = head = None
reverse_list(slow) for value in reversed(values):
head = ListNode(value, head)
# Compare the first half with the
reversed second half # Check if the linked list is a
return are_lists_equal(head, palindrome
reversed_second_half) result = is_palindrome(head)
the nodes in groups of k. All the remaining nodes after multiples of k should
be left as it is.
Example 1:
Input:
k: 3
Output:
Result: 3→2→1→6→5→4→9→8→7
Example 2:
Input:
k: 2
Output:
Result: 2→1→4→3→6→5→7
LOGIC
nodes.
nodes.
Example 1:
Output:
Example 2:
Output:
PYTHON CODE
class ListNode: list1, list2 = temp1, temp2
def __init__(self, value=0,
next=None): if not head or not head.next:
self.value = value return head
self.next = next slow = fast = head
def reorder_linked_list(head): while fast.next and fast.next.
def reverse_list(node): next:
prev, current = None, node slow = slow.next
while current: fast = fast.next.next
next_node = current.next reversed_second_half =
current.next = prev reverse_list(slow.next)
prev = current slow.next = None
current = next_node merge_lists(head,
return prev reversed_second_half)
def merge_lists(list1, list2): return head
while list2: def create_linked_list(values):
temp1, temp2 = list1.next, if not values:
list2.next return None
list1.next, list2.next = head = ListNode(values[0])
list2, temp1 current = head
for value in values[1:]: # Create a linked list
current.next = ListNode(value) linked_list =
current = current.next create_linked_list(elements)
return head
# Reorder the linked list
def print_linked_list(head): reorder_linked_list(linked_list)
while head:
print(head.value, end=" → ") # Print the result
head = head.next print("\nReordered Linked List:")
print("None") print_linked_list(linked_list)
Input-1
Head: 10->20->30->40->50
K: 2
Output-1
40->50->10->20->30
we have rotated the linked list exactly 2 times. On the First rotation 5
becomes head and 4 becomes tail, and on the second rotation 4 becomes head and 3
• Find the length of the linked list to determine the effective rotation
(adjust k if it's greater than the length).
• Iterate k times, each time moving the last node to the front of the
list.
• Return the updated head of the linked list after rotations.
PYTHON CODE
class ListNode: k = k % length # Adjust k if it's greater
def __init__(self, value=0, next=None): than the length of the list
self.value = value
self.next = next for _ in range(k):
def insert_node(head, val): temp = head
new_node = ListNode(val) while temp.next.next is not None:
if head is None: temp = temp.next
return new_node end = temp.next
temp = head temp.next = None
while temp.next is not None: end.next = head
temp = temp.next head = end
temp.next = new_node
return head return head
def rotate_right(head, k):
if head is None or head.next is None: def print_list(head):
return head while head.next is not None:
length = 0 print(head.value, end="->")
temp = head head = head.next
while temp is not None: print(head.value)
length += 1
temp = temp.next
# Get input from the user
head = None
print("Enter the linked list values (enter -1 to stop):")
while True:
val = int(input())
if val == -1:
break
head = insert_node(head, val)
numbers while maintaining their original order. The even numbers should be
placed at the beginning of the linked list, followed by the odd numbers.
Example 1:
1,2,3
• In our original linked list, we have numbers: 1 → 2 → 3.
• We want to separate even numbers from odd numbers and keep the order the
same.
• So, first, we find the even number, which is 2. We keep it at the beginning.
• Next, we find the odd numbers, which are 1 and 3. We keep their order and
2 → 1 → 6 → 4 → 8.
2 1 6 4 8
2 4 6 8 1
Example 2:
2 → 1 → 6 → 4 → 8.
We want to separate even numbers from odd numbers and keep the order the same.
So, first, we find the even numbers, which are 2, 6, 4, and 8. We keep them at the
Next, we find the odd number, which is 1. We keep it after the even numbers,
Original list:
1 2 3 4 5
Output:
2 4 1 3 5
LOGIC
Edge Cases:
If the linked list is empty or has only one node, no rearrangement is needed.
Initialization:
Create two pointers, odd and even, to track the odd and even nodes separately.
Initialize even to the second node (if exists) or None if there is no second node.
Rearrangement:
Traverse the linked list using a loop until either odd or even becomes None.
Connect the odd node to the next odd node (if exists).
Connect the even node to the next even node (if exists).
Move odd and even pointers to their respective next odd and even nodes.
Continue this process until the end of the linked list is reached.
Finalization:
Connect the last odd node to the starting node of the even nodes.
PYTHON CODE
class ListNode: def create_linked_list(values):
def __init__(self, val=0, next=None): if not values:
self.val = val return None
self.next = next head = ListNode(values[0])
def oddEvenList(head): current = head
if not head or not head.next: for value in values[1:]:
return head current.next = ListNode(value)
# Separate odd and even nodes current = current.next
odd_head = odd = ListNode(0) return head
even_head = even = ListNode(0) # Helper function to print the linked list
is_odd = True def print_linked_list(head):
while head: while head:
if is_odd: print(head.val, end=" ")
odd.next = head head = head.next
odd = odd.next print()
else: # Get input from the user
even.next = head elements = list(map(int, input("Enter the elements
even = even.next of the linked list: ").split()))
is_odd = not is_odd head = create_linked_list(elements)
head = head.next # Perform the operation
# Append even nodes to the end of odd nodes result = oddEvenList(head)
odd.next = even_head.next # Print the result
even.next = None print("\nResulting Linked List:")
return odd_head.next print_linked_list(result)
# Helper function to create a linked list from a
list of values
JAVA CODE
class Node { }
int data; current.next = newNode;
Node next; }
public Node(int data) { public void segregateEvenOdd() {
this.data = data; if (head == null) {
this.next = null; System.out.println("The list
} is empty.");
} return;
class LinkedList { }
Node head; Node evenHead = null, evenTail =
null;
public void append(int data) { Node oddHead = null, oddTail =
Node newNode = new Node(data); null;
if (head == null) { Node current = head;
head = newNode; while (current != null) {
return; int data = current.data;
} if (data % 2 == 0) { // even node
Node current = head; if (evenHead == null) {
while (current.next != null) { evenHead = evenTail = current;
current = current.next;
} else { if (oddHead != null) {
evenTail.next = current; oddTail.next = null;
evenTail = current; }
} head = evenHead != null ? evenHead :
} else { // odd node oddHead;
if (oddHead == null) { }
oddHead = oddTail = current;
} else { public void printList() {
oddTail.next = Node current = head;
current; while (current != null) {
oddTail = current; System.out.print(current.
} data + " ");
} current = current.next;
current = current.next; }
} System.out.println();
// Join even and odd lists }
if (evenHead != null) { }
evenTail.next = oddHead;
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
System.out.println("Original list:");
list.printList();
list.segregateEvenOdd();
formed) parentheses substring. A valid parentheses substring is defined as a substring that has an
Input: "(()"
Output: 2
Input: ")()())"
Output: 4
For each opening parenthesis '(', push its index onto the stack.
If the stack becomes empty, push the current index onto the stack.
If not empty, update the maximum length by calculating the difference between the current index
4. The maximum length is the length of the longest valid parentheses substring.
PYTHON CODE
def longest_valid_parentheses(s):
stack = [-1]
max_length = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_length = max(max_length, i - stack[-1])
return max_length
# Example usage
s = "(())"
result = longest_valid_parentheses(s)
print("Length of the longest valid parentheses substring:", result)
JAVA CODE
import java.util.Stack;
class Main {
public static void main(String[] args) {
String s = "(()";
Stack<Integer> st = new Stack<>();
int max = 0;
st.push(-1);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
st.push(i);
} else {
st.pop();
if (st.isEmpty()) {
st.push(i);
} else {
int len = i - st.peek();
max = Math.max(max, len);
}
}
}
System.out.println("Length of the longest valid parentheses substring: " + max);
}
}
INFIX TO POSTFIX CONVERSION
Implement a Java program that converts an infix expression to a postfix expression using a stack.
Examples:
Infix: (a+b)*(c-d)
Postfix: ab+cd-*
Infix: a+b*c-d/e
Postfix: abc*+de/-
LOGIC
✔ Initialize an empty stack for operators and an empty list for the postfix expression.
✔ Scan the infix expression from left to right.
✔ If a character is an operand (letter or digit), add it to the postfix expression.
✔ If a character is '(', push it onto the stack.
✔ If a character is ')', pop operators from the stack and append to the postfix expression
until '(' is encountered. Discard '('.
✔ If a character is an operator (+, -, *, /):
✔ Pop operators from the stack and append to postfix while the stack is not empty and the top
operator has higher or equal precedence.
✔ Push the current operator onto the stack.
✔ After scanning all characters, pop any remaining operators from the stack and append to the
postfix expression.
✔ The resulting list is the postfix expression.
PYTHON CODE
class InfixToPostfixConverter: self.operator_stack.pop() # Pop the '('
def __init__(self): elif self.is_operator(ch):
self.operator_stack = [] while (self.operator_stack and
self.postfix_expression = [] self.get_precedence(ch) <= self.
def is_operator(self, ch): get_precedence(self.operator_stack[-1])):
return ch in ['+', '-', '*', '/'] self.postfix_expression.append(self.
def get_precedence(self, operator): operator_stack.pop())
if operator in ['+', '-']: self.operator_stack.append(ch)
return 1 while self.operator_stack:
elif operator in ['*', '/']: self.postfix_expression.append(self.
return 2 operator_stack.pop())
else: return ''.join(self.postfix_expression)
return 0 def main():
def infix_to_postfix(self, infix): infix_converter = InfixToPostfixConverter()
for ch in infix: infix_expression = input("Enter infix
if ch.isalnum(): self. expression: ")
postfix_expression.append(ch) postfix_expression = infix_converter.
elif ch == '(': infix_to_postfix(infix_expression)
self.operator_stack.append(ch) print(f"Infix: {infix_expression}")
elif ch == ')': print(f"Postfix: {postfix_expression}")
while self.operator_stack and if __name__ == "__main__":
self.operator_stack[-1] != '(': main()
self.postfix_expression.append(self.
operator_stack.pop())
JAVA CODE
import java.util.Scanner; StringBuilder postfix = new StringBuilder();
import java.util.Stack; Stack<Character> operatorStack = new
public class Main { Stack<>();
private static boolean isOperator(char ch) { for (char ch : infix.toCharArray()) {
return ch == '+' || ch == '-' || ch == if (Character.isLetterOrDigit(ch)) {
'*' || ch == '/'; postfix.append(ch);
} } else if (ch == '(') {
private static int getPrecedence(char operatorStack.push(ch);
operator) { } else if (ch == ')') {
switch (operator) { while (!operatorStack.isEmpty()
case '+': && operatorStack.peek() != '(') {
case '-': postfix.
return 1; append(operatorStack.pop());
case '*': }
case '/': operatorStack.pop(); // Pop the
return 2; '('
default: } else if (isOperator(ch)) {
return 0; while (!operatorStack.isEmpty()
} && getPrecedence(ch) <=
} getPrecedence(operatorStack.peek())) {
private static String infixToPostfix(String
infix) {
postfix.append(operatorStack.pop());
}
operatorStack.push(ch);
}
}
while (!operatorStack.isEmpty()) {
postfix.append(operatorStack.pop());
}
return postfix.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter infix expression 1: ");
String infix1 = scanner.nextLine();
String postfix1 = infixToPostfix(infix1);
System.out.println("Postfix expression 1: " + postfix1);
scanner.close();
}
}
EVALUATE POSTFIX EXPRESSION
You are given a postfix expression, and your task is to evaluate it using a stack. A postfix expression
is an arithmetic expression in which the operators come after their operands. For example, the infix
Your goal is to implement a Java program that takes a postfix expression as input, evaluates it using a
Output: 17
Explanation: The given postfix expression represents the infix expression (3 * 4) + 5, which evaluates
to 17.
Output: 14
Explanation: The given postfix expression represents the infix expression (7 / 2) * 4, which evaluates
to 14.
LOGIC
✔ If it is an operator (+, -, *, /), pop two operands from the stack, perform the operation and push
✔ After scanning the entire expression, the result is the only element left in the stack.
PYTHON CODE
class PostfixEvaluator: result = operators[char](operand1,
def __init__(self): operand2)
self.operand_stack = []
self.operand_stack.
def evaluate_postfix(self, expression):
operators = {'+': lambda x, y: x + y, append(result)
'-': lambda x, y: x - y, return self.operand_stack.pop()
'*': lambda x, y: x * y, def main():
'/': lambda x, y: x // y} postfix_evaluator =
# Use // for integer division PostfixEvaluator()
for char in expression.split(): postfix_expression = input("Enter
if char.isdigit():
self.operand_stack. the postfix expression: ")
append(int(char)) result = postfix_evaluator.
elif char in operators: evaluate_postfix(postfix_expression)
operand2 = self.operand_stack. print("Result:", result)
pop() if __name__ == "__main__":
operand1 = self.operand_stack. main()
pop()
JAVA CODE
import java.util.Stack; case '*':
import java.util.Scanner; stack.push(operand1 * operand2);
public class Main { break;
public static int evaluatePostfix(String case '/’:
expression) { stack.push(operand1 / operand2);
Stack<Integer> stack = new Stack<>(); break;
for (char c : expression.toCharArray()) }
{ }
if (Character.isDigit(c)) { }
stack.push(Character. return stack.pop();
getNumericValue(c)); }
} else { public static void main(String[] args) {
int operand2 = stack.pop(); Scanner scanner = new Scanner(System.
int operand1 = stack.pop(); in);
switch (c) { System.out.print("Enter the postfix
case '+': expression: ");
stack.push(operand1 + operand2); String postfixExpression = scanner.
break; nextLine();
case '-': int result =
stack.push(operand1 - operand2); evaluatePostfix(postfixExpression);
break; System.out.println("Result: " + result);
}
}
BASIC CALCULATOR
Design a basic calculator using a stack data structure. The calculator should be able to perform
addition, subtraction, multiplication, and division operations. Implement the calculator logic using a
stack and provide a simple Java program that takes user input for arithmetic expressions and outputs
the result.
Examples:
Input: 3 + 5 * 2
Output: 13
Input: 8 / 2 - 1
Output: 3
LOGIC:
✔ Initialize two stacks, one for operands (operands) and another for operators (operators).
✔ Iterate through each character in the input expression from left to right.
✔ If a digit is encountered, convert consecutive digits into a number and push it onto the
operands stack.
✔ Pop operators from the operators stack and operands from the operands stack while the top
operator on the stack has equal or higher precedence than the current operator.
✔ Evaluate the popped operator and operands, then push the result back onto the operands stack.
✔ After processing all characters, evaluate any remaining operators and operands on the stacks.
✔ The final result is the only element left on the operands stack.
PYTHON CODE
def calculate(expression):
operands = []
operators = []
def precedence(op):
if op in {'+', '-'}:
return 1
elif op in {'*', '/'}:
return 2
else:
return 0
def evaluate():
b = operands.pop()
a = operands.pop()
op = operators.pop()
if op == '+':
result = a + b
elif op == '-':
result = a - b
elif op == '*':
result = a * b
else:
result = a / b
operands.append(result)
i = 0
while i < len(expression):
char = expression[i]
if char.isdigit():
num = int(char)
while i + 1 < len(expression) and expression[i + 1].isdigit():
num = num * 10 + int(expression[i + 1])
i += 1
operands.append(num)
elif char in {'+', '-', '*', '/'}:
while operators and precedence(char) <= precedence(operators[-1]):
evaluate()
operators.append(char)
i += 1
while operators:
evaluate()
return operands[0]
# Example Usage:
expression1 = "3 + 5 * 2"
expression2 = "8 / 2 - 1"
result1 = calculate(expression1)
result2 = calculate(expression2)
print(f"Input: {expression1}\nOutput: {result1}")
print(f"Input: {expression2}\nOutput: {result2}")
JAVA CODE
import java.util.*; operators.push(c);
public class Main { }
public static void main(String[] args) { }
Scanner scanner = new Scanner(System.in); while (!operators.isEmpty()) {
Stack<Integer> operands = new Stack<>(); evaluate(operands, operators);
Stack<Character> operators = new Stack<>(); }
String input = scanner.nextLine(); System.out.println(operands.pop());
for (int i = 0; i < input.length(); i++) { }
char c = input.charAt(i);
if (Character.isDigit(c)) { private static int precedence(char c) {
int num = c - '0'; if (c == '+' || c == '-') {
while (i + 1 < input.length() && Character. return 1;
isDigit(input.charAt(i + 1))) { } else if (c == '*' || c == '/') {
num = num * 10 + (input.charAt(i + 1) - '0'); return 2;
i++; } else {
} return 0;
operands.push(num); }
} else if (c == '+' || c == '-' || c == '*' || c }
== '/') {
while (!operators.isEmpty() && precedence(c) <= private static void evaluate(Stack<Integer>
precedence(operators.peek())) { operands, Stack<Character> operators) {
evaluate(operands, operators); int b = operands.pop();
}
int a = operands.pop();
char op = operators.pop();
int result;
if (op == '+') {
result = a + b;
} else if (op == '-') {
result = a - b;
} else if (op == '*') {
result = a * b;
} else {
result = a / b;
}
operands.push(result);
}
}
IMPLEMENT A STACK USING QUEUES
You are required to implement a stack using queues. A stack is a data structure that follows the Last
In, First Out (LIFO) principle, where the last element added to the stack is the first one to be
removed.
pop(): Remove the element on the top of the stack and return it.
top(): Return the element on the top of the stack without removing it.
push(x) operation:
pop() operation:
Move all elements except the last one from the non-empty queue to the empty queue.
Remove and return the last element from the non-empty queue.
top() operation:
isEmpty() operation:
functionality of a queue, which follows the First-In-First-Out (FIFO) principle, using two stacks that
dequeue(): Remove and return the front element of the queue. If the queue is empty, return -1.
peek(): Return the front element of the queue without removing it. If the queue is empty, return -1.
Initialization:
Enqueue Operation:
Dequeue Operation:
If stack2 is not empty, pop from stack2 (since it has the front element).
If stack2 is empty:
While stack1 is not empty, pop from stack1 and push onto stack2.
Return True if both stack1 and stack2 are empty; otherwise, return False.
PYTHON CODE
class QueueUsingStacks:
def __init__(self):
self.stack1 = [] # Used for enqueue operation
self.stack2 = [] # Used for dequeue operation
def enqueue(self, element):
# Implement enqueue operation using stack1
self.stack1.append(element)
def dequeue(self):
# Implement dequeue operation using stack2 if it's not empty, otherwise transfer elements
from stack1 to stack2
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
# Pop from stack2 to perform dequeue operation
if self.stack2:
return self.stack2.pop()
else:
# Queue is empty
print("Queue is empty")
return -1 # Return a default value to indicate an empty queue
def is_empty(self):
# Check if both stacks are empty to determine if the queue is empty
return not self.stack1 and not self.stack2
def main():
queue = QueueUsingStacks()
while True:
print("\nChoose operation:")
print("1. Enqueue")
print("2. Dequeue")
print("3. Check if the queue is empty")
print("4. Exit")
choice = int(input())
if choice == 1:
enqueue_element = int(input("Enter the element to enqueue: "))
queue.enqueue(enqueue_element)
elif choice == 2:
dequeued_element = queue.dequeue()
if dequeued_element != -1:
print("Dequeued element:", dequeued_element)
elif choice == 3:
print("Is the queue empty?", queue.is_empty())
elif choice == 4:
break
else:
print("Invalid choice. Please enter a valid option.")
if __name__ == "__main__":
main()
JAVA CODE
import java.util.Scanner;
import java.util.Stack;
class QueueUsingStacks {
private Stack<Integer> stack1; // Used for enqueue operation
private Stack<Integer> stack2; // Used for dequeue operation
public QueueUsingStacks() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void enqueue(int element) {
// Implement enqueue operation using stack1
stack1.push(element);
}
public int dequeue() {
// Implement dequeue operation using stack2 if it's not empty, otherwise transfer
elements from stack1 to stack2
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
// Pop from stack2 to perform dequeue operation
if (!stack2.isEmpty()) {
return stack2.pop();
} else {
// Queue is empty
System.out.println("Queue is empty");
return -1; // Return a default value to indicate an empty queue
}
}
public boolean isEmpty() {
// Check if both stacks are empty to determine if the queue is empty
return stack1.isEmpty() && stack2.isEmpty();
}
}
public class Main {
public static void main(String[] args) {
QueueUsingStacks queue = new QueueUsingStacks();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nChoose operation:");
System.out.println("1. Enqueue");
System.out.println("2. Dequeue");
System.out.println("3. Check if the queue is empty");
System.out.println("4. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the element to enqueue:");
int enqueueElement = scanner.nextInt();
queue.enqueue(enqueueElement);
break;
case 2:
int dequeuedElement = queue.dequeue();
if (dequeuedElement != -1) {
System.out.println("Dequeued element: " +
dequeuedElement);
}
break;
case 3:
System.out.println("Is the queue empty? " + queue.isEmpty());
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please enter a valid
option.");
}
}
}
}
ZIG ZAG LEVEL ORDER TRAVERSAL
Given the root node of a tree, print its nodes in zig zag order, i.e. print the
first level left to right, next level right to left, third level left to right and
so on.
Note
You need to complete the given function. The input and printing of output will be
handled by the driver code.
Input Format
The first line of input contains a string represeting the nodes, N is to show null
node.
Output Format
For each test case print the nodes of the tree in zig zag traversal.
Test cases:
Explanation
Example 1 Original tree was:
Input 1
/ \
1 2 3 4 5 6 7 2 3
Output / \ / \
4 5 6 7
1 3 2 4 5 6 7
After Zig Zag traversal, tree formed would be:
1
/ \
3 2
/ \ / \
4 5 6 7
Test cases:
Explanation
Example 2 Original Tree was:
Input
5
5 8 7 / \
Output 8 7
if arr[i] != 'N':
current_node.left = Node(int(arr[i]))
queue.append(current_node.left)
i += 1
if i < len(arr) and arr[i] != 'N':
current_node.right = Node(int(arr[i]))
queue.append(current_node.right)
i += 1
return root
if __name__ == "__main__":
t = int(input())
for _ in range(t):
s = input().split()
root = buildTree(s)
tree = Solution()
arr = tree.rightView(root)
for x in arr:
print(x, end=" ")
print()
JAVA CODE
import java.io.BufferedReader; if (root == null) {
import java.io.IOException; return list;
import java.io.InputStreamReader; }
import java.util.ArrayList;
import java.util.LinkedList; Queue<Node> q = new LinkedList<>();
import java.util.Queue; q.add(root);
while (!q.isEmpty()) {
class Node {
int n = q.size();
int data;
for (int i = 0; i < n; i++) {
Node left; Node curr = q.poll();
Node right; if (i == n - 1) {
list.add(curr.data);
Node(int data) { }
this.data = data; if (curr.left != null) {
left = null; q.add(curr.left);
right = null; }
} if (curr.right != null) {
} q.add(curr.right);
class Solution { }
ArrayList<Integer> rightView(Node root) { } }
ArrayList<Integer> list = new return list;
ArrayList<>(); }}
public class Main { i++;
static Node buildTree(String str) {
if (str.length() == 0 || str.charAt(0) == if (i >= ip.length)
'N') { break;
return null;
} currVal = ip[i];
if (!currVal.equals("N")) {
String[] ip = str.split(" "); currNode.right = new Node(Integer.
Node root = new Node(Integer. parseInt(currVal));
parseInt(ip[0])); queue.add(currNode.right);
Queue<Node> queue = new LinkedList<>(); }
queue.add(root); i++;
int i = 1; }
return root;
while (!queue.isEmpty() && i < ip.length) }
{
Node currNode = queue.poll(); public static void main(String[] args) throws
IOException {
String currVal = ip[i]; BufferedReader br = new
if (!currVal.equals("N")) { BufferedReader(new InputStreamReader(System.in));
currNode.left = new Node(Integer. int t = Integer.parseInt(br.readLine());
parseInt(currVal));
queue.add(currNode.left);
}
while (t-- > 0) {
String s = br.readLine();
Node root = buildTree(s);
Solution tree = new Solution();
ArrayList<Integer> arr = tree.rightView(root);
for (int x : arr)
System.out.print(x + " ");
System.out.println();
}
}
}
DIAMETER OF BINARY TREE
Given a root of a binary tree, write a function to get the diameter of the tree. The diameter of a
binary tree is the length of the longest path between any two nodes in a tree. This path may or may not
pass through the root.
Input Format
You are given a string s which describes the nodes of the binary tree. (The first element corresponds to
the root, the second is the left child of the root and so on). In the function, you are provided with
the root of the binary tree.
Output Format
Return the diameter of the binary tree.
Example 1
Input
8 2 1 3 N N 5
Output
5
Explanation
1 2 N
Output
2
Explanation
Note:
The sequence of nodes in the linked list should be the same as that of the preorder traversal of the
binary tree.
The linked list nodes are the same binary tree nodes. You are not allowed to create extra nodes.
The right child of a node points to the next node of the linked list whereas the left child points to
NULL.
Example
Reverse Preorder traversal
This process rearranges the connections in the tree, effectively turning it into a linked list. The linked
list retains the order of nodes as if traversing the tree in a preorder fashion.
PYTHON CODE
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def flatten(root):
if not root:
return
current = root
while current:
if current.left:
# Find the rightmost node in the left subtree
rightmost = current.left
while rightmost.right:
rightmost = rightmost.right
# Move the right subtree of the current node to the rightmost node in the
left subtree
rightmost.right = current.right
# Set the left subtree as the new right subtree
current.right = current.left
# Set the left child to null
current.left = None
# Move to the next node in the modified tree
current = current.right
def print_linked_list(root):
while root:
print(root.val, '*>', end=' ')
root = root.right
print('null')
# Example usage:
# Constructing a sample binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)
# Flatten the binary tree to a linked list
flatten(root)
# Print the linked list
print_linked_list(root)
JAVA CODE
class TreeNode {
int val;
TreeNode left, right;
Lowest common ancestor of two nodes x, y in a tree or directed acyclic graph is the lowest node that has
both nodes x, y as its descendants.
Your task is to complete the function findLCA which receives the root of the tree, x, y as its
parameters and returns the LCA of these values.
Input Format:
The first line contains the values of the nodes of the tree in the level order form.
The second line contains two integers separated by space which denotes the nodes x and y.
Output Format:
Print the LCA of the given nodes in a single line.
Example 1
Input
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
7 5
Output
1
Explanation
1
/ \
2 3
/ / \
4 5 6
\
7
The root of the tree is the deepest node which contains both the nodes 7 and 5 as its
descendants, hence 1 is the answer.
Example 2
Input
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
4 2
Output
2
Explanation
1
/ \
2 3
/ / \
4 5 6
\
7
The node will value 2 of the tree is the deepest node which contains both the nodes 4 and 2 as its
descendants, hence 2 is the answer.
LOGIC
1. Perform a recursive traversal of the tree.
2. If the current node is one of the given nodes (`n1` or `n2`), return the
current node.
3. Recursively search for the LCA in the left and right subtrees.
4. If both left and right subtrees return non-null values, the current node is the
LCA.
5. Return the LCA found during the traversal.
PYTHON CODE
class Node: curr_node.right = Node(int(curr_val))
def __init__(self, key): queue.append(curr_node.right)
self.data = key i += 1
self.left = None return root
self.right = None def find_lca(root, n1, n2):
def build_tree(arr): if root is None:
if not arr or arr[0] == "N": return None
return None if root.data == n1 or root.data == n2:
root = Node(int(arr[0])) return root
queue = [root] left_lca = find_lca(root.left, n1, n2)
i = 1 right_lca = find_lca(root.right, n1, n2)
while queue and i < len(arr): if left_lca is not None and right_lca is
curr_node = queue.pop(0) not None:
curr_val = arr[i] return root
if curr_val != "-1": return left_lca if left_lca is not None
curr_node.left = else right_lca
Node(int(curr_val)) # Input
queue.append(curr_node.left) s = input().split()
i += 1 root = build_tree(s)
if i >= len(arr): x, y = map(int, input().split())
break # Find LCA
curr_val = arr[i] ans = find_lca(root, x, y)
if curr_val != "-1": print(ans.data if ans else "N")
JAVA CODE
queue.remove();
import java.util.LinkedList; String currVal = ip[i];
import java.util.Queue; if (!currVal.equals("-1")) {
import java.io.*; currNode.left = new
import java.util.*; Node(Integer.parseInt(currVal));
class Main { queue.add(currNode.left);
static Node buildTree(String str) { }
if (str.length() == 0 || str. i++;
charAt(0) == 'N') { if (i >= ip.length) break;
return null; currVal = ip[i];
} if (!currVal.equals("-1")) {
String ip[] = str.split(" "); currNode.right = new
Node root = new Node(Integer. Node(Integer.parseInt(currVal));
parseInt(ip[0])); queue.add(currNode.right);
Queue<Node> queue = new }
LinkedList<>(); i++;
queue.add(root); }
int i = 1;
while (queue.size() > 0 && i < ip.length) { return root;
Node currNode = queue.peek(); }
public static void main(String[] args) class Solution {
throws IOException { public static Node findLCA(Node node,int
Scanner sc = new Scanner(System.in); n1,int n2) {
String s = sc.nextLine(); if (node == null)
Node root = buildTree(s); return null;
int x = sc.nextInt();
int y = sc.nextInt(); if (node.data == n1 || node.data ==
Solution g = new Solution(); n2)
Node ans = g.findLCA(root,x,y); return node;
System.out.println(ans.data); Node left_lca = findLCA(node.left,
} n1, n2);
} Node right_lca = findLCA(node.right,
class Node { n1, n2);
int data; if (left_lca != null && right_lca !=
Node left; null)
Node right; return node;
Node(int data) { return (left_lca != null) ? left_lca :
this.data = data; right_lca;
left = null; }
right = null; }
}}
VALIDATE BINARY SEARCH TREE
Given a binary tree with N number of nodes, check if that input tree is BST (Binary Search Tree) or not.
If yes, print true, print false otherwise. A binary search tree (BST) is a binary tree data structure
which has the following properties.
• The left subtree of a node contains only nodes with data less than the node’s data.
• The right subtree of a node contains only nodes with data greater than the node’s data.
• Both the left and right subtrees must also be binary search trees.
Input Format
The first line contains an Integer 't', which denotes the number of test
cases or queries to be run. Then the test cases follow.
The first line of input contains the elements of the tree in the level order
form separated by a single space.
If any node does not have a left or right child, take -1 in its place.
Output Format
For each test case, print true if the binary tree is a BST, else print false.
1
3 2 5 1 4 -1 -1 -1 -1 -1 -1
Output
false
Explanation
For the root node, all the nodes in the right subtree (5) are greater than 3. But node with data 4 in
the left subtree of node 3 is greater than 3, this does not satisfy the condition for the binary search
tree. Hence, the function should return false.
LOGIC
2
/ \
1 3
k=3
Output: 3
The 3rd smallest element is 3.
Notes
Input Format: There are two arguments in the input. First one is the root of the BST and
second one is an integer k.
Output: Return an integer, the k-th smallest element of the BST.
LOGIC
3. When the count equals `k`, store the value of the current node as the k-th smallest
element (`result[1]`).
kthSmallestHelper(root.right, k, result);
}
}
CONVERT SORTED LIST TO BST
Given a Singly Linked List which has data members sorted in ascending order. Construct a
Balanced Binary Search Tree which has same data members as the given Linked List.
Input: Linked List 1->2->3
Base Case:
If n is less than or equal to 0, return None (base case).
Recursive Calls:
Recursively construct the left subtree (left) by calling sortedListToBSTRecur on the
first half of the linked list.
Create the root of the current subtree with the data of the current head node.
Move the head pointer to the next node in the linked list.
Recursively construct the right subtree (right) by calling sortedListToBSTRecur on
the second half of the linked list.
Driver Code:
The push function is used to add elements to the linked list, and the main code
initializes the linked list with values, constructs the BST, and prints the pre-order
traversal.
PYTHON CODE
class LinkedList: def sortedListToBSTRecur(self, n):
def __init__(self): if n <= 0:
self.head = None return None
class LNode: left = self.sortedListToBSTRecur(n // 2)
def __init__(self, data): root = self.TNode(self.head.data)
self.data = data root.left = left
self.next = None self.head = self.head.next
self.prev = None root.right = self.sortedListToBSTRecur(n -
class TNode: n // 2 - 1)
def __init__(self, data): return root
self.data = data def countNodes(self, head):
self.left = None count = 0
self.right = None temp = head
def sortedListToBST(self): while temp is not None:
n = self.countNodes(self.head) temp = temp.next
return self.sortedListToBSTRecur(n) count += 1
return count
def push(self, new_data): if __name__ == "__main__":
new_node = self.LNode(new_data) llist = LinkedList()
new_node.prev = None llist.push(7)
new_node.next = self.head llist.push(6)
if self.head is not None: llist.push(5)
self.head.prev = new_node llist.push(4)
self.head = new_node llist.push(3)
def printList(self, node): llist.push(2)
while node is not None: llist.push(1)
print(node.data, end=" ") print("Given Linked List ")
node = node.next llist.printList(llist.head)
def preOrder(self, node): root = llist.sortedListToBST()
if node is None: print("\nPre-Order Traversal of constructed BST ")
return llist.preOrder(root)
print(node.data, end=" ")
self.preOrder(node.left)
self.preOrder(node.right)
JAVA CODE
class LinkedList { TNode sortedListToBST() {
static LNode head; int n = countNodes(head);
class LNode { return sortedListToBSTRecur(n);
int data; }
LNode next, prev;
LNode(int d) { TNode sortedListToBSTRecur(int n) {
data = d; if (n <= 0)
next = prev = null; return null;
}}
class TNode { TNode left = sortedListToBSTRecur(n / 2);
int data; TNode root = new TNode(head.data);
TNode left, right; root.left = left;
TNode(int d) { head = head.next;
data = d;
left = right = null;
}}
root.right = sortedListToBSTRecur(n - n / 2 - new_node.prev = null;
1); new_node.next = head;
return root; if (head != null)
} head.prev = new_node;
int countNodes(LNode head) { head = new_node;
int count = 0; }
LNode temp = head; void printList(LNode node) {
while (temp != null) { while (node != null) {
temp = temp.next; System.out.print(node.data + " ");
count++; node = node.next;
} }
return count; }
} void preOrder(TNode node) {
void push(int new_data) { if (node == null)
LNode new_node = new LNode(new_data); return;
System.out.print(node.data + " "); llist.push(1);
preOrder(node.left); System.out.println("Given Linked List ");
preOrder(node.right); llist.printList(head);
} TNode root = llist.sortedListToBST();
public static void main(String[] args) { System.out.println("");
LinkedList llist = new LinkedList(); System.out.println("Pre-Order Traversal
llist.push(7); of constructed BST ");
llist.push(6); llist.preOrder(root);
llist.push(5); }
llist.push(4); }
llist.push(3);
llist.push(2);
DEPTH-FIRST SEARCH
You are given a graph represented as an adjacency list. Implement the Depth-First
Search (DFS) algorithm to traverse the graph and return the order in which the
nodes are visited.
Depth first Search or Depth first traversal is a recursive algorithm for
searching all the vertices of a graph or tree data structure
A standard DFS implementation puts each vertex of the graph into one of two
categories:
1. Visited
2. Not Visited
DFS(G, u)
u.visited = true
for each v ∈ G.Adj[u]
if v.visited == false
DFS(G,v)
init() {
For each u ∈ G
u.visited = false
For each u ∈ G
DFS(G, u)
}
PYTHON CODE
from collections import defaultdict for adj in self.adjLists[vertex]:
class Graph: if not self.visited[adj]:
def __init__(self, vertices): self.DFS(adj)
self.adjLists = defaultdict(list) if __name__ == "__main__":
self.visited = [False] * vertices g = Graph(4)
def addEdge(self, src, dest): g.addEdge(0, 1)
self.adjLists[src].append(dest) g.addEdge(0, 2)
def DFS(self, vertex): g.addEdge(1, 2)
self.visited[vertex] = True g.addEdge(2, 3)
print(vertex, end=" ") print("Following is Depth First Traversal")
g.DFS(2)
JAVA CODE
import java.util.*; void addEdge(int src, int dest) {
class Graph { adjLists[src].add(dest);
private LinkedList<Integer> adjLists[]; }// DFS algorithm
private boolean visited[]; void DFS(int vertex) {
// Graph creation visited[vertex] = true;
Graph(int vertices) { System.out.print(vertex + " ");
adjLists = new LinkedList[vertices]; Iterator<Integer> ite =
visited = new boolean[vertices]; adjLists[vertex].listIterator();
for (int i = 0; i < vertices; i++) while (ite.hasNext()) {
adjLists[i] = new int adj = ite.next();
LinkedList<Integer>(); if (!visited[adj])
} DFS(adj);
// Add edges } }
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.DFS(2);
}
}
PRIM’S ALGORITHM
Given a weighted graph, we have to find the minimum spanning tree (MST) of that graph using
Prim’s algorithm. Print the final weight of the MST.
Input Format
The first line contains one integer v representing the number of nodes.
Next lines contains a v*v matrix representing the graph. matrix[i][j] represents the value of
the weight between the ith node and the jth node. If there is no edge, the value is 0.
Output Format
Print the final weight of the MST.
Example 1
Input
5
0 2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 0 9
0 5 7 9 0
Output
16
Explanation
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
Total sum = 16
Example 2
Input
5
0 4 2 0 0
4 0 1 3 0
2 1 0 7 2
0 3 7 0 5
0 0 2 5 0
Output
8
Explanation
Edge Weight
2 - 1 1
0 - 2 2
1 - 3 3
2 - 4 2
Total sum = 8
LOGIC
1. Initialize:
Create an array `key[]` to store the key values of vertices, initially set to `INFINITY`
except for the first vertex, which is set to 0.
Create an array `parent[]` to store the parent (or the vertex that leads to the minimum key
value) for each vertex.
Create a boolean array `mstSet[]` to represent whether a vertex is included in the MST or
not.
Initialize all keys as `INFINITY`, set the first key to 0, and set all elements in
`mstSet[]` as `false`.
2. Select Vertices:
Repeat the following until all vertices are included in the MST:
a. Choose the vertex `u` with the minimum key value from the set of vertices not yet
included in the MST (`mstSet[]` is `false`).
b. Include `u` in the MST by setting `mstSet[u]` to `true`.
c. Update the key values of all adjacent vertices of `u` if they are not included in the
MST and the weight of the edge (`graph[u][v]`) is less than the current key value of the vertex
`v`.
3. Print MST:
Print the sum of the key values of all vertices in the MST. This sum
represents the weight of the minimum spanning tree.
This logic using adjacency lists to represent the graph. It initializes
key values, updates them during the algorithm's execution, and prints
the final weight of the MST.
PYTHON CODE
import sys print(total_sum)
def minKey(key, mstSet, V): def primMST(graph):
min_val = sys.maxsize V = len(graph)
min_index = -1 parent = [-1] * V
for v in range(V): key = [sys.maxsize] * V
if not mstSet[v] and key[v] < min_val: mstSet = [False] * V
min_val = key[v] key[0] = 0
min_index = v parent[0] = -1
return min_index for _ in range(V - 1):
def printMST(parent, graph): u = minKey(key, mstSet, V)
V = len(graph) mstSet[u] = True
total_sum = 0 for v in range(V):
for i in range(1, V): if graph[u][v] != 0 and not
total_sum += graph[i][parent[i]] mstSet[v] and graph[u][v] < key[v]:
parent[v] = u
key[v] = graph[u][v]
printMST(parent, graph)
# Input
V = int(input())
graph = [list(map(int, input().split())) for _ in range(V)]
Return the minimum number of liters of fuel to reach the capital city.
Example 1:
Explanation:
Explanation:
An ArrayList adj is created to represent an adjacency list for a graph. It's used to store the
connections between different nodes (roads).
Graph Construction:
The roads array is used to construct an undirected graph (adjacency list). Each road connection
is added to the adj list.
Recursive DFS (Depth-First Search):
The solve function is a recursive DFS function that explores the graph, calculating the number
of people in each subtree.
The base case is when a leaf node is reached, i.e., a node with only one connection.
Fuel Cost Calculation:
For each node (except the root), the fuel cost is calculated based on the number of people in
the subtree and the number of seats available. The cost is added to the global variable ans.
Main Function:
The minimumFuelCost function initializes the adj list, calls the solve function to calculate
the fuel cost, and returns the final result.
Example Usage:
An example is provided where roads are defined, and the minimum fuel cost is calculated for a
given number of seats.
PYTHON CODE
from math import ceil for i in adj[src]:
class Solution: if i != parent:
def __init__(self): people += self.solve(adj, seats, i, src)
self.ans = 0 if src != 0:
def minimum_fuel_cost(self, roads, seats): self.ans += ceil(people / seats)
adj = [[] for _ in range(len(roads) + 1)] return people
n = len(roads) + 1 # Example Usage
self.ans = 0 solution = Solution()
for a, b in roads: roads = [[3, 1], [3, 2], [1, 0], [0, 4], [0, 5],
adj[a].append(b) [4, 6]]
adj[b].append(a) seats = 2
self.solve(adj, seats, 0, -1) result = solution.minimum_fuel_cost(roads,
return self.ans seats)
def solve(self, adj, seats, src, parent): print(result)
people = 1
JAVA CODE
import java.util.ArrayList; solve(adj, seats, 0, -1);
public class Solution { return ans;
private long ans = 0L; }
public long minimumFuelCost(int[][] roads, int private long
seats) { solve(ArrayList<ArrayList<Integer>> adj, int seats,
ArrayList<ArrayList<Integer>> adj = new int src, int parent) {
ArrayList<>(); long people = 1L;
int n = roads.length + 1; for (int i : adj.get(src)) {
ans = 0L; if (i != parent) {
for (int i = 0; i < n; i++) { people += solve(adj, seats, i, src);
adj.add(new ArrayList<>()); }
} }
for (int[] a : roads) { if (src != 0) {
adj.get(a[0]).add(a[1]); ans += (long) Math.ceil((double) people
adj.get(a[1]).add(a[0]); / seats);
} }
return people;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] roads = {{3, 1}, {3, 2}, {1, 0}, {0, 4}, {0, 5}, {4, 6}};
int seats = 2;
long result = solution.minimumFuelCost(roads, seats);
System.out.println(result);
}
}
NUMBER OF ISLANDS
You are given a 2D matrix grid of size n * m. You have to find the number of distinct islands
where a group of connected 1s (horizontally or vertically) forms an island. Two islands are
considered to be distinct if and only if one island is not equal to another (rotated or
reflected islands are not euqal).
Input Format
The first line contains two integers value of N and M.
Next N line contains M boolean values where 1 denotes land and 0 denotes water.
Output Format
Print total number of distinct islands.
Example 1
Input
3 4
1 1 0 0
0 0 0 1
1 1 1 0
Output
3
Explanation
1 1 in row 1
1 in row 2
down right
1 1 1 in row 3
Example 2
Input
3 4
1 1 0 0
0 0 0 1
0 1 1 0
Output
2
Explanation
There are 3 islands once again, but island in row 1 and row 3 are not distinct, hence only
2 distinct islands.
LOGIC
Initialize Variables:
Implement a DFS function that explores the connected land cells of an island.
Mark visited cells as -1 to indicate they have been processed.
Traverse the Grid:
Input Format
The First line of input contain two integers N denoting number of people and M denoting size of
prerequisites array.
Output Format
print 1 if it is possible to finish all the courses else print 0.
Example 1
Input
4 3
1 2
1 3
1 0
Output
1
Explanation
4 3
1 2
2 3
3 1
Output
3. Perform BFS by removing courses with no prerequisites, updating in-degrees, and adding
4. If all courses are taken (sum of in-degrees is 0), return 1; otherwise, return 0.
5. The result indicates whether it is possible to finish all courses based on the given
prerequisites.
PYTHON CODE
from collections import defaultdict if degree[neighbor] == 0:
class Solution: no_prerequisites.add(neighbor)
def canFinish(self, n, prerequisites): return int(sum(degree) == 0)
G = defaultdict(list) # Input handling
degree = [0] * n N, M = map(int, input().split())
for e in prerequisites: prerequisites = [list(map(int, input().
G[e[1]].append(e[0]) split())) for _ in range(M)]
degree[e[0]] += 1 # Call the solution class
no_prerequisites = set(i for i in Obj = Solution()
range(n) if degree[i] == 0) print(Obj.canFinish(N, prerequisites))
while no_prerequisites:
course = no_prerequisites.pop()
for neighbor in G[course]:
degree[neighbor] -= 1
JAVA CODE
import java.util.*;
class Solution {
public int canFinish(int n, int[][] prerequisites) {
ArrayList<Integer>[] G = new ArrayList[n];
int[] degree = new int[n];
ArrayList<Integer> bfs = new ArrayList();
for (int i = 0; i < n; ++i) G[i] = new ArrayList<Integer>();
for (int[] e : prerequisites) {
G[e[1]].add(e[0]);
degree[e[0]]++;
}
for (int i = 0; i < n; ++i) if (degree[i] == 0) bfs.add(i);
for (int i = 0; i < bfs.size(); ++i)
for (int j: G[bfs.get(i)])
if (--degree[j] == 0) bfs.add(j);
if(bfs.size() == n)
return 1;
else
return 0;
}}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N= sc.nextInt();
int M= sc.nextInt();
int prerequisites[][] = new int[M][2];
for(int i=0; i<M; i++){
for(int j=0; j<2; j++)
prerequisites[i][j]= sc.nextInt();
}
Solution Obj = new Solution(); System.out.println(Obj.canFinish(N,prerequisites));
}
}
LETTER COMBINATIONS OF A
PHONE NUMBER
Given a string containing digits from 2-9 inclusive, print all possible letter
combinations that the number could represent. Print the answer in sorted order.
A mapping of digit to letters (just like on the telephone buttons) is given
below.
Note
1 does not map to any letters.
2 : abc
3 : def
4 : ghi
5 : jkl
6 : mno
7 : pqrs
8 : tuv
9 : wxyz
Input Format
The first line of input contains a string of digits.
Output Format
Print all possible letter combinations that the number could represent,
separated by spaces.
Example 1 Example 2
Input
Input
2
23 Output
Output
a b c
ad ae af bd be bf cd ce cf Explanation
Explanation
2 maps to a, b, c.
Get the mapping (key) of the first digit in the input string s.
For each character in the mapping:
Recursively call the function with the remaining digits (s[1:]) and the updated
combination (ans + char).
The recursion will continue until the base case is reached.
Mapping (keypad) Explanation:
The keypad array is used to map each digit to the corresponding letters on a
telephone keypad.
For example, keypad[2] corresponds to "abc," keypad[3] corresponds to "def," and so
on.
PYTHON CODE
def possible_words(s, ans):
# Base Case
if not s:
print(ans)
return
# Recursive Step
for char in key:
# Recursively call the function with the remaining digits and updated combination
possible_words(s[1:], ans + char)
# Input handling
s = input("Enter a string of digits: ")
for(int i=0;i<key.length();i++){
possibleWords(s.substring(1),ans+key.
charAt(i));
}
}
PERMUTATIONS
Problem Statement: Generating Permutations using Backtracking
Given a set of distinct integers, write a program to generate all possible permutations of the
elements in the set.
Example:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
LOGIC
Base Case:
• If the left index is equal to the right index, print the current permutation.
Recursion:
• Iterate through each element from the left index to the right index.
• Swap the current element with the element at index 'i'.
• Recursively generate permutations for the remaining elements.
• Backtrack by undoing the swap to restore the original order.
PYTHON CODE
def generate_permutations(nums, left, right): # Backtrack: Undo the swap to restore the original
if left == right: order
# Base case: Print the current permutation nums[left], nums[i] = nums[i],
print(nums) nums[left]
else:
for i in range(left, right + 1): # Input handling
# Swap the current element with the n = int(input("Enter the number of elements in the
element at index 'i' set: "))
nums[left], nums[i] = nums[i], nums = list(map(int, input("Enter the elements of
nums[left] the set: ").split()))
The same number may be chosen from nums an unlimited number of times. Two
combinations are unique if the frequency of at least one of the chosen
numbers is different.
Input Format
Input is managed for you. (You are given an array nums and target target in
the combinationSum() function).
Output Format
Output is managed for you. (You can return the possible valid combinations
in any order. The combinations will be automatically printed in sorted
order).
Example 1
Input
4 16
6 2 7 5
Output
2 2 2 2 2 2 2 2
2 2 2 2 2 6
2 2 2 5 5
2 2 5 7
2 2 6 6
2 7 7
5 5 6
Explanation
3 5
1 2 3
Output
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
2 3
Explanation
(1 1 1 1 1)
(1 1 1 2)
(1 1 3)
(1 2 2)
(2 3)
LOGIC
Sort the array nums to handle duplicates and for easier comparison later.
Use a backtracking function to explore all possible combinations, keeping
track of the current combination in the tempList.
If the current combination sums up to the target, add it to the result
list.
Recursively call the backtracking function for each element in the array,
allowing duplicates to be reused.
Sort the result list and its sublists for proper ordering, and print the
unique combinations.
PYTHON CODE
class Solution: # Input handling
def combinationSum(self, nums, target): n, target = map(int, input().split())
nums.sort()
nums = list(map(int, input().split()))
result = []
self.backtrack(result, [], nums,
target, 0) # Call the solution class
return result ob = Solution()
ans = ob.combinationSum(nums, target)
def backtrack(self, result, tempList, nums,
remain, start): # Sort the result
if remain < 0:
return
ans.sort(key=lambda x: (len(x), x))
elif remain == 0:
result.append(tempList.copy()) # Print the result
else: for combination in ans:
for i in range(start, len(nums)): print(*combination)
tempList.append(nums[i])
self.backtrack(result,
tempList, nums, remain - nums[i], i)
tempList.pop()
JAVA CODE
import java.util.*; tempList.add(nums[i]);
class Solution { backtrack(list, tempList, nums, remain -
nums[i], i); // not i + 1 because we can reuse
public List<List<Integer>> same elements
combinationSum(int[] nums, int target) { tempList.remove(tempList.size() -
List<List<Integer>> list = new 1);
ArrayList<>(); }
Arrays.sort(nums); }
backtrack(list, new ArrayList<>(), nums, }
target, 0); }
return list; public class Main {
} public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
private void backtrack(List<List<Integer>> int n = sc.nextInt();
list, List<Integer> tempList, int [] nums, int int target = sc.nextInt();
remain, int start){ int []nums = new int[n];
if(remain < 0) return; for(int i = 0 ; i < n ; ++i){
else if(remain == 0){ nums[i] = sc.nextInt();
list.add(new ArrayList<>(tempList)); }
}
else{
for(int i = start; i < nums.length;
i++){
Solution ob = new Solution();
List<List<Integer>> ans = ob.combinationSum(nums,target);
for(int i = 0 ; i < ans.size() ; ++i){
Collections.sort(ans.get(i));
}
Collections.sort(ans, (o1, o2) -> {
int m = Math.min(o1.size(), o2.size());
for (int i = 0; i < m; i++) {
if (o1.get(i) == o2.get(i)){
continue;
}else{
return o1.get(i) - o2.get(i);
}
}
return 1;
});
for (int i = 0; i < ans.size (); i++)
{
for (int j = 0; j < ans.get(i).size (); j++)
{
System.out.print(ans.get(i).get(j)+" ");
}
System.out.println();
}}}
GENERATE PARENTHESES
Given a positive integer n, write a function to generate all combinations of well-formed
parentheses. The goal is to generate all possible combinations of parentheses such that they
are balanced.
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and
suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by
"l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in
the original string.
LOGIC
• If at any point the current matching prefix length is equal to the length of the
• The reason is that a happy prefix cannot include the entire string, so the length of
the matching prefix should be less than the length of the string.
PYTHON CODE
def longest_happy_prefix(s): # Return the longest happy prefix
n = len(s)
return s[:length]
# Compute the prefix function using KMP
# Get input from the user
algorithm
input_str = input("Enter a string: ")
prefix_function = [0] * n
j = 0 # Find and print the longest happy prefix
for i in range(1, n): result = longest_happy_prefix(input_str)
while j > 0 and s[i] != s[j]: print("Longest Happy Prefix:", result)
j = prefix_function[j - 1]
if s[i] == s[j]:
j += 1
prefix_function[i] = j
# The length of the longest happy prefix is
given by the last value in the prefix function
length = prefix_function[-1]
JAVA CODE
public class LongestHappyPrefix { }
public static String }
longestHappyPrefix(String s) { }
int n = s.length(); int happyPrefixLength = lps[n - 1];
int[] lps = new int[n]; return happyPrefixLength > 0 ? s.
int len = 0; substring(0, happyPrefixLength) : "";
for (int i = 1; i < n; ) { }
if (s.charAt(i) == s.charAt(len)) { public static void main(String[] args) {
lps[i++] = ++len; System.out.
} else { println(longestHappyPrefix("level"));
if (len != 0) { }
len = lps[len - 1]; }
} else {
lps[i++] = 0;
LONGEST SUBSTRING WITHOUT
REPEATING CHARACTERS
You are given a string s. Your task is to find the length of the longest substring that
contains each character at most once.
Input Format
First line contains the string s.
Output Format
Complete the function longestSubstring() where you return the required integer.
Example 1
Input
xyzxyzyy
Output
3
Explanation
Input
xxxxxx
Output
1
LOGIC
✔ We use a sliding window approach to find the longest substring without repeating
characters.
✔ Maintain two pointers, start and end, representing the current substring.
✔ Use a dictionary (char_index_map) to keep track of the last index of each character
encountered.
✔ If a character is already in the current substring, update the start index to the
next index of the previous occurrence of that character.
✔ Update the last index of the current character in the char_index_map.
✔ Update the length of the current substring and keep track of the maximum length
encountered.
PYTHON CODE
def longestSubstring(s): char_index_map[s[end]] = end
char_index_map = {} # To store the last # Update the length of the current
index of each character substring
start = 0 # Start index of the current max_length = max(max_length, end -
substring start + 1)
max_length = 0 # Length of the longest return max_length
substring input_str2 = "xxxxxx"
for end in range(len(s)): result2 = longestSubstring(input_str2)
if s[end] in char_index_map and print("Output:", result2) # Output: 1
char_index_map[s[end]] >= start:
# If the character is already in
the current substring, update the start index
start = char_index_map[s[end]] + 1
# Update the last index of the current
character
JAVA CODE
import java.util.*; res = Math.max(res, right - left + 1);
class Solution { right++;
public int longestSubstring(String s) { }
Map<Character, Integer> chars = new return res;
HashMap(); }}
int left = 0; public class Main {
int right = 0; public static void main (String[] args)
int res = 0; throws java.lang.Exception {
while (right < s.length()) { Scanner sc=new Scanner(System.in);
char r = s.charAt(right); String s = sc.nextLine();
chars.put(r, chars.getOrDefault(r,0) + 1); Solution ob = new Solution();
while (chars.get(r) > 1) { int ans=ob.longestSubstring(s);
char l = s.charAt(left); System.out.println(ans);
chars.put(l, chars.get(l) - 1); }
left++; }
}
LONGEST PALINDROMIC SUBSTRING
Given a string s, find the longest palindromic substring in s.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"
LOGIC
PYTHON CODE
def longest_palindromic_substring(s):
def expand_around_center(left, right): if right1 - left1 > end - start:
while left >= 0 and right < len(s) and start, end = left1, right1
s[left] == s[right]: if right2 - left2 > end - start:
left -= 1 start, end = left2, right2
right += 1
return left + 1, right - 1 return s[start:end + 1]
start, end = 0, 0 # Get input from the user
for i in range(len(s)): input_str = input("Enter a string: ")
left1, right1 = expand_around_center(i, # Find and print the longest palindromic
i) # Odd-length palindrome substring
left2, right2 = expand_around_center(i, result =
i + 1) # Even-length palindrome longest_palindromic_substring(input_str)
print("Longest Palindromic Substring:", result)
JAVA CODE
import java.util.Scanner; palindrom[i][j] = true;
class LongestPalindromicSubstring { if(j-i+1 > longestSoFar) {
private static String longestSoFar = j-i+1;
findLongestPalindromicSubstring(String input) { startIndex = i;
if(input.isEmpty()) { endIndex = j;
return ""; } } } }
} return input.substring(startIndex,
int n = input.length(); endIndex+1);
int longestSoFar = 0, startIndex = 0, }
endIndex = 0; public static void main(String[] args) {
boolean[][] palindrom = new boolean[n][n]; Scanner keyboard = new Scanner(System.in);
for(int j = 0; j < n; j++) { String input = keyboard.next(); System.
palindrom[j][j] = true; out.
for(int i = 0; i < j; i++) { println(findLongestPalindromicSubstring(input));
if(input.charAt(i) == input.charAt(j) }
&& (j-i <= 2 || palindrom[i+1][j-1])) { }
SHORTEST PALINDROME
Problem Statement:
Given a string, find the shortest palindrome that can be obtained by adding characters in front
of it.
Example 1:
Input: "race"
Output: "ecarace"
Explanation: By adding "eca" in front of "race," we get the shortest palindrome "ecarace."
Example 2:
Input: "abc"
Output: "cba"
Explanation: By adding "cba" in front of "abc," we get the shortest palindrome "cbaabc."
Example 3:
Input: "level"
Output: "level"
Explanation: The given string "level" is already a palindrome, so no additional characters are
needed.
Input: "abc" Output: "cbaabc"
LOGIC
Iterate from the end of the string, considering each prefix.
Start from the end of the string "abc."
Consider each prefix, trying to find the longest palindrome.
Consider the prefix "cba" from "abc."
The prefix "cba" is a palindrome.
Reverse the remaining suffix "abc" and append it to the original string.
Reverse "abc" to get "cba."
Append the reversed suffix to the original string.
Result: "cbaabc"
So, by adding the palindrome "cba" in front of the original string "abc" and then appending the
reversed suffix "abc," we get the shortest palindrome "cbaabc."
PYTHON CODE
def shortest_palindrome(s):
def is_palindrome(string):
return string == string[::-1]
for i in range(len(s), 0, -1):
prefix = s[:i]
if is_palindrome(prefix):
suffix = s[i:]
return suffix[::-1] + s
return s
# Get input from the user
input_str = input("Enter a string: ")
Return the minimum number of deletions such that the smallest element in nums divides all the
elements of numsDivide. If this is not possible, return -1.
3. If such an element is found, count the number of elements in nums that are different from this smallest
divisor.
5. This logic ensures that the smallest divisor is selected to minimize the deletions needed for the array to
The length of the given array is should be greater or equal to 3 i.e. LENGTH >=3.
There must be only one peak in the array or the largest element in the array.
The array must follows the condition: ARRAY[0] < ARRAY[1] < ARRAY[i-1] < ARRAY[ i] > ARRAY[ i+1
] > ARRAY[..] > ARRAY[length-1]
The task is to find the peak index of the mountain array.
Suppose we have given the input [60, 20, 90, 110, 10].
The output will be 3. Because the largest element in the array is 110 whose index is 3.
LOGIC
def find_peak_index(arr):
left, right = 0, len(arr) - 1
return left
PYTHON CODE
def find_peak_index(arr):
left, right = 0, len(arr) - 1
while left < right:
mid = left + (right - left) // 2
if arr[mid] < arr[mid + 1]:
left = mid + 1
else:
right = mid
# At the end, left and right will be equal
return left
def main():
n = int(input("Enter the length of the array: "))
arr = list(map(int, input("Enter the elements of the array separated by spaces: ").
split()))
peak_index = find_peak_index(arr)
print("The peak index is:", peak_index)
if __name__ == "__main__":
main()
JAVA CODE
import java.util.Scanner; Scanner scanner = new Scanner(System.in);
public class Main { System.out.print("Enter the length
public static int findPeakIndex(int[] arr) { of the array: ");
int left = 0; int n = 0;
int right = arr.length - 1; while (!scanner.hasNextInt()) {
while (left < right) { System.out.println("Invalid input.
int mid = left + (right - left) / 2; Please enter a valid integer.");
if (arr[mid] < arr[mid + 1]) { scanner.next(); // consume the invalid
left = mid + 1; input
} else { }
right = mid; n = scanner.nextInt();
}} System.out.print("Enter the elements of the
return left; // or right, they are equal at array separated by spaces: ");
the end int[] arr = new int[n];
} for (int i = 0; i < n; i++) {
public static void main(String[] args) { while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a valid integer.");
scanner.next(); // consume the invalid input
}
arr[i] = scanner.nextInt();
}
int peakIndex = findPeakIndex(arr);
System.out.println("The peak index is: " + peakIndex);
scanner.close();
}
}
NUMBER OF SUBSTRING CONTAINS ALL
THREE CHARACTERS
Print the number of substrings containing all three characters i.e. a,b,c at least once in a
given string.
Test Case
Input:
1
acbaa
Output:
5
Explanation:
The substrings containing at least one occurrence of the characters a, b and c are acb, acba,
acbaa, cba and cbaa.
LOGIC
1. initialize pointers start and end to define a substring.
2. Iterate through the string using these pointers.
3. Use an array hash_count to count occurrences of each character in the
substring.
4. Check if the substring contains at least one occurrence of each of 'a',
'b', and 'c'.
5. If yes, update the count with the number of substrings that can be formed
with the remaining characters.
6. Move the pointers accordingly.
7. Print the count for each test case.
PYTHON CODE
def countSubstringsWithABC():
test_cases = int(input("Enter the number of test cases: "))
while test_cases > 0:
S = input("Enter the string: ")
start, end, count = 0, 0, 0
if len(S) < 3:
count = 0
else:
while end < len(S):
hash_count = [0] * 26
for i in range(start, end):
hash_count[ord(S[i]) - ord('a')] += 1
if all(count > 0 for count in hash_count[:3]):
count += len(S) - end + 1
start += 1
else:
end += 1
print(count)
test_cases -= 1
# Example usage:
countSubstringsWithABC()
JAVA CODE
import java.util.Scanner; while (test_cases != 0) {
public class Main { System.out.println("Enter the string:
public static void main(String args[]) { ");
Scanner sc = new Scanner(System.in); String S = sc.next();
int test_cases = 0; int start = 0, end = 0, count = 0;
while (true) { if (S.length() < 3)
try { count = 0;
System.out.println("Enter the number of else {
test cases:"); while (end < S.length()) {
test_cases = sc.nextInt(); int hash[] = new int[26];
break; for (int i = start; i < end; i++) {
} catch (java.util.InputMismatchException e){ hash[S.charAt(i) - 'a']++;
System.out.println("Invalid }
input. Please enter a valid integer."); if (hash[0] > 0 && hash[1] > 0 && hash[2] >
sc.nextLine(); 0) {
} }
count += S.length() - end + 1;
start++;
} else {
end++;
}
}
}
System.out.println(count);
test_cases--;
}
}
}
TRAPPING RAIN WATER
Trapping Rain Water
Given with n non-negative integers representing an elevation map where the width of
each bar is 1, we need to compute how much water it is able to trap after raining.
arr[] = {3, 0, 2, 0, 4}.
Explanation : trap “3 units” of
Three units of water can be stored in two indexes 1
water between 3 and 2, “1 unit” on
and 3, and one unit of water at index 2.
top of bar 2 and “3 units” between
Water stored in each index = 0 + 3 + 1 + 3 + 0 = 7
2 and 4.
LOGIC
1. Iterate Through Bars:
Iterate through each bar from the second to the secondtolast bar
2. Find Left and Right Boundaries:
For each bar at index `i`, find the maximum height on its left and right sides.
3. Calculate Trapped Water:
Determine the minimum height between the left and right boundaries.
Subtract the height of the current bar at index `i`.
Add the result to the total trapped water.
4. Return Result:
The total trapped water is the final result.
PYTHON CODE
def maxWater(arr, n):
res = 0
for i in range(1, n - 1):
left = arr[i]
for j in range(i):
left = max(left, arr[j])
right = arr[i]
for j in range(i + 1, n):
right = max(right, arr[j])
res += min(left, right) - arr[i]
return res
# Example usage:
arr = [1, 0, 2, 1, 0, 1]
n = len(arr)
print(maxWater(arr, n))
JAVA CODE
public class Main { res += Math.min(left, right) - arr[i];
public static int maxWater(int[] arr, int n) { }
for (int i = 1; i < n - 1; i++) { return res;
int left = arr[i]; }
for (int j = 0; j < i; j++) { public static void main(String[] args) {
left = Math.max(left, arr[j]); int[] arr = { 1, 0, 2, 1, 0, 1};
} int n = arr.length;
int right = arr[i]; System.out.print(maxWater(arr, n));
for (int j = i + 1; j < n; j++) { }
right = Math.max(right, arr[j]); }
}
SPIRAL MATRIX
Print a given matrix in spiral form.
Given a 2D array, print it in spiral form. Refer the following examples.
Example 1:
Example 1:
Input: Input:
1 2 3 4 1 2 3 4 5 6
5 6 7 8 7 8 9 10 11 12
9 10 11 12 13 14 15 16 17 18
13 14 15 16
Output:
1 2 3 4 5 6 12 18 17 16 15 14
Output:
13 7 8 9 10 11
1 2 3 4 8 12 16 15 14 13 9 5 6 7
11 10
LOGIC
1. Initialization:
Initialize four variables: `k` for the starting row, `l` for the starting column, `m` for the ending row,
and `n` for the ending column.
2. Spiral Traversal:
While `k` is less than `m` and `l` is less than `n`, do the following:
Print the elements of the top row from index `l` to `n1`.
Increment `k`.
Print the elements of the rightmost column from index `k` to `m1`.
Decrement `n`.
If `k` is still less than `m`, print the elements of the bottom row from index `n1` to `l`.
Decrement `m`.
If `l` is still less than `n`, print the elements of the leftmost column from index `m1` to `k`.
Increment `l`.
3. Repeat Until Completion:
Repeat the above steps until all elements are printed.
This approach ensures that the matrix is traversed in a spiral manner, starting from the outer layer and moving
towards the center.
PYTHON CODE
def spiralPrint(a):
k, l, m, n = 0, 0, len(a), len(a[0])
while k < m and l < n:
for i in range(l, n):
print(a[k][i], end=" ")
k += 1
for i in range(k, m):
print(a[i][n - 1], end=" ")
n -= 1
if k < m:
for i in range(n - 1, l - 1, -1):
print(a[m - 1][i], end=" ")
m -= 1
if l < n:
for i in range(m - 1, k - 1, -1):
print(a[i][l], end=" ")
l += 1
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
spiralPrint(matrix)
JAVA CODE
import java.util.Scanner; System.out.print(a[m - 1][i] + " ");
}
class Main { m--;
static void spiralPrint(int m, int n, }
int a[][]) { if (l < n) {
int i, k = 0, l = 0; for (i = m - 1; i >= k; --i) {
while (k < m && l < n) { System.out.print(a[i][l] + "
for (i = l; i < n; ++i) { ");
System.out.print(a[k][i] + " }
"); l++;
} }
k++; }
for (i = k; i < m; ++i) { }
System.out.print(a[i][n - 1] + public static void main(String[]
" "); args) {
} Scanner scanner = new
n--; Scanner(System.in);
if (k < m) { System.out.print("Enter the number
for (i = n - 1; i >= l; --i) { of rows: ");
int R = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int C = scanner.nextInt();
int a[][] = new int[R][C];
System.out.println("Enter the matrix elements:");
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
a[i][j] = scanner.nextInt();
}
}
scanner.close();
spiralPrint(R, C, a);
}
}
0-1 KNAPSACK ALGORITHM
You are given N items that cannot be broken. Each item has a weight and value associated
with it.
Find the maximum value of items you can collect in the KnapSack so that the total weight
Output Format
Print the maximum value that can be collected with total weight less than or equal to W.
Example 1
Input
3 5
1 2 3
1 5 3
Output
Explanation
We can choose item number 2 and 3 to get the value as 5+3(8) and total weight as 5 which
Input
4 10
5 4 6 3
10 40 30 50
Output
90
Explanation
We can choose item number 2 and 4 to get the value as 40+50(90) and total weight as 7 which
(not necessarily contiguous) in which the elements are in strictly increasing order.
In other words, the Longest Increasing Subsequence problem asks for the length of the
longest subsequence such that all elements of the subsequence are sorted in ascending
order.
Consider the input sequence: [10, 22, 9, 33, 21, 50, 41, 60, 80]
The Longest Increasing Subsequence in this case is: [10, 22, 33, 50, 60, 80]
EXPLANATION
We start with the first element, 10, and consider it as the first element of a potential
increasing subsequence.
Move to the next element, 22. It's greater than 10, so we include it in the potential
subsequence.
Move to the next element, 9. It's less than 22, so we can't include it in the current
Move to the next element, 33. It's greater than 22, so we include it in the potential
subsequence.
EXPLANATION
Move to the next element, 21. It's less than 33, so we skip it.
Move to the next element, 50. It's greater than 33, so we include it in the potential
subsequence.
Move to the next element, 41. It's less than 50, so we skip it.
Move to the next element, 60. It's greater than 50, so we include it in the potential
subsequence.
Move to the next element, 80. It's greater than 60, so we include it in the potential
subsequence.
The final Longest Increasing Subsequence is [10, 22, 33, 50, 60, 80] with a length of 6.
LOGIC
1. Initialize:
Create an array `lis` of length `n` filled with 1s.
2. Dynamic Programming:
Iterate through each element in the array (index `i` from 1 to `n`).
For each element, compare it with previous elements.
If current element is greater than the previous one and can extend the LIS, update `lis[i]`.
3. Result:
Return the maximum value in the `lis` array, representing the length of the Longest
Increasing Subsequence.
PYTHON CODE
def lis(arr, n):
lis = [1] * n
max_length = 0
for i in range(n):
max_length = max(max_length, lis[i])
return max_length
# Example usage:
arr = [10, 22, 33, 50, 60, 80]
n = len(arr)
print(lis(arr, n))
JAVA CODE
class Main { max = lis[i];
static int lis(int arr[], int n) return max;
{ }
int lis[] = new int[n]; public static void main(String args[])
int i, j, max = 0; {
for (i = 0; i < n; i++) int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
lis[i] = 1; int n = arr.length;
for (i = 1; i < n; i++) System.out.println(lis(arr, n));
for (j = 0; j < i; j++) }
if (arr[i] > arr[j] && lis[i] < lis[j] + 1) }
lis[i] = lis[j] + 1;
for (i = 0; i < n; i++)
if (max < lis[i])
WILDCARD PATTERN MATCHING
You are given a pattern string containing letters and wildcard characters. The wildcard
character * can match any sequence of characters (including an empty sequence), and the
wildcard character ? can match any single character. Your task is to implement a function that
determines whether a given input string matches the provided pattern.
3. Fill 2D Array:
Iterate through each `i` and `j`.
If pattern at `j1` is '*', update `T[i][j] = T[i1][j] or T[i][j1]`.
If pattern at `j1` is '?' or matches word at `i1`, set `T[i][j] = T[i1][j1]`.
4. Result:
Return `T[n][m]`.
PYTHON CODE
def isMatch(word, pattern):
n = len(word)
m = len(pattern)
T = [[False] * (m + 1) for _ in range(n + 1)]
T[0][0] = True
for j in range(1, m + 1):
if pattern[j - 1] == '*':
T[0][j] = T[0][j - 1]
for i in range(1, n + 1):
for j in range(1, m + 1):
if pattern[j - 1] == '*':
T[i][j] = T[i - 1][j] or T[i][j - 1]
elif pattern[j - 1] == '?' or word[i - 1] == pattern[j - 1]:
T[i][j] = T[i - 1][j - 1]
return T[n][m]
# Example usage:
word = "xyxzzxy"
pattern = "x*****x?"
if isMatch(word, pattern):
print("Match")
else:
print("No Match")
JAVA CODE
public class Main { T[i][j] = T[i - 1][j - 1];
public static boolean isMatch(String word, String }
pattern) { }
int n = word.length(); }
int m = pattern.length(); return T[n][m];
boolean[][] T = new boolean[n + 1][m + 1]; }public static void main(String[] args) {
T[0][0] = true; String word = "xyxzzxy";
for (int j = 1; j <= m; j++) { String pattern = "x***x?";
if (pattern.charAt(j - 1) == '*') { if (isMatch(word, pattern)) {
T[0][j] = T[0][j - 1]; System.out.print("Match");
} } else {
} System.out.print("No Match");
for (int i = 1; i <= n; i++) { }
for (int j = 1; j <= m; j++) { }
if (pattern.charAt(j - 1) == '*') { }
T[i][j] = T[i - 1][j] || T[i][j - 1];
} else if (pattern.charAt(j - 1) == '?' ||
word.charAt(i - 1) == pattern.charAt(j -
1)) {
HOUSE ROBBER
You are a professional robber planning to rob houses along a street. Each house has a
certain amount of money stashed, the only constraint stopping you from robbing each of
them is that adjacent houses have security systems connected and it will automatically
contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the
maximum amount of money you can rob tonight without alerting the police.
Test cases:
Explanation: Rob house 1 (money = 1) and then
Example 1:
rob house 3 (money = 3).
Input: nums = [1,2,3,1]
Total amount you can rob = 1 + 3 = 4.
Output: 4
Test cases:
Explanation: Rob house 1 (money = 2), rob house
Example 2:
3 (money = 9) and rob house 5 (money = 1).
Input: nums = [2,7,9,3,1]
Total amount you can rob = 2 + 9 + 1 = 12.
Output: 12
LOGIC
1. Base Cases:
If no houses, no money can be robbed.
If only one house, rob the money in that house.
2. Dynamic Programming:
Create a list `dp` to store max robbed amounts.
3. Recurrence Relation:
To calculate max amount at each house, choose the maximum between:
Amount robbed without current house.
Amount robbed with the current house, plus the amount two houses ago.
4. Initialization:
Initialize first two values in `dp`.
5. Iterative Update:
Iterate through houses, updating `dp` based on the recurrence relation.
6. Result:
Result is the maximum amount in the `dp` list.
This method ensures choosing the best option at each house, either by skipping it or
considering it, to maximize the total amount robbed.
PYTHON CODE
class Solution:
def rob(self, nums):
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
return dp[-1]
solution = Solution()
nums1 = [1, 2, 3, 1]
print("Maximum amount you can rob:", solution.rob(nums1)) # Output: 4
nums2 = [2, 7, 9, 3, 1]
print("Maximum amount you can rob:", solution.rob(nums2)) # Output: 12
JAVA CODE
class Solution {
public int rob(int[] nums) {
final int n = nums.length;
if (n == 0)
return 0;
if (n == 1)
return nums[0];
// dp[i] := max money of robbing nums[0..i]
int[] dp = new int[n];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < n; ++i)
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
return dp[n - 1];
}
}
EDIT DISTANCE
Given two strings s1 and s2. Return the minimum number of operations
required to convert s1 to s2. The possible operations are permitted:
https://learn.codemithra.com