0% found this document useful (0 votes)
25 views

Module For CSE & EEE

it is a module of javaa

Uploaded by

Prince Jaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Module For CSE & EEE

it is a module of javaa

Uploaded by

Prince Jaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

MODULE -1

Constructor Type Of Constructor With Ex

 Create a class named Student with properties like name, age, and studentId. Implement a
constructor to initialize these properties when a Student object is created.Add methods to
display student information.

 Write a program to print the area of a rectangle by creating a class named


'Area'taking the values of its length and breadth as parameters of its
constructor and having a method named 'returnArea' which returns the area of
the rectangle. Length and breadth of rectangle are entered through keyboard.

 Write a program to store Student details such as name(String), roll no(int) and
fees(float). Declare two contructors, a default contructor with a print statement
“System.out.println("Default");”and a parameterized constructor to intialise allt\he
three variables. Use this to execute the default constructor from the parameterized
constructor. Display the values using a display method.

 Write a Java class named Person with member variables name and age. Implement adefault
constructor that initializes name to "Unknown" and age to 0.
Create a parameterized constructor for the Person class that takes two parameters (nameand age)
and initializes the member variables accordingly.
Extend the Person class to create a subclass named Student. Add a member variable studentId
to the Student class. Implement a parameterized constructor for the Studentclass that initializes
name, age, and studentId.

INHERITANCE N IT'S TYPES WITH EXAMPLE

 Create a superclass named Animal with a method sound(). Extend this class to create asubclass
named Dog with a method bark().

 Create a superclass named Vehicle with a method start(). Extend this class to create asubclass
named Car, and then further extend Car to create a subclass named SportsCar, each with
additional methods.

 Design a banking system with multiple account types: SavingsAccount,


CheckingAccount, and LoanAccount.
Implement inheritance to model these account types with common properties andmethods
such as accountNumber, balance, deposit, and withdraw.
Consider how to handle interest calculations for savings accounts and overdraft
protection for checking accounts.
Polymorphism and it's types with example

 Write a program to demonstrate method overloading. A method which can add two numbers
should be overloaded: Once without parameters, once with two integer numbers and one with
two double numbers. Display the results in the methods.

 Develop a program in Java which has a static method min2() that takes two int arguments and
returns the value of the smallest one. Add an overloaded function that does the samething with two
double values and display the output.

 Consider a scenario where you have a base class Shape with a method calculateArea() tocalculate
the area of a shape. Now, you want to create subclasses Rectangle and Circlethat inherit from
the Shape class. Both Rectangle and Circle should have their own implementation of the
calculateArea() method to calculate the area specific to their shape.
Design the class hierarchy and implement the calculateArea() method in each subclass to
override the method from the Shape class. Also, create instances of Rectangle andCircle, and
demonstrate how the overridden methods work.

Data abstraction with example

 You are tasked with creating a simple system to manage shapes. Design an abstract class Shape
with abstract methods calculateArea() and calculatePerimeter(). Then, create concrete
subclasses such as Rectangle and Circle that extend the Shape class and implement the
abstract methods.
 You are tasked with designing a system for managing different types of animals in a zoo.Design
an abstract class Animal with an abstract method makeSound(). Then, create concrete
subclasses such as Lion and Elephant that extend the Animal class and implement the
makeSound() method to represent the unique sound each animal makes.
INTERFACE

 You are creating a sorting algorithm library. Design an interface SortAlgorithm with amethod
sort(int[] array). Then, create classes such as BubbleSort and MergeSort that implement the
SortAlgorithm interface and provide their own implementation of the sort() method to perform
sorting using the respective algorithms.

Provide constructors for each class if necessary, and demonstrate how to use these classes by
creating instances of BubbleSort and MergeSort, and calling their sort() methods with a sample
array.
Encapsulation

Design aclassPerson to represent a person's name and age. Implement the Person classwith the
following requirements:

It should have private instance variables name (String) and age (int).
Provide public methods getName() and getAge() to access the name and age variables,
respectively.
Implement a constructor that accepts parameters to initialize the name and agevariables.
Ensure that the age cannot be negative. If an attempt is made to set a negative age, set itto 0

MODULE -2
Access modifiers and package

Access Modifier and Package Practice Ǫuestion :

Create a Java class named Person with private instance variables for name, age, andemail.
Provide public methods to set and get these variables.
Write another class to test the Person class by creating instances and
accessing/modifying the private variables using the public methods.
Package Practice:

Create a package named math and define a class called Calculator within it. Implement basic
arithmetic operations (addition, subtraction, multiplication, division).
Create another package named app and write a class called Main in it. Import the Calculator
class from the math package and use its methods to perform arithmetic operations

Exception Handaling: try catch throw throws and finally

Division Exception:
Write a Java program that takes two integers as input from the user and calculates theirdivision.
Handle the ArithmeticException that may occur if the second number is zero.

Array Index Out of Bounds:


Define an array of integers. Attempt to access an element at an index beyond the array'sbounds.
Handle the ArrayIndexOutOfBoundsException that may occur.

Explanation of final keyword (final variable,final method,and final class)Super


keyword with ex
Static Nested Class (Static Inner Class):

Ǫuestion:

You are designing a music player application. Create a static nested class Song within the
MusicPlayer class to represent individual songs. The Song class should have instance variablestitle and
artist. Implement a method play() in the Song class that prints "Now playing [title] by[artist]".

Non-Static Nested Class (Inner Class):

Ǫuestion:

You are developing a banking application. Create an inner class Transaction within the Accountclass to
represent individual transactions. The Transaction class should have instance variables amount and
timestamp. Implement a method printTransaction() in the Transaction class thatprints "Transaction of
[amount] at [timestamp]".

Local Inner Class:

Ǫuestion:

You are working on a game application. Create a method startGame() in the Game class. Inside this
method, define a local inner class Player representing a game player. The Player class shouldhave instance
variables name and score. Implement a method displayScore() in the Player classthat prints "Player [name]
scored [score]".

Anonymous Inner Class:

Ǫuestion:

