Q. 1. Adding Nodes at the Beginning of a Linked List.
Suppose you are developing an application that requires the implementation of a dynamic
data structure to store and manage a list of items. You decide to use a singly linked list to
achieve this. You have been given a Java program that allows the user to input values and
inserts them at the beginning of the linked list.
Input Format
The user is first prompted to enter the number of nodes they want to insert at the beginning
of the linked list, Input should be an integer representing the number of nodes.
For each space separated node, the user is prompted to enter the value (integer) of the node.
Output Format
After inserting all the nodes at the beginning, the program will display the contents of the
linked list, Separated by space.
Sample input1
5
12345
Sample output1
54321
Sample input2
7
78 35 78 16 94 36 91
Sample output2
91 36 94 16 78 35 78
Q. 2. Remove Strings from LinkedList Based on Comparison.
Write a Java program that takes input from the user to create a LinkedList of strings and then
removes all the elements of the LinkedList that are less than or equal to a given string.
Hint: use import java.util.LinkedList class and its functions for example add, compareTo etc.
Input Format
First line input consists of an integer value n, that is size of linkedlist.
Second line input consists of n string values representing the elements of the linked list.
Third line input consists of a string value to be compared with the other strings in the
linkedlist.
Output Format
Output consists of string values after performing the expected operations.
NOTE: program will compare data by lexicographically.
Sample input1
4
apple banana cherry kiwi
cherry
Sample output1
[kiwi]
Sample input2
5
hi hello pune hellohello punjab
Punjab
Sample output2
[hi, hello, pune, hellohello, punjab]
Q.3. Java Program to Find the Length of the Longest String Using Recursion.
Write a Java program that takes input from the user of strings and then finds and prints the
length of the longest string using recursion only.
Input Format
First line input consists of sentence in string, input should be taken in String Array.
Output Format
Output consists of integer value, that is the length of longest string form above entered
elements in the arraylist.
Sample input1
Chitkara is Best University in Punjab
Sample output1
10
Explanation:
University is the longest word in give String, length of it is 10.
Sample input2
Welcome to chitkara rajpura campus
Sample output2
8
Explanation:
chitkara is the longest word in given String, length of it is 8.
Q. 4. Removing Duplicate Characters from a String.
Imagine you are developing a text processing tool, and you need to implement a Java program
that removes duplicate characters from a given input string. Write a program that takes user
input for a string and uses recursion to remove duplicate characters.
Input Format
The user should enter a string that they want to process, and the program will remove
consecutive duplicate characters from this input string.
Output Format
The program will print the resulting string after removing consecutive duplicate characters
from the input string.
Sample input1
banana
Sample output1
banana
Sample input2
programming
Sample output2
programing
Question 5. Cost of groceries
Question Statement: Chef visited a grocery store for fresh supplies. There are N items in the store where the ith
item has a freshness value Ai and cost Bi.
Chef has decided to purchase all the items having a freshness value greater than equal to X. find the total cost of
groceries the chef buys.
Input format:
Each test case consists of multiple lines of input.
The first line of each test case contains two space-separated integers
N and X — the number of items and the minimum freshness value an item should have.
The second line contains N space-separated integers, the array A, denoting the freshness value of each item.
The third line contains N space-separated integers, the array B, denoting the cost of each item.
Output Format:
For each test case, output on a new line, the total cost of the groceries Chef buys.
Example:
Input:
2 20 //N and X
15 67 //the array A, denoting the freshness value of each item
10 90 //the array B, denoting the cost of each item
Output:
90 //total cost of groceries the chef buys
Explanation:
Item 2 has freshness value greater than equal to X=20
Thus, Chef buys item 2
The total cost is 90
Question 6: Running with Alice and Bob
Question Statement: Alice and Bob recently got into running, and decided to compare how much they ran on
different days.
They each ran for N days — on the ith day, Alice ran Ai meters and Bob ran Bi meters. On each day,
Alice is unhappy if Bob ran strictly more than twice her distance, and happy otherwise.
Similarly, Bob is unhappy if Alice ran strictly more than twice his distance, and happy otherwise.
For example:
If Alice ran 200 meters and Bob ran 500, Alice would be unhappy but Bob would be happy.
If Alice ran 500 meters and Bob ran 240, Alice would be happy and Bob would be unhappy.
If Alice ran 300 meters and Bob ran 500, both Alice and Bob would be happy.
On how many of the N days were both Alice and Bob happy?
Input format:
Each test case consists of multiple lines of input.
The first line of the test case contains single integer N- number of days.
The second line contains N space-separated integers, the array A, the distance run by the Alice on the N days.
The third line contains N space-separated integers, the array B, the distance run by the Bob on the N days.
Output Format:
For each test case, output on a new line the number of days when both Alice and Bob were happy.
Example:
Input:
3 //N- number of days
100 200 300 //the array A, the distance run by the Alice on the N days
300 200 100 // the array B, the distance run by the Bob on the N days
Output:
1
Explanation:
Alice is unhappy on the first day, since she ran 100 meters but Bob ran 300; and 300 is more than twice
of 100.
Similarly, Bob is unhappy on the third day.
Both Alice and Bob are happy on the second day, so the answer is 1.
Question 7: Message Processing
Question Statement:
You are working on a chat application that needs to process user messages. The chat application receives
messages as input, and you need to remove any spaces present in the messages before displaying them on the
screen. The messages can contain multiple words, and there can be multiple spaces present after any word.
Write a Java program that takes a message as input and removes all spaces present in the message, including
any extra spaces that might occur after any word. In case of empty String, it should not return anything.
Input Format:
String S
Output Format:
Updated string
Constraints:
1 <= Length of string S <= 10^6
Example:
Input:
abc def g hi
Output:
Abcdefghi
Question 8: Kth Element from last Linked List
Given a linked list with n nodes. Find the kth element from last without computing the length of the linked list.
Input Format
First line contains space separated integers representing the node values of the linked list. The list ends when the input comes
as '-1'. The next line contains a single integer k.
Constraints
n < 10^5
Output Format
Output a single line containing the node value at the kth element from last.
Example:
Sample Input
1 2 3 4 5 6 -1
Sample Output
Note: The linked list is 1 2 3 4 5 6. -1 is not included in the list. So the third element from the last is 4
Question 9: Recursive Text Search Program.
Imagine you are working on a text analysis project, and you have a large body of text as a
single string. You want to search for specific words or phrases within this text. You've written a
Java program that takes the input of the larger text and the target word or phrase. The
program uses recursion to find all occurrences of the target word or phrase within the larger
text and then displays the positions (indices) where each occurrence is found.
Input Format
The first line of input should contain the larger string (the text in which you want to search for
occurrences of a substring).
The second line of input should contain the target substring (the word or phrase you want to
find).
Output Format
If the target substring is found in the larger string, the program prints the positions (indices)
where each occurrence starts. These positions are separated by spaces and presented in a
single line.
If the target substring is not found in the larger string, the program prints "-1" to indicate that
no occurrences were found.
Sample input1
abababababab
ab
Sample output1
[0, 2, 4, 6, 8, 10]
Sample input2
Hello this is java
Programming
Sample output2
-1
Question 10: Reversing a String with Preserved Space Positions.
You are tasked with creating a Java program that reverses a given string while preserving the
positions of spaces within the string. Your program should take a user-provided string as input
and then output the reversed string with spaces preserved.
Input Format
The program takes one line of input, which is a string containing a sequence of characters. The
input string can consist of letters, digits, spaces, and special characters.
Note: Please note that the input should be provided in a single line.
Output Format
The program outputs a single line, which is the reversed string with preserved space positions.
Sample input1
Java is fun!
Sample output1
!nuf si avaJ
Sample input2
This is a long string with spaces in between all words.
Sample output2
.sdr ow l lane ewtebn isec apshti wg nirtsgn ola sisihT
Coding Block Link: Coding Blocks IDE
Q. 11. Input Validation with Exception Handling.
A company has a program that processes employee data, including their names, IDs, and
salaries. Sometimes, the program encounters errors when processing the data, such as invalid
IDs or negative salaries. You need to implement exception handling to handle these errors and
display appropriate error messages to the user.
Note: if exception occurred in any input line, program will not continue it will just display
exception message.
Input Format
First line input consists of String value that is name of Employee,
Second line input consists of Integer value that is Employee ID,
Third input consists double value that is Salary of Employee.
Output Format
If the input is valid (name is a string containing only letters, id is a positive integer, and salary is
a non-negative double), it prints: “Data Processed”.
If the name contains numbers or special characters, it throws custom exception: “Invalid
Name”
If the id is non-positive (<= 0), it throws custom exception: “Invalid ID”
If the salary is negative (< 0), it throws custom exception: “Invalid Salary”
Sample input1
John
-1
Sample output1
Invalid ID
Sample input2
Sarah
1234
-5500
Sample output2
Invalid salary
Q. 12. Finding Productive Character Pairs in a String.
A company has to tag it’s products. Each product has an associated product type which is used
to tag the products. Product type is a sequence of lower-case letters from the English
alphabet. The company wants to have an algorithm for their system which takes the product
type and outputs the tag. To generate the tag, pairs of adjacent characters are formed from
the start of the product type. From each pair, the lexicographically smallest character will be
removed. If a character will be left unpaired then that character will be taken as it is in the tag.
Input Format
The input consists of a string - productType, representing the product type of the product.
Output Format
Print a string representing the tag for the given product. Note The product type consists of
lower-case letters from the English alphabet ('a' - 'z'). If both characters in a pair are the same,
then any character in the pair can be removed.
Sample input1
electronics
Sample output1
letois
Explanation:
The product type is "electronics". The pairing of characters is done as (el)(ec)(tr)(on)(ic)s. From
every pair, the characters removed are: e,c,r,n,c respectively. As the character "s" is left
unpaired, it will be kept for the tag as it is. the tag is: letois So, the output is letois
Sample input2
laptop
Sample output2
ltp
Q. 13. Triplet From LinkedList
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a
given number, say, Target. As any number of answers can be possible, return the first one you get while traversing.
Input Format
The First Line contains 3 Integers n, m and k as the Size of the Three LinedLists. Next 3 Lines contains n, m and k number of
integers respectively as the elements of Linked Lists. Next Line contains an Integer as Target.
Constraints
The Size of the Lists can be different.
Output Format
Display the 3 elements from each of the Lists whose sum is equal to the target separated by space.
Sample Input
3 3 3
12 6 29
23 5 8
90 20 59
101
Sample Output
6 5 90
Explanation
In the Given Sample Input, 6, 5 and 90 from lists 1, 2 and 3 respectively add to give 101.
Q 14 parenthesis
Samantha is working on a code editor that needs to ensure that every opening parenthesis in a line of code
has a corresponding closing parenthesis. She needs to check if the input string contains valid pairs of
parentheses.
Example:
s = "while (i < n) { sum += i; i++; }"
Samantha's program will scan through each character in the input string s and check if there are matching
opening and closing parentheses. In this case, the string contains multiple pairs of parentheses that are
balanced, so her program will return True.
Another example:
s = "if (x > 0 { y = 2x; }"
In this case, there is a missing closing parenthesis after "x > 0". Samantha's program will return False,
since the input string s is not valid.
Input First line contains the string
Q15 Good subarray
Question Statement:
given an array ‘arr’ consisting of ‘N’ elements, and an integer ‘s’. A non-empty subarray of ‘arr’ is good if it
contains exactly ‘s’ distinct integers. Your task is to return the number of good subarrays in the given array.
Input Format:
The first line contains the size of the array.
Second line of the input contains the integer ‘s’ denoting the number of distinct integers in the subarray. Third
line contains the array elements.
Output Format:
output prints the integer denoting the number of good subarrays in the given array.
Example:
Input:
5
2
12123
Output: 7
Explanation:
all the good subarrays is the above given array are : [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Input:
5
3
12123
Output: 3
Explanation:
all the good subarrays is the above given array are : [1,2,3], [2,1,2,3], [1,2,1,2,3]
Q16. Code-5 Mark
Q17. Code-5-Mark
Q18. Code-5-Mark
Q19. Code-5-Mark
Q20. Code-5-Mark
Q21. Code-5-Mark
You're developing a Java program that manages scores for a basic game. The game awards scores to players based
on their performance, and you're responsible for storing these scores in an array. To make the scores easily readable
for users, you've chosen to incorporate the bubble sort algorithm. This will help you arrange the scores in ascending
order, ensuring a neat presentation.
Your task is to implement the bubble sort algorithm to sort the player scores in the array in ascending order. After
sorting, display the sorted scores to the user.
Input Format
The first line of input should contain an integer numberOfScores, which represents the total number of game scores
to be sorted.
The next numberOfScores lines should each contain a single integer representing the individual game scores.
Output Format
The code will display the sorted game scores in ascending order, separated by spaces, after applying the bubble sort
algorithm.
Sample Input 1
10
1379462850
Sample Output 1
0123456789
Sample Input 2
12 36 63 78 95 102
Sample Output 2
12 36 63 78 95 102
Q22. Code-5-Mark
Q23. Code-5-Mark
Q24.
A ticket for an unlimited number of rides on all rickshaws and bus. It costs c4 ruppees.
Kumail Bhaiya knows for sure the number of rides he is going to make and the transport he is going to use. He
asked you for help to find the minimum sum of ruppees he will have to spend on the tickets.
Input Format
Each Test case has 4 lines which are as follows:
The first line contains four integers c1, c2, c3, c4 (1 ≤ c1, c2, c3, c4 ≤ 1000) — the costs of the tickets.
The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rickshaws and cabs Ramu is
going to use.
The third line contains n integers ai (0 ≤ ai ≤ 1000) — the number of times Ramu is going to use the rickshaw
number i.
The fourth line contains m integers bi (0 ≤ bi ≤ 1000) — the number of times Ramu is going to use the cab number
i.
Constraints
1 <= T <= 1000 , where T is no of testcases
1 ≤ c1, c2, c3, c4 ≤ 1000
1 ≤ n, m ≤ 1000
0 ≤ ai , bi ≤ 1000
Output Format
For each testcase , print a single number - the minimum sum of rupees Kumail will have to spend on the tickets in a
new line.
Sample Input
1 3 7 19
23
25
444
output
12
Explanation
Q25. code-10 marks
26. code-10 marks
Q27 code-10 marks
PrepBuddy is now tired of long problem statements of questions so he will provide you a simple question.
You are given a number N, you have to find the largest number less than or equal to N which fulfills the following
criteria.
Every digit of the number should be greater than or equal to its preceding digit.
Input Format
The first line contains an integer T where T is the number of test cases
For every Test case:
The next line contains one integer N.
Output format
For every test case print the answer in the new line.
Constraints
1 <= T <= 70
1 <= N <=10^5
Time Limit
1 second
Example
Sample Input
50
Sample Output
49
Sample test case explanation
Digits of 49 are 4 and 9, where 9 is greater than 4.
Q28. Code-5 Mark
You are working on a simple game in Java where players earn scores based on their performance. After each game,
you record the player's score in an array. To display the scores in a user-friendly way, you decide to implement the
bubble sort algorithm to sort the scores in ascending order.
Your task is to implement the bubble sort algorithm to sort the player scores in the array in ascending order. After
sorting, display the sorted scores to the user.
Input Format
The first line of input should contain an integer numberOfScores, which represents the total number of game scores
to be sorted.
The second line of input should contain space seperated integer representing the individual game scores.
Output Format
The code will display the sorted game scores in ascending order, separated by spaces, after applying the bubble sort
algorithm.
NOTE: Solve the code with steps mentioned above, don't use any pre-defined methods.
Sample Input 1:
10
1379462850
Sample Output 1:
0123456789
Sample Input 2:
12 36 63 78 95 102
Sample Output 2:
12 36 63 78 95 102
Q28. Code-5 Mark
You are a Computer Science teacher at a local high school. Your students have just taken a multiple-choice exam,
and you need to grade their exams using a Java program. Each student's exam consists of 10 questions, and the
answer choices for each question are labeled A, B, C, D, and E.
You have the following data:
The students' answers, stored in a 2D array char[][] answers, where each row corresponds to a student and each
column corresponds to a question.
The correct answers, stored in an array char[] keys, where each element represents the correct answer for a
question.
Your task is to write a Java program that grades each student's exam and prints the correct count of answers for
each student.
Answer Key : char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
Input Format
First line of program will prompt the user to enter the number of students taking the exam.
For each student, the program will prompt the user to enter their answers for each of the 10 questions.
Output Format
Output consists line separated integer values, i.e. count of correct answers for each student
Explanation:
Input:
ABACC D EEAD
DBABCAEEAD
EDDACBEEAD
CBAE DCEEAD
ABD CCDEEAD
BBECCDEEAD
BBACCDEEAD
EBECCDEEAD
Output:
Sample Input1:
ABACCDEEAD
DBABCAEEAD
Sample Output1:
6
Q30. Code-5 Mark
The input consists of two parts:
A string 's' representing the input string.
An integer 'd', denoting the number of elements to rotate the string.
Output Format
A string value representing the right-rotated string after applying the rotation.
A string value representing the reverse of right-rotated string after applying the rotation.
If string n is less than d print “-1”.
Sample Input 1:
hello
Sample Output 1:
ohell
lleho
Sample Input 2:
hello
10
Sample Output 2:
-1
Q31. code-5 marks
Problem Statement
Claudia gave Arif an array A of n integers and asked him to make all the elements equal by doing a certain
operation any number of times ( possibly zero).
The operations are:
Arif can either double or triple an element of the array
He can do the operation on an element any number of times
Input Format
The first line contains one integer, N, which denotes the number of integers.
The second line contains N separated integers denoting the elements of the array.
Output Format
Print "YES" (without the quotes) if it is possible to have the elements equal, or "NO" otherwise.
Constraints
2 <= n <= 10^5
1 <= A_i <= 10^9
Time Limit
1 second
Example
Sample Input
75 150 75 50
Sample Output
YES
Sample test case Explanation
For Input 1,
The first and third elements are doubled twice.
The second element is doubled once.
The fourth element is doubled and then tripled.
Q32. code-5 marks
Mike and Exam
Problem Statement
Mike went for the math exam and he tries to solve the problem. He prepared and carefully studied for the exam.
Now he read the question and understood what he has to do, but he isn't able to implement that logic in the code. So
he asked for help.
That question was, Given an array containing N elements and an integer K, the array contains +ve and -ve values
both. You have to find the number of ways to calculate the number K using array numbers only. You can use the
addition or subtraction operator (see sample test case explanation for better understanding).
Input Format
The first line contains an integer T, denoting the number of test cases.
Each test case contains two integers N and K.
Second-line contains N elements space-separated.
Output format
For each test case print the required output in a new line.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10
1 ≤ K ≤ 10^2
-10^2 ≤ arr[] ≤ 10^2
Time Limit
1 second
Example
Q33. code-5 marks
Q34. code-5 marks
Q35. Code-10-Mark
Govinda is very fond of playing with numbers. He recently innovated a new type of number named Govinda
number. He defined that number as
A govinda number is a composite number, the sum of whose digits is the sum of the digits of its prime factors
obtained as a result of prime factorization (excluding 1 ). The first few such numbers are 4,22 ,27 ,58 ,85 ,94 and
121 . For example, 378 = 2 × 3 × 3 × 3 × 7 is a govinda number since 3 + 7 + 8 = 2 + 3 + 3 + 3 + 7. Write a
program to check whether a given integer is a govinda number.
He gave Kumail bhaiya a number and asked to identify that this number is govinda number or not. As Kumail
bhaiya is so tired, can you help him to identify the same?
Input Format
There will be only one line of input:N , the number which needs to be checked.
Constraints
1 < N < 2,147,483,647 (max value of an integer of the size of 4 bytes)
Output Format
1 if the number is a Govinda number. 0 if the number is a not Govinda number.
Sample Input
456
Sample Output
0
Q36. Code-10-Mark
Q37. Code-10-Mark
You're currently developing a basic contact management program using Java. The program allows users to perform
two main actions: adding contacts and searching for contacts by their names. For the search functionality, you've
chosen to utilize the linear search algorithm to locate a contact's information based on their name.
To represent contacts, you've defined a custom Contact class with attributes like 'name', 'phoneNumber', and 'email'. All
the contacts in your system are stored in an array named contactsArray, which contains instances of the Contact class.
Your objective is to implement the linear search algorithm to efficiently find a contact's details using their name. If
the specified contact is found, you should return the relevant contact information. Conversely, if the contact isn't
found in the list, you should return -1.
In essence, your task is to create the necessary Java code that employs the linear search algorithm for this purpose.
Input format
The first line of input should contain an integer numberOfContacts,
representing the total number of contacts in the system.
The next numberOfContacts lines should each contain three space-separated
strings representing the details of a contact:
The first string is the contact's name.
The second string is the contact's phone number.
The third string is the contact's email.
Output format
If the contact with the specified name is found in the contact list, the output
will be the details of the contact in the following format:
<Name>
<Phone Number>
<Email>
If the contact with the specified name is not found in the contact list, the
output will be -1.
Sample Input 1:
Rahul
Sample Output 1:
Rahul
8844665577
[email protected]
Q38. Code-10-Mark
The first line of input contains an integer n, which represents the number of songs in the playlist.
The second line contains n space-separated strings, each representing the name of a song in
the playlist. The third line will prompt the user to enter the name of the song to search for.
Output format
If the song is found in the playlist, the output will be the index of the song in the sorted playlist,
represented as an integer.
If the song is not found in the playlist, the output will be -1.
Explanation:
Input
Number of Songs: 5
Songs_List: Jai_Ho Mera_Mann Sakhiyaan Laare
Rockon Searching_Song : Mera_Mann
The playlist after sorting in alphabetical order:
Songs : Jai_Ho Laare Mera_Mann Rockon Sakhiyaan
Index : 0 1 2 3 4
Comparing all the song in PlayList with the target song name
(Mera_Mann). Mera_Mann found at index 2, Since they match,
Algorithm will return 2 as the result.
Sample Input 1:
Jai_Ho Mera_Mann Sakhiyaan Laare
Rockon Mera_Mann
Sample Output 1: