Dsa Q With Answer
Dsa Q With Answer
elements 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
Example 2:
Input:
n=2
a[] = {4,6}
Output: 1
Your Task:
You don't need to take any input. Just complete the function maxEvenOdd() that returns the
maximum length.
Constraints:
int maxLength = 1;
int currentLength = 1;
currentLength++;
} else {
currentLength = 1;
return maxLength;
}
Q1 Given an integer array and another integer element. The task is to find if the given element is
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 element to 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
output is 4.
Your Task:
The task is to complete the function search() which takes the array arr[], its size N and the
element X as inputs and returns the index of first occurrence of X in the given array. If the
element X does not exist in the array, the function should return -1.
Constraints:
if (arr[i] == X) {
return i;
return -1;
// Example 1
int n1 = 4;
int x1 = 3;
// Example 2
int n2 = 5;
int x2 = 5;
}
Q2 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
Example 2:
Input:
x=4
Output: 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.
Constraints:
1 ≤ x ≤ 107
public class Main {
if (x == 0 || x == 1) {
return x;
if (mid * mid == x) {
return mid;
// If mid*mid is less than or equal to x, update ans and search in the right half
start = mid + 1;
ans = mid;
end = mid - 1;
return ans;
// Example 1
int x1 = 5;
int x2 = 4;
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) of
that subarray.
In case of multiple subarrays, return the subarray indexes which come first on moving from left
to right.
Note:- You have to return an ArrayList consisting of two elements left and right. In case no such
Example 1:
Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
is 12.
Example 2:
Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
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 containing
the starting and ending positions of the first 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 such
subarray is found, return an array consisting of only one element that is -1.
Constraints:
int sum = 0;
sum += arr[end];
sum -= arr[start];
start++;
if (sum == S) {
return result;
end++;
return result;
// Example 1
int N1 = 5, S1 = 12;
}
Q4 You are given an array arr[] of N integers. The task is to find the smallest positive number
Example 1:
Input:
N=5
arr[] = {1,2,3,4,5}
Output: 6
number is 6.
Example 2:
Input:
N=5
arr[] = {0,-10,1,3,-20}
Output: 2
number is 2.
Your Task:
The task is to complete the function missingNumber() which returns the smallest positive
Constraints:
}
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.
Constraints:
arr[j + 1] = temp;
swapped = true;
// If no two elements were swapped in the inner loop, then the array is already sorted
if (!swapped) {
break;
// Example 1
bubblesort(arr1, arr1.length);
bubblesort(arr2, arr2.length);
}
Q2 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.
Constraints:
int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their
current position
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
insert(arr, i);
// Example 1
insertionSort(arr1, arr1.length);
insertionSort(arr2, arr2.length);
}
Q3 Merge three sorted arrays
Given three sorted arrays A, B and C of size N, M and P respectively. The task is to merge them
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
arrays, 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
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 takes
Constraints:
int i = 0, j = 0, k = 0;
merged.add(A[i]);
i++;
merged.add(B[j]);
j++;
} else {
merged.add(C[k]);
k++;
while (i < N) {
merged.add(A[i]);
i++;
while (j < M) {
merged.add(B[j]);
j++;
while (k < P) {
merged.add(C[k]);
k++;
return merged;
// Example 1
// Example 2
}
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 there
Example 1:
Input:
N=4
S = 1111
Output: 6
Example 2:
Input:
N=5
S = 01101
Output: 3
Your Task:
The task is to complete the function binarySubstring() which takes the length
of 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.
Constraints:
1 ≤ |S| ≤ 104
public class Main {
int count = 0;
if (s.charAt(i) == '1') {
count++;
// Example 1
int N1 = 4;
String S1 = "1111";
// Example 2
int N2 = 5;
String S2 = "01101";
}
Q2 Isomorphic Strings
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 characters
Example 1:
Input:
str1 = aab
str2 = xxy
Output:
Explanation:
There are two diƯerent characters in aab and xxy, i.e a and b with frequency 2 and 1
respectively.
Example 2:
Input:
str1 = aab
str2 = xyz
Output:
Explanation:
There are two diƯerent characters in aab but there are three diƯerent charactersin xyz. So there
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 two
strings are isomorphic. The function returns true if strings are isomorphic else it returns false.
Expected Time Complexity: O(|str1|+|str2|).
Constraints:
if (str1.length() != str2.length()) {
return false;
map1[i] = -1;
map2[i] = -1;
if (map1[ch1] == -1) {
map1[ch1] = ch2;
if (map2[ch2] == -1) {
map2[ch2] = ch1;
return true;
// Example 1
// Example 2
str1 = "aab";
str2 = "xyz";
}
Q3 Check if a string is Isogram or not
Example 1:
Input:
S = machine
Output: 1
we print 1.
Example 2:
Input:
S = geeks
Output: 0
Your Task:
This is a function problem. You only need to complete the function isIsogram() that takes a
Note: N = |S|
Constraints:
ch = Character.toLowerCase(ch);
if (seen[ch - 'a']) {
// Example 1
String S1 = "machine";
// Example 2
String S2 = "geeks";
Q4 Pangram Checking
Example 1:
Input:
Output:
Explanation:
Example 2:
Input:
s = "sdfs"
Output:
Explanation:
is 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,
Constraints:
1 ≤ |s| ≤ 104
ch = Character.toLowerCase(ch);
if (!present) {
}
public static void main(String[] args) {
// Example 1
// Example 2
String s2 = "sdfs";
}
Q1 Count nodes of linked list
Given a singly linked list. The task is to find the length of the linked list, where length is defined
Example 1:
Input:
LinkedList: 1->2->3->4->5
Output: 5
Example 2:
Input:
LinkedList: 2->4->6->7->5->1->0
Output: 7
is 7.
Your Task:
Your task is to complete the given function getCount(), which takes a head reference as an
Constraints:
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
int count = 0;
count++;
current = current.next;
return count;
}
Implement stack using array
Write a program to implement a Stack using Array. Your task is to use the class as shown in the
comments 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, 4
Explanation:
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 present
at the top and popped out from the stack. If the stack is empty then return -1 from the pop()
method.
Constraints:
int[] arr;
int top;
int capacity;
MyStack(int size) {
capacity = size;
top = -1;
void push(int x) {
if (top == capacity - 1) {
System.out.println("Stack Overflow");
return;
arr[++top] = x;
int pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return -1;
return arr[top--];
}
public class Main {
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // Output: 3
stack.push(4);
System.out.println(stack.pop()); // Output: 4
}
Implement Stack using Linked List
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 comments
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 4
Explanation:
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
present at the top and popped out from the stack. If the stack is empty then return -1 from the
pop() method.
Constraints:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
// Stack class implementing push and pop operations using linked list
class MyStack {
Node top;
void push(int x) {
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
int pop() {
if (top == null) {
System.out.println("Stack Underflow");
return -1;
top = top.next;
return popped;
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // Output: 3
stack.push(4);
System.out.println(stack.pop()); // Output: 4
}
Delete middle element of a stack
Given a stack, delete the middle element of the stack without using any additional data
structure.
Note: The output shown by the compiler is the stack from top to bottom.
Example 1:
Input:
Output:
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 look
Example 2:
Input:
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 look
Your Task:
You don't need to read input or print anything. Complete the function deleteMid() which takes
the stack and its size as input parameters and modifies the stack in-place.
Constraints:
2 ≤ size of stack ≤ 105
import java.util.Stack;
if (stack.isEmpty() || sizeOfStack == 0) {
return;
deleteMidUtil(stack, mid);
// Utility function to recursively delete elements until reaching the middle element
if (mid == 1) {
stack.pop();
return;
// Push the popped element back if it's not the middle element
stack.push(temp);
// Example 1
stack1.push(10);
stack1.push(20);
stack1.push(30);
stack1.push(40);
stack1.push(50);
deleteMid(stack1, stack1.size());
// Example 2
stack2.push(10);
stack2.push(20);
stack2.push(30);
stack2.push(40);
deleteMid(stack2, stack2.size());
}
Implement two stacks in an array
Your task is to implement 2 stacks in one array eƯiciently. You need to implement 4 methods.
twoStacks : Initialize the data structures and variables to be used to implement 2 stacks in one
array.
pop1 : pops element from first stack and returns the popped element. If first stack is empty, it
pop2 : pops element from second stack and returns the popped element. If second stack is
Example 1:
Input:
push1(2)
push1(3)
push2(4)
pop1()
pop2()
pop2()
Output:
3 4 -1
Explanation:
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 empty
Example 2:
Input:
push1(1)
push2(2)
pop1()
push1(3)
pop1()
pop1()
Output:
1 3 -1
Explanation:
pop1() the poped element will be 1 from stack1 and stack1 will be empty
pop1() the poped element will be 3 from stack1 and stack1 will be empty
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 and
pop1, pop2 which returns the integer poped out from stack one and two. If no integer is present
Constraints:
The sum of count of elements in both the stacks < size of the given array
class TwoStacks:
self.size = n
self.arr = [None] * n
self.top1 = -1
self.top2 = n
self.top1 += 1
self.arr[self.top1] = x
else:
print("Stack Overflow")
self.top2 -= 1
self.arr[self.top2] = x
else:
print("Stack Overflow")
def pop1(self):
if self.top1 >= 0:
x = self.arr[self.top1]
self.top1 -= 1
return x
else:
print("Stack 1 is empty")
return -1
def pop2(self):
if self.top2 < self.size:
x = self.arr[self.top2]
self.top2 += 1
return x
else:
print("Stack 2 is empty")
return -1
# Example usage:
stacks = TwoStacks(5)
stacks.push1(2)
stacks.push1(3)
stacks.push2(4)
print(stacks.pop1()) # Output: 3
print(stacks.pop2()) # Output: 4
print(stacks.pop2()) # Output: -1
Operation on Queue
Input:
Q=6
Queries = i 2 i 4 i 3 i 5 h f 8
Output:
2
No
Explanation: Inserting 2, 4, 3, and 5
onto the queue: 2 4 3 5. h means front
So front is 2. f is find. 8 is not in
queue so No.
Example 2:
Input:
Q=4
Queries = i 3 i 4 r f 3
Output: No
Explanation: Inserting 3 and 4 . When
we return and remove 3 and then when
we find 3 , it will return NO as
output as 3 is not present in the
queue.
Your Task:
Your task is to complete
functions enqueue(), dequeue(), front() and find() which performs the
operations 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 <= Q <= 103
class Solution {
while(it.hasNext()){
//if element is present in queue, we return "Yes".
if(it.next()==x){
return "Yes";
}
}
//we reach the end without finding the given value so we return "No".
return "No";
}
}
Suppose there is a circle. There are N petrol pumps on that circle. You will
be given two sets of data.
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 without exhausting 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 is
2nd 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 returns an integer denoting a point from where a truck will be able
to complete the circle (The truck will stop 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)
Constraints:
2 ≤ N ≤ 10000
1 ≤ petrol, distance ≤ 1000
class Solution
//Function to find starting point where the truck can start to get through
int n = petrol.length;
int start = 0;
int end = 1;
//we run a loop while all petrol pumps are not visited and we have
start = (start+1)%n;
if(start == 0)
return -1;
}
end = (end+1)%n;
return start;
}
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 must
be 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 that
element.
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 the
hash 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.
Constraints:
1 <= hashSize <= 1000
1 <= sizeOfArray <= 10000
0 <= Array[] <= 105
class Solution{
hash_table[i] = -1;
for(int i=0;i<array_size;i++)
if(hash_table[arr[i]%hash_size]==-1)
hash_table[arr[i]%hash_size]=arr[i];
else
int counter=0;
int k=(arr[i])%hash_size;
int flag=0;
if(hash_table[k]==arr[i])
flag=1;
break;
k=(k+1)%hash_size;
counter++;
if(flag==1)
continue;
if(counter<hash_size)
hash_table[k]=arr[i];
return hash_table;
}
You are given an array of distinct integers and a sum. Check if there's a pair
with the given sum in the array.
Example 1:
Input:
N = 10
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sum = 14
Output:
1
Explanation:
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
and sum = 14. There is a pair {4, 10}
with sum 14.
Example 2:
Input:
N=2
arr[] = {2, 5}
sum = 10
Output:
0
Explanation:
arr[] = {2, 5} and sum = 10.
There is no pair with sum 10.
Your Task:
You don't need to read input or print anything. Your task is to complete the
provided function sumExists () which take the array arr[], its size N, and an
integer sum as inputs and returns 1 if there exists a pair with the given sum in
the array, else, it returns 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 1000
1 <= arri <= 106
1 <= sum <= 1000
// Back-end complete function Template for Java
class Geeks {
// Function to check if there is a pair with the given sum in the array.
// distinct
continue;
else {
if (st.contains(sum - arr[i])) {
return 1;
return 0;