Coding
Coding
1. Implement a function that receives an array of integers and returns the first repeating
element. If there are no repeating elements, return -1.
Input Format
The input begins with an integer N (the size of the array), followed by N space-
separated integers (the elements of the array).
Output Format
Solution
import java.util.*;
try {
int n = Integer.parseInt(scanner.next());
System.out.println("Invalid input");
return;
if (!scanner.hasNextInt()) {
System.out.println("Invalid input");
return;
arr[i] = scanner.nextInt();
if (seen.contains(arr[i])) {
repeated.add(arr[i]);
} else {
seen.add(arr[i]);
if (repeated.contains(arr[i])) {
System.out.println(arr[i]);
return;
System.out.println("-1");
} catch (Exception e) {
System.out.println("Invalid input");
} finally {
scanner.close();
Sample Input
5
12325
Output
2. Given an integer array, implement a function that moves all zeroes in the array to the end
while maintaining the relative order of the non-zero elements. The function should modify
the array in place.
Input Format
Output Format
Print the modified array with all zeroes moved to the end.
Solution
import java.util.*;
int n = scanner.nextInt();
arr[i] = scanner.nextInt();
moveZeroesToEnd(arr);
System.out.println();
scanner.close();
}
int index = 0;
if (arr[i] != 0) {
arr[index++] = arr[i];
arr[i] = temp;
Sample Input
0 1 0 3 12 0
Output
1 3 12 0 0 0
Input Format
Output Format
If duplicates are found, print each duplicate on a new line in the order they appear.
If no duplicates are found, print No duplicates found.
Solution
import java.util.Scanner;
public class FindAllDuplicates {
int n = scanner.nextInt();
if (n <= 0) {
System.out.println("Invalid input");
return;
if (value < 0) {
System.out.println("Invalid input");
return;
array[i] = value;
// System.out.println("Duplicates:");
findDuplicates(array);
scanner.close();
if (array[i] == array[j]) {
System.out.println(array[i]);
hasDuplicates = true;
break;
if (!hasDuplicates) {
Input Format
352375
Output Format
4. Given an array of integers, implement a function that doubles the values at all odd indices
while keeping the values at even indices unchanged.
Input Format
The first line of input contains an integer n representing the number of elements in
the array.
The second line of input contains n integers representing the elements of the array.
Output Format
Print the array after doubling the values of elements at odd indices.
Solution
import java.util.Scanner;
public class DoubleOddIndices {
int n = scanner.nextInt();
arr[i] = scanner.nextInt();
doubleOddIndices(arr);
System.out.println();
scanner.close();
arr[i] *= 2;
Sample Input
12345
Output
14385
5. Given a matrix of size m × n, implement a function that reads the matrix elements from
the user and prints its transpose.
Input Format
Output Format
Solution
import java.util.Scanner;
class Matrix {
private int m, n;
this.m = m;
this.n = n;
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
} else {
System.out.println("Invalid input");
}
}
sb.append(matrix[i][j]);
if (j < n - 1) sb.append("\n"); // Append newline after each row except the last one
return sb.toString();
// Validate that the input is an integer and within the correct range
if (scanner.hasNextInt()) {
int m = scanner.nextInt();
if (scanner.hasNextInt()) {
int n = scanner.nextInt();
matrix.setValues(scanner);
System.out.println(matrix.getTranspose());
} else {
System.out.println("Invalid input");
} else {
System.out.println("Invalid input");
} else {
System.out.println("Invalid input");
scanner.close();
Sample Input
23
123
456
Output
14
25
36
6. Given a singly linked list of n integers, implement a function that sorts the linked list using
the insertion sort algorithm.
Input Format
The first line contains an integer n, the number of elements in the linked list.
The second line contains n integers, representing the elements of the linked list.
Output Format
Solution
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
head = head.next;
current.next = sorted;
sorted = current;
} else {
temp = temp.next;
current.next = temp.next;
temp.next = current;
}
return sorted;
head = head.next;
System.out.println();
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Invalid input");
return;
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
head = insertionSortList(head);
printList(head);
scanner.close();
Sample Input
40 20 10 30 50
Output
10 20 30 40 50
7. You are given a singly linked list and an integer k. Your task is to reverse every k
consecutive nodes in the linked list. If there are fewer than k nodes left at the end of the list,
leave them as they are. The process should continue throughout the entire list, and the
modified list should be printed.
Input Format
Output Format
Solution
import java.util.Scanner;
int val;
ListNode next;
dummy.next = head;
groupEnd = groupEnd.next;
// Reverse k nodes
curr.next = prev;
prev = curr;
curr = next;
prevGroupEnd.next = prev;
groupStart.next = nextGroupStart;
prevGroupEnd = groupStart;
current = nextGroupStart;
return dummy.next;
current = current.next;
System.out.println();
try {
current.next = newNode;
current = newNode;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
return null;
return head;
int k;
try {
k = Integer.parseInt(scanner.nextLine().trim());
} catch (NumberFormatException e) {
System.out.println("Invalid input");
return;
}
printList(newHead);
scanner.close();
Sample Input
123456789
Output
432187659
Input Format
The first line contains an integer n representing the size of the matrix.
The next n lines each contain n integers, representing the elements of each row in
the matrix.
Output Format
Print the matrix after rotating it by 90 degrees clockwise. Each row of the rotated
matrix should be printed on a new line.
Solution
import java.util.Scanner;
public class MatrixRotation {
int n = scanner.nextInt();
System.out.println("Invalid input");
return;
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
} else {
System.out.println("Invalid input");
return;
rotateMatrix(matrix, n);
printMatrix(matrix, n);
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
matrix[i][n - 1 - j] = temp;
System.out.println();
Sample Input
54
15
Output
15
54
Input Format
The first line contains an integer n, the number of nodes in the binary tree.
The next n lines contain integers representing the keys of the nodes, inserted level-
wise (starting from the root).
Output Format
Solution
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class BinaryTree {
int data;
data = item;
Node root;
queue.add(root);
int i = 1;
if (i < keys.length) {
queue.add(current.left);
if (i < keys.length) {
queue.add(current.right);
return false;
return false;
return true;
int n = scanner.nextInt();
try {
keys[i] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid input");
return;
if (!BinaryTree.validateInput(n, keys)) {
System.out.println("Invalid input");
return;
if (n > 0) {
tree.insertLevelOrder(keys);
System.out.println(tree.calculateHeight(tree.root));
} else {
scanner.close();
Sample Input
10
20
30
Output
10. Given an integer n representing the number of nodes in a binary search tree (BST),
followed by n integers representing the node values in level-order insertion, and an
additional integer searchKey, implement a function to construct the BST and determine
whether the searchKey exists in the tree.
Input Format
The first line contains an integer n, the number of nodes in the binary search tree.
The next n lines contain integers representing the keys of the nodes, inserted level-
wise.
The last line contains the integer value to search in the BST.
Output Format
Print Found if the value exists in the tree, otherwise print Not Found.
Sample Input
10
15
Output
Found
Input Format
The input starts with a V×V matrix, where V=4. Each of the next 4 lines contains 4
integers representing the adjacency matrix of the graph. All integers will be either 0
or 1.
Output Format
Solution
import java.util.Scanner;
if (!visited[v]) {
visited[v] = true;
recStack[v] = true;
return true;
else if (recStack[i])
return true;
return false;
return true;
return false;
// Check if input is 0 or 1
System.out.println("Invalid input");
isValidInput = false;
break;
graph[i][j] = input;
} else {
System.out.println("Invalid input");
isValidInput = false;
break;
if (!isValidInput) break;
if (isValidInput) {
if (isCyclic(graph)) {
} else {
scanner.close();
}
Sample Input
0100
0010
0001
1000
Output
12. Given an array of integers height representing the heights of vertical lines on a 2D plane,
where each line's width is 1, find the maximum area of water that can be trapped between
any two lines. The area is determined by the width of the container and the height of the
shorter line.
Input Format
Output Format
A single integer represents the maximum area of water that can be trapped between
two lines.
Solution
import java.util.Scanner;
class Solution {
int left = 0;
int res = 0;
} else {
right--;
return res;
int n = -1;
while (n <= 0) {
if (invalidInput) {
System.out.println("Invalid input");
invalidInput = false;
if (scanner.hasNextInt()) {
n = scanner.nextInt();
if (n <= 0) {
invalidInput = true;
n = -1;
} else {
invalidInput = true;
scanner.next();
}
int[] height = new int[n];
int i = 0;
invalidInput = false;
while (i < n) {
if (invalidInput) {
System.out.println("Invalid input");
invalidInput = false;
if (scanner.hasNextInt()) {
height[i] = scanner.nextInt();
i++;
} else {
invalidInput = true;
scanner.next();
System.out.println(result);
scanner.close();
Sample Input
71239456
Output
42
Database Management System
13. In a content management system (CMS), users are assigned different roles based on their
access level. The system has three types of roles: Administrator, Editor, and Viewer. Each
user is linked to a specific role, which defines their permissions in the system. Your task to
retrieve the names of all users along with their role descriptions. Use an INNER JOIN to
combine data from the users and roles tables.
Input Table
Users Table
Solution
);
);
(1, 'Administrator'),
(2, 'Editor'),
(3, 'Viewer');
VALUES
SELECT
u.user_name,
r.role_description
FROM
users u
INNER JOIN
roles r
ON
u.role_id = r.role_id;
Output Table
user_name | role_description
--------- | ----------------
Alice | Administrator
Bob | Editor
Charlie | Viewer
14. Emma is a Human Resources (HR) manager at a company. She wants to maintain a record
of all employees in a table called Employees. She needs to add a new employee, John Doe,
who has just joined the HR department.
The Employees table has the following columns:
Implement an SQL query to insert John Doe’s details (ID = 101, Name = 'John Doe', Age = 30,
Department = 'HR')
Solution
Name VARCHAR(100),
Age INT,
Department VARCHAR(50)
);
Output Table
Solution
EmployeeName VARCHAR(100),
DepartmentID INT
);
DepartmentName VARCHAR(100)
);
VALUES
VALUES
(101, 'Sales'),
(102, 'Marketing'),
(103, 'Engineering');
FROM Employees E
Output
OOPS
16. A job recruitment portal allows companies to post job openings for full-time jobs and
internships. You need to implement a Job class with attributes jobTitle and companyName.
This class should be extended into:
Input Format
o A string jobTitle
o A string companyName
Solution
import java.util.*;
class Job {
this.jobTitle = jobTitle;
this.companyName = companyName;
super(jobTitle, companyName);
@Override
}
class Internship extends Job {
super(jobTitle, companyName);
this.stipend = stipend;
@Override
System.out.println("Internship: " + jobTitle + " at " + companyName + " with Stipend " +
stipend);
int N = Integer.parseInt(sc.nextLine().trim());
if (input.length < 3) {
System.out.println("Invalid input");
continue;
continue;
if (jobType.equals("FullTime")) {
job.display();
} else if (jobType.equals("Internship")) {
if (input.length != 4) {
System.out.println("Invalid input");
continue;
try {
System.out.println("Invalid input");
continue;
internship.display();
} catch (NumberFormatException e) {
System.out.println("Invalid input");
} else {
System.out.println("Invalid input");
sc.close();
}
}
Sample Input
Output
17. You are working on a vehicle tracking system, implementing a base class Vehicle with
attributes and methods for general vehicle information. Create a subclass ElectricVehicle
that extends Vehicle and includes additional attributes and methods specific to electric
vehicles.
Input Format
1. For Vehicle
2. For ElectricVehicle
A single line with the make, model, battery capacity (in kWh), and charging status: make
model battery_capacity charging_status (True or False)
Output Format
Solution
import java.util.Scanner;
class Vehicle {
if (make.isEmpty() || model.isEmpty()) {
}
this.make = make;
this.model = model;
System.out.println("" + make);
System.out.println("" + model);
super(make, model);
if (batteryCapacity <= 0) {
this.batteryCapacity = batteryCapacity;
this.chargingStatus = chargingStatus;
@Override
super.displayInfo();
}
public class VehicleTrackingSystem {
vehicle.displayInfo();
electricVehicle.displayInfo();
scanner.close();
Sample Input
Toyota Camry
Output
Toyota
Camry
Tesla
ModelS
75.0 kWh
Charging
18. You are given the dimensions of a rectangle, specifically its length and width. Your task is
to calculate and print the area and perimeter of the rectangle.
Input Format
The first line of input contains a single floating-point number length, representing the
length of the rectangle.
The second line of input contains a single floating-point number width, representing
the width of the rectangle.
Output Format
Print the area of the rectangle on the first line and the perimeter of the rectangle on
the second line single floating-point number.
Code
import java.util.Scanner;
class Rectangle {
System.out.println(calculateArea());
System.out.println(calculatePerimeter());
}
public class RectangleMain {
rectangle.length = scanner.nextDouble();
rectangle.width = scanner.nextDouble();
System.out.println("Invalid input");
} else {
rectangle.displayResults();
Sample Input
5.5
3.0
Output
16.5
17.0
19. You are given the lengths of three sides of a triangle. Create a class Triangle to determine
if these sides form a valid triangle(based on triangular inequality: a + b > c) and, if so, classify
the type of triangle they form. A triangle can be classified as:
Input Format
Three floating-point numbers representing the lengths of the sides of the triangle
(side1, side2, side3).
Output Format
If the input values form a valid triangle, the program should print the type of triangle
equilateral, isosceles, or scalene.
Code
import java.util.Scanner;
class Triangle {
side1 = s1;
side2 = s2;
side3 = s3;
return (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1);
}
public class Main {
double s1 = scanner.nextDouble();
double s2 = scanner.nextDouble();
double s3 = scanner.nextDouble();
if (triangle.isValidTriangle()) {
if (triangle.isEquilateral()) {
System.out.println("equilateral");
} else if (triangle.isIsosceles()) {
System.out.println("isosceles");
} else if (triangle.isScalene()) {
System.out.println("scalene");
} else {
System.out.println("Invalid triangle");
scanner.close();
Sample Input
Output
Equilateral
20. Dharani is planning to apply for a loan. She can choose between a home loan and a
personal loan. Each loan type has a specific interest rate of 5% for a home loan and 10% for
a personal loan. Samantha wants to enter the loan amount and type and get an instant
interest calculation. Implement an abstract class to help Dharani calculate the loan interest
amount based on her input.
Input Format
A double value for loanAmount represents the loan amount Dharani wants.
A string value for loanType represents the type of loan Dharani chooses.
Output Format
Code
import java.util.Scanner;
this.loanAmount = loanAmount;
System.out.print( calculateInterest());
super(loanAmount);
@Override
super(loanAmount);
@Override
try {
Loan loan;
if (loanType.equalsIgnoreCase("HomeLoan")) {
} else if (loanType.equalsIgnoreCase("PersonalLoan")) {
} else {
loan.displayLoanDetails();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
Sample Input
5000
HomeLoan
Output
250.0