Professional Documents
Culture Documents
Input Explanation:
The first line contains a single integer ‘N’ denoting the number of positive
integers.
Next line contains the integers to be stored
Output Explanation:
Print integers in order as stored in the hash table.
Sample Input 1:
4
3 2 13 1
Sample Output 1:
1 2 3 13
Sample Input 2:
4
3 13 1 4
Sample Output 2:
4 1 3 13
#Solution:
import java.util.*;
class LinearProbingHashTable {
Scanner sc=new Scanner(System.in);
private int tableSize;
private Integer[] table;
private int keysize;
Input Explanation:
The first line contains a single integer ‘N’ denoting the number of positive
integers.
Next line contains the integers to be stored
Output Explanation:
Print integers in order as stored in the hash table.
Sample Input 1:
4
3 2 13 1
Sample Output 1:
1 2 3 13
Sample Input 2:
4
3 13 1 4
Sample Output 2:
4 1 3 13
#Solution:
import java.util.*;
class QuadProbingHashTable
{
Scanner sc=new Scanner(System.in);
private int tableSize;
private Integer[] table;
private int keysize;
if (table[i]==null)
{
table[i]=key;
return;
}
for (int j = 0; j < tableSize; j++) {
table[t] = key;
return;
}
}
}
QuadProbingHashTable(int size)
{
this.tableSize=size;
this.table=new Integer[tableSize];
keysize=sc.nextInt();
for(int i=0;i<keysize;i++)
{
add(sc.nextInt());
}
void display()
{
for(int i=0;i<5;i++)
{
if(table[i]!=null) System.out.print(table[i]+" ");
}
}
}
public class Main {
public static void main(String[] args) {
QuadProbingHashTable QPHT =new QuadProbingHashTable(5);
QPHT.display();
}
}
Q.3. Maximum in continuous stream of data
Given an infinite stream of integers, find the maximum element at any point of
time.
Input Explanation:
The first line contains a single integer ‘N’ denoting the number of elements in
the stream.
Next line denotes elements of the stream.
Output Explanation:
Maximum element at any point of time.
Sample Input 1:
10
5 3 2 10 12 9 11 17 21 15
Sample Output 1:
5 5 5 10 12 12 12 17 21 21
Sample Input 2:
7
5 9 11 13 9 11 10
Sample Output 2:
5 9 11 13 13 13 13
#Solution:
import java.util.*;
class MaxInStream {
Scanner sc=new Scanner(System.in);
int numOfElements;
int[] elements;
MaxInStream()
{
numOfElements=sc.nextInt();
elements=new int[numOfElements];
for(int i=0;i<numOfElements;i++)
{
elements[i]=sc.nextInt();
}
}
int[] maxElement()
{
int[] ans = new int[numOfElements];
PriorityQueue<Integer> pq
= new PriorityQueue<>((a, b) -> a - b);
if (pq.size() < 1)
pq.add(elements[i]);
else {
if (elements[i] > pq.peek()) {
pq.remove();
pq.add(elements[i]);
}
}
ans[i] = pq.peek();
}
return ans;
}
void display()
{
int[] v = maxElement();
for (int it : v)
System.out.print(it + " ");
}
}
}
Q.4. Print Nodes of Specific Level
You are tasked with implementing a function to print the nodes of a specific
level in a binary search tree. The tree nodes contain integer values, and the
levels are 0-indexed.
Input Explanation:
Input consists of three lines,
Line 1: Total Number of Nodes for BST as N,
Line 2: N space separated Nodes to be inserted in BST,
Line 3: Level which you want to print as K.
Output Explanation:
Space separated Nodes from Kth level.
Sample Input 1:
5
43516
2
Sample Output 1:
16
Sample Input 2:
7
10 5 15 3 7 12 18
2
Sample Output 2:
3 7 12 18
#Solution:
import java.util.*;
class Node {
int data;
Node left, right;
if (level==1){
System.out.print(root.data + " ");
return;
}
return root;
}
int K = sc.nextInt();
PrintLevel(root, K+1);
}
}
Q.5. Identifying Leaf Nodes in a Binary Search Tree
You are given a Java program that constructs a binary search tree based on
user input and identifies and prints the leaf nodes of the tree. The program
defines a Node class representing individual nodes in the tree and includes a
LeafNodes method that prints the values of leaf nodes.
Input Explanation:
Input consists of two lines,
Line 1: Total Number of Nodes for BST as N,
Line 2: N space separated Nodes to be inserted in BST,
Output Explanation:
Space separated Leaf Nodes from BST.
Sample Input 1:
9
8 3 10 1 6 4 7 13 14
Sample Output 1:
1 4 7 14
Sample Input 2:
7
10 5 15 3 7 12 18
Sample Output 2:
3 7 12 18
#Solution:
import java.util.*;
class Node {
int Data;
Node left, right;
if (root.left != null)
LeafNodes(root.left);
if (root.right != null)
LeafNodes(root.right);
}
return root;
}
LeafNodes(root);
}
}
Q.6. Right View of a Binary Search Tree
You are provided with a Java program that constructs a binary search tree
based on user input and identifies and prints the right view of the tree. The
program defines a Node class representing individual nodes in the tree and
includes a RightView method that prints the values of nodes visible from the
right side of the tree.
Input Explanation:
Input consists of two lines,
Line 1: Total Number of Nodes for BST as N,
Line 2: N space separated Nodes to be inserted in BST,
Output Explanation:
Space separated Nodes which can be viewed from right side.
Sample Input 1:
9
8 3 10 1 6 4 7 13 14
Sample Output 1:
8 10 13 14
Sample Input 2:
7
10 5 15 3 7 12 18
Sample Output 2:
10 15 18
#Solution:
import java.util.*;
class Node {
int Data;
Node left, right;
RightView(root.right, RH+1);
RightView(root.left, RH+1);
}
return root;
}
Input Explanation:
Input consists of two lines,
Line 1: Total Number of Nodes for BST as N,
Line 2: N space separated Nodes to be inserted in BST,
Output Explanation:
Output consists of Integer value which will represent Height of binary search
tree.
Sample Input 1:
10
10 5 15 3 7 12 18 20 2 9
Sample Output 1:
4
Sample Input 2:
6
538279
Sample Output 2:
3
#Solution:
import java.util.*;
class Node {
int Data;
Node left, right;
return root;
}
Input Explanation:
Input consists of two lines,
Line 1: Total Number of Nodes for BST as N,
Line 2: N space separated Nodes to be inserted in BST,
Output Explanation:
Space separated Nodes which can be viewed from left side.
Sample Input 1:
9
8 3 10 1 6 4 7 13 14
Sample Output 1:
8314
Sample Input 2:
7
10 5 15 3 7 12 18
Sample Output 2:
10 5 3
#Solution:
import java.util.*;
class Node {
int Data;
Node left, right;
LeftView(root.left, RH+1);
LeftView(root.right, RH+1);
}
return root;
}
Input Explanation:
The program takes three lines of input from the user.
• The first line contains an integer N representing the number of
individuals in the community.
• The second line contains N space-separated integers, each representing
the unique identifier of an individual in the community, used to
construct the Binary Search Tree (BST).
• The third line contains two integers N1 and N2 representing the
identifiers of two individuals in the community for whom the LCA needs
to be determined.
Output Explanation:
The program outputs a single integer representing the unique identifier of the
Lowest Common Ancestor (LCA) of the two specified individuals in the
community.
Sample Input 1:
9
8 3 10 1 6 4 7 13 14
3 14
Sample Output 1:
8
Sample Input 2:
8
8 3 10 1 6 4 7 13
14 12
Sample Output 2:
-1
#Solution:
import java.util.*;
class Node {
int Data;
Node left, right;
return -1;
}
return root;
}
Note: The vault may also open if the last characters of previous guess and first
few or all characters match the vault password. For example if the word at
which the vault will open is “save” and the 2nd guess of thief is “hansa” and
3rd guess is “vein” then the vault will open at 3rd guess because last two
characters of “hansa” is “sa” and first two characters of “vein” is “ve” so it will
make “save” and the vault will open.
P.S. Use KMP Algorithm
Input Explanation:
1st Line: password of the vault
2nd Line: 5 passwords the leader wrote down in paper
Output Explanation:
Return the attempt number at which vault will open.
Return -1 if it doesn’t open
Sample Input 1:
save
fried hansa veins rambo jumbo
Sample Output 1:
3
Sample Input 2:
coffee
round think morocco fees light
Sample Output 2:
-1
#Solution:
import java.util.*;
class AttemptToOpenVault{
Scanner sc=new Scanner(System.in);
String password,attempts=""; String[] attemptpassword;
int[] attemptNumber=new int[5];
AttemptToOpenVault(){
password=sc.nextLine();
attemptpassword=sc.nextLine().split(" ");
for(int i=0;i<5;i++)
{attempts+=attemptpassword[i];attemptNumber[i]=attempts.length();}
}
void lpsArray(int[] lps){
int j=0,i=1;
lps[0]=0;
while(i<password.length()){
if(password.charAt(i)==password.charAt(j)){
j++;
lps[i]=j;
i++;
}
else{
if(j!=0) j=lps[j-1];
else {lps[i]=0;i++;}
}
}
}
void kmpAlgo(){
int[] lps=new int[password.length()];
int i=0,j=0;
lpsArray(lps);
while(i<attempts.length()){
if(password.charAt(j)==attempts.charAt(i)){
i++;j++;
}
if(j==password.length()){
if(i<=attemptNumber[0])System.out.println(1);
if(i>attemptNumber[0] &&
i<=attemptNumber[1])System.out.println(2);
if(i>attemptNumber[1] &&
i<=attemptNumber[2])System.out.println(3);
if(i>attemptNumber[2] &&
i<=attemptNumber[3])System.out.println(4);
if(i>attemptNumber[3] &&
i<=attemptNumber[4])System.out.println(5);
j=lps[j-1];
return;
}
else if(i<attempts.length() &&
password.charAt(j)!=attempts.charAt(i)){
if(j!=0) j=lps[j-1];
else i++;
}
}
System.out.println(-1);
}
}
public class Main{
public static void main(String[] args){
AttemptToOpenVault ATOV=new AttemptToOpenVault();
ATOV.kmpAlgo();
}
}
Q.11. All about Palindromes
Mananjay is playing with his son as well as teaching him about the
palindromes. So, he took out some scrabble tiles and now has some alphabet
tiles with different frequencies of each of those letters. First he arranged all
those alphabets in a random order giving him an arbitrary word. Now he has
started counting how many palindromes he can make using those alphabets
without disturbing the order in which he arranged them. Help him complete
this fun game.
Input Explanation:
Random word Mananjay made
Output Explanation:
Number of palindromes in that word that he can make
Sample Input 1:
aabab
Sample Output 1:
5
Sample Input 2:
ababab
Sample Output 2:
6
#Solution:
import java.util.*;
class AllAboutPalindromes{
Scanner sc=new Scanner(System.in);
String s;
AllAboutPalindromes(){
s=sc.next();
}
void palindromeSubStrs()
{
TreeMap<String , Integer> m = new TreeMap<>();
int n = s.length();
s = "@" + s + "#";
int i = 1;
while (i <= n)
{
while (s.charAt(i - rp - 1) == s.charAt(i +
j+
rp))
rp++;
R[j][i] = rp;
int k = 1;
while ((R[j][i - k] != rp - k) && (k < rp))
{
R[j][i + k] = Math.min(R[j][i - k],
rp - k);
k++;
}
rp = Math.max(rp - k,0);
i += k;
}
}
s = s.substring(1, s.length()-1);
m.put(s.substring(0,1), 1);
for (int i = 1; i < n; i++)
{
for (int j = 0; j <= 1; j++)
for (int rp = R[j][i]; rp > 0; rp--)
m.put(s.substring(i - rp - 1, i - rp - 1
+ 2 * rp + j), 1);
m.put(s.substring(i, i + 1), 1);
}
System.out.println(m.size());
}
}
public class Main
{
public static void main(String args[])
{
AllAboutPalindromes AAP=new AllAboutPalindromes();
AAP.palindromeSubStrs();
}
}
Q.12. Repeated Name
Mahesh was reading a book and realised that some words are repeated too
many times in the book. Can you write a Java program using Z-algorithm to
find how many times a word is being repeated in a given string?
Note: Rahul and rAhul are the same words and not different.
Input Explanation:
1st Line: String in which word is to be searched for
2nd Line: Word to be searched
Output Explanation:
Number of times word comes in given text.
Sample Input 1:
Rahulkllklfjohfohohfohoa
Rahul
Sample Output 1:
2
Sample Input 2:
maahiahimaahima
maahi
Sample Output 2:
2
#Solution:
import java.util.*;
class RepeatedName
{
Scanner sc=new Scanner(System.in);
String toSearch,inSearch;
int[] Z;
RepeatedName(){
inSearch=sc.nextLine();
toSearch=sc.nextLine();
}
void zArray()
{
String temp=toSearch+"$"+inSearch;
Z=new int[temp.length()];
int left=0, right=0,count=0;
for(int i=0; i<temp.length();i++){
if(i<=right){
Z[i]=Math.min(right-i+1, Z[i-left]);
}
while(i+Z[i]<temp.length() && Character.toLowerCase(temp.charAt(Z[i])) ==
Character.toLowerCase(temp.charAt(i+Z[i])))
Z[i]++;
if(i-Z[i]-1>right){
left=i;
right=i+Z[i]-1;}}
for(int i=toSearch.length()+1;i<temp.length();i++){
if(Z[i]==toSearch.length()){
count++;
}
}
System.out.println(count);
}
}
public class Random3
{
public static void main(String args[])
{
RepeatedName RN=new RepeatedName();
RN.zArray();
}
}
Q.13. Decipher the Alphabetic Code
While digging in his backyard, Anil has found a treasure box and a bottle with a
note inside it. The first line in the note says,” Biggers will be rewarded and the
Smalls will be slaughtered” and the second line is some arbitrary space
separated words which does not make any sense. After searching about such a
treasure and note online, he came to understand that the note holds the
password for the treasure box. The arbitrary space separated words actually
form a number which could be used to open the box.
The number of those arbitrary words in the note is the number of digits of the
required number to open the box. A word represents a digit which can not be
less than 0 and greater than 9. So if the word deciphered into a number comes
greater than 9, it is taken as 9 and if it comes less than 0, it is taken as 0. The
word can be transformed into a number by using following rules:
• Sum of values of each alphabet in the word gives the desired digit
Input Explanation:
Space separated words.
Output Explanation:
Returns the code number.
Sample Input 1:
ABc CDeF GHi akN
Sample Output 1:
0862
Sample Input 2:
AbCD CDeF
Sample Output 2:
68
#Solution:
import java.util.*;
class DecipherTheCode{
Scanner sc=new Scanner(System.in);
private String str; private int[] code; private int count=1;
DecipherTheCode(){
str=sc.nextLine();
for(int i=0;i<str.length();i++){
if((int) str.charAt(i)==32) count++;
}
code=new int[count];
}
void decipher(){
int i=0,j=0;
while(i<str.length()){
if((int)str.charAt(i)==32) {i++;j++;}
if((int)str.charAt(i)>90) code[j]-=(int)str.charAt(i)-96;
else code[j]+=(int)str.charAt(i)-64;
i++;
}
for(j=0;j<code.length;j++){
if(code[j]>9) code[j]=9;if(code[j]<0) code[j]=0;
System.out.print(code[j]);
}
}
}
public class Main{
public static void main(String[] args){
DecipherTheCode DTC= new DecipherTheCode();
DTC.decipher();
}
}
Q.14. Palindrome Obsession
Naman is so obsessed with palindromes that everywhere he sees a line or
word he starts thinking how he could make that line or word a palindrome.
Help him a write a Java program which guides him how many characters he has
to take off from the line/word so that it becomes a palindrome.
Input Explanation:
A string
Output Explanation:
Number of characters to delete to make it a palindrome.
Sample Input 1:
lifeefql
Sample Output 1:
2
Explanation:
Remove “i” and “q” to make it a palindrome.
Sample Input 2:
free to eearn
Sample Output 2:
4
Explanation:
Remove “f”, “o”, “a” and “n” to make it a palindrome
#Solution:
import java.util.*;
class PalindromeObsession
{
Scanner sc=new Scanner (System.in);
String str;
int n;
PalindromeObsession(){
str=sc.nextLine();
n=str.length();
}
void numOfChar()
{
int[][]lps=new int[n][n];
for(int i=0;i<n;i++) lps[i][i]=1;
for (int l = 2; l <= n; l++){
for (int i = 0; i < n - l + 1; i++)
{
int j = i + l - 1;
if (str.charAt(i) ==
str.charAt(j) && l == 2)
lps[i][j] = 2;
else if (str.charAt(i) ==
str.charAt(j))
lps[i][j] = lps[i + 1][j - 1] + 2;
else
lps[i][j] = Integer.max(lps[i][j - 1],
lps[i + 1][j]);
}
}
int count=n-lps[0][n-1];
System.out.println(count);
}
}
public class Main{
public static void main(String[] args){
PalindromeObsession PO =new PalindromeObsession();
PO.numOfChar();
}
}
Q.15. Magnetic Force
Arun has K(>1) very strong magnets with him. He had a container and divided it
into smaller spaces using cardboard so that no two magnets get attracted
towards each other and combine to get destroyed from the edges. He placed
some wood chips in some of the divisions he made in the container. Now he
has only N places to store the magnets which is sufficiently more or equal to K
magnets. The position of places which are empty are stored in an array. Now,
you need to place the magnets, such that the minimum distance between the
magnets is as large as possible. Return the largest minimum distance.
Input Explanation:
Line1:space separated number of places empty and number of magnets
Line2: space separated position of empty places.
Output Explanation:
Largest minimum distance between the magnets.
Sample Input 1:
64
0 3 4 7 10 9
Sample Output 1:
3
Sample Input 2:
52
42136
Sample Output 2:
5
#Solution:
import java.util.*;
class MagneticForce {
static boolean isCompatible(int arr[], int dist, int magnets) {
int n = arr.length;
int k = arr[0];
magnets--;
for (int i = 1; i < n; i++) {
if (arr[i] - k >= dist) {
magnets--;
if (magnets == 0) {
return true;
}
k = arr[i];
}
}
return false;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
int K=sc.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
Arrays.sort(arr);
int maxD = arr[size - 1] - arr[0];
int ans = Integer.MIN_VALUE;
for (int d = 1; d <= maxD; d++) {
boolean possible = isCompatible(arr, d, K);
if (possible) {
ans = Math.max(ans, d);
}
}
System.out.println(ans);
sc.close();
}
}
Q.16. MotoGP
Varun enjoys watching MotoGP. He invited his friend over the weekend at his
farm house and asked his friend to pick a racer and see who wins. They decide
to choose the racer such that the race is close . This can happen only if the
racers are comparable in their skill, i.e. the difference in their skills is less.
There are N racers participating in the race. The skill of the racer k is
represented by an integer T[k]. Varun and his friend need to pick 2 racers for
the race such that the difference in their skills is minimum. This way, it will be a
very interesting race. Your task is to help him do this and report the minimum
difference that is possible between 2 racers in the race.
Input Explanation:
Line1:Number of racers
Line2: space separated skills of each racer.
Output Explanation:
Minimum difference that is possible between the skills of racers.
Sample Input 1:
5
4 9 1 32 13
Sample Output 1:
3
Sample Input 2:
3
21 1 9
Sample Output 2:
8
#Solution:
import java.util.*;
import java.lang.Math;
class MotoGP
{
static void minSkill(int [] arr)
{
Arrays.sort(arr);
int minSkillDifference=Math.abs(arr[1]-arr[0]);
for(int i=1; i<arr.length; i++) {
minSkillDifference = Math.min(arr[i]-arr[i-1], minSkillDifference);
}
System.out.print(minSkillDifference);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
minSkill(arr);
sc.close();
}
}
Q.17. Number of Sticks
Mananjay has N sticks of K length. K being different or the same for every stick.
He just wants to know how many sticks of particular length L can he make
using only two or only a single of the sticks he has in stock. Two sticks or Single
stick used to make the stick of particular length L can not be used twice.
Input Explanation:
Line1: space separated number of sticks in stock N and Length L of the required
stick
Line2: space separated length of sticks in stock.
Output Explanation:
Return number of sticks Mananjay can form using the sticks in stock.
Sample Input 1:
5 13
4 9 1 32 13
Sample Output 1:
2
Sample Input 2:
3 11
21 1 9
Sample Output 2:
0
#Solution:
import java.util.*;
class NumberOfSticks
{
static void numSticks(int[] arr, int K,int N)
{
int count=0;
Arrays.sort(arr);
for(int i=0;i<N;i++)
{
if(arr[i]>K)
{
++i;
if(i>=N)break;
}
if(arr[i]==K)
{
++count;
++i;
if(i>=N)break;
}
int length=arr[i];
if(length<K)
{
for(int j=i+1;j<N;j++)
{
length+=arr[j];
if(length>K)
{
length-=arr[j];
}
if(length==K)
{
++count;
arr[j]=0;
break;
}
if(length<K)
{
length-=arr[j];
}
}
}
}
System.out.print(count);
}
}
Q.18. Swap Books
Akshay has been given a task to sort the books kept in the rack with respect to
the volume number of those books. Find out the minimum number of swaps
required to sort the books in strictly ascending order.
Input Explanation:
Line1:Number of books
Line2: space separated Volume number of books.
Output Explanation:
Minimum number of swaps required.
Sample Input 1:
5
4 7 11 9 8
Sample Output 1:
1
Sample Input 2:
3
21 1 9
Sample Output 2:
2
#Solution:
import java.util.*;
class SwapBooks
{
static int minSwaps(int[] arr)
{
int len = arr.length;
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<len;i++)
map.put(arr[i], i);
Arrays.sort(arr);
boolean[] visited = new boolean[len];
Arrays.fill(visited, false);
int ans = 0;
for(int i=0;i<len;i++) {
if(visited[i] || map.get(arr[i]) == i)
continue;
int j = i, cycle_size = 0;
while(!visited[j]) {
visited[j] = true;
j = map.get(arr[j]);
cycle_size++;
}
if(cycle_size > 0) {
ans += (cycle_size - 1);
}
}
return ans;
}
Input Explanation:
Line1: space separated size of array N and integer M whose ceiling number is
to be found out.
Line2: space separated N integers
Output Explanation:
Space separated Ceiling number K and its index if present, else -1
Sample Input 1:
3 10
21 1 9
Sample Output 1:
21 0
Sample Input 2:
5 12
4 7 11 9 8
Sample Output 2:
-1
#Solution:
import java.util.*;
public class CeilingNum {
static int ceiling=-1;
static void ceiling(int arr[],int target) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
Arrays.sort(arr);
int start=0;
int end=arr.length-1;
while(start<=end) {
int mid=(start+end)/2;
if(arr[mid]==target)
{ceiling=arr[mid];System.out.print(ceiling+" "+map.get(ceiling));return;}
if(arr[mid]<target) start=mid+1;
else end=mid-1;
}
if(start>arr.length-1) {System.out.print(-1);return;}
ceiling=arr[start];
System.out.print(ceiling+" "+map.get(ceiling));
}
Input Explanation:
Line1: space separated number of places empty and number of cows
Line2: space separated position of empty places.
Output Explanation:
Largest minimum distance between the cows.
Sample Input 1:
64
0 3 4 7 10 9
Sample Output 1:
3
Sample Input 2:
52
42136
Sample Output 2:
5
#Solution:
import java.util.*;
class AggressiveCows {
static boolean isCompatible(int arr[], int dist, int cows) {
int n = arr.length;
int k = arr[0];
cows--;
for (int i = 1; i < n; i++) {
if (arr[i] - k >= dist) {
cows--;
if (cows == 0) {
return true;
}
k = arr[i];
}
}
return false;
}
public static void main(String args[]) {
A user wants to organize folders in the directory structure, after inserting these
folders using the provided program, the user wants to know the contents of
the directory structure in different orders. (Inorder, Preorder, Postorder,
Levelorder)
Input Explanation:
Input consists of two lines,
Line 1: Total Number of Nodes for BST as N,
Line 2: N space separated Nodes to be inserted in BST.
Output Explanation:
Output consists of four lines,
Line 1: Space separated Inorder Traversal for BST with user input.
Line 2: Space separated Preorder Traversal for BST with user input.
Line 3: Space separated Postorder Traversal for BST with user input.
Line 4: Space separated Levelorder Traversal for BST with user input.
Sample Input 1:
7
1234567
Sample Output 1:
1234567
1234567
7654321
1234567
Sample Input 2:
5
42513
Sample Output 2:
12345
42135
13254
42513
#Solution:
import java.util.*;
class Main{
static class Node{
int Data;
Node left, right;
Node (int Data){
this.Data = Data;
left = right = null;
}
}
Inorder(root.left);
System.out.print(root.Data + " ");
Inorder(root.right);
}
while(!q.isEmpty()){
Node temp = q.poll();
System.out.print(temp.Data + " ");
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
}
}
return root;
}
Inorder(root);
System.out.println();
Preorder(root);
System.out.println();
Postorder(root);
System.out.println();
Levelorder(root);
}
}
Q.22. Republic Day Parade I
Like every year, the government hosted a grand Republic Day parade on
January 26, 2024, to showcase the military and cultural might of India. What's
special this year is the fact that this is the first Republic Day celebrations
hosted at the ceremonial boulevard after Rajpath was renamed Kartavya Path
last year. The 75th Republic Day Parade also saw one of the biggest
contingents from the Indian Air Force, who put on display a massive fleet of N
aircrafts. Now considering these aircrafts were numbered based on their
combat ability, they started flying at random and formed an AVL Tree
structure. After some time, one aircraft left the formation and remaining
aircrafts restructured as per AVL Tree deletion. The aircraft which left, left
from a Kth position of Top View of AVL Tree Structure.
Given a group of random numbers assigned to the aircrafts, find out what is
the order of aircraft numbers after the deletion in AVL Tree Structure if
PREORDER traversal is used.
Input Explanation:
The first line contains two space separated integers ‘N’ and ‘M’ where N is the
number of aircrafts and M is the aircraft number we have to remove.
The second line contains space separated positive integers denoting the
number assigned to the N aircrafts
Output Explanation:
Print the aircraft numbers using preorder traversal.
Sample Input 1:
53
10 8 12 9 11
Sample Output 1:
10 8 9 11
Sample Input 2:
73
25 20 36 10 22 30 40
Sample Output 2:
30 20 10 22 36 40
#Solution:
import java.util.*;
class RDParade{
int value;
int height;
Node left;
Node right;
Node(int value){
this.value=value;
height=0;
left=null;
right=null;
Node root;
RDParade(){
root=null;
return node.height;
if(node==null) return 0;
return getHeight(node.left)-getHeight(node.right);
}
Node leftRotate(Node x)
Node y= x.right;
Node T2=y.left;
x.right=T2;
y.left=x;
x.height=1+Math.max(getHeight(x.left),getHeight(x.right));
y.height=1+Math.max(getHeight(y.left),getHeight(y.right));
return y;
Node rightRotate(Node x)
Node y= x.left;
Node T2=y.right;
x.left=T2;
y.right=x;
x.height=1+Math.max(getHeight(x.left),getHeight(x.right));
y.height=1+Math.max(getHeight(y.left),getHeight(y.right));
return y;
if(node==null)
node=new Node(key);
return node;
if(node.value>key) node.left=insert(node.left,key);
if(node.value<key) node.right=insert(node.right,key);
node.height=1 + Math.max(getHeight(node.left),getHeight(node.right));
int balance=getBalance(node);
//Case 1 LL
//Case 2 RR
//Case 1 LR
node.left=leftRotate(node.left);
return rightRotate(node);
//Case 2 RL
node.right=rightRotate(node.right);
return leftRotate(node);
return node;
else//node==key
if(node.left==null || node.right==null){
Node temp=null;
if(temp==node.left) temp=node.right;
else temp=node.left;
if(temp==null) {
temp=node;
node=null;
else node=temp;
else {
Node temp=inOrderSuccessor(node.right);
node.value=temp.value;
node.right=remove(node.right,temp.value);
node.height=1+Math.max(getHeight(node.left),getHeight(node.right));
int balance=getBalance(node);
//Case 1 LL
//Case 2 RR
//Case 1 LR
node.left=leftRotate(node.left);
return rightRotate(node);
//Case 2 RL
node.right=rightRotate(node.right);
return leftRotate(node);
}
return node;
while(node.left!=null) node=node.left;
return node;
int hd;
Node node;
this.hd=hd;
this.node=node;
Q.add(new Pair(0,node));
while(!Q.isEmpty())
Pair pair=Q.poll();
if(!topViewMap.containsKey(pair.hd))
topViewMap.put(pair.hd,pair.node);
if(pair.node.left!=null)
Q.add(new Pair(pair.hd-1,pair.node.left));
if(pair.node.right!=null)
Q.add(new Pair(pair.hd+1,pair.node.right));
return topViewMap;
if(node!=null)
System.out.print(node.value+" ");
preOrder(node.left);
preOrder(node.right);
void doInsertTopViewRemovePreorder()
int numOfAircrafts;
int aircraftPosition2Remove;
int aircraftNumber2Remove;
numOfAircrafts=sc.nextInt();
aircraftPosition2Remove=sc.nextInt();
for(int i=0;i<numOfAircrafts;i++)
root=insert(root,sc.nextInt());
Map<Integer,Node> topViewMap=topView(root);
aircraftNumber2Remove=listAircrafts.get(aircraftPosition2Remove-
1).getValue().value;
root=remove(root,aircraftNumber2Remove);
preOrder(root);
}
}
RDP.doInsertTopViewRemovePreorder();
}
Q.23. Coin Change
Given an unlimited supply of coins of given denominations, find the minimum
number of coins required to get the desired change.
Input Explanation:
The first line contains two space separated integers ‘N’ and ‘M’ where N is the
change required and ‘M’ is the number of coin denominations.
Next line denotes ‘M’ coin denominations
Output Explanation:
Minimum number of coins required to get to desired change.
Sample Input 1:
22 4
1 2 5 10
Sample Output 1:
3
Sample Input 2:
30 4
2 5 15 20
Sample Output 2:
2
#Solution:
import java.util.*;
class CoinChange
{
Scanner sc=new Scanner(System.in);
int change,numCoins;
int[]coins;
CoinChange()
{
change=sc.nextInt();
numCoins=sc.nextInt();
coins=new int[numCoins];
for(int i=0;i<numCoins;i++)
{
coins[i]=sc.nextInt();
}
}
int minCoins()
{
int table[] = new int[change + 1];
table[0] = 0;
if(table[change]==Integer.MAX_VALUE)
return -1;
return table[change];
void display ()
{
System.out.println (minCoins());
}
}
Given a group of random numbers assigned to the aircrafts, find out what is
the order of aircraft numbers after the deletion in BST Tree Structure if
INORDER traversal is used.
Input Explanation:
The first line contains two space separated integers ‘N’ and ‘M’ where N is the
number of aircrafts and M is the aircraft number we have to remove.
The second line contains space separated positive integers denoting the
number assigned to the N aircrafts
Output Explanation:
Print the aircraft numbers using INORDER traversal.
Sample Input 1:
53
10 8 12 9 11
Sample Output 1:
8 9 10 11
Sample Input 2:
73
25 20 36 10 22 30 40
Sample Output 2:
10 20 22 30 36 40
#Solution:
import java.util.*;
class RDParadeII{
Scanner sc=new Scanner(System.in);
private class Node{
int value;
int height;
Node left;
Node right;
Node(int value){
this.value=value;
height=0;
left=null;
right=null;
}
}
Node root;
RDParadeII(){
root=null;
}
Node leftRotate(Node x)
{
Node y= x.right;
Node T2=y.left;
x.right=T2;
y.left=x;
x.height=1+Math.max(getHeight(x.left),getHeight(x.right));
y.height=1+Math.max(getHeight(y.left),getHeight(y.right));
return y;
}
Node rightRotate(Node x)
{
Node y= x.left;
Node T2=y.right;
x.left=T2;
y.right=x;
x.height=1+Math.max(getHeight(x.left),getHeight(x.right));
y.height=1+Math.max(getHeight(y.left),getHeight(y.right));
return y;
}
Node insert(Node node,int key)
{
if(node==null)
{
node=new Node(key);
return node;
}
if(node.value>key) node.left=insert(node.left,key);
if(node.value<key) node.right=insert(node.right,key);
return node;
}
Node inSuccess=inOrderSuccessor(node.right);
node.value=inSuccess.value;
node.right=remove(node.right,inSuccess.value);
}
return node;
}
Node inOrderSuccessor(Node node){
while(node.left!=null) node=node.left;
return node;
}
while(!Q.isEmpty())
{
Pair pair=Q.poll();
if(!topViewMap.containsKey(pair.hd))
topViewMap.put(pair.hd,pair.node);
if(pair.node.left!=null)
Q.add(new Pair(pair.hd-1,pair.node.left));
if(pair.node.right!=null)
Q.add(new Pair(pair.hd+1,pair.node.right));
}
return topViewMap;
}
void inOrder(Node node)
{
if(node!=null)
{
inOrder(node.left);
System.out.print(node.value+" ");
inOrder(node.right);
}
}
void doInsertTopViewRemovePreorder()
{
int numOfAircrafts;
int aircraftPosition2Remove;
int aircraftNumber2Remove;
numOfAircrafts=sc.nextInt();
aircraftPosition2Remove=sc.nextInt();
for(int i=0;i<numOfAircrafts;i++)
root=insert(root,sc.nextInt());
Map<Integer,Node> topViewMap=topView(root);
ArrayList<Map.Entry<Integer, Node>> listAircrafts = new
ArrayList<Map.Entry<Integer, Node>>(topViewMap.entrySet());
aircraftNumber2Remove=listAircrafts.get(aircraftPosition2Remove-
1).getValue().value;
root=remove(root,aircraftNumber2Remove);
inOrder(root);
}