You are developing a GUI application for a calculator. Implement an action listener for the "Add"button
using an anonymous inner class. When the "Add" button is clicked, it should display a message
"Performing addition operation".

Reading and Writing to Files:

Ǫuestion:

You are creating a program to manage employee information. Write a method writeToFile(String data) in
the EmployeeManager class that writes the provided data to a text file named employees.txt. Use
FileWriter and BufferedWriter for writing the data to the file.
Multithreading

Write a Java to create a thread that prints the numbers from 1 to 5 with a delay of 1 second
between each number. Use the Thread class to create the thread.
Write a Java program to create two threads, one that prints even numbers from 2 to 10 and
another that prints odd numbers from 1 to 9. Ensure that the threads execute concurrently and
print numbers with a delay of 500 milliseconds between each number.

Collections Framework

Array List,
Write a Java program that uses an ArrayList to store the names of students in a class. The
program should have the following functionalities:
Add names of at least five students to the ArrayList.
Print the total number of students in the class.
Print all the names of students in the class.
Remove one student from the class.
Print the updated list of students after removal.

LinkedList
Write a Java program to implement a singly linked list. Define a class called Node to
represent each node in the linked list. The Node class should have a data field and a reference
to the next node.

Then, create a class called LinkedList to manage the linked list. Implement methods to:

Insert a node at the beginning of the list.


Insert a node at the end of the list.
Insert a node at a specific position in the list.
Delete a node from the beginning of the list.
Delete a node from the end of the list.
Delete a node from a specific position in the list.
Display the elements of the list.
HashSet,

You are tasked with developing a Java program to manage a list of programming languages
used in a software development company. As part of this program, you need to implement
functionality to store and display unique programming languages using HashSet.

Design a Java program to implement this functionality:

Initialize a HashSet to store unique programming languages.


Add at least five programming languages to the HashSet.
Display the unique programming languages stored in the HashSet.
Write a Java program to fulfill the above requirements.

HashMap
You are developing a Java application to manage student information at a school. As part of
this application, you need to implement functionality to store and retrieve student details
using HashMap.

Design a Java program to implement this functionality:

Initialize a HashMap to store student details.


Add at least three student records to the HashMap. Each record should include the student's
name as the key and their grade level as the value.
Display the student details stored in the HashMap.

Thread class and Runnable interface


With company specific examples

Ǫuestion on Thread class:

You are tasked with creating a Java program to simulate a simple stopwatch using the Thread class. Design
a program that starts a stopwatch when the user presses a key and stops it whenthe user presses another
key. Display the elapsed time between starting and stopping the stopwatch.
Write a Java program to fulfill the above requirements.

Ǫuestion on Runnable interface

You are developing a Java program to simulate a basic ticket reservation system using the Runnable
interface. Design a program that represents multiple ticket booking agents who are trying to reserve tickets
concurrently. Implement the Runnable interface to handle the bookingprocess for each agent. Ensure that
the booking process is thread-safe to avoid conflicts whenagents try to book tickets simultaneously.

Write a Java program to fulfill the above requirements.


MODULE -3

ARRAY
Ǫ1 Array insert at index
Insertion is a basic but frequently used operation. Arrays in most languages cannnot be dynamically
shrinked or expanded. Here, we will work with such arrays and try to insert anelement at some index.

You are given an array arr(0-based index). The size of the array is given by sizeOfArray. You needto insert an
element at given index.

Example 1:

Input:
sizeOfArray = 6
arr[] = {1, 2, 3, 4, 5}
index = 5, element = 90
Output: 1 2 3 4 5 90
Explanation: 90 is inserted at index 5(0-
based indexing). After inserting,array
elements are like
1, 2, 3, 4, 5, 90.
Example 2:

Input:
sizeOfArray = 6
arr[] = {1, 2, 3, 4, 5}
index = 2, element = 90
Output: 1 2 90 3 4 5
Explanation: 90 is inserted at index 2(0-
based indexing). After inserting,array
elements are like
1, 2, 90, 3, 4, 5.
Your Task:
You don't need to read input or print anything.. The input is already taken care of by the drivercode. You only
need to complete the function insertAtIndex() that takes arr, sizeOfArray, index,element as input and modifies
the array arr as per requirements. The printing is done by drivercode.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(1).

Constraints:
1 <= sizeOfArray <= 10000
0 <= element, arri <= 106
0 <= index <= sizeOfArray-1
Ǫ2 Array insert at end
Insertion is a basic but frequently used operation. Arrays in most languages can not bedynamically
shrinked or expanded. Here, we will work with such arrays and try to insert anelement at the end of the
array.

You are given an array arr. The size of the array is given by sizeOfArray. You need to insert anelement at the end.
Array already have the sizeofarray -1 elements.Example 1:

Input:
sizeOfArray = 6
arr[] = {1, 2, 3, 4, 5}
element = 90
Output: 1 2 3 4 5 90
Explanation: After inserting 90 at theend,
we have array elements as
1 2 3 4 5 90.
Example 2:

Input:
sizeOfArray = 4
arr[] = {1, 2, 3}
element = 50
Output: 1 2 3 50
Explanation: After inserting 50 at theend,
we have array elements as
1 2 3 50.
Your Task:
You don't need to read input or print anything. You only need to complete the function insertAtEnd() that
takes arr, sizeOfArray, element as input and modifies arr as per requirements.The driver code takes care of the
printing.

Expected Time Complexity: O(1).


Expected Auxiliary Space: O(1).

Constraints:
1 <= sizeOfArray <= 1000
0 <= element, arri <= 106
Ǫ3 You are given an array of size n. Find the maximum possible length of a subarray such that itselements are
arranged alternately either as even and odd or odd and even .

Example 1:

Input:
n=5
a[] = {10,12,14,7,8}
Output: 3
Explanation: The max length of subarrayis 3
and the subarray is {14 7 8}. Here the array
starts as an even element and has odd and even
elements alternately. Example 2:

Input:
n=2
a[] = {4,6}
Output: 1
Explanation: The array contains {4 6}.So,
we can only choose 1 element asthat will
be the max length subarray. Your Task:
You don't need to take any input. Just complete the function maxEvenOdd() that returns themaximum
length.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(1).

Constraints: 1
<= n <= 106
1 <= Ai <= 103
Searching

Ǫ1 Given an integer array and another integer element. The task is to find if the given element ispresent in array
or not.

Example 1:

Input:
n=4
arr[] = {1,2,3,4}
x=3
Output: 2
Explanation: There is one test case with
array as {1, 2, 3 4} and elementto be
searched as 3. Since 3 is present at
index 2, output is 2.
Example 2:

Input:
n=5
arr[] = {1,2,3,4,5}
x=5
Output: 4
Explanation: For array elements
{1,2,3,4,5} element to be searchedis 5
and it is at index 4. So, the output is 4.
Your Task:
The task is to complete the function search() which takes the array arr[], its size N and theelement X as
inputs and returns the index of first occurrence of X in the given array. If theelement X does not exist in
the array, the function should return -1.

Expected Time Complexity: O(n).


Expected Auxiliary Space: O(1).

Constraints: 1
<= n <= 106
0 <= arr[i] <= 106
0 <= x <= 105
Ǫ2 Square root of a number
Given an integer x, find the square root of x. If x is not a perfect square, then return floor(√x).

Example 1:

Input:
x=5
Output: 2
Explanation: Since, 5 is not a perfect
square, floor of square_root of 5 is 2.
Example 2:

Input:
x=4
Output: 2
Explanation: Since, 4 is a perfect
square, so its square root is 2.

Your Task:
You don't need to read input or print anything. The task is to complete the function floorSqrt()which takes x as
the input parameter and return its square root.
Note: Try Solving the question without using the sqrt function. The value of x>=0.

Expected Time Complexity: O(log N)


Expected Auxiliary Space: O(1)

Constraints:
1 ≤ x ≤ 107

Ǫ3 Find Indexes of a subarray with given sum


Given an unsorted array A of size N that contains only non negative integers, find a continuous sub-array
that adds to a given number S and return the left and right index(1-based indexing) ofthat subarray.

In case of multiple subarrays, return the subarray indexes which come first on moving from leftto right.

Note:- You have to return an ArrayList consisting of two elements left and right. In case no suchsubarray
exists return an array consisting of element -1.

Example 1:

Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
Explanation: The sum of elementsfrom
2nd position to 4th positionis 12.
Example 2:

Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
Explanation: The sum of elementsfrom
1st position to 5th position is 15.
Your Task:
You don't need to read input or print anything. The task is to complete the function subarraySum() which
takes arr, N, and S as input parameters and returns an ArrayList containingthe starting and ending positions of
thefirst such occurring subarray from the left where sum equals to S. The two indexes in the array should be
according to 1-based indexing. If no suchsubarray is found, return an array consisting of only one element
that is -1.

Expected Time Complexity: O(N)


Expected Auxiliary Space: O(1)

Constraints:
1 <= N <= 105
0 <= Ai <= 109
0<= S <= 109

Ǫ4 You are given an array arr[] of N integers. The task is to find the smallest positive numbermissing from the
array.

Note: Positive number starts from 1.

Example 1:
Input:
N=5
arr[] = {1,2,3,4,5}
Output: 6
Explanation: Smallest positive missing
number is 6.
Example 2:

Input:
N=5
arr[] = {0,-10,1,3,-20}
Output: 2
Explanation: Smallest positive missing
number is 2.
Your Task:
The task is to complete the function missingNumber() which returns the smallest positivemissing
number in the array.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(1).

Constraints:
1 <= N <= 106
-106 <= arr[i] <= 106
Sorting

Ǫ1 Bubble Sort

EasyAccuracy
Given an Integer N and a list arr. Sort the array using bubble sort algorithm.Example 1:

Input:
N=5
arr[] = {4, 1, 3, 9, 7}
Output:
13479
Example 2:

Input:
N = 10
arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
Output:
1 2 3 4 5 6 7 8 9 10

Your Task:
You don't have to read input or print anything. Your task is to complete the function bubblesort()which takes
the array and it's size as input and sorts the array using bubble sort algorithm.

Expected Time Complexity: O(N^2).


Expected Auxiliary Space: O(1).

Constraints: 1
<= N <= 103
1 <= arr[i] <= 103
Ǫ2 The task is to complete the insert() function which is used to implement Insertion Sort.

Example 1:

Input:
N=5
arr[] = { 4, 1, 3, 9, 7}
Output:
13479
Example 2:

Input:
N = 10
arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
Output:
1 2 3 4 5 6 7 8 9 10

Your Task:
You don't have to read input or print anything. Your task is to complete the function insert() and
insertionSort() where insert() takes the array, it's size and an index i and insertionSort() uses insert function
to sort the array in ascending order using insertion sort algorithm.

Expected Time Complexity: O(N*N).


Expected Auxiliary Space: O(1).

Constraints:
1 <= N <= 1000
1 <= arr[i] <= 1000
Ǫ3 Merge three sorted arrays
Given three sorted arrays A, B and C of size N, M and P respectively. The task is to merge theminto a single
array which must be sorted in increasing order.

Example 1:

Input:
N = 4, A[] = [1 2 3 4]
M = 5, B[] = [1 2 3 4 5]
P = 6, C[] = [1 2 3 4 5 6]
Output: 1 1 1 2 2 2 3 3 3 4 4 4 5 5 6
Explanation: Merging these three sortedarrays,
we have:
1 1 1 2 2 2 3 3 3 4 4 4 5 5 6.
Example 2:

Input:
N = 2, A[] = [1 2]
M = 3, B[] = [2 3 4]
P = 4, C[] = [4 5 6 7]
Output: 1 2 2 3 4 4 5 6 7
Explanation: Merging three sorted arrays,we
have: 1 2 2 3 4 4 5 6 7.

Your Task:
This is a function problem. You only need to complete the function mergeThree() that takesA,B,C as
parameters. The function returns an array or vector.

