Merge Two Sorted Linked Lists
Merge Two Sorted Linked Lists
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
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, [Link] = l2
next=None): l2 = [Link]
[Link] = value current = [Link]
[Link] = next
# If any list is not exhausted,
def merge_sorted_lists(l1, l2): append the remaining nodes
# Dummy node to start the merged list if l1 is not None:
dummy = ListNode() [Link] = l1
current = dummy elif l2 is not None:
[Link] = l2
# Traverse both lists until one of
them is exhausted # Return the merged list starting
while l1 is not None and l2 is not from the dummy node's next
None: return [Link]
if [Link] < [Link]:
[Link] = l1 # Helper function to create a linked list
l1 = [Link] from a list of values
def create_linked_list(values):
if not values: # Sample sorted values for the first and
return None second lists
head = ListNode(values[0]) list1_values = [1, 3, 15, 67]
current = head list2_values = [2, 4, 6]
for value in values[1:]:
[Link] = ListNode(value) # Create two sorted linked lists
current = [Link] list1 = create_linked_list(list1_values)
return head list2 = create_linked_list(list2_values)
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
def __init__(self, value=0, are equal
next=None): def are_lists_equal(list1,
[Link] = value list2):
[Link] = next while list1 and list2:
if [Link] !=
def is_palindrome(head): [Link]:
# Function to reverse a linked return False
list list1 = [Link]
def reverse_list(node): list2 = [Link]
prev = None return True
while node:
next_node = [Link] # Find the middle of the linked
[Link] = prev list
prev = node slow = fast = head
node = next_node while fast and [Link]:
return prev slow = [Link]
fast = [Link]
# 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)
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.
groups.
PYTHON CODE
class ListNode: # Initialize pointers
def __init__(self, value=0, dummy = ListNode()
next=None): [Link] = head
[Link] = value current = dummy
[Link] = next
# Reverse nodes in groups of k
def reverse_k_elements(head, k): while [Link] is not None:
def reverse_group(curr, k): prev, start, end =
prev, temp = None, curr reverse_group([Link], k)
count = 0 [Link] = prev
[Link] = end
# Count the number of nodes in current = start
the group
while temp is not None and count return [Link]
< k:
next_node = [Link] # Helper function to create a linked list
[Link] = prev from a list of values
prev = temp def create_linked_list(values):
temp = next_node if not values:
count += 1 return None
head = ListNode(values[0])
return prev, curr, temp current = head
for value in values[1:]: # Create a linked list
[Link] = ListNode(value) head = create_linked_list(elements)
current = [Link]
return head # Reverse nodes in groups of k
result = reverse_k_elements(head, k)
# Helper function to print the linked
list # Print the result
def print_linked_list(head): print("\nResult:")
while head is not None: print_linked_list(result)
print([Link], end=" ")
head = [Link]
print()
Example 1:
5}
Inpu
t
Output:
Example 2:
Output:
PYTHON CODE
class ListNode: list1, list2 = temp1, temp2
def __init__(self, value=0,
next=None): if not head or not [Link]:
[Link] = value return head
[Link] = next slow = fast = head
def reorder_linked_list(head): while [Link] and
def reverse_list(node): [Link]:
prev, current = None, node slow = [Link]
while current: fast = [Link]
next_node = reversed_second_half =
[Link] reverse_list([Link])
[Link] = prev [Link] = None
prev = current merge_lists(head,
current = next_node reversed_second_half)
return prev return head
def merge_lists(list1, list2): def create_linked_list(values):
while list2: if not values:
temp1, temp2 = return None
[Link], [Link] head = ListNode(values[0])
[Link], [Link] current = head
= list2, temp1
for value in values[1:]: # Create a linked list
[Link] = linked_list =
ListNode(value) create_linked_list(elements)
current = [Link]
return head # Reorder the linked list
reorder_linked_list(linked_list)
def print_linked_list(head):
while head: # Print the result
print([Link], end=" → print("\nReordered Linked List:")
") print_linked_list(linked_list)
head = [Link]
print("None")
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
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.
beginning.
• Next, we find the odd numbers, which are 1 and 3. We keep their order
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
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:
[Link] = val return None
[Link] = next head = ListNode(values[0])
def oddEvenList(head): current = head
if not head or not [Link]: for value in values[1:]:
return head [Link] = ListNode(value)
# Separate odd and even nodes current = [Link]
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([Link], end=" ")
[Link] = head head = [Link]
odd = [Link] print()
else: # Get input from the user
[Link] = head elements = list(map(int, input("Enter the
even = [Link] elements of the linked list: ").split()))
is_odd = not is_odd head = create_linked_list(elements)
head = [Link] # Perform the operation
# Append even nodes to the end of odd nodes result = oddEvenList(head)
[Link] = even_head.next # Print the result
[Link] = 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; [Link] = newNode;
Node next; }
public Node(int data) { public void segregateEvenOdd() {
[Link] = data; if (head == null) {
[Link] = null; [Link]("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 = [Link];
} if (data % 2 == 0) { // even
Node current = head; node
while ([Link] != null) { if (evenHead == null) {
current = [Link]; evenHead = evenTail =
current;
} else { if (oddHead != null) {
[Link] = current; [Link] = null;
evenTail = current; }
} head = evenHead != null ? evenHead
} else { // odd node : oddHead;
if (oddHead == null) { }
oddHead = oddTail = current;
} else { public void printList() {
[Link] = Node current = head;
current; while (current != null) {
oddTail = current;
} [Link]([Link] + " ");
} current = [Link];
current = [Link]; }
} [Link]();
// Join even and odd lists }
if (evenHead != null) { }
[Link] = oddHead;
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link]("Original list:");
[Link]();
[Link]();
that has an equal number of '(' and ')' characters and is correctly closed.
Examples:
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
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] == '(':
[Link](i)
else:
[Link]()
if not stack:
[Link](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 [Link];
class Main {
public static void main(String[] args) {
String s = "(()";
Stack<Integer> st = new Stack<>();
int max = 0;
[Link](-1);
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
if (c == '(') {
[Link](i);
} else {
[Link]();
if ([Link]()) {
[Link](i);
} else {
int len = i - [Link]();
max = [Link](max, len);
}
}
}
[Link]("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
self.postfix_expression = [] and
def is_operator(self, ch): self.get_precedence(ch) <=
return ch in ['+', '-', '*', '/'] self.get_precedence(self.operator_stack[-
def get_precedence(self, operator): 1])):
if operator in ['+', '-']: self.postfix_expression.append([Link]
return 1 _stack.pop())
elif operator in ['*', '/']: self.operator_stack.append(ch)
return 2 while self.operator_stack:
else: self.postfix_expression.append([Link]
return 0 _stack.pop())
def infix_to_postfix(self, infix): return
for ch in infix: ''.join(self.postfix_expression)
if [Link](): def main():
self.postfix_expression.append(ch) infix_converter =
elif ch == '(': InfixToPostfixConverter()
infix_expression = input("Enter infix
self.operator_stack.append(ch) expression: ")
elif ch == ')': postfix_expression =
while self.operator_stack infix_converter.infix_to_postfix(infix_expre
and self.operator_stack[-1] != '(': ssion)
print(f"Infix: {infix_expression}")
self.postfix_expression.append([Link] print(f"Postfix: {postfix_expression}")
JAVA CODE
import [Link]; StringBuilder postfix = new
import [Link]; StringBuilder();
public class Main { Stack<Character> operatorStack = new
private static boolean isOperator(char Stack<>();
ch) { for (char ch : [Link]())
return ch == '+' || ch == '-' || ch {
== '*' || ch == '/'; if
} ([Link](ch)) {
private static int getPrecedence(char [Link](ch);
operator) { } else if (ch == '(') {
switch (operator) { [Link](ch);
case '+': } else if (ch == ')') {
case '-': while (!
return 1; [Link]() &&
case '*': [Link]() != '(') {
case '/':
return 2; [Link]([Link]());
default: }
return 0; [Link](); // Pop
} the '('
} } else if (isOperator(ch)) {
private static String while (!
infixToPostfix(String infix) { [Link]() && getPrecedence(ch)
[Link]([Link]());
}
[Link](ch);
}
}
while (![Link]()) {
[Link]([Link]());
}
return [Link]();
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter infix expression 1: ");
String infix1 = [Link]();
String postfix1 = infixToPostfix(infix1);
[Link]("Postfix expression 1: " + postfix1);
[Link]();
}
}
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 expression "3 + 4" is written as "3 4 +" in postfix notation.
Your goal is to implement a Java program that takes a postfix expression as input, evaluates it
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
✔ Initialize an empty stack for operands.
✔ If it is an operator (+, -, *, /), pop two operands from the stack, perform the operation and
✔ 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 = []
def evaluate_postfix(self, expression):
operators = {'+': lambda x, y: x + self.operand_stack.append(result)
y, return
'-': lambda x, y: x - self.operand_stack.pop()
y, def main():
'*': lambda x, y: x * postfix_evaluator =
y,
PostfixEvaluator()
'/': lambda x, y: x //
y} # Use // for integer division postfix_expression = input("Enter
for char in [Link](): the postfix expression: ")
if [Link](): result =
postfix_evaluator.evaluate_postfix(pos
self.operand_stack.append(int(char)) tfix_expression)
elif char in operators:
operand2 =
print("Result:", result)
self.operand_stack.pop() if __name__ == "__main__":
operand1 = main()
self.operand_stack.pop()
JAVA CODE
import [Link]; case '*':
import [Link]; [Link](operand1 *
public class Main { operand2);
public static int evaluatePostfix(String break;
expression) { case '/’:
Stack<Integer> stack = new [Link](operand1 /
Stack<>(); operand2);
for (char c : break;
[Link]()) { }
if ([Link](c)) { }
}
[Link]([Link](c)); return [Link]();
} else { }
int operand2 = [Link](); public static void main(String[] args) {
int operand1 = [Link](); Scanner scanner = new
switch (c) { Scanner([Link]);
case '+': [Link]("Enter the postfix
[Link](operand1 + expression: ");
operand2); String postfixExpression =
break; [Link]();
case '-': int result =
[Link](operand1 - evaluatePostfix(postfixExpression);
operand2); [Link]("Result: " +
break; result);
BASIC CALCULATOR
Design a basic calculator using a stack data structure. The calculator should be able to
calculator logic using a stack and provide a simple Java program that takes user input for
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
✔ 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.
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:
the functionality of a queue, which follows the First-In-First-Out (FIFO) principle, using two
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
[Link](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:
[Link]([Link]())
# Pop from stack2 to perform dequeue operation
if self.stack2:
return [Link]()
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: "))
[Link](enqueue_element)
elif choice == 2:
dequeued_element = [Link]()
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 [Link];
import [Link];
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
[Link](element);
}
public int dequeue() {
// Implement dequeue operation using stack2 if it's not empty, otherwise
transfer elements from stack1 to stack2
if ([Link]()) {
while (![Link]()) {
[Link]([Link]());
}
}
// Pop from stack2 to perform dequeue operation
if (![Link]()) {
return [Link]();
} else {
// Queue is empty
[Link]("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 [Link]() && [Link]();
}
}
public class Main {
public static void main(String[] args) {
QueueUsingStacks queue = new QueueUsingStacks();
Scanner scanner = new Scanner([Link]);
while (true) {
[Link]("\nChoose operation:");
[Link]("1. Enqueue");
[Link]("2. Dequeue");
[Link]("3. Check if the queue is empty");
[Link]("4. Exit");
int choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter the element to enqueue:");
int enqueueElement = [Link]();
[Link](enqueueElement);
break;
case 2:
int dequeuedElement = [Link]();
if (dequeuedElement != -1) {
[Link]("Dequeued element: " +
dequeuedElement);
}
break;
case 3:
[Link]("Is the queue empty? " +
[Link]());
break;
case 4:
[Link](0);
break;
default:
[Link]("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
1
/ \
3 2
/ \ / \
4 5 6 7
Test cases:
Explanation
Example 2 Original Tree was:
Input
5
5 8 7 / \
8 7
Output
New tree formed is:
5 7 8
5
/ \
7 8
LOGIC
• We use two stacks: currentLevel to store nodes at the current level, and nextLevel
for the next level.
• Start with the root node and push it onto currentLevel.
• While currentLevel is not empty:
• Pop a node from currentLevel.
• Print its data.
• If traversing from left to right, push its left and right children onto nextLevel if
they exist.
• If traversing from right to left, push its right and left children onto nextLevel if
they exist.
• If currentLevel becomes empty, switch the values of currentLevel and nextLevel.
• Repeat until all nodes are traversed.
PYTHON CODE
class Node: else:
def __init__(self, data): if [Link]:
[Link] = data next_level.append([Link])
[Link] = None if [Link]:
[Link] = None next_level.append([Link])
def zigzag_level_order_traversal(root): if not current_level:
if not root: left_to_right = not left_to_right
return current_level, next_level =
current_level = [] next_level, current_level
next_level = [] root = Node(1)
left_to_right = True [Link] = Node(2)
current_level.append(root) [Link] = Node(3)
while current_level: [Link] = Node(4)
node = current_level.pop() [Link] = Node(5)
print([Link], end=" ") [Link] = Node(6)
if left_to_right: [Link] = Node(7)
if [Link]: zigzag_level_order_traversal(root)
next_level.append([Link])
if [Link]:
next_level.append([Link])
JAVA CODE
import [Link]; String currVal = ip[i];
import [Link]; if () {
import [Link].*; [Link] = new
import [Link].*; Node([Link](currVal));
class Main { [Link]([Link]);
static Node buildTree(String str) { }
if ([Link]() == 0 || i++;
[Link](0) == 'N') {
return null; if (i >= [Link]) {
} break;
String ip[] = [Link](" "); }
Node root = new currVal = ip[i];
Node([Link](ip[0])); if () {
Queue<Node> queue = new [Link] = new
LinkedList<>(); Node([Link](currVal));
[Link](root); [Link]([Link]);
int i = 1; }
while ([Link]() > 0 && i < i++;
[Link]) { }
Node currNode = [Link](); return root;
[Link](); }
public static void main(String[] args) class Solution {
throws IOException { public static void
BufferedReader br = new binaryTreeZigZagTraversal(Node root) {
BufferedReader(new if (root == null) {
InputStreamReader([Link])); return;
String s1 = [Link](); }
Node root1 = buildTree(s1); Stack<Node> currentLevel = new
Solution g = new Solution(); Stack<>();
Stack<Node> nextLevel = new
[Link](root1); Stack<>();
} boolean leftToRight = true;
} [Link](root);
class Node {
int data; while (![Link]()) {
Node left; Node node =
Node right; [Link]();
Node(int data) { [Link]([Link] + " ");
[Link] = data;
left = null; if (leftToRight) {
right = null; if ([Link] != null) {
}
} [Link]([Link]);
}
if ([Link] != null) { if ([Link]()) {
leftToRight = !
[Link]([Link]); leftToRight;
} Stack<Node> temp =
} else { currentLevel;
if ([Link] != null) { currentLevel = nextLevel;
nextLevel = temp;
[Link]([Link]); }
} }
if ([Link] != null) { }
}
[Link]([Link]);
}
}
SUM ROOT TO LEAF NODES
Given a binary tree, where every node value is a Digit from 1-9. Find the sum of all the
self.tree_paths_sum_util([Link], val))
JAVA CODE
class Node { return treePathsSumUtil([Link], val) +
int data; treePathsSumUtil([Link], val);
Node left, right; }
Node(int item) { int treePathsSum(Node node) {
data = item; return treePathsSumUtil(node, 0);
left = right = null; }
}} }
class BinaryTree { public class Main {
Node root; public static void main(String args[]) {
int treePathsSumUtil(Node node, int val) BinaryTree tree = new BinaryTree();
{ [Link] = new Node(6);
if (node == null) [Link] = new Node(3);
return 0; [Link] = new Node(5);
val = (val * 10 + [Link]); [Link] = new Node(4);
if ([Link] == null && [Link] ==
null)
[Link] = new Node(2);
[Link] = new Node(5);
[Link] = new Node(4);
[Link] = new Node(7);
[Link]("Sum of all paths is " + [Link]([Link]));
}
}
BINARY RIGHT SIDE VIEW
You are given a root pointer to the root of binary tree. You have to print the right view of the
tree from top to bottom.
Note
The right view of a tree is the set of nodes that are visible from the right side.
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 contains the number of test cases.
The second line contains a string giving array representation of a tree, if the root has no
children give N in input.
Output Format
For each test case print the right view of the binary tree.
Example 1
Input
1
1 2 3
1
/ \
2 3
Output
1 3
Explanation
'1' and '3' are visible from the right side.
Example 2
Input:
1
1 2 3 N N 4
1
/ \
2 3
/
4
Output
1 3 4
Explanation
'1', '3', and '4' are visible from the right side.
LOGIC
1. Initialize an empty queue.
2. Enqueue the root of the tree.
3. While the queue is not empty:
Get the size of the current level (`level_size`).
Traverse the nodes at the current level:
Dequeue a node from the front of the queue.
If it is the last node in the level, add its value to the result (rightmost node).
Enqueue its left and right children (if they exist).
4. Return the result, which contains the values of the rightmost nodes at each level.
PYTHON CODE
from collections import deque
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None
class Solution:
def rightView(self, root):
result = []
if not root:
return result
queue = deque()
[Link](root)
while queue:
level_size = len(queue)
for i in range(level_size):
current = [Link]()
if i == level_size - 1:
[Link]([Link])
if [Link]:
[Link]([Link])
if [Link]:
[Link]([Link])
return result
def buildTree(arr):
if not arr or arr[0] == 'N':
return None
root = Node(int(arr[0]))
queue = deque([root])
i = 1
while queue and i < len(arr):
current_node = [Link]()
if arr[i] != 'N':
current_node.left = Node(int(arr[i]))
[Link](current_node.left)
i += 1
if i < len(arr) and arr[i] != 'N':
current_node.right = Node(int(arr[i]))
[Link](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 = [Link](root)
for x in arr:
print(x, end=" ")
print()
JAVA CODE
import [Link]; if (root == null) {
import [Link]; return list;
import [Link]; }
import [Link];
Queue<Node> q = new LinkedList<>();
import [Link];
[Link](root);
import [Link];
while (![Link]()) {
class Node { int n = [Link]();
int data; for (int i = 0; i < n; i++) {
Node left; Node curr = [Link]();
Node right; if (i == n - 1) {
[Link]([Link]);
Node(int data) { }
[Link] = data; if ([Link] != null) {
left = null; [Link]([Link]);
}
right = null;
if ([Link] != null) {
} [Link]([Link]);
} }
class Solution { } }
ArrayList<Integer> rightView(Node return list;
root) { }}
ArrayList<Integer> list = new
ArrayList<>();
public class Main { i++;
static Node buildTree(String str) {
if ([Link]() == 0 || [Link](0) if (i >= [Link])
== 'N') { break;
return null;
} currVal = ip[i];
if () {
String[] ip = [Link](" "); [Link] = new
Node root = new Node([Link](currVal));
Node([Link](ip[0])); [Link]([Link]);
Queue<Node> queue = new }
LinkedList<>(); i++;
[Link](root); }
int i = 1; return root;
}
while (![Link]() && i <
[Link]) { public static void main(String[] args)
Node currNode = [Link](); throws IOException {
BufferedReader br = new
String currVal = ip[i]; BufferedReader(new
if () { InputStreamReader([Link]));
[Link] = new int t =
Node([Link](currVal)); [Link]([Link]());
[Link]([Link]);
}
while (t-- > 0) {
String s = [Link]();
Node root = buildTree(s);
Solution tree = new Solution();
ArrayList<Integer> arr = [Link](root);
for (int x : arr)
[Link](x + " ");
[Link]();
}
}
}
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):
[Link] = value
[Link] = None
[Link] = None
def flatten(root):
if not root:
return
current = root
while current:
if [Link]:
# Find the rightmost node in the left subtree
rightmost = [Link]
while [Link]:
rightmost = [Link]
# Move the right subtree of the current node to the rightmost node
in the left subtree
[Link] = [Link]
# Set the left subtree as the new right subtree
[Link] = [Link]
# Set the left child to null
[Link] = None
# Move to the next node in the modified tree
current = [Link]
def print_linked_list(root):
while root:
print([Link], '*>', end=' ')
root = [Link]
print('null')
# Example usage:
# Constructing a sample binary tree
root = TreeNode(1)
[Link] = TreeNode(2)
[Link] = TreeNode(5)
[Link] = TreeNode(3)
[Link] = TreeNode(4)
[Link] = 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): [Link](curr_node.right)
[Link] = key i += 1
[Link] = None return root
[Link] = 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 [Link] == n1 or [Link] == n2:
root = Node(int(arr[0])) return root
queue = [root] left_lca = find_lca([Link], n1, n2)
i = 1 right_lca = find_lca([Link], n1,
while queue and i < len(arr): n2)
curr_node = [Link](0) if left_lca is not None and right_lca
curr_val = arr[i] is not None:
if curr_val != "-1": return root
curr_node.left = return left_lca if left_lca is not
Node(int(curr_val)) None else right_lca
[Link](curr_node.left) # Input
i += 1 s = input().split()
if i >= len(arr): root = build_tree(s)
break x, y = map(int, input().split())
curr_val = arr[i] # Find LCA
if curr_val != "-1": ans = find_lca(root, x, y)
print([Link] if ans else "N")
JAVA CODE
[Link]();
import [Link]; String currVal = ip[i];
import [Link]; if () {
import [Link].*; [Link] = new
import [Link].*; Node([Link](currVal));
class Main { [Link]([Link]);
static Node buildTree(String str) { }
if ([Link]() == 0 || i++;
[Link](0) == 'N') { if (i >= [Link]) break;
return null; currVal = ip[i];
} if () {
String ip[] = [Link](" "); [Link] = new
Node root = new Node([Link](currVal));
Node([Link](ip[0])); [Link]([Link]);
Queue<Node> queue = new }
LinkedList<>(); i++;
[Link](root); }
int i = 1;
while ([Link]() > 0 && i < [Link]) return root;
{ }
Node currNode = [Link]();
public static void main(String[] args) class Solution {
throws IOException { public static Node findLCA(Node
Scanner sc = new node,int n1,int n2) {
Scanner([Link]); if (node == null)
String s = [Link](); return null;
Node root = buildTree(s);
int x = [Link](); if ([Link] == n1 || [Link]
int y = [Link](); == n2)
Solution g = new Solution(); return node;
Node ans = [Link](root,x,y); Node left_lca = findLCA([Link],
[Link]([Link]); n1, n2);
} Node right_lca =
} findLCA([Link], n1, n2);
class Node { if (left_lca != null &&
int data; right_lca != null)
Node left; return node;
Node right; return (left_lca != null) ?
Node(int data) { left_lca : right_lca;
[Link] = data; }
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
kthSmallestHelper([Link], 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:
[Link] = None return None
class LNode: left = [Link](n // 2)
def __init__(self, data): root = [Link]([Link])
[Link] = data [Link] = left
[Link] = None [Link] = [Link]
[Link] = None [Link] = [Link](n
class TNode: - n // 2 - 1)
def __init__(self, data): return root
[Link] = data def countNodes(self, head):
[Link] = None count = 0
[Link] = None temp = head
def sortedListToBST(self): while temp is not None:
n = [Link]([Link]) temp = [Link]
return [Link](n) count += 1
return count
def push(self, new_data): if __name__ == "__main__":
new_node = [Link](new_data) llist = LinkedList()
new_node.prev = None [Link](7)
new_node.next = [Link] [Link](6)
if [Link] is not None: [Link](5)
[Link] = new_node [Link](4)
[Link] = new_node [Link](3)
def printList(self, node): [Link](2)
while node is not None: [Link](1)
print([Link], end=" ") print("Given Linked List ")
node = [Link] [Link]([Link])
def preOrder(self, node): root = [Link]()
if node is None: print("\nPre-Order Traversal of constructed BST
return ")
print([Link], end=" ") [Link](root)
[Link]([Link])
[Link]([Link])
JAVA CODE
class LinkedList { TNode sortedListToBST() {
static LNode head; int n =
class LNode { countNodes(head);
int data; return
LNode next, prev; sortedListToBSTRecur(n);
LNode(int d) { }
data = d;
next = prev = null; TNode sortedListToBSTRecur(int n)
}} {
class TNode { if (n <= 0)
int data; return null;
TNode left, right;
TNode(int d) { TNode left = sortedListToBSTRecur(n / 2);
data = d; TNode root = new TNode([Link]);
left = right = null; [Link] = left;
}} head = [Link];
[Link] = sortedListToBSTRecur(n - n / 2 new_node.prev = null;
- 1); new_node.next = head;
return root; if (head != null)
} [Link] = 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 = [Link]; [Link]([Link] + " ");
count++; node = [Link];
} }
return count; }
} void preOrder(TNode node) {
void push(int new_data) { if (node == null)
LNode new_node = new LNode(new_data); return;
[Link]([Link] + " "); [Link](1);
preOrder([Link]); [Link]("Given Linked List ");
preOrder([Link]); [Link](head);
} TNode root = [Link]();
public static void main(String[] args) { [Link]("");
LinkedList llist = new [Link]("Pre-Order
LinkedList(); Traversal of constructed BST ");
[Link](7); [Link](root);
[Link](6); }
[Link](5); }
[Link](4);
[Link](3);
[Link](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)
[Link] = true
for each v ∈ [Link][u]
if [Link] == false
DFS(G,v)
init() {
For each u ∈ G
[Link] = false
For each u ∈ G
DFS(G, u)
}
PYTHON CODE
from collections import defaultdict for adj in [Link][vertex]:
class Graph: if not [Link][adj]:
def __init__(self, vertices): [Link](adj)
[Link] = defaultdict(list) if __name__ == "__main__":
[Link] = [False] * vertices g = Graph(4)
def addEdge(self, src, dest): [Link](0, 1)
[Link][src].append(dest) [Link](0, 2)
def DFS(self, vertex): [Link](1, 2)
[Link][vertex] = True [Link](2, 3)
print(vertex, end=" ") print("Following is Depth First
Traversal")
[Link](2)
JAVA CODE
import [Link].*; void addEdge(int src, int dest) {
class Graph { adjLists[src].add(dest);
private LinkedList<Integer> }// DFS algorithm
adjLists[]; void DFS(int vertex) {
private boolean visited[]; visited[vertex] = true;
// Graph creation [Link](vertex + " ");
Graph(int vertices) { Iterator<Integer> ite =
adjLists = new adjLists[vertex].listIterator();
LinkedList[vertices]; while ([Link]()) {
visited = new boolean[vertices]; int adj = [Link]();
for (int i = 0; i < vertices; i+ if (!visited[adj])
+) DFS(adj);
adjLists[i] = new } }
LinkedList<Integer>();
public static void main(String args[]) {
Graph g = new Graph(4);
[Link](0, 1);
[Link](0, 2);
[Link](1, 2);
[Link](2, 3);
[Link](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 = [Link] V = len(graph)
min_index = -1 parent = [-1] * V
for v in range(V): key = [[Link]] * V
if not mstSet[v] and key[v] < mstSet = [False] * V
min_val: key[0] = 0
min_val = key[v] parent[0] = -1
min_index = v for _ in range(V - 1):
return min_index u = minKey(key, mstSet, V)
def printMST(parent, graph): mstSet[u] = True
V = len(graph) for v in range(V):
total_sum = 0 if graph[u][v] != 0 and not
for i in range(1, V): mstSet[v] and graph[u][v] < key[v]:
total_sum += graph[i][parent[i]]
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 += [Link](adj, seats, i,
[Link] = 0 src)
def minimum_fuel_cost(self, roads, if src != 0:
seats): [Link] += ceil(people / seats)
adj = [[] for _ in range(len(roads) + return people
1)] # Example Usage
n = len(roads) + 1 solution = Solution()
[Link] = 0 roads = [[3, 1], [3, 2], [1, 0], [0, 4], [0,
for a, b in roads: 5], [4, 6]]
adj[a].append(b) seats = 2
adj[b].append(a) result = solution.minimum_fuel_cost(roads,
[Link](adj, seats, 0, -1) seats)
return [Link] print(result)
def solve(self, adj, seats, src,
JAVA CODE
import [Link]; solve(adj, seats, 0, -1);
public class Solution { return ans;
private long ans = 0L; }
public long minimumFuelCost(int[][] roads, private long
int seats) { solve(ArrayList<ArrayList<Integer>> adj, int
ArrayList<ArrayList<Integer>> adj = new seats, int src, int parent) {
ArrayList<>(); long people = 1L;
int n = [Link] + 1; for (int i : [Link](src)) {
ans = 0L; if (i != parent) {
for (int i = 0; i < n; i++) { people += solve(adj, seats, i,
[Link](new ArrayList<>()); src);
} }
for (int[] a : roads) { }
[Link](a[0]).add(a[1]); if (src != 0) {
[Link](a[1]).add(a[0]); ans += (long) [Link]((double)
} people / 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 = [Link](roads, seats);
[Link](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
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:
def canFinish(self, n, prerequisites): no_prerequisites.add(neighbor)
G = defaultdict(list) return int(sum(degree) == 0)
degree = [0] * n # Input handling
for e in prerequisites: N, M = map(int, input().split())
G[e[1]].append(e[0]) prerequisites = [list(map(int,
degree[e[0]] += 1 input().split())) for _ in range(M)]
no_prerequisites = set(i for i in # Call the solution class
range(n) if degree[i] == 0) Obj = Solution()
while no_prerequisites: print([Link](N, prerequisites))
course = no_prerequisites.pop()
for neighbor in G[course]:
degree[neighbor] -= 1
JAVA CODE
import [Link].*;
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) [Link](i);
for (int i = 0; i < [Link](); ++i)
for (int j: G[[Link](i)])
if (--degree[j] == 0) [Link](j);
if([Link]() == n)
return 1;
else
return 0;
}}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int N= [Link]();
int M= [Link]();
int prerequisites[][] = new int[M][2];
for(int i=0; i<M; i++){
for(int j=0; j<2; j++)
prerequisites[i][j]= [Link]();
}
Solution Obj = new Solution();
[Link]([Link](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 2
Example 1
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<[Link]();i++){
possibleWords([Link](1),ans+[Link](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
if left == right: original order
# Base case: Print the current nums[left], nums[i] = nums[i],
permutation nums[left]
print(nums)
else: # Input handling
for i in range(left, right + 1): n = int(input("Enter the number of elements in
# Swap the current element with the the set: "))
element at index 'i' nums = list(map(int, input("Enter the elements
nums[left], nums[i] = nums[i], of the set: ").split()))
nums[left]
# Call the function to generate permutations
# Recursively generate permutations print("Permutations of the set:")
for the remaining elements generate_permutations(nums, 0, n - 1)
generate_permutations(nums, left +
1, right)
JAVA CODE
import [Link]; [Link]("Permutations of the set:");
public class PermutationsBacktracking { generatePermutations(nums, 0, n - 1);
public static void main(String[] args) { [Link]();
Scanner scanner = new Scanner([Link]); }
// Get input from the user private static void generatePermutations(int[] nums, int
[Link]("Enter the number of elements in the left, int right) {
set: "); if (left == right) {
int n = [Link](); // Base case: Print the current permutation
int[] nums = new int[n]; printArray(nums);
[Link]("Enter the elements of the set:"); } else {
for (int i = 0; i < n; i++) { for (int i = left; i <= right; i++) {
nums[i] = [Link]();
}
// Swap the current element with the element private static void swap(int[] nums, int i,
at index 'i' int j) {
swap(nums, left, i); int temp = nums[i];
nums[i] = nums[j];
// Recursively generate nums[j] = temp;
permutations for the remaining elements }
generatePermutations(nums, private static void printArray(int[]
left + 1, right); nums) {
// Backtrack: Undo the swap for (int num : nums) {
to restore the original order [Link](num + " ");
swap(nums, left, i); }
} [Link]();
}} }
}
COMBINATION SUM
Given an array of distinct integers nums and a target integer target,
return a list of all unique combinations of nums where the chosen
numbers sum to target. You may return the combinations in any order.
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())
[Link]()
nums = list(map(int,
result = []
[Link](result, [], nums, input().split()))
target, 0)
return result # Call the solution class
ob = Solution()
def backtrack(self, result, tempList, ans = [Link](nums, target)
nums, remain, start):
if remain < 0:
return # Sort the result
elif remain == 0: [Link](key=lambda x: (len(x), x))
[Link]([Link]())
else: # Print the result
for i in range(start, for combination in ans:
len(nums)):
[Link](nums[i])
print(*combination)
[Link](result,
tempList, nums, remain - nums[i], i)
[Link]()
JAVA CODE
import [Link].*; [Link](nums[i]);
class Solution { backtrack(list, tempList, nums, remain -
nums[i], i); // not i + 1 because we can
public List<List<Integer>> reuse same elements
combinationSum(int[] nums, int target) { [Link]([Link]()
List<List<Integer>> list = new - 1);
ArrayList<>(); }
[Link](nums); }
backtrack(list, new ArrayList<>(), }
nums, target, 0); }
return list; public class Main {
} public static void main(String args[])
{
private void backtrack(List<List<Integer>> Scanner sc = new
list, List<Integer> tempList, int [] nums, Scanner([Link]);
int remain, int start){ int n = [Link]();
if(remain < 0) return; int target = [Link]();
else if(remain == 0){ int []nums = new int[n];
[Link](new for(int i = 0 ; i < n ; ++i){
ArrayList<>(tempList)); nums[i] = [Link]();
} }
else{
for(int i = start; i < [Link];
i++){
Solution ob = new Solution();
List<List<Integer>> ans = [Link](nums,target);
for(int i = 0 ; i < [Link]() ; ++i){
[Link]([Link](i));
}
[Link](ans, (o1, o2) -> {
int m = [Link]([Link](), [Link]());
for (int i = 0; i < m; i++) {
if ([Link](i) == [Link](i)){
continue;
}else{
return [Link](i) - [Link](i);
}
}
return 1;
});
for (int i = 0; i < [Link] (); i++)
{
for (int j = 0; j < [Link](i).size (); j++)
{
[Link]([Link](i).get(j)+" ");
}
[Link]();
}}}
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.
generate_parenthesis_helper(open_count + 1,
close_count, current + "(")
if close_count < open_count:
generate_parenthesis_helper(open_count,
JAVA CODE
import [Link]; if ([Link]() == 2 * n) {
import [Link]; [Link](current);
import [Link]; return;
public class GenerateParentheses { }
public static List<String> if (openCount < n) {
generateParenthesis(int n) { generateParenthesisHelper(n,
List<String> result = new openCount + 1, closeCount, current + "(",
ArrayList<>(); result);
generateParenthesisHelper(n, 0, 0, }
"", result); if (closeCount < openCount) {
return result; generateParenthesisHelper(n,
} openCount, closeCount + 1, current + ")",
private static void result);
generateParenthesisHelper(int n, int }
openCount, int closeCount, String current, }
List<String> result) {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]();
List<String> combinations = generateParenthesis(n);
[Link]("Combinations of well-formed parentheses for n = " + n +
":");
for (String combination : combinations) {
[Link](combination);
}
}
}
LONGEST HAPPY PREFIX
A string is called a happy prefix if is a non-empty prefix which is also a suffix
(excluding itself).
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
1. Prefix and Suffix Matching:
• If at any point the current matching prefix length is equal to the length of
• 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
for i in range(1, n): prefix
while j > 0 and s[i] != s[j]: result =
j = prefix_function[j - 1]
longest_happy_prefix(input_str)
if s[i] == s[j]:
print("Longest Happy Prefix:",
j += 1
prefix_function[i] = j
result)
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
JAVA CODE
import [Link].*; res = [Link](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 [Link] {
while (right < [Link]()) { Scanner sc=new Scanner([Link]);
char r = [Link](right); String s = [Link]();
[Link](r, [Link](r,0) + Solution ob = new Solution();
1); int ans=[Link](s);
while ([Link](r) > 1) { [Link](ans);
char l = [Link](left); }
[Link](l, [Link](l) - }
1);
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):
if right1 - left1 > end - start:
def expand_around_center(left, right):
start, end = left1, right1
while left >= 0 and right < len(s)
if right2 - left2 > end - start:
and s[left] == s[right]:
start, end = left2, right2
left -= 1
right += 1
return s[start:end + 1]
return left + 1, right - 1
# Get input from the user
start, end = 0, 0
input_str = input("Enter a string: ")
for i in range(len(s)):
# Find and print the longest palindromic
left1, right1 =
substring
expand_around_center(i, i) # Odd-length
result =
palindrome
longest_palindromic_substring(input_str)
left2, right2 =
print("Longest Palindromic Substring:",
expand_around_center(i, i + 1) # Even-
result)
length palindrome
JAVA CODE
import [Link]; palindrom[i][j] = true;
class LongestPalindromicSubstring { if(j-i+1 > longestSoFar) {
private static String longestSoFar = j-i+1;
findLongestPalindromicSubstring(String startIndex = i;
input) { endIndex = j;
if([Link]()) { } } } }
return ""; return [Link](startIndex,
} endIndex+1);
int n = [Link](); }
int longestSoFar = 0, startIndex = 0, public static void main(String[] args) {
endIndex = 0; Scanner keyboard = new
boolean[][] palindrom = new boolean[n] Scanner([Link]);
[n]; String input = [Link]();
for(int j = 0; j < n; j++) { [Link](findLongestPalindromicSub
palindrom[j][j] = true; string(input));
for(int i = 0; i < j; i++) { }
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
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
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 [Link]; Scanner scanner = new Scanner([Link]);
public class Main { [Link]("Enter the length
public static int findPeakIndex(int[] arr) { of the array: ");
int left = 0; int n = 0;
int right = [Link] - 1; while (![Link]()) {
while (left < right) { [Link]("Invalid input.
int mid = left + (right - left) / 2; Please enter a valid integer.");
if (arr[mid] < arr[mid + 1]) { [Link](); // consume the
left = mid + 1; invalid input
} else { }
right = mid; n = [Link]();
}} [Link]("Enter the elements of
return left; // or right, they are equal the array separated by spaces: ");
at the end int[] arr = new int[n];
} for (int i = 0; i < n; i++) {
public static void main(String[] args) { while (![Link]()) {
[Link]("Invalid input. Please enter a valid integer.");
[Link](); // consume the invalid input
}
arr[i] = [Link]();
}
int peakIndex = findPeakIndex(arr);
[Link]("The peak index is: " + peakIndex);
[Link]();
}
}
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 [Link]; while (test_cases != 0) {
public class Main { [Link]("Enter the
public static void main(String args[]) { string:");
Scanner sc = new Scanner([Link]); String S = [Link]();
int test_cases = 0; int start = 0, end = 0, count =
while (true) { 0;
try { if ([Link]() < 3)
[Link]("Enter the number count = 0;
of test cases:"); else {
test_cases = [Link](); while (end < [Link]()) {
break; int hash[] = new
} catch ([Link] int[26];
e){ for (int i = start; i < end; i++)
[Link]("Invalid {
input. Please enter a valid integer."); hash[[Link](i) - 'a']++;
[Link](); }
count += [Link]() - end + 1;
start++;
} else {
end++;
}
}
}
[Link](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.
Explanation : trap “3 units” of
arr[] = {3, 0, 2, 0, 4}.
water between 3 and 2, “1 unit”
Three units of water can be stored in two indexes
on top of bar 2 and “3 units”
1 and 3, and one unit of water at index 2.
between 2 and 4.
Water stored in each index = 0 + 3 + 1 + 3 + 0
= 7
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 += [Link](left, right) - arr[i];
public static int maxWater(int[] arr, int n) }
{ return res;
for (int i = 1; i < n - 1; i++) { }
int left = arr[i]; public static void main(String[] args) {
for (int j = 0; j < i; j++) { int[] arr = { 1, 0, 2, 1, 0, 1};
left = [Link](left, arr[j]); int n = [Link];
} [Link](maxWater(arr, n));
int right = arr[i]; }
for (int j = i + 1; j < n; j++) { }
right = [Link](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 [Link]; [Link](a[m - 1][i] + "
");
class Main { }
static void spiralPrint(int m, int m--;
n, int a[][]) { }
int i, k = 0, l = 0; if (l < n) {
while (k < m && l < n) { for (i = m - 1; i >= k; --i)
for (i = l; i < n; ++i) { {
[Link](a[k][i] + " [Link](a[i][l] +
"); " ");
} }
k++; l++;
for (i = k; i < m; ++i) { }
[Link](a[i][n - 1] }
+ " "); }
} public static void main(String[]
n--; args) {
if (k < m) { Scanner scanner = new
for (i = n - 1; i >= l; --i) Scanner([Link]);
{ [Link]("Enter the
number of rows: ");
int R = [Link]();
[Link]("Enter the number of columns: ");
int C = [Link]();
int a[][] = new int[R][C];
[Link]("Enter the matrix elements:");
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
a[i][j] = [Link]();
}
}
[Link]();
spiralPrint(R, C, a);
}
}
0-1 KNAPSACK ALGORITHM
You are given N items that cannot be broken. Each item has a weight and value
Find the maximum value of items you can collect in the KnapSack so that the total
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
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
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
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
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
int i, j, max = 0; args[])
for (i = 0; i < n; i++) {
lis[i] = 1; int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60
for (i = 1; i < n; i++) };
for (j = 0; j < i; j++) int n = [Link];
if (arr[i] > arr[j] && lis[i] < lis[j] + 1) [Link](lis(arr, n));
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.
1. Initialize 2D Array:
Create a 2D array `T` of size `(n+1) x (m+1)`.
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 = [Link](); }
int m = [Link](); 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 ([Link](j - 1) == '*') { if (isMatch(word, pattern)) {
T[0][j] = T[0][j - 1]; [Link]("Match");
} } else {
} [Link]("No Match");
for (int i = 1; i <= n; i++) { }
for (int j = 1; j <= m; j++) { }
if ([Link](j - 1) == '*') { }
T[i][j] = T[i - 1][j] || T[i][j - 1];
} else if ([Link](j - 1) == '?'
||
[Link](i - 1) ==
[Link](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:
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:", [Link](nums1)) # Output: 4
nums2 = [2, 7, 9, 3, 1]
print("Maximum amount you can rob:", [Link](nums2)) # Output: 12
JAVA CODE
class Solution {
public int rob(int[] nums) {
final int n = [Link];
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] = [Link](nums[0], nums[1]);
for (int i = 2; i < n; ++i)
dp[i] = [Link](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: