Sebi Coding Paper
Sebi Coding Paper
1. Sorting :-
1. BubbleSort -
void bubbleSort(int arr[])
{
int n = [Link];
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
2. SelectionSort -
void sort(int arr[])
{
int n = [Link];
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_idx]) {
min_idx = j;
} }
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
3. InserationSort -
void sort(int arr[])
{
int n = [Link];
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
4. QuickSort -
static int partition(int[] arr, int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for(int j = low; j <= high - 1; j++)
{
if (arr[j] < pivot)
{
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return (i + 1);
}
[Link] -
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
6. HeapSort -
heapify(arr, i, 0);
}
}
2. Searching -
1. BinarySearch -
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1; }
Kth Smallest Element in the Array : Best time complexity -
Reverse LinkedList -
reverse singly linked list -
Node reverse(Node node)
{
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = [Link];
[Link] = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
switch(c)
{
case '+':
[Link](val2+val1);
break;
case '-':
[Link](val2- val1);
break;
case '/':
[Link](val2/val1);
break;
case '*':
[Link](val2*val1);
break;
}
}
}
return [Link]();
}
}
}
if([Link]())
return true;
else return false;
}
// Driver code
public static void main(String args[])
{
int N = 3;
/*
row - Starting row index
m - ending row index
col - starting column index
n - ending column index
i - iterator
*/
while (row < m && col < n)
{
if (row + 1 == m || col + 1 == n)
break;
Binary Tree :
Insertion :
static void insert(Node temp, int key)
{
if (temp == null) {
root = new Node(key);
return;
}
Queue<Node> q = new LinkedList<Node>();
[Link](temp);
if ([Link] == null) {
[Link] = new Node(key);
break;
}
else
[Link]([Link]);
if ([Link] == null) {
[Link] = new Node(key);
break;
}
else
[Link]([Link]);
}
}
if (temp == delNode)
{
temp = null;
return;
}
if ([Link]!=null)
{
if ([Link] == delNode)
{
[Link] = null;
return;
}
else
[Link]([Link]);
}
if ([Link] != null)
{
if ([Link] == delNode)
{
[Link] = null;
return;
}
else
[Link]([Link]);
}
}
}
if (keyNode != null)
{
int x = [Link];
deleteDeepest(root, temp);
[Link] = x;
}
}
if ([Link] != null)
[Link]([Link]);
}
printLeaves([Link]);
// Print it if it is a leaf node
if ([Link] == null && [Link] == null)
[Link]([Link] + " ");
printLeaves([Link]);
}
if ([Link] != null) {
// to ensure top down order, print the node
// before calling itself for left subtree
[Link]([Link] + " ");
printBoundaryLeft([Link]);
}
else if ([Link] != null) {
[Link]([Link] + " ");
printBoundaryLeft([Link]);
}
if ([Link] != null) {
// to ensure bottom up order, first call for right
// subtree, then print this node
printBoundaryRight([Link]);
[Link]([Link] + " ");
}
else if ([Link] != null) {
printBoundaryRight([Link]);
[Link]([Link] + " ");
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
Divide and Conquer: Write your own pow(x, n) to calculate x*n,Median of two sorted arrays,
Count Inversions, Closest Pair of Points, Strassen’s Matrix Multiplication
Pattern Searching:
Naive Pattern Searching,KMP Algorithm, Rabin-Karp Algorithm,
Finite Automata, Boyer Moore Algorithm – Bad Character Heuristic,
Suffix Array, Anagram Substring Search (Or Search for all
permutations), Pattern Searching using a Trie of all Suffixes,
Aho-Corasick Algorithm for Pattern Searching, kasai’s Algorithm
for Construction of LCP array from Suffix Array
Backtracking: Print all permutations of a given string, The
Knight’s tour problem, Rat in a Maze, N Queen Problem, Subset Sum,
m Coloring Problem, Hamiltonian Cycle, Sudoku, Tug of War
------------------------------------------------------------------
------------------------------------------------------------------
Search ::
public Node search(Node root, int key)
{
// Base Cases: root is null or key is present at root
if (root==null || [Link]==key)
return root;
Insertion :
void insert(int key)
{
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
Node insertRec(Node root, int key)
{
Deletion ::
void deleteKey(int key)
{ root = deleteRec(root, key); }
/* A recursive function to
delete an existing key in BST
*/
Node deleteRec(Node root, int key)
{
/* Base Case: If the tree is empty */
if (root == null)
return root;
return root;
}
int minValue(Node root)
{
int minv = [Link];
while ([Link] != null)
{
minv = [Link];
root = [Link];
}
return minv;
}
------------------------------------------------------------------
------------------------------------------------------------------
BackTracking :
import [Link];
import [Link];
import [Link];
import [Link];
public static void main(String[] args) {
SnakeNLadder s = new SnakeNLadder();
[Link]();
}
}
class SnakeNLadder
{
final static int WINPOINT = 100;
if(currentPlayer == -1)
{
player1 = calculatePlayerValue(player1,diceValue);
[Link]("First Player :: " + player1);
[Link]("Second Player :: " + player2);
[Link]("------------------");
if(isWin(player1))
{
[Link]("First player wins");
return;
}
}
else
{
player2 = calculatePlayerValue(player2,diceValue);
[Link]("First Player :: " + player1);
[Link]("Second Player :: " + player2);
[Link]("------------------");
if(isWin(player2))
{
[Link]("Second player wins");
return;
}
}
currentPlayer= -currentPlayer;
}while("r".equals(str));
}
------------------------------------------------------------------------------------------------------------------------
SoDoku Problem ::
public class Sudoku {
// N is the size of the 2D matrix N*N
static int N = 9;
return true;
}
// Driver Code
public static void main(String[] args)
{
int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
if (solveSudoku(grid, 0, 0))
print(grid);
else
[Link]("No Solution exists");
}
// This is code is contributed by Pradeep Mondal P
}
------------------------------------------------------------------------------------------------------------------------
Integer to Roman -
public class IntegerToRoman
{
public static void intToRoman(int num)
{
[Link]("Integer: " + num);
int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] romanLetters = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
Roman to Integer ::
1. import [Link].*;
1. import [Link].*;
2. public class RomanToInteger2
3. {
4. public static void convertRomanToInt(String s)
5. {
6. Map<Character, Integer> map=new HashMap<Character, Integer>();
7. //adding elements to the Map
8. [Link]('I',1);
9. [Link]('V',5);
10. [Link]('X',10);
11. [Link]('L',50);
12. [Link]('C',100);
13. [Link]('D',500);
14. [Link]('M',1000);
15. s = [Link]("IV","IIII");
16. s = [Link]("IX","VIIII");
17. s = [Link]("XL","XXXX");
18. s = [Link]("XC","LXXXX");
19. s = [Link]("CD","CCCC");
20. s = [Link]("CM","DCCCC");
21. int number = 0;
22. //loop iterates over the roman numeral
23. for (int i = 0; i < [Link](); i++)
24. {
25. //getting each character of roman numeral and adding it to the variable number
26. number = number + ([Link]([Link](i)));
27. }
28. //prints the corresponding integer value
29. [Link]("The corresponding Integer value is: "+number);
30.}
31. //driver code
32. public static void main (String args[])
33. {
34. //function calling
35. convertRomanToInt("MCMXV");
36. }
37.}
38.}
-------------------------------------------------------------------------------------------------------
Form Maximum number from given Digit --
class GFG {
Iterator it = [Link]();
while ([Link]())
[Link]([Link]());
}
// Driver code
public static void main(String[] args)
{
Vector<String> arr;
arr = new Vector<>();
-------------------------------------------------------------------------------------------------------
For Calendar problem -
Use map -
Start for year count from given year to -1.
Years No. of odd
Ordinary year 1
Leap year 2
100 years 5
200 years 3
300 years 1
400 years 0
month – 31 – 3
30 – 2
28 – 0
29 – 1
Leap year – feb 29 - 1
Ordinary year – feb 28 - 0
-------------------------------------------------------------------------------------------------------
Tree Problem :
Binary Tree -
To get any order , we always need -
1. Inorder and preorder 2. Inorder and postorder
1.
public class PrintPost {
static int preIndex = 0;
void printPost(int[] in, int[] pre, int inStrt, int inEnd)
{
if (inStrt > inEnd)
return;
// Driver code
public static void main(String ars[])
{
int in[] = { 4, 2, 5, 1, 3, 6 };
int pre[] = { 1, 2, 4, 5, 3, 6 };
int len = [Link];
PrintPost tree = new PrintPost();
[Link](in, pre, 0, len - 1);
}
}
class Solution {
static class INT {
int data;
INT(int d) { data = d; }
}
findPostOrderUtil(pre, n, Integer.MIN_VALUE,
Integer.MAX_VALUE, preIndex);
}
// Driver code
public static void main(String args[])
{
int pre[] = { 40, 30, 35, 80, 100 };
int n = [Link];
// Calling function
findPostOrder(pre, n);
}
}
[Link]
2.
/* Java program to construct tree using inorder and
postorder traversals */
import [Link].*;
class GFG
{
// Base case
if (inStrt > inEnd)
return null;
// Driver code
public static void main(String[] args)
{
int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
int n = [Link];
Node root = buildTree(in, post, n);
[Link]("Preorder of the constructed tree : \n");
preOrder(root);
}
}
-------------------------------------------------------------------------------------------------------
// Java program to construct BST from given preorder traversal
import [Link].*;
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
class BinaryTree {
// Push root
[Link](root);
return root;
}
[Link]
-------------------------------------------------------------------------------------------------------
to reach up to number K.
* Add one to the operand
• Multiply the operand by 2.
class GFG{
// dp is initialised
// to store the steps
int dp[] = new int[k + 1];
for(int i = 1; i <= k; i++)
{
dp[i] = dp[i - 1] + 1;
// Driver Code
public static void main (String []args)
{
int K = 12;
[Link]( minOperation(K));
}
}
-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------
Lowest Common Ancestor in a BST --
}
Node lcabst(Node node,int n1,int n2)
{
if(node==null)
return null;
if([Link]==n1 || [Link]==n2)
return node;
if([Link]>n1 && [Link]>n2)
return lcabst([Link],n1,n2);
else if( [Link]<n1 && [Link]<n2)
return lcabst([Link],n1,n2);
return node;
}
-------------------------------------------------------------------------------------------------------
LEFT View OF TREE ::
void leftView(Node root)
{
// Your code here
if(root==null)
return;
n--;
}
[Link]([Link]+" ");
}
}
------------------------------------------------------------------------------------------
import [Link].*;
String in = [Link]();
char ch = [Link](i);
if([Link](ch))
{
re += ch;
}
}
[Link](ch);
}
}
while(![Link]())
{
if([Link]()=='(')
{
[Link]("Invalid");
}
re+=[Link]();
}
}
return -1;
}
}
1. Infix to Postfix
/* Java implementation to convert
infix expression to postfix*/
// Note that here we use ArrayDeque class for Stack
// operations
import [Link];
import [Link];
import [Link];
class Test {
result += [Link]();
[Link]();
}
[Link](c);
}
}
return result;
}
// Driver's code
public static void main(String[] args)
{
String exp = "a+b*(c^d-e)^(f+g*h)-i";
// Function call
[Link](infixToPostfix(exp));
}
}
3. Prefix to Infix -
Algorithm for Prefix to Infix:
• Read the Prefix expression in reverse order (from right to left)
• If the symbol is an operand, then push it onto the Stack
• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator between them.
string = (operand1 + operator + operand2) -----------> Yhi DIFF HAI
And push the resultant string back to Stack
• Repeat the above steps until the end of Prefix expression.
• At the end stack will have only 1 string i.e resultant string
4. Prefix to PostFix -
Algorithm for Prefix to Postfix:
• Read the Prefix expression in reverse order (from right to left)
• If the symbol is an operand, then push it onto the Stack
• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator after them.
string = operand1 + operand2 + operator -----------> Yhi DIFF HAI
And push the resultant string back to Stack
• Repeat the above steps until end of Prefix expression.
5. Postfix to Infix -
Algorithm for Postfix to Infix:
• Read the Postfix expression from left to right
• If the symbol is an operand, then push it onto the Stack
• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator before them.
string = operand2 + operator + operand1 -----------> Yhi DIFF HAI
( OP2 > OP1)
And push the resultant string back to Stack
• Repeat the above steps until end of Postfix expression.
6. PostFix to Prefix -
Algorithm for Postfix to Prefix:
• Read the Postfix expression from left to right
• If the symbol is an operand, then push it onto the Stack
• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator before them.
string = operator + operand2 + operand1 -----------> Yhi DIFF HAI
( OP2 > OP1)
And push the resultant string back to Stack
• Repeat the above steps until end of Postfix expression.
------------------------------------------------------------------------------------------------------------------------
Rate in The MAZE - moment allowed – forward and down
/* Java program to solve Rat in
a Maze problem using backtracking */
printSolution(sol);
return true;
}
return false;
}
N = [Link];
[Link](maze);
}
}
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
------------------------------------------------------------------------------------------------------------------------
String Questions -
[Link](ch)
[Link](ch)
int i = [Link](i) - ‘A’ --- 1
int j = [Link](j) – ‘a’ --- 1
int k = [Link](k) – ‘0’ – 1
To Count only English Alphbhets - Create array of 26
To Count all the char – create array of 256
A – Z – 65- 90
a – z - 97 – 122
0 – 9 - 47 - 58
Category No of letters unmatched
Pangram 0( all 26 char should be there)
Lipogram >1
Pangrammatic Lipogram 1
Anagram (same number of char in both string in any order)
Paliandrome ( same order of char s1 and resverse s1 )
// similar to [Link]
str = [Link]("\\p{Punct}","");
[Link](str);
}
Output = Welcome to GeeksforGeeks
2 . Rearrange the String such taht no two adjusent are same char
// Java program to rearrange characters in a string
// so that no two adjacent characters are same.
USE priority Queue -
import [Link].*;
import [Link].*;
class GFG {
static int MAX_CHAR = 26;
// Function to rearrange character of a string
// so that no char repeat twice
static void rearrangeString(String str)
{
int n = [Link]();
// Store frequencies of all characters in string
int[] count = new int[MAX_CHAR];
for (int i = 0; i < n; i++)
count[[Link](i) - 'a']++;
// Insert all characters with their
// frequencies into a priority_queue
PriorityQueue<Key> pq
= new PriorityQueue<>(new KeyComparator());
for (char c = 'a'; c <= 'z'; c++) {
int val = c - 'a';
if (count[val] > 0)
[Link](new Key(count[val], c));
}
// 'str' that will store resultant value
str = "";
// work as the previous visited element
// initial previous element be. ( '#' and
// it's frequency '-1' )
Key prev = new Key(-1, '#');
// traverse queue
while ([Link]() != 0) {
// pop top element from queue and
// add it to string.
Key k = [Link]();
[Link]();
str = str + [Link];
// If frequency of previous character
// is less than zero that means it is
// useless, we need not to push it
if ([Link] > 0)
[Link](prev);
// Driver's code
public static void main(String args[])
{
String str = "bbbaa";
// Function call
rearrangeString(str);
}
}
------------------------------------------------------------------------------------------------------------------------
Area of Histogram ::
//Java program to find maximum rectangular area in linear time
import [Link];
public class RectArea
{
// The main function to find the maximum rectangular area under given
// histogram with n bars
static int getMaxArea(int hist[], int n)
{
// Create an empty stack. The stack holds indexes of hist[] array
// The bars stored in stack are always in increasing order of their
// heights.
Stack<Integer> s = new Stack<>();
// If this bar is lower than top of stack, then calculate area of rectangle
// with stack top as the smallest (or minimum height) bar. 'i' is
// 'right index' for the top and element before top in stack is 'left index'
else
{
tp = [Link](); // store the top index
[Link](); // pop the top
// Now pop the remaining bars from stack and calculate area with every
// popped bar as the smallest bar
while ([Link]() == false)
{
tp = [Link]();
[Link]();
area_with_top = hist[tp] * ([Link]() ? i : i - [Link]() - 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
return max_area;
------------------------------------------------------------------------------------------------------------------------
All possible unique BST – with Value N
// A Java program to construct all unique BSTs for keys from 1 to n
import [Link];
public class Main {
// function for constructing trees
static ArrayList<Node> constructTrees(int start, int end)
{
ArrayList<Node> list=new ArrayList<>();
/* if start > end then subtree will be empty so returning NULL
in the list */
if (start > end)
{
[Link](null);
return list;
}
/* iterating through all values from start to end for constructing\
left and right subtree recursively */
for (int i = start; i <= end; i++)
{
/* constructing left subtree */
ArrayList<Node> leftSubtree = constructTrees(start, i - 1);
/* constructing right subtree */
ArrayList<Node> rightSubtree = constructTrees(i + 1, end);
/* now looping through all left and right subtrees and connecting
them to ith root below */
for (int j = 0; j < [Link](); j++)
{
Node left = [Link](j);
for (int k = 0; k < [Link](); k++)
{
Node right = [Link](k);
Node node = new Node(i); // making value i as root
[Link] = left; // connect left subtree
[Link] = right; // connect right subtree
[Link](node); // add this tree to list
}
}
}
return list;
}
// A utility function to do preorder traversal of BST
static void preorder(Node root)
{
if (root != null)
{
[Link]([Link]+" ") ;
preorder([Link]);
preorder([Link]);
}
}
public static void main(String args[])
{
ArrayList<Node> totalTreesFrom1toN = constructTrees(1, 3);
/* Printing preorder traversal of all constructed BSTs */
[Link]("Preorder traversals of all constructed BSTs are ");
for (int i = 0; i < [Link](); i++)
{
preorder([Link](i));
[Link]();
}
}
}
// node structure
class Node
{
int key;
Node left, right;
Node(int data)
{
[Link]=data;
left=right=null;
}
};
------------------------------------------------------------------------------------------------------------------------
// Java program to print ancestors of given node
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node
{
int data;
Node left, right, nextRight;
Node(int item)
{
data = item;
left = right = nextRight = null;
}
}
class BinaryTree
{
Node root;
/* If target is present in tree, then prints the ancestors
and returns true, otherwise returns false. */
boolean printAncestors(Node node, int target)
{
/* base cases */
if (node == null)
return false;
if ([Link] == target)
return true;
/* If target is present in either left or right subtree
of this node, then print this node */
if (printAncestors([Link], target) || printAncestors([Link], target))
{
[Link]([Link] + " ");
return true;
}
/* Else return false */
return false;
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* Construct the following binary tree
1
/\
2 3
/\
45
/
7
*/
[Link] = new Node(1);
[Link] = new Node(2);
[Link] = new Node(3);
[Link] = new Node(4);
[Link] = new Node(5);
[Link] = new Node(7);
[Link]([Link], 7);
}
}
4 2 1
------------------------------------------------------------------------------------------------------------------------
// Java program to check if binary tree is subtree of another binary tree
1. Using two way recussion we can do it.
2. Using inorder and preorder in two array( from original tree) and other inorder and
preorder( from subtree ) - in two other array and compare them if it’s subarray if
INORIGINAL to INSUB and PREORIGINAL to PRESUB, it’s subtree.
// A binary tree node
class Node
{
int data;
Node left, right, nextRight;
Node(int item)
{
data = item;
left = right = nextRight = null;
}
}
class BinaryTree
{
Node root1,root2;
/* A utility function to check whether trees with roots as root1 and
root2 are identical or not */
boolean areIdentical(Node root1, Node root2)
{
/* base cases */
if (root1 == null && root2 == null)
return true;
if (root1 == null || root2 == null)
return false;
/* Check if the data of both roots is same and data of left and right
subtrees are also same */
return ([Link] == [Link]
&& areIdentical([Link], [Link])
&& areIdentical([Link], [Link]));
}
// TREE 1
/* Construct the following tree
26
/\
10 3
/ \ \
4 6 3
\
30 */
tree.root1 = new Node(26);
[Link] = new Node(3);
[Link] = new Node(3);
[Link] = new Node(10);
[Link] = new Node(4);
[Link] = new Node(30);
[Link] = new Node(6);
// TREE 2
/* Construct the following tree
10
/\
4 6
\
30 */
// BST Node
static class Node
{
int key;
Node left, right;
public Node()
{}
// Base case
if (root == null)
return;
pre = tmp;
}
suc = tmp;
}
return;
}
// Go to right subtree
else
{
pre = root;
findPreSuc([Link], key);
}
}
return node;
}
// Driver code
public static void main(String[] args)
{
/*
* Let us create following BST
* 50
* /\
* 30 70
* /\/\
* 20 40 60 80
*/
findPreSuc(root, key);
if (pre != null)
[Link]("Predecessor is " + [Link]);
else
[Link]("No Predecessor");
if (suc != null)
[Link]("Successor is " + [Link]);
else
[Link]("No Successor");
}
}
Predecessor is 60
Successor is 70
------------------------------------------------------------------------------------------------------------------------
// An iterative java program to solve tree isomorphism problem
/* A binary tree node has data, pointer to left and right children */
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right;
}
}
class BinaryTree
{
Node root1, root2;
/* Given a binary tree, print its nodes in reverse level order */
boolean isIsomorphic(Node n1, Node n2)
{
// Both roots are NULL, trees isomorphic by definition
if (n1 == null && n2 == null)
return true;
// Exactly one of the n1 and n2 is NULL, trees not isomorphic
if (n1 == null || n2 == null)
return false;
if ([Link] != [Link])
return false;
// There are two possible cases for n1 and n2 to be isomorphic
// Case 1: The subtrees rooted at these nodes have NOT been
// "Flipped".
// Both of these subtrees have to be isomorphic.
// Case 2: The subtrees rooted at these nodes have been "Flipped"
return (isIsomorphic([Link], [Link]) && isIsomorphic([Link],[Link])) ||
(isIsomorphic([Link], [Link]) && isIsomorphic([Link], [Link]));
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create trees shown in above diagram
tree.root1 = new Node(1);
[Link] = new Node(2);
[Link] = new Node(3);
[Link] = new Node(4);
[Link] = new Node(5);
[Link] = new Node(6);
[Link] = new Node(7);
[Link] = new Node(8);
------------------------------------------------------------------------------------------------------------------------
For Time and Date and Day Calculator --
import [Link].*;
import [Link].*;
import [Link].*;
public class dateTime
{
public static void main(String arg[])
{
Scanner sc = new Scanner([Link]);
String in = [Link]();
LocalDate dd = [Link](2022,9,13);
Month m = [Link](dd);
DayOfWeek dd1 = [Link](dd);
[Link]([Link]()); [Link]([Link]()); }
---------------------------------------------------------------------------------------------------------------
import [Link];
class Test
{
// method to get length of the longest valid
static int findMaxLen(String str)
{
int n = [Link]();
Stack<Integer> stk = new Stack<>();
[Link](-1);
// Initialize result
int result = 0;
for (int i = 0; i < n; i++)
{
if ([Link](i) == '(')
[Link](i);
else
{
if(![Link]())
[Link]();
if (![Link]())
result= [Link](result,i - [Link]());
else
[Link](i);
}
}
return result;
}
// Driver code
public static void main(String[] args)
{
String str = "((()()";
// Function call
[Link](findMaxLen(str));
str = "()(()))))";
// Function call
[Link](findMaxLen(str));
}
}
---------------------------------------------------------------------------------------------------------------
l[0]=a[0];
for(i=1;i<n;i++)
l[i]=[Link](l[i-1],a[i]);
r[n-1]=a[n-1];
for(i=n-2;i>=0;i--)
r[i]=[Link](r[i+1],a[i]);
int water=0;
for(i=0;i<n;i++)
{
water+=[Link](l[i],r[i])-a[i];
}
[Link](water);
}
}
}
3 0 0 2 0 4 ->>> 10
------------------------------------------------------------------------------------------------
class GFG
{
// Java program to find Maximum Product Subarray
Dynamic Programming :
3. Edit Distance :
Find minimum number of edits (operations) required to convert
‘str1’ into ‘str2’.
[Link] (m,n-1) 2. Remove(m-1,n) 3. Replace(m-1.n-1)
static int editDist(String str1, String str2, int m,
int n)
{
if (m == 0)
return n;
if (n == 0)
return m;
if ([Link](m - 1) == [Link](n - 1))
return editDist(str1, str2, m - 1, n - 1);
return 1 + min(editDist(str1, str2, m, n - 1), // Insert
editDist(str1, str2, m - 1, n), // Remove
editDist(str1, str2, m – 1, n - 1) // Replace
);
}
[Link](minCost(cost, 2, 2));
//output 8
5. Coin Change --
coins[] = { coins1, coins2, .. , coinsn}
sum =
all possible denomination we have to find -
MatrixChainOrder(arr, 1, N - 1));
[Link] Coefficient --
// Check palindrome
for (int k = 0; k < (j - i + 1) / 2; k++)
{
if ([Link](i + k) != [Link](j - k))
flag = 0;
}
// Palindrome
if (flag!=0 && (j - i + 1) > maxLength) {
start = i;
maxLength = j - i + 1;
}
}
}
[Link]("Longest palindrome subString is: ");
printSubStr(str, start, start + maxLength - 1);
return maxLength;
}
static void printSubStr(String str, int low, int high)
{
for (int i = low; i <= high; ++i)
[Link]([Link](i));
}
if (rod_length <= n)
cut = price[index]
+ cutRod(price, index, n - rod_length);
----------------------------------------------------------------
BackTracking
Problems ::
[Link] and Ladder –
Using one Hashmap we
can do it.
class Solution
{
//Function to find a solved Sudoku.
static boolean SolveSudoku(int grid[][])
{
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
if(grid[i][j] == 0)
{
static boolean isValid(int[][] grid, int row, int col, int c){
for(int i=0; i<9; i++){
if(grid[i][col] == c) return false;
if(grid[row][i] == c) return false;
if (grid[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)
return false;
}
return true;
}
--------------------------------------------
Find all possible paths from top to bottom
Input: 1 2 3
4 5 6
Output: 1 4 5 6
1 2 5 6
1 2 3 6
Explanation: We can see that there are 3
paths from the cell (0,0) to (1,2).
class Solution {
public static void find(int i, int j, int n, int m, int [][]
grid,ArrayList<Integer> path, ArrayList<ArrayList<Integer>> paths){
if(i > n-1 || j > m-1){
return;
}
if(i == n-1 && j == m-1){
[Link](grid[i][j]);
[Link](new ArrayList<>(path));
return;
}
[Link](grid[i][j]);
find(i+1, j, n, m, grid, new ArrayList<Integer>(path), paths);
find(i, j+1, n, m, grid, new ArrayList<Integer>(path), paths);
}
return paths;
}
}
--------------------------------------------
LRU Cache Implementation
// Java program to implement LRU cache
// using LinkedHashSet
import [Link].*;
class LRUCache {
Set<Integer> cache;
int capacity;
while ([Link]())
[Link]([Link]() + " ");
}
if ([Link]() == capacity) {
int firstKey = [Link]().next();
[Link](firstKey);
}
[Link](key);
}
5 4 1 3
------------------------------------------------------------------------------------------------------------------------
Greedy Problems ::
1. Activity Selection Problem ;
1) Sort the activities according to their finishing time
2) Select the first activity from the sorted array and print it.
3) Do the following for the remaining activities in the sorted array.
…….a) If the start time of this activity is greater than or equal to the finish time of the previously
selected activity then select this activity and print it.
---------------------------------------------------------------------------------------------------------------
2. Job Sequencing Problem
1. Maximize the total profit if only one job can be scheduled at a time.
Input: Five Jobs with following deadlines and profits
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output: Following is maximum profit sequence of jobs: c, a, e
Greedily choose the jobs with maximum profit first, by sorting the jobs in decreasing order of
their profit. This would help to maximize the total profit as choosing the job with maximum profit
for every time slot will eventually maximize the total profit
// Java code for the above approach
import [Link].*;
class Job {
// Each job has a unique-id,profit and deadline
char id;
int deadline, profit;
// Constructors
public Job() {}
public Job(char id, int deadline, int profit)
{
[Link] = id;
[Link] = deadline;
[Link] = profit;
}
// Function to schedule the jobs take 2 arguments
// arraylist and no of jobs to schedule
void printJobScheduling(ArrayList<Job> arr, int t)
{
// Length of array
int n = [Link]();
// Sort all jobs according to decreasing order of
// profit
[Link](arr, (a, b) -> [Link] - [Link]);
// To keep track of free time slots
boolean result[] = new boolean[t];
// To store result (Sequence of jobs)
char job[] = new char[t];
// Iterate through all given jobs
for (int i = 0; i < n; i++) {
for (int j = [Link](t - 1, [Link](i).deadline – 1); j >= 0; j--)
{
// Free slot found
if (result[j] == false) {
result[j] = true;
job[j] = [Link](i).id;
break;
}
}
}
// Print the sequence
for (char jb : job)
[Link](jb + " ");
[Link]();
}
// Driver's code
public static void main(String args[])
{
ArrayList<Job> arr = new ArrayList<Job>();
[Link](new Job('a', 2, 100));
[Link](new Job('b', 1, 19));
[Link](new Job('c', 2, 27));
[Link](new Job('d', 1, 25));
[Link](new Job('e', 3, 15));
[Link]("Following is maximum profit sequence of jobs");
Job job = new Job();
//maximum time we need to pass
[Link](arr, 3);
}
}
Following is maximum profit sequence of jobs
c a e
--------------------------------------------------------------------------------
3. Huffman Coding :
1. Build a Huffman Tree from input characters.
import [Link];
import [Link];
import [Link];
class HuffmanNode {
int data;
char c;
HuffmanNode left;
HuffmanNode right;
}
}
class Huffman {
return;
printCode([Link], s + "0");
printCode([Link], s + "1");
// main function
// number of characters.
int n = 6;
hn.c = charArray[i];
[Link] = charfreq[i];
[Link] = null;
[Link] = null;
[Link](hn);
HuffmanNode x = [Link]();
[Link]();
HuffmanNode y = [Link]();
[Link]();
f.c = '-';
[Link] = x;
[Link] = y;
root = f;
[Link](f);
printCode(root, "");
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
---------------------------------------------------------
Prims Algorithm ::
// A Java program for Prim's Minimum Spanning Tree (MST)
// algorithm. The program is for adjacency matrix
// representation of the graph
import [Link].*;
import [Link].*;
import [Link].*;
class MST {
private static final int V = 5;
int minKey(int key[], Boolean mstSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;
return min_index;
}
// A utility function to print the constructed MST
// stored in parent[]
void printMST(int parent[], int graph[][])
{
[Link]("Edge \tWeight");
for (int i = 1; i < V; i++)
[Link](parent[i] + " - " + i + "\t"+ graph[i][parent[i]]);
}
void primMST(int graph[][])
{
// Array to store constructed MST
int parent[] = new int[V];
int key[] = new int[V];
// To represent set of vertices included in MST
Boolean mstSet[] = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is
// picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
{ if (graph[u][v] != 0 && mstSet[v] == false
&& graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// print the constructed MST
printMST(parent, graph);
}
public static void main(String[] args)
{
MST t = new MST();
int graph[][] = new int[][] { { 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 } };
// Print the solution
[Link](graph);
}
}
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
-------------------------------------------------------------------------------------------------------
class ShortestPath {
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}
return min_index;
}
// A utility function to print the constructed distance
// array
void printSolution(int dist[])
{
[Link]("Vertex \t\t Distance from Source");
for (int i = 0; i < V; i++)
[Link](i + " \t\t " + dist[i]);
}
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V]; // The output array.
Boolean sptSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
{
if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v]
< dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
// print the constructed distance array
printSolution(dist);
}
// Driver's code
public static void main(String[] args)
{
int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
ShortestPath t = new ShortestPath();
// Function call
[Link](graph, 0);
}
}
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
------------------------------------------------------------------------
// Java program for Kruskal's algorithm to
import [Link].*;
import [Link].*;
class Graph {
};
// union-find
class subset {
};
Graph(int v, int e)
{
V = v;
E = e;
if (subsets[i].parent != i)
return subsets[i].parent;
subsets[xroot].parent = yroot;
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
void KruskalMST()
int e = 0;
int i = 0;
[Link](edge);
subsets[v].parent = v;
subsets[v].rank = 0;
while (e < V - 1) {
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
int minimumCost = 0;
minimumCost += result[i].weight;
}
// Driver's Code
[Link][0].src = 0;
[Link][0].dest = 1;
[Link][0].weight = 10;
[Link][1].src = 0;
[Link][1].dest = 2;
[Link][1].weight = 6;
[Link][2].src = 0;
[Link][2].dest = 3;
[Link][2].weight = 5;
[Link][3].dest = 3;
[Link][3].weight = 15;
[Link][4].src = 2;
[Link][4].dest = 3;
[Link][4].weight = 4;
// Function call
[Link]();
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree: 19
---------------------------------------------------------------------------------------------------------------
Cycle Ditecttion in The Graph Using Union-Find Algo – Like Disjoint Set
// a graph
import [Link].*;
import [Link].*;
import [Link].*;
class Graph {
class Edge {
};
Graph(int v, int e)
V = v;
E = e;
if (parent[i] == i)
return i;
{
parent[x] = y;
parent[i] = i;
if (x == y)
return 1;
[Link](parent, x, y);
return 0;
// Driver Method
{
int V = 3, E = 3;
[Link][0].src = 0;
[Link][0].dest = 1;
[Link][1].src = 1;
[Link][1].dest = 2;
[Link][2].src = 0;
[Link][2].dest = 2;
if ([Link](graph) == 1)
else
---------------------------------------------------------------------------------------------------------------
Graph Problem ::
BFS:
import [Link].*;
1. import [Link].*;
2. public class BFSTraversal
3. {
4. private int vertex; /* total number number of vertices in the graph */
5. private LinkedList<Integer> adj[]; /* adjacency list */
6. private Queue<Integer> que; /* maintaining a queue */
7. BFSTraversal(int v)
8. {
9. vertex = v;
10. adj = new LinkedList[vertex];
11. for (int i=0; i<v; i++)
12. {
13. adj[i] = new LinkedList<>();
14. }
15. que = new LinkedList<Integer>();
16. }
17. void insertEdge(int v,int w)
18. {
19. adj[v].add(w); /* adding an edge to the adjacency list (edges are bidirectional in this
example) */
20. }
21. void BFS(int n)
22. {
23. boolean nodes[] = new boolean[vertex]; /* initialize boolean array for holding the d
ata */
24. int a = 0;
25. nodes[n]=true;
26. [Link](n); /* root node is added to the top of the queue */
27. while ([Link]() != 0)
28. {
29. n = [Link](); /* remove the top element of the queue */
30. [Link](n+" "); /* print the top element of the queue */
31. for (int i = 0; i < adj[n].size(); i++) /* iterate through the linked list and push all neig
hbors into queue */
32. {
33. a = adj[n].get(i);
34. if (!nodes[a]) /* only insert nodes into queue if they have not been explored alr
eady */
35. {
36. nodes[a] = true;
37. [Link](a);
38. }
39. }
40. }
41. }
42. public static void main(String args[])
43. {
44. BFSTraversal graph = new BFSTraversal(10);
45. [Link](0, 1);
46. [Link](0, 2);
47. [Link](0, 3);
48. [Link](1, 3);
49. [Link](2, 4);
50. [Link](3, 5);
51. [Link](3, 6);
52. [Link](4, 7);
53. [Link](4, 5);
54. [Link](5, 2);
55. [Link](6, 5);
56. [Link](7, 5);
57. [Link](7, 8);
58. [Link]("Breadth First Traversal for the graph is:");
59. [Link](2);
60. }
61.}
output : 2 4 7 5 8
DFS ::
import [Link].*;
•
• class DFSTraversal {
• private LinkedList<Integer> adj[]; /*adjacency list representation*/
• private boolean visited[];
•
• /* Creation of the graph */
• DFSTraversal(int V) /*'V' is the number of vertices in the graph*/
• {
• adj = new LinkedList[V];
• visited = new boolean[V];
•
• for (int i = 0; i < V; i++)
• adj[i] = new LinkedList<Integer>();
• }
•
• /* Adding an edge to the graph */
• void insertEdge(int src, int dest) {
• adj[src].add(dest);
• }
•
• void DFS(int vertex) {
• visited[vertex] = true; /*Mark the current node as visited*/
• [Link](vertex + " ");
•
• Iterator<Integer> it = adj[vertex].listIterator();
• while ([Link]()) {
• int n = [Link]();
• if (!visited[n])
• DFS(n);
• }
• }
•
• public static void main(String args[]) {
• DFSTraversal graph = new DFSTraversal(8);
•
• [Link](0, 1);
• [Link](0, 2);
• [Link](0, 3);
• [Link](1, 3);
• [Link](2, 4);
• [Link](3, 5);
• [Link](3, 6);
• [Link](4, 7);
• [Link](4, 5);
• [Link](5, 2);
•
• [Link]("Depth First Traversal for the graph is:");
• [Link](0);
• }
• }
OUTPUT :: 0 1 3 5 2 4 7 6
---------------------------------------------------------------------------------------------------------------
Topological Sorting -
// A Java program to print topological
// sorting of a DAG
import [Link].*;
import [Link].*;
// Constructor
Graph(int v)
{
V = v;
adj = new ArrayList<ArrayList<Integer> >(v);
for (int i = 0; i < v; ++i)
[Link](new ArrayList<Integer>());
}
// Driver code
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g = new Graph(6);
[Link](5, 2);
[Link](5, 0);
[Link](4, 0);
[Link](4, 1);
[Link](2, 3);
[Link](3, 1);
---------------------------------------------------------------------------------------------------------------
Tree Problems :
class Node {
int data;
Node(int item)
data = item;
class Tree {
Node root;
return null;
if (inStart == inEnd)
return new Node(inOrder[inStart]);
int index = 0;
if (data == inOrder[j]) {
index = j;
found = true;
break;
if (found == true)
break;
return startNode;
* tree */
void printInorder(Node node)
if (node == null)
return;
printInorder([Link]);
printInorder([Link]);
int n = [Link];
[Link](node);
4 8 10 12 14 20 20
2. PreOrder and PostOrder : Full Binary Tree
int data;
[Link] = data;
static node constructTreeUtil(int pre[], int post[], int l, int h, int size)
// Base case
return null;
preindex++;
int i;
if (post[i] == pre[preindex])
break;
if (i <= h)
return root;
preindex = 0;
if (root == null)
return;
printInorder([Link]);
printInorder([Link]);
int pre[] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 };
int post[] = { 8, 9, 4, 5, 2, 6, 7, 3, 1 };
printInorder(root);
8 4 9 2 5 1 6 3 7
import [Link].*;
class GFG
{
int data;
};
[Link] = data;
return (node);
// Base case
return null;
(index)--;
if (inStrt == inEnd)
return node;
[Link](in[i], i);
if (node == null)
return;
preOrder([Link]);
preOrder([Link]);
// Driver code
int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
int n = [Link];
preOrder(root);
1 2 4 8 5 3 6 7
---------------------------------------------------------------------------------------------------------------
Given Inorder Traversal of a Special Binary Tree in which the key of every node is
greater than keys in left and right children, construct the Binary Tree and return root.
class Node
int data;
Node(int item)
{
data = item;
class BinaryTree
Node root;
return null;
if (start == end)
return node;
return node;
max = arr[i];
maxind = i;
return maxind;
if (node == null)
return;
printInorder([Link]);
printInorder([Link]);
[Link](mynode);
5 10 40 30 28
---------------------------------------------------------------------------------------------------------------
10
/ \
-2 6
/ \ / \
8 -4 7 5
To 20(4-2+12+6)
/ \
4(8-4) 12(7+5)
/ \ / \
0 0 0 0
{
if (node == null)
return 0;
// Store the old value
int old_val = [Link];
[Link] = toSumTree([Link]) + toSumTree([Link]);
return [Link] + old_val;
}
---------------------------------------------------------------------------------------------------------------
1
/ \
2 3
/ \ \
4 5 6
Output:
12
/ \
6 3
/ \ \
4 5 6
{
if (root == null)
return 0;
if ([Link] == null && [Link] == null)
return [Link];
int leftsum = updatetree([Link]);
int rightsum = updatetree([Link]);
[Link] += leftsum;
return [Link] + rightsum;
}
---------------------------------------------------------------------------------------------------------------
Flip the Tree - In the flip operation, the leftmost node becomes the root of the flipped tree and its
parent becomes its right child and the right sibling becomes its left child and the same should be
done for all left most nodes recursively.
[Link]=[Link];
[Link]=root;
[Link]=[Link]=null;
return flippedRoot;
}
---------------------------------------------------------------------------------------------------------------
10 –> 8 –> 3
10 –> 8 –> 5
10 –> 2 –> 2
{
int path[] = new int[1000];
printPathsRecur(node, path, 0);
}
void printPathsRecur(Node node, int path[], int pathLen)
{
if (node == null)
return;
path[pathLen] = [Link];
pathLen++;
if ([Link] == null && [Link] == null)
printArray(path, pathLen);
else
{
printPathsRecur([Link], path, pathLen);
printPathsRecur([Link], path, pathLen);
}
}
---------------------------------------------------------------------------------------------------------------
Reverse tree path : Given a tree and node data, the task to reverse the
path to that particular Node.
We can use same concept as above , just need to check when root data is equal
to given particular node.
Input:
7
/ \
6 5
/ \ / \
4 3 2 1
Data = 4
Output: Inorder of tree
7 6 3 4 2 5 1
{
if (root == null)
return;
[Link](pathLen, root);
pathLen++;
// reversed
if ([Link] == key) {
int i = 0, j = pathLen - 1;
reverseTreePathUtil([Link], path,
pathLen, key);
reverseTreePathUtil([Link], path,
pathLen, key);
}
static void reverseTreePath(Node root, int key)
{
if (root == null)
return;
ArrayList<Node> path = new ArrayList<Node>();
for(int i = 0; i < 50; i++)
{
[Link](null);
}
reverseTreePathUtil(root, path, 0, key);
}
-----------------------------------------------------------------------------------------------
class BinaryTree {
Node root;
------------------------------------------------------------------------------------------------
Replace each node in binary tree with the sum of its inorder predecessor and
successor
- Do simple inorder and store the value in ArrayList the again do inorder and change value
of each node with [Link] = [Link](i-1) + [Link](i+1)
---------------------------------------------------------------------------------------------------------------
Input: {4, 3, 2, 1}
Output: 2
Explanation: Swap index 0 with 3 and 1 with 2 to form the sorted array {1, 2, 3,
4}.
// Java program to find
import [Link];
import [Link];
import [Link].*;
class GfG
int n = [Link];
ArrayList <Pair <Integer, Integer> > arrpos =new ArrayList <Pair <Integer,Integer> >
();
[Link](new Comparator<Pair<Integer,Integer>>()
@Override
return -1;
else if ([Link]().equals([Link]()))
return 0;
else
return 1;
});
[Link](vis, false);
int ans = 0;
if (vis[i] || [Link](i).getValue() == i)
continue;
int cycle_size = 0;
int j = i;
while (!vis[j])
vis[j] = true;
j = [Link](j).getValue();
cycle_size++;
if(cycle_size > 0)
}
return ans;
class MinSwaps
[Link]([Link](a));
---------------------------------------------------------------------------------------------------------------
Given the binary Tree and the two nodes say ‘a’ and ‘b’, determine whether the two nodes
are cousins of each other or not.
Two nodes are cousins of each other if they are at same level and have different parents.
/ \
3 5
/ \ / \
7 8 1 3
Say two node be 7 and 1, result is TRUE.
Say two nodes are 3 and 5, result is FALSE.
Say two nodes are 7 and 5, result is FALSE.
{
// Base case
if (node == null)
return false;
return (([Link] == a && [Link] == b) ||
([Link] == b && [Link] == a) ||
isSibling([Link], a, b) ||
isSibling([Link], a, b));
}
------------------------------------------------------------------------------------------------------------------------
int data;
Node(int item)
data = item;
}
}
class Leaf
int leaflevel=0;
class BinaryTree
Node root;
if (node == null)
return true;
if ([Link] == 0)
[Link] = level;
return true;
int level = 0;
if ([Link]([Link]))
else
Covered node: 6, 5, 7
Uncovered node: 9, 4, 3, 17, 22, 20
class BinaryTree
{
Node root;
int sum(Node t)
{
if (t == null)
return 0;
return [Link] + sum([Link]) + sum([Link]);
}
int uncoveredSumLeft(Node t)
{
if ([Link] == null && [Link] == null)
return [Link];
if ([Link] != null)
return [Link] + uncoveredSumLeft([Link]);
else
return [Link] + uncoveredSumLeft([Link]);
}
int uncoveredSumRight(Node t)
{
if ([Link] == null && [Link] == null)
return [Link];
if ([Link] != null)
return [Link] + uncoveredSumRight([Link]);
else
return [Link] + uncoveredSumRight([Link]);
}
int uncoverSum(Node t)
{
int lb = 0, rb = 0;
if ([Link] != null)
lb = uncoveredSumLeft([Link]);
if ([Link] != null)
rb = uncoveredSumRight([Link]);
if ([Link]([Link]))
[Link]("Sum of covered and uncovered is
same");
else
[Link]("Sum of covered and uncovered is
not same");
}
}
---------------------------------------------------------------------------------------------------------------
Output : True
{
int n = [Link] - 1;
for (int i=(n/2-1) ; i>=0 ; i--)
{
// Left child will be at index 2*i+1
// Right child will be at index 2*i+2
if (level[i] > level[2 * i + 1])
return false;
if (2*i + 2 < n)
{
if (level[i] > level[2 * i + 2])
return false;
}
}
return true;
}
---------------------------------------------------------------------------------------------------------------
{
int d = 0;
while (node != null)
{
d++;
node = [Link];
}
return d;
}
/* This function tests if a binary tree is perfect
or not. It basically checks for two things :
1) All leaves are at same level
2) All internal nodes have two children */
static boolean isPerfectRec(Node root, int d, int level)
{
if (root == null)
return true;
{
// if empty tree
if(node == null)
return true;
// if leaf node
if([Link] == null && [Link] == null )
return true;
// if none work
return false;
}
---------------------------------------------------------------------------------------------------------------
{
/* Base case : Both empty */
if (a == null && b == null)
return true;
1
/ \
2 3
/ \ / \
4 5 6 7
and pointer to a node say 5.
Output : 6, 7
{
if (root == node_to_find)
{
[Link]("Cousin Nodes : None" + "\n");
return;
}
}
}
if (found == true)
{
[Link]("Cousin Nodes : ");
size_ = [Link]();
if (size_ == 0)
[Link]("None");
for (int i = 0; i < size_; i++)
{
p = [Link]();
[Link]();
[Link]("");
return;
}
------------------------------------------------------------------
Perfect Binary Tree Specific Level Order Traversal
Output should be like - 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31
17 30 18 29 19 28 20 27 21 26 22 25 23 24
[Link]([Link]);
if ([Link] != null)
[Link](" " + [Link] + " " + [Link]);
if ([Link] == null)
return;
while (![Link]())
{
first = [Link]();
[Link]();
second = [Link]();
[Link]();
if ([Link] != null)
{
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
}
------------------------------------------------------------------
return root;
}
int maxPathSumUtil(Node node, Res res) {
// Base cases
if (node == null)
return 0;
if ([Link] == null && [Link] == null)
return [Link];
int ls = maxPathSumUtil([Link], res);
int rs = maxPathSumUtil([Link], res);
if ([Link] != null && [Link] != null) {
[Link] = [Link]([Link], ls + rs + [Link]);
return [Link](ls, rs) + [Link];
}
return ([Link] == null) ? rs + [Link]:ls + [Link];
}
return ans.v;
}
------------------------------------------------------------------
return root;
}
------------------------------------------------------------------
bstToArray([Link], arr);
[Link]([Link]);
bstToArray([Link], arr);
}
arrToMinHeap([Link], arr);
arrToMinHeap([Link], arr);
}
static void convertToMinHeap(Node root)
{
// initialize static index to zero
index = 0;
ArrayList<Integer> arr = new ArrayList<Integer>();
bstToArray(root, arr);
arrToMinHeap(root, arr);
}
------------------------------------------------------------------
Lowest Common Ancestor in a Binary Search Tree.
Node lca(Node node, int n1, int n2)
{
if (node == null)
return null;
return node;
}
------------------------------------------------------------------
------------------------------------------------------------------
MATRIX -
or
i--;
[Link]("");
}
/* through this for loop we choose each element
of last row as starting point (except the
[0][c-1] it has already been processed in
previous for loop) and print diagonal
starting at it. arr[R-1][0], arr[R-1][1]....
arr[R-1][c-1] are all starting points */
[Link]("");
}
}
// Driver code
public static void main(String[] args)
{
int arr[][] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 },
{ 17, 18, 19, 20 },
};
R = [Link];
C = arr[0].length;
// Function call
diagonalOrder(arr);
}
}
------------------------------------------------------------------
// Driver code
public static void main(String[] args)
{
int mat[][] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int n = 3;
printMatrixDiagonal(mat, n);
}
}
------------------------------------------------------------------
String -
for(int k=0;k<(j-i+1)/2;k++)
{
if([Link](i+k)!=[Link](j-k))
flag=0;
}
}
}
String re = [Link](start,start+maxlen);
return re;
}
------------------------------------------------------------------------------------------------------------------------
for(int i=0;i<n;i++)
{
arr[i]=[Link]();
}
List<Integer> al = [Link](arr);
HashMap<Integer,Integer> hc = new HashMap<>();
HashMap<Integer,Integer> hi = new HashMap<>();
for(int i=0;i<n;i++)
{
if([Link](arr[i]))
{
[Link](arr[i],[Link](arr[i])+1);
}
else
{
[Link](arr[i],1);
[Link](arr[i],i);
}
}
else
return 1;
}
});
// Initialize result
int ans = 0;
// Return result
return ans;
}
------------------------------------------------------------------------------------------------------------------------
or
boolean inorder(Node node,ArrayList<Node> al,int x)
{
if(node==null) return false;
[Link]([Link]);
if([Link]==x) return true;
[Link]([Link]()-1);
return false;
}
if(!inorder(node,al1,a) || !inorder(node,al2,b))
return -1;
int i;
for( i=0;i<[Link]() && i<[Link]();i++)
{
if([Link](i)!=[Link](i)) break;
}
int lca=[Link](i-1);
int d1=findD(lca,a,0);
int d2=findD(lca,b,0);
return d1+d2;
}
if([Link]==n) return d;
return left;
}
------------------------------------------------------------------------------------------------------------------------
-Min distance between two given nodes of a Binary Tree
public static int ans;
//Function that finds distance between two node.
public static int _findDistance(Node root, int n1, int n2)
{
if (root == null) return 0;
int left = _findDistance([Link], n1, n2);
int right = _findDistance([Link], n1, n2);
//if any node(n1 or n2) is found
if ([Link] == n1 || [Link] == n2)
{
if (left != 0 || right != 0)
{
ans = [Link](left, right);
return 0;
}
else
return 1;
}
//if current root is LCA of n1 and n2.
else if (left != 0 && right != 0)
{
ans = left + right;
return 0;
}
//if there is a descendant(n1 or n2).
else if (left != 0 || right != 0)
//increment its distance
return [Link](left, right) + 1;
//if neither n1 nor n2 exist as descendant.
return 0;
}
// The main function that returns distance between n1
// and n2.
public static int findDistance(Node root, int n1, int n2)
{
ans = 0;
_findDistance(root, n1, n2);
return ans;
}
------------------------------------------------------------------------------------------------------------------------
[Link](node);
boolean nullTrue=false;
while(![Link]())
{
Node temp=[Link]();
//[Link]([Link]);
if([Link]!=null)
{
if(nullTrue || [Link] > [Link])
return false;
[Link]([Link]);
}
else
nullTrue=true;
if([Link]!=null)
{
if(nullTrue || [Link] > [Link])
return false;
[Link]([Link]);
}
else nullTrue=true;
}
return true;
}
------------------------------------------------------------------------------------------------------------------------
Largest BST
static boolean checkBST(Node node,int min,int max)
{
if(node==null) return true;
if(checkBST(node,Integer.MIN_VALUE,Integer.MAX_VALUE))
{
int c=count(node);
// [Link](c);
ans= [Link](ans,c);
}
larBST([Link]);
larBST([Link]);
return ans;
}
------------------------------------------------------------------------------------------------------------------------
Connected Component in this Graph -
------------------------------------------------------------------------------------------------------------------------
000
000
200
[
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
------------------------------------------------------------------------------------------------------------------------