Expected Time Complexity: O(N + M + P)


Expected Auxiliary Space: O(N + M + P) for the resultant array only.

Constraints:
1 <= N, M, P <= 106
1 <= A[i], B[i], C[i] <= 106
Q4 Given an array arr[] of n integers. Check whether it contains a triplet that
sums up to zero.

Note: Return 1, if there is at least one triplet following the condition else
return 0.

Example 1:

Input: n = 5, arr[] = {0, -1, 2, -3, 1}


Output: 1
Explanation: 0, -1 and 1 forms a triplet
with sum equal to 0.
Example 2:

Input: n = 3, arr[] = {1, 2, 3}


Output: 0
Explanation: No triplet with zero sum exists.

Your Task:
You don't need to read input or print anything. Your task is to complete the
boolean function findTriplets() which takes the array arr[] and the size of thearray
(n) as inputs and print 1 if the function returns true else print 0 if the function
returns false.

Expected Time Complexity: O(n2)


Expected Auxiliary Space: O(1)

Constraints:
1 <= n <= 104
-106 <= Ai <= 106
STRING

Q1 Given a binary string S. The task is to count the number of substrings that start
and end with 1. For example, if the input string is “00100101”, then thereare three
substrings “1001”, “100101” and “101”.

Example 1:

Input:
N=4
S = 1111
Output: 6
Explanation: There are 6 substrings from
the given string. They are 11, 11, 11,
111, 111, 1111.
Example 2:

Input:
N=5
S = 01101
Output: 3
Explanation: There 3 substrings from the
given string. They are 11, 101, 1101.
Your Task:
The task is to complete the function binarySubstring() which takes the lengthof
binary string n and a binary string a as input parameter and counts the number of
substrings starting and ending with 1 and returns the count.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(1).

Constraints:
1 ≤ |S| ≤ 104
Ǫ2 Isomorphic Strings
EasyAccuracy: 34.21%Submissions: 174K+Points: 2
Given two strings 'str1' and 'str2', check if these two strings are isomorphic to each other.

If the characters in str1 can be changed to get str2, then two strings, str1 and str2, are isomorphic. A
character must be completely swapped out for another character while maintaining the order of the
characters. A character may map to itself, but no two charactersmay map to the same character.

Example 1:

Input:
str1 = aabstr2
= xxyOutput:
1
Explanation:
There are two different characters in aab and xxy, i.e a and b with frequency 2 and 1 respectively.Example 2:

Input:
str1 = aabstr2
= xyzOutput:
0
Explanation:
Thereare two different characters in aab but there are three different charactersin xyz. So therewon't be one to
one mapping between str1 and str2.
Your Task:
You don't need to read input or print anything.Your task is to complete the function areIsomorphic() which
takes the string str1 and string str2 as input parameter and check if twostrings are isomorphic. The function
returns true if strings are isomorphic else it returns false.

Expected Time Complexity: O(|str1|+|str2|).


Expected Auxiliary Space: O(Number of different characters).Note: |s|
represents the length of string s.

Constraints:
1 <= |str1|, |str2| <= 105
Ǫ3 Check if a string is Isogram or not BasicAccuracy:
63.25%Submissions: 54K+Points: 1
Given a string S of lowercase alphabets, check if it is isogram or not. An Isogram is a string inwhich no
letter occurs more than once.

Example 1:

Input:
S = machine
Output: 1
Explanation: machine is an isogram
as no letter has appeared twice. Hencewe print
1.
Example 2:

Input:
S = geeksOutput:
0
Explanation: geeks is not an isogram as 'e'
appears twice. Hence we print 0.Your Task:
This is a function problem. You only need to complete the function isIsogram() that takes astring as a
parameter and returns either true or false.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(Number of distinct characters).Note: N
= |S|

Constraints: 1 <=
|s| <= 103
Ǫ4 Pangram Checking
EasyAccuracy: 61.34%Submissions: 74K+Points: 2Given a
string s check if it is "Panagram" or not.

A "Panagram" is a sentence containing every letter in the English Alphabet.Example

1:

Input:
s = "Bawds jog, flick quartz, vex nymph"Output:
1
Explanation:
In the given input, there
are all the letters of the English
alphabet. Hence, the output is 1.
Example 2:

Input:
s = "sdfs"Output:
0
Explanation:
In the given input, there
aren't all the letters present in the
English alphabet. Hence, the outputis 0.
Your Task:
You do not have to take any input or print anything. You need to complete the function checkPangram()
that takes a string as a parameter and returns true if the string is a Panagram,or else it returns false.

Expected Time Complexity: O( |s| )


Expected Auxiliary Space: O(1)
|s| denotes the length of the input string.

Constraints:
1 ≤ |s| ≤ 104
Both Uppercase & Lowercase are considerable
MODULE -4

Linked list

Ǫ1 Count nodes of linked list


BasicAccuracy: 85.99%Submissions: 152K+Points: 1
Given a singly linked list. The task is to find the length of the linked list, where length is definedas the
number of nodes in the linked list.

Example 1:

Input:
LinkedList: 1->2->3->4->5
Output: 5
Explanation: Count of nodes in the
linked list is 5, which is its length.
Example 2:

Input:
LinkedList: 2->4->6->7->5->1->0
Output: 7
Explanation: Count of nodes in the
linked list is 7. Hence, the outputis 7.
Your Task:
Your task is to complete the given function getCount(), which takes a head reference as anargument and
should return the length of the linked list.

Expected Time Complexity : O(N)


Expected Auxilliary Space : O(1)

Constraints: 1
<= N <= 105
1 <= value <= 103
Q2 Count nodes of linked list
BasicAccuracy: 85.99%Submissions: 152K+Points: 1
Given a singly linked list. The task is to find the length of the linked list, where
length is defined as the number of nodes in the linked list.

Example 1:

Input:
LinkedList: 1->2->3->4->5
Output: 5
Explanation: Count of nodes in the
linked list is 5, which is its length.
Example 2:

Input:
LinkedList: 2->4->6->7->5->1->0
Output: 7
Explanation: Count of nodes in the
linked list is 7. Hence, the output
is 7.
Your Task:
Your task is to complete the given function getCount(), which takes a head
reference as an argument and should return the length of the linked list.

Expected Time Complexity : O(N)


Expected Auxilliary Space : O(1)

Constraints:
1 <= N <= 105
1 <= value <= 103
Add two numbers represented by linked lists MediumAccuracy:
34.52%Submissions: 231K+Points: 4
Given two decimal numbers, num1 and num2, represented by linked lists of size n and m respectively. The
task is to return a linked list that represents the sum of these two numbers.

For example, the number 190 will be represented by the linked list, 1->9->0->null, similarly 25 by2->5->null.
Sum of these two numbers is 190 + 25 = 215, which will be represented by 2->1->5-
>null. You are required to return the head of the linked list 2->1->5->null.

Note: There can be leading zeros in the input lists, but there should not be any leading zeros inthe output list.

Example 1:

Input:
n=2
num1 = 45 (4->5->null)m = 3
num2 = 345 (3->4->5->null)Output:
3->9->0->null
Explanation:
For the given two linked list (4 5) and (3 4 5), after adding the two linked list resultant linked listwill be (3 9
0).
Example 2:

Input:
n=4
num1 = 0063 (0->0->6->3->null)
m=2
num2 = 07 (0->7->null)
Output:
7->0->null
Explanation:
For the given two linked list (0 0 6 3) and (0 7), after adding the two linked list resultant linked listwill be (7 0).
Your Task:
The task is to complete the function addTwoLists() which has node reference of both the linkedlists and
returns the head of the sum list.

Expected Time Complexity: O(n+m)


Expected Auxiliary Space: O(max(n,m)) for the resultant list.

Constraints:
1 <= n, m <= 104
Stack

Implement stack using array


BasicAccuracy: 54.76%Submissions: 157K+Points: 1
Write a program to implement a Stack using Array.Your task is to use the class as shown in thecomments in
the code editor and complete the functions push() and pop() to implement a stack.

Example 1:

Input:
push(2) push(3)
pop() push(4)
pop() Output: 3,
4Explanation:
push(2) the stack will be {2} push(3)
the stack will be {2 3} pop()
poped element will be 3,
the stack will be {2} push(4)
the stack will be {2 4} pop()
poped element will be 4
Example 2:

Input:
pop() push(4)
push(5) pop()
Output: -1, 5
Your Task:
You are required to complete two methods push() and pop(). The push() method takes one argument, an
integer 'x' to be pushed into the stack and pop() which returns an integer presentat the top and popped out
from the stack. If the stack is empty then return -1 from the pop() method.

Expected Time Complexity : O(1) for both push() and pop().Expected


Auixilliary Space : O(1) for both push() and pop().

Constraints: 1
<= Ǫ <= 100
1 <= x <= 100
Implement Stack using Linked List
BasicAccuracy: 53.98%Submissions: 123K+Points: 1
Let's give it a try! You have a linked list and you have to implement the functionalities push and pop of
stack using this given linked list. Your task is to use the class as shown in the commentsin the code editor
and complete the functions push() and pop() to implement a stack.

Example 1:

Input:
push(2) push(3)
pop() push(4)
pop() Output: 3
4 Explanation:
push(2) the stack will be {2} push(3)
the stack will be {2 3} pop()
poped element will be 3,
the stack will be {2} push(4)
the stack will be {2 4} pop()
poped element will be 4
Example 2:

Input:
pop() push(4)
push(5) pop()
Output: -1 5
Your Task: You are required to complete two methods push() and pop(). The push() method takes one
argument, an integer 'x' to be pushed into the stack and pop() which returns an integerpresent at the top and
popped out from the stack. If the stack is empty then return -1 from the pop() method.

Expected Time Complexity: O(1) for both push() and pop().Expected


Auxiliary Space: O(1) for both push() and pop().

Constraints: 1
<= Ǫ <= 100
1 <= x <= 100
Delete middle element of a stack
EasyAccuracy: 53.71%Submissions: 127K+Points: 2
Given a stack, delete the middle element of the stack without using any additional datastructure.
Middle element:- floor((size_of_stack+1)/2) (1-based indexing) from bottom of the stack.Note: The

output shown by the compiler is the stack from top to bottom.

Example 1:

Input:
Stack = {10, 20, 30, 40, 50}
Output:
ModifiedStack = {10, 20, 40, 50}
Explanation:
If you print the stack the bottom-most element will be 10 and the top-most element will be 50. Middle element
will be element at index 3 from bottom, which is 30. Deleting 30, stack will looklike {10 20 40 50}.
Example 2:

Input:
Stack = {10 20 30 40}
Output:
ModifiedStack = {10 30 40}Explanation:
If you print the stack the bottom-most element will be 10 and the top-most element will be 40. Middle element
will be element at index 2 from bottom, which is 20. Deleting 20, stack will looklike {10 30 40}.
Your Task:
You don't need to read input or print anything. Complete the function deleteMid() which takesthe stack and
its size as input parameters and modifies the stack in-place.

Expected Time Complexity: O(N)


Expected Auxiliary Space: O(N)

Constraints:
2 ≤ size of stack ≤ 105
Implement two stacks in an array
EasyAccuracy: 56.49%Submissions: 150K+Points: 2
Your task is to implement 2 stacks in one array efficiently. You need to implement 4 methods.

twoStacks : Initialize the data structures and variables to be used to implement 2 stacks in onearray.
push1 : pushes element into first stack. push2 :
pushes element into second stack.
pop1 : pops element from first stack and returns the popped element. If first stack is empty, itshould return -1.
pop2 : pops element from second stack and returns the popped element. If second stack isempty, it should
return -1.

Example 1:

Input:
push1(2)
push1(3)
push2(4)
pop1()
pop2()
pop2() Output:
3 4 -1
Explanation:
push1(2) the stack1 will be {2} push1(3)
the stack1 will be {2,3}push2(4) the
stack2 will be {4}
pop1() the poped element will be 3 from stack1 and stack1 will be {2} pop2() the
poped element will be 4 from stack2 and now stack2 is emptypop2() the stack2 is now
empty hence returned -1.
Example 2:

Input:
push1(1)
push2(2)
pop1()
push1(3)
pop1()
pop1() Output:
1 3 -1
Explanation:
push1(1) the stack1 will be {1}
push2(2) the stack2 will be {2}
pop1() the poped element will be 1 from stack1 and stack1 will be emptypush1(3)
the stack1 will be {3}
pop1() the poped element will be 3 from stack1 and stack1 will be emptypop1() the
stack1 is now empty hence returned -1.
Your Task:
You don't need to read input or print anything. You are required to complete the 4 methods push1, push2
which takes one argument an integer 'x' to be pushed into stack one and two andpop1, pop2 which returns the
integer poped out from stack one and two. If no integer is presentin the stack return -1.

Expected Time Complexity: O(1) for all the four methods.Expected


Auxiliary Space: O(1) for all the four methods.

Constraints:
1 <= Number of queries <= 104
1 <= Number of elements in the stack <= 100
The sum of count of elements in both the stacks < size of the given array
MODULE -5

Ǫueue

Implement Ǫueue using array


BasicAccuracy: 47.24%Submissions: 128K+Points: 1
Implement a Ǫueue using an Array. Ǫueries in the Ǫueue are of the following type:
(i) 1 x (a query of this type means pushing 'x' into the queue)
(ii) 2 (a query of this type means to pop element from queue and print the poped element)Example 1:

Input:
Ǫ=5
Ǫueries = 1 2 1 3 2 1 4 2
Output: 2 3
Explanation:
In the first test case for query1 2 the
queue will be {2}
1 3 the queue will be {2 3}
2 poped element will be 2 the
queue will be {3}
1 4 the queue will be {3 4}
2 poped element will be 3
Example 2:

Input:
Ǫ=4
Ǫueries = 1 3 2 2 1 4
Output: 3 -1
Explanation:
In the second testcase for query1 3 the
queue will be {3}
2 poped element will be 3 thequeue
will be empty
2 there is no element in thequeue
and hence -1
1 4 the queue will be {4}.Your
Task :
You are required to complete the two methods push() which take one argument an integer 'x' tobe pushed into
the queue and pop() which returns a integer poped out from othe queue. If the queue is empty, it should
return -1 on a pop operation.

Expected Time Complexity: O(1) for both push() and pop().Expected


Auxiliary Space: O(1) for both push() and pop().

Constraints:1 ≤
Ǫ ≤ 105
0 ≤ x ≤ 105

Operations on Ǫueue
BasicAccuracy: 58.39%Submissions: 19K+Points: 1
Given a queue of integers and Ǫ queries. The task is to perform operations on queue accordingto the query.

Ǫueries are as:

i x : (adds element x in the queue from rear).r :

(Removes the front element of queue).

h : (Returns the front element).

f y : (check if the element y is present or not in the queue). Return "Yes" if present, else "No".Example 1:

Input:
Ǫ=6
Ǫueries = i 2 i 4 i 3 i 5 h f 8Output:
2
No
Explanation: Inserting 2, 4, 3, and 5
onto the queue: 2 4 3 5. h means frontSo
front is 2. f is find. 8 is not in queue so No.
Example 2:

Input:
Ǫ=4
Ǫueries = i 3 i 4 r f 3Output:
No
Explanation: Inserting 3 and 4 . When we
return and remove 3 and then whenwe find 3 ,
it will return NO as
output as 3 is not present in thequeue.
Your Task:
Your task is to complete functions enqueue(), dequeue(), front() and find() which performs theoperations
described above in the problem description.

Expected Time Complexity: O(1) for enqueue(), dequeue() and front(); O(N) for find().Expected
Auxiliary Space: O(1) for all the 4 functions.

Constraints:
1 <= Ǫ <= 103

Reverse First K elements of Ǫueue


EasyAccuracy: 81.28%Submissions: 119K+Points: 2
Given an integer K and a queue of integers, we need to reverse the order of the first K elementsof the queue,
leaving the other elements in the same relative order.

Only following standard operations are allowed on queue.enqueue(x) :

Add an item x to rear of queue


dequeue() : Remove an item from front of queue
size() : Returns number of elements in queue.front() :
Finds front item.
Note: The above operations represent the general processings. In-built functions of therespective
languages can be used to solve the problem.

Example 1:

Input:
53
12345
Output:
32145
Explanation:
After reversing the given
input from the 3rd position the resultantoutput
will be 3 2 1 4 5.
Example 2:

Input:
44
4321
Output:
1234
Explanation:
After reversing the given
input from the 4th position the resultantoutput
will be 1 2 3 4.
Your Task:
Complete the provided function modifyǪueue() that takes queue and K as parameters andreturns a
modified queue. The printing is done automatically by the driver code.

Expected Time Complexity : O(N)


Expected Auxiliary Space : O(K)

Constraints:
1 <= K <= N <= 105
Circular tour
MediumAccuracy: 34.79%Submissions: 161K+Points: 4
Suppose there is a circle. There are N petrol pumps on that circle. You will be given two sets ofdata.
1. The amount of petrol that every petrol pump has.
2. Distance from that petrol pump to the next petrol pump.
Find a starting point where the truck can start to get through the complete circle withoutexhausting its petrol in
between.
Note : Assume for 1 litre petrol, the truck can go 1 unit of distance.Example 1:

Input:
N=4
Petrol = 4 6 7 4
Distance = 6 5 3 5
Output: 1
Explanation: There are 4 petrol pumps with
amount of petrol and distance to next petrol
pump value pairs as {4, 6}, {6, 5},
{7, 3} and {4, 5}. The first point from where
truck can make a circular tour is2nd petrol
pump. Output in this case is 1(index of 2nd
petrol pump).
Your Task:
Your task is to complete the function tour() which takes the required data as inputs and returnsan integer
denoting a point from where a truck will be able to complete the circle (The truck willstop at each petrol
pump and it has infinite capacity). If there exists multiple such starting points, then the function must
return the first one out of those. (return -1 otherwise)

Expected Time Complexity: O(N)


Expected Auxiliary Space : O(1)

Constraints:
2 ≤ N ≤ 10000
1 ≤ petrol, distance ≤ 1000
Graph

Q1 Given an undirected graph with V nodes and E edges, create and returnan
adjacency list of the graph. 0-based indexing is followed everywhere.

Example 1:

Input:
V = 5, E = 7
edges = {(0,1),(0,4),(4,1),(4,3),(1,3),(1,2),(3,2)}

Output:
{{1,4},
{0,2,3,4},
{1,3},
{1,2,4},
{0,1,3}}
Explanation:
Node 0 is connected to 1 and 4.
Node 1 is connected to 0,2,3 and 4.
Node 2 is connected to 1 and 3.
Node 3 is connected to 1,2 and 4.
Node 4 is connected to 0,1 and 3.
Example 2:

Input:
V = 4, E = 3
edges = {(0,3),(0,2),(2,1)}
Output:
{{2,3}
{2},
{0,1}
{0}}
Explanation:
Node 0 is connected to 2 and 3.
Node 1 is only connected to 2.
Node 2 is connected to 0 and 1.
Node 3 is only connected to 0.
Your task:
You don't need to read input or print anything. Your task is to complete the
function printGraph() which takes the integer V denoting the number of vertices
and edges as input parameters and returns the list of list denoting theadjacency list.

Expected Time Complexity: O(V + E)


Expected Auxiliary Space: O(V + E)

Constraints:
1 ≤ V, E ≤ 105
BFS of graph
EasyAccuracy: 44.09%Submissions: 347K+Points: 2
Given a directed graph. The task is to do Breadth First Traversal of this graph
starting from 0.
Note: One can move from node u to node v only if there's an edge from u to v. Find
the BFS traversal of the graph starting from the 0th vertex, from left to right
according to the input graph. Also, you should only take nodes directly orindirectly
connected from Node 0 in consideration.

Example 1:

Input:
V = 5, E = 4
adj = {{1,2,3},{},{4},{},{}}

Output:
01234
Explanation:
0 is connected to 1 , 2 , 3.
2 is connected to 4.
so starting from 0, it will go to 1 then 2
then 3. After this 2 to 4, thus bfs will be
0 1 2 3 4.
Example 2:
Input:
V = 3, E = 2
adj = {{1,2},{},{}}

Output:
012
Explanation:
0 is connected to 1 , 2.
so starting from 0, it will go to 1 then 2,
thus bfs will be 0 1 2.

Your task:
You dont need to read input or print anything. Your task is to complete the
function bfsOfGraph() which takes the integer V denoting the number of vertices
and adjacency list as input parameters and returns a list containingthe BFS
traversal of the graph starting from the 0th vertex from left to right.

Expected Time Complexity: O(V + E)


Expected Auxiliary Space: O(V)

Constraints:
1 ≤ V, E ≤ 104
DFS of Graph
You are given a connected undirected graph. Perform a Depth First Traversalof
the graph.
Note: Use the recursive approach to find the DFS traversal of the graph
starting from the 0th vertex from left to right according to the graph.

Example 1:

Input: V = 5 , adj = [[2,3,1] , [0], [0,4], [0], [2]]

Output: 0 2 4 3 1
Explanation:
0 is connected to 2, 3, 1.
1 is connected to 0.
2 is connected to 0 and 4.
3 is connected to 0.
4 is connected to 2.
so starting from 0, it will go to 2 then 4,
and then 3 and 1.
Thus dfs will be 0 2 4 3 1.
Example 2:

Input: V = 4, adj = [[1,3], [2,0], [1], [0]]

Output: 0 1 2 3
Explanation:
0 is connected to 1 , 3.
1 is connected to 0, 2.
2 is connected to 1.
3 is connected to 0.
so starting from 0, it will go to 1 then 2
then back to 0 then 0 to 3
thus dfs will be 0 1 2 3.
Your task:
You don't need to read input or print anything. Your task is to complete the
function dfsOfGraph() which takes the integer V denoting the number of
vertices and adjacency list as input parameters and returns a list containingthe
DFS traversal of the graph starting from the 0th vertex from left to right
according to the graph.
Expected Time Complexity: O(V + E) Expected
Auxiliary Space: O(V) Constraints:
1 ≤ V, E ≤ 104
Find the number of islands
MediumAccuracy: 42.12%Submissions: 177K+Points: 4
Given a grid of size n*m (n is the number of rows and m is the number of
columns in the grid) consisting of '0's (Water) and '1's(Land). Find the
number of islands.

Note: An island is either surrounded by water or boundary of grid and is formed


by connecting adjacent lands horizontally or vertically or diagonallyi.e., in all 8
directions.

Example 1:

Input:
grid = {{0,1},{1,0},{1,1},{1,0}}
Output:
1
Explanation:
The grid is-
01
10
11
10
All lands are connected.
Example 2:

Input:
grid = {{0,1,1,1,0,0,0},{0,0,1,1,0,1,0}}
Output:
2
Expanation:
The grid is-
0111000
0011010
There are two islands :- one is colored in blue
and other in orange.
Your Task:
You don't need to read or print anything. Your task is to complete the
function numIslands() which takes the grid as an input parameter and
returns the total number of islands.

Expected Time Complexity: O(n*m)


Expected Space Complexity: O(n*m)

Constraints:
1 ≤ n, m ≤ 500
MODULE -6

Hashing

Linear Probing in Hashing


EasyAccuracy: 25.49%Submissions: 41K+Points: 2
Linear probing is a collision-handling technique in hashing. Linear probing says
that whenever a collision occurs, search for the immediate next position.

Given an array of integers and a hash table size. Fill the array elements into a hash
table using Linear Probing to handle collisions. Duplicate elements mustbe
mapped to the same position in the hash table while colliding elements must be
mapped to the [(value+1)%hashSize] position.

Note :- If there's no more space to insert a new element, just drop thatelement.

Example 1:

Input:
hashSize = 10
sizeOfArray = 4
Array[] = {4,14,24,44}
Output:
-1 -1 -1 -1 4 14 24 44 -1 -1
Explanation: 4%10=4. So put 4 in
hashtable[4].Now, 14%10=4, but
hashtable[4] is alreadyfilled so put
14 in the next slot and so on.
Example 2:

Input:
hashSize = 10
sizeOfArray = 4
Array[] = {9,99,999,9999}
Output:
99 999 9999 -1 -1 -1 -1 -1 -1 9
Explanation: 9%10=9. So put 9 in
hashtable[9]. Now, 99%10=9, but
hashtable[9] is already filled so
put 99 in the (99+1)%10 =0 slot so
99 goes into hashtable[0] and so on.
Your Task:
You don't need to read input or print anything. Your task is to complete the
function linearProbing() which takes the hash table size (HashSize), an integers
array arr[], and its size N as input parameters and inserts all the elements of the
array arr[] into a hash table. The function should return thehash table.
The empty cells of the hash table are to be given a value of -1.
Also, if there's no more space to insert a new element, just drop that element.

Expected Time Complexity: O(N)


Expected Auxiliary Space: O(N)

Constraints:
1 <= hashSize <= 1000
1 <= sizeOfArray <= 10000
0 <= Array[] <= 105
Separate chaining in Hashing
Separate chaining technique in hashing allows to us to use a linked list at each
hash slot to handle the problem of collisions. That is, every slot of the hash tableis
a linked list, so whenever a collision occurs, the element can be appened as a
node to the linked list at the slot.

In this question, we'll learn how to fill up the hash table using Separate
chaining technique. Given an array (consisting of distinct integers) and a
hashtable size, you have to fill the elements of the array into a hash table of
given size.

Example 1:

Input:
hashSize = 10
sizeOfArray = 6
arr[] = {92,4,14,24,44,91}
Output:
1->91
2->92
4->4->14->24->44
Explanation: 92%10=2 so 92 goes to slot 2.
4%10=4 so 4 goes to slot 4. 14%10=4. But 4
is already occupied so we make a linked
list at this position and add 14 after 4
in slot 4 and so on.
Example 2:

Input:
hashSize = 10
sizeOfArray = 5
arr[] = {12,45,36,87,11}
Output:
1->11
2->12
5->45
6->36
7->87
Explanation: 12%10=2 so 12 goes to slot 2.
45%10=5 goes to slot 5. 36%10=6 goes to
slot 6. 87%10=7 goes to slot 7 and finally
11%10=1 goes to slot 1.
Your Task:
This is a function problem. You need to complete the
function separateChaining that takes hashSize, arr, and sizeOfArr as
parameters, inserts elements of arr in the hashTable at positions by using
arr[i]%hashSize and then returns the has table. The printing isdone
automatically by the driver code.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(N).

Constraints:
2 <= hashSize <= 103
1 <= sizeOfArray <= 103
0 <= arri <= 107
Sorting Elements of an Array by Frequency MediumAccuracy:
44.93%Submissions: 49K+Points: 4
Given an array of integers, sort the array according to frequency of elements. That is elementsthat have
higher frequency come first. If frequencies of two elements are same, then smaller number comes first.

Example 1:

Input:
N=5
A[] = {5,5,4,6,4}
Output: 4 4 5 5 6
Explanation: The highest frequency here is
2. Both 5 and 4 have that frequency. Now
since the frequencies are same then
smallerelement comes first. So 4 4 comes
firstthen comes 5 5. Finally comes 6.
The output is 4 4 5 5 6.
Example 2:

Input:
N=5
A[] = {9,9,9,2,5}
Output: 9 9 9 2 5
Explanation: The highest frequency here is
3. The element 9 has the highest frequencySo
9 9 9 comes first. Now both 2 and 5 have
same frequency. So we print smaller element
first.
The output is 9 9 9 2 5.Your
Task:

You only need to complete the function sortByFreq that takes arr, and n as parameters andreturns the
sorted array.

Expected Time Complexity: O(NLogN).


Expected Auxiliary Space: O(N).

Constraints:1
≤ N ≤ 105
1 ≤ Ai ≤ 105
Tree

Preorder Traversal

Given a binary tree, find its preorder traversal.

Example 1:

Input:
1
/
4
/ \
4 2
Output: 1 4 4 2
Example 2:

Input:
6
/ \
3 2
\/
12
Output: 6 3 1 2 2

Your Task:
You just have to complete the function preorder() which takes the root node of
the tree as input and returns an array containing the preorder traversal ofthe tree.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(N).

Constraints:
1 <= Number of nodes <= 104
0 <= Data of a node <= 105
Inorder Traversal
Given a Binary Tree, find the In-Order Traversal of it.

Example 1:

Input:
1
/ \
3 2
Output: 3 1 2

Example 2:

Input:
10
/ \
20 30
/ \ /
40 60 50
Output: 40 20 60 10 50 30

Your Task:
You don't need to read input or print anything. Your task is to complete the
function inOrder() that takes root node of the tree as input and returns a list
containing the In-Order Traversal of the given Binary Tree.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(N).

Constraints:
1 <= Number of nodes <= 105
0 <= Data of a node <= 105
Postorder Traversal
Given a binary tree, find the Postorder Traversal of it.
For Example, the postorder traversal of the following tree is:5
10 39 1

1
/ \
10 39
/
5

Example 1:

Input:
19
/ \
10 8
/ \
11 13
Output: 11 13 10 8 19
Example 2:

Input:
11
/
15
/
7
Output: 7 15 11

Your Task:
You don't need to read input or print anything. Your task is to complete the
function postOrder() that takes root node as input and returns an array
containing the postorder traversal of the given Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Constraints:
1 <= Number of nodes <= 105 0 <= Data of a node <

***********************************************

You might also like