[go: up one dir, main page]

0% found this document useful (0 votes)
13 views65 pages

Dsa Q With Answer

The document contains multiple programming tasks involving array manipulations, including finding the maximum length of alternating even and odd subarrays, searching for an element in an array, calculating the floor of a square root, finding a subarray that sums to a given number, and identifying the smallest positive missing number. Each task includes example inputs and outputs, along with expected time and space complexities. The document also provides Java implementations for these tasks, demonstrating various sorting algorithms such as bubble sort and insertion sort.

Uploaded by

toabhay1202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views65 pages

Dsa Q With Answer

The document contains multiple programming tasks involving array manipulations, including finding the maximum length of alternating even and odd subarrays, searching for an element in an array, calculating the floor of a square root, finding a subarray that sums to a given number, and identifying the smallest positive missing number. Each task includes example inputs and outputs, along with expected time and space complexities. The document also provides Java implementations for these tasks, demonstrating various sorting algorithms such as bubble sort and insertion sort.

Uploaded by

toabhay1202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Q3 You are given an array of size n.

Find the maximum possible length of a subarray such that its

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

Explanation: The max length of subarray

is 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 as

that will be the max length subarray.

Your Task:

You don't need to take any input. Just complete the function maxEvenOdd() that returns the

maximum length.

Expected Time Complexity: O(N).

Expected Auxiliary Space: O(1).

Constraints:

1 <= n <= 106

1 <= Ai <= 103 I have to execute this program in eclipse


public class Main {

public static int maxEvenOdd(int[] arr) {

int maxLength = 1;

int currentLength = 1;

for (int i = 1; i < arr.length; i++) {

if ((arr[i] % 2 == 0 && arr[i - 1] % 2 != 0) || (arr[i] % 2 != 0 && arr[i - 1] % 2 == 0)) {

currentLength++;

maxLength = Math.max(maxLength, currentLength);

} else {

currentLength = 1;

return maxLength;

public static void main(String[] args) {

int[] arr1 = {10, 12, 14, 7, 8};

System.out.println("Output for Example 1: " + maxEvenOdd(arr1)); // Output: 3

int[] arr2 = {4, 6};

System.out.println("Output for Example 2: " + maxEvenOdd(arr2)); // Output: 1

}
Q1 Given an integer array and another integer element. The task is to find if the given element is

present 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 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

Explanation: For array elements

{1,2,3,4,5} element to be searched

is 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 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.

Expected Time Complexity: O(n).

Expected Auxiliary Space: O(1).

Constraints:

1 <= n <= 106

0 <= arr[i] <= 106

0 <= x <= 105


public class Main {

public static int search(int[] arr, int N, int X) {

for (int i = 0; i < N; i++) {

if (arr[i] == X) {

return i;

return -1;

public static void main(String[] args) {

// Example 1

int n1 = 4;

int[] arr1 = {1, 2, 3, 4};

int x1 = 3;

System.out.println("Output for Example 1: " + search(arr1, n1, x1)); // Output: 2

// Example 2

int n2 = 5;

int[] arr2 = {1, 2, 3, 4, 5};

int x2 = 5;

System.out.println("Output for Example 2: " + search(arr2, n2, x2)); // Output: 4

}
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

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
public class Main {

public static int floorSqrt(int x) {

if (x == 0 || x == 1) {

return x;

int start = 1, end = x, ans = 0;

while (start <= end) {

int mid = (start + end) / 2;

// If x is a perfect square, return mid

if (mid * mid == x) {

return mid;

// If mid*mid is less than or equal to x, update ans and search in the right half

if (mid <= x / mid) {

start = mid + 1;

ans = mid;

} else { // If mid*mid is greater than x, search in the left half

end = mid - 1;

return ans;

public static void main(String[] args) {

// Example 1

int x1 = 5;

System.out.println("Output for Example 1: " + floorSqrt(x1)); // Output: 2


// Example 2

int x2 = 4;

System.out.println("Output for Example 2: " + floorSqrt(x2)); // Output: 2

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

subarray 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 elements

from 2nd position to 4th position

is 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 elements

from 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 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.

Expected Time Complexity: O(N)

Expected Auxiliary Space: O(1)

Constraints:

1 <= N <= 105

0 <= Ai <= 109

0<= S <= 109


import java.util.ArrayList;

public class Main {

public static ArrayList<Integer> subarraySum(int[] arr, int N, int S) {

ArrayList<Integer> result = new ArrayList<>();

int start = 0, end = 0;

int sum = 0;

while (end < N) {

sum += arr[end];

while (sum > S) {

sum -= arr[start];

start++;

if (sum == S) {

result.add(start + 1); // Convert to 1-based indexing

result.add(end + 1); // Convert to 1-based indexing

return result;

end++;

result.add(-1); // If no such subarray exists

return result;

public static void main(String[] args) {

// Example 1

int N1 = 5, S1 = 12;

int[] A1 = {1, 2, 3, 7, 5};

ArrayList<Integer> result1 = subarraySum(A1, N1, S1);

System.out.println("Output for Example 1: " + result1); // Output: [2, 4]


// Example 2

int N2 = 10, S2 = 15;

int[] A2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

ArrayList<Integer> result2 = subarraySum(A2, N2, S2);

System.out.println("Output for Example 2: " + result2); // Output: [1, 5]

}
Q4 You are given an array arr[] of N integers. The task is to find the smallest positive number

missing 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 positive

missing number in the array.

Expected Time Complexity: O(N).

Expected Auxiliary Space: O(1).

Constraints:

1 <= N <= 106

-106 <= arr[i] <= 106


class Solution
{
//Function to find the smallest positive number missing from the
array.
static int segregateArr (int arr[], int n)
{
int j = 0, i;
for(i = 0; i < n; i++)
{
if(arr[i] <= 0)
{
//changing the position of negative numbers and 0.
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
//incrementing count of non-positive integers.
j++;
}
}
return j;
}

//Finding the smallest positive missing number in an array


//that contains only positive integers.
static int findMissingPositive(int arr[],int st, int end)
{

//marking arr[i] as visited by making arr[arr[i]-1] negative.


//note that 1 is subtracted because indexing starts from 0 and
//positive numbers start from 1.
for(int i=st; i<end; i++)
{
if(Math.abs(arr[i])+st - 1 < end && arr[ Math.abs(arr[i])+st
- 1] > 0)
arr[ Math.abs(arr[i])+st - 1] = -1*arr[ Math.abs(arr[i])+st
- 1];
}

for(int i=st; i<end; i++)


{
if (arr[i] > 0)
{
//returning the first index where value is positive.
// st is subtracted because we do not have to consider
negative numbers present at the start of array.
// 1 is added because indexing starts from 0.
return i-st+1;
}
}
return end-st+1;
}

//Function to find the smallest positive number missing from the


array.
static int missingNumber(int arr[], int size)
{
//first separating positive and negative numbers.
int shift = segregateArr(arr, size);

//shifting the array to access only positive part.


//calling function to find result and returning it.
return findMissingPositive(arr,shift, size);
}

}
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


public class Main {

public static void bubblesort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

boolean swapped = false;

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

int temp = arr[j];

arr[j] = arr[j + 1];

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;

public static void main(String[] args) {

// Example 1

int[] arr1 = {4, 1, 3, 9, 7};

bubblesort(arr1, arr1.length);

System.out.println("Output for Example 1:");

for (int num : arr1) {

System.out.print(num + " ");

System.out.println(); // Move to the next line


// Example 2

int[] arr2 = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

bubblesort(arr2, arr2.length);

System.out.println("Output for Example 2:");

for (int num : arr2) {

System.out.print(num + " ");

System.out.println(); // Move to the next line

}
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.

Expected Time Complexity: O(N*N).

Expected Auxiliary Space: O(1).

Constraints:

1 <= N <= 1000

1 <= arr[i] <= 1000


public class Main {

public static void insert(int arr[], int i) {

int key = arr[i];

int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their
current position

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

public static void insertionSort(int arr[], int n) {

for (int i = 1; i < n; ++i) {

insert(arr, i);

public static void main(String[] args) {

// Example 1

int[] arr1 = {4, 1, 3, 9, 7};

insertionSort(arr1, arr1.length);

System.out.println("Output for Example 1:");

for (int num : arr1) {

System.out.print(num + " ");

System.out.println(); // Move to the next line


// Example 2

int[] arr2 = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

insertionSort(arr2, arr2.length);

System.out.println("Output for Example 2:");

for (int num : arr2) {

System.out.print(num + " ");

System.out.println(); // Move to the next line

}
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

into 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 sorted

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

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 takes

A,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


import java.util.ArrayList;

public class Main {

public static ArrayList<Integer> mergeThree(int A[], int B[], int C[]) {

ArrayList<Integer> merged = new ArrayList<>();

int i = 0, j = 0, k = 0;

int N = A.length, M = B.length, P = C.length;

while (i < N && j < M && k < P) {

if (A[i] <= B[j] && A[i] <= C[k]) {

merged.add(A[i]);

i++;

} else if (B[j] <= A[i] && B[j] <= C[k]) {

merged.add(B[j]);

j++;

} else {

merged.add(C[k]);

k++;

// Add remaining elements of A[]

while (i < N) {

merged.add(A[i]);

i++;

// Add remaining elements of B[]

while (j < M) {
merged.add(B[j]);

j++;

// Add remaining elements of C[]

while (k < P) {

merged.add(C[k]);

k++;

return merged;

public static void main(String[] args) {

// Example 1

int[] A1 = {1, 2, 3, 4};

int[] B1 = {1, 2, 3, 4, 5};

int[] C1 = {1, 2, 3, 4, 5, 6};

ArrayList<Integer> merged1 = mergeThree(A1, B1, C1);

System.out.println("Output for Example 1:");

System.out.println(merged1); // Output: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6]

// Example 2

int[] A2 = {1, 2};

int[] B2 = {2, 3, 4};

int[] C2 = {4, 5, 6, 7};

ArrayList<Integer> merged2 = mergeThree(A2, B2, C2);

System.out.println("Output for Example 2:");

System.out.println(merged2); // Output: [1, 2, 2, 3, 4, 4, 5, 6, 7]

}
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

are 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 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.

Expected Time Complexity: O(N).

Expected Auxiliary Space: O(1).

Constraints:

1 ≤ |S| ≤ 104
public class Main {

public static int binarySubstring(int n, String s) {

int count = 0;

for (int i = 0; i < n; i++) {

if (s.charAt(i) == '1') {

count++;

// Count of substrings = count * (count - 1) / 2

return count * (count - 1) / 2;

public static void main(String[] args) {

// Example 1

int N1 = 4;

String S1 = "1111";

System.out.println("Output for Example 1: " + binarySubstring(N1, S1)); // Output: 6

// Example 2

int N2 = 5;

String S2 = "01101";

System.out.println("Output for Example 2: " + binarySubstring(N2, S2)); // Output: 3

}
Q2 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 characters

may map to the same character.

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

won'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 two

strings 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 diƯerent characters).

Note: |s| represents the length of string s.

Constraints:

1 <= |str1|, |str2| <= 105


public class Main {

public static boolean areIsomorphic(String str1, String str2) {

if (str1.length() != str2.length()) {

return false;

// Initialize mapping arrays

int[] map1 = new int[256];

int[] map2 = new int[256];

for (int i = 0; i < 256; i++) {

map1[i] = -1;

map2[i] = -1;

for (int i = 0; i < str1.length(); i++) {

char ch1 = str1.charAt(i);

char ch2 = str2.charAt(i);

// Check mapping from str1 to str2

if (map1[ch1] == -1) {

map1[ch1] = ch2;

} else if (map1[ch1] != ch2) {

return false; // Mapping is di erent

// Check mapping from str2 to str1

if (map2[ch2] == -1) {

map2[ch2] = ch1;

} else if (map2[ch2] != ch1) {


return false; // Mapping is di erent

return true;

public static void main(String[] args) {

// Example 1

String str1 = "aab";

String str2 = "xxy";

System.out.println("Output for Example 1: " + areIsomorphic(str1, str2)); // Output: true

// Example 2

str1 = "aab";

str2 = "xyz";

System.out.println("Output for Example 2: " + areIsomorphic(str1, str2)); // Output: false

}
Q3 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 in

which no letter occurs more than once.

Example 1:

Input:

S = machine

Output: 1

Explanation: machine is an isogram

as no letter has appeared twice. Hence

we print 1.

Example 2:

Input:

S = geeks

Output: 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 a

string 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


public class Main {

public static boolean isIsogram(String S) {

// Array to store whether a character has been encountered before

boolean[] seen = new boolean[26];

for (char ch : S.toCharArray()) {

// Convert character to lowercase

ch = Character.toLowerCase(ch);

// Check if character has been encountered before

if (seen[ch - 'a']) {

return false; // Not an isogram

// Mark character as encountered

seen[ch - 'a'] = true;

return true; // Isogram

public static void main(String[] args) {

// Example 1

String S1 = "machine";

System.out.println("Output for Example 1: " + (isIsogram(S1) ? 1 : 0)); // Output: 1

// Example 2

String S2 = "geeks";

System.out.println("Output for Example 2: " + (isIsogram(S2) ? 1 : 0)); // Output: 0


}

Q4 Pangram Checking

EasyAccuracy: 61.34%Submissions: 74K+Points: 2

Given 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:

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:

Explanation:

In the given input, there

aren't all the letters present in the

English alphabet. Hence, the output

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,

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

public class Main {

public static boolean checkPangram(String s) {

// Array to store whether a letter is present or not

boolean[] isPresent = new boolean[26];

// Iterate through the characters of the string

for (char ch : s.toCharArray()) {

// Convert character to lowercase

ch = Character.toLowerCase(ch);

// Check if character is a lowercase letter

if (ch >= 'a' && ch <= 'z') {

// Mark the presence of the letter

isPresent[ch - 'a'] = true;

// Check if all letters are present

for (boolean present : isPresent) {

if (!present) {

return false; // Not a pangram

return true; // Pangram

}
public static void main(String[] args) {

// Example 1

String s1 = "Bawds jog, flick quartz, vex nymph";

System.out.println("Output for Example 1: " + (checkPangram(s1) ? 1 : 0)); // Output: 1

// Example 2

String s2 = "sdfs";

System.out.println("Output for Example 2: " + (checkPangram(s2) ? 1 : 0)); // Output: 0

}
Q1 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


class Node {

int data;

Node next;

Node(int data) {

this.data = data;

next = null;

public class Main {

public static int getCount(Node head) {

int count = 0;

Node current = head;

// Traverse through the linked list and count nodes

while (current != null) {

count++;

current = current.next;

return count;

public static void main(String[] args) {

// Example 1: Creating linked list: 1->2->3->4->5

Node head1 = new Node(1);

head1.next = new Node(2);

head1.next.next = new Node(3);


head1.next.next.next = new Node(4);

head1.next.next.next.next = new Node(5);

System.out.println("Output for Example 1: " + getCount(head1)); // Output: 5

// Example 2: Creating linked list: 2->4->6->7->5->1->0

Node head2 = new Node(2);

head2.next = new Node(4);

head2.next.next = new Node(6);

head2.next.next.next = new Node(7);

head2.next.next.next.next = new Node(5);

head2.next.next.next.next.next = new Node(1);

head2.next.next.next.next.next.next = new Node(0);

System.out.println("Output for Example 2: " + getCount(head2)); // Output: 7

}
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 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:

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 present

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 Auixilliary Space : O(1) for both push() and pop().

Constraints:

1 <= Q <= 100

1 <= x <= 100


class MyStack {

int[] arr;

int top;

int capacity;

MyStack(int size) {

capacity = size;

arr = new int[capacity];

top = -1;

// Function to push element x into the stack

void push(int x) {

if (top == capacity - 1) {

System.out.println("Stack Overflow");

return;

arr[++top] = x;

// Function to pop element from stack

int pop() {

if (top == -1) {

System.out.println("Stack Underflow");

return -1;

return arr[top--];

}
public class Main {

public static void main(String[] args) {

MyStack stack = new MyStack(5);

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

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 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:

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
present 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 <= Q <= 100

1 <= x <= 100


// Node class to represent each node in the linked list

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;

// Function to push element x into the stack

void push(int x) {

Node newNode = new Node(x);

if (top == null) {

top = newNode;

} else {

newNode.next = top;

top = newNode;

// Function to pop element from stack

int pop() {

if (top == null) {
System.out.println("Stack Underflow");

return -1;

int popped = top.data;

top = top.next;

return popped;

public class Main {

public static void main(String[] args) {

MyStack stack = new MyStack();

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

EasyAccuracy: 53.71%Submissions: 127K+Points: 2

Given a stack, delete the middle element of the stack without using any additional data

structure.

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 look

like {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 look

like {10 30 40}.

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.

Expected Time Complexity: O(N)

Expected Auxiliary Space: O(N)

Constraints:
2 ≤ size of stack ≤ 105

import java.util.Stack;

public class Main {

// Function to delete the middle element of the stack

public static void deleteMid(Stack<Integer> stack, int sizeOfStack) {

// Base case: If the stack is empty or the middle element is reached

if (stack.isEmpty() || sizeOfStack == 0) {

return;

// Pop elements until we reach the middle element

int mid = (sizeOfStack + 1) / 2;

deleteMidUtil(stack, mid);

// Utility function to recursively delete elements until reaching the middle element

private static void deleteMidUtil(Stack<Integer> stack, int mid) {

// Base case: If the middle element is reached

if (mid == 1) {

stack.pop();

return;

// Pop the top element and call the function recursively

int temp = stack.pop();

deleteMidUtil(stack, mid - 1);

// Push the popped element back if it's not the middle element
stack.push(temp);

public static void main(String[] args) {

// Example 1

Stack<Integer> stack1 = new Stack<>();

stack1.push(10);

stack1.push(20);

stack1.push(30);

stack1.push(40);

stack1.push(50);

deleteMid(stack1, stack1.size());

System.out.println("Modified Stack 1: " + stack1); // Output: [10, 20, 40, 50]

// Example 2

Stack<Integer> stack2 = new Stack<>();

stack2.push(10);

stack2.push(20);

stack2.push(30);

stack2.push(40);

deleteMid(stack2, stack2.size());

System.out.println("Modified Stack 2: " + stack2); // Output: [10, 30, 40]

}
Implement two stacks in an array

EasyAccuracy: 56.49%Submissions: 150K+Points: 2

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.

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, it

should return -1.

pop2 : pops element from second stack and returns the popped element. If second stack is

empty, 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 empty

pop2() 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 empty

push1(3) the stack1 will be {3}

pop1() the poped element will be 3 from stack1 and stack1 will be empty

pop1() 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 and

pop1, pop2 which returns the integer poped out from stack one and two. If no integer is present

in 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
class TwoStacks:

def __init__(self, n):

self.size = n

self.arr = [None] * n

self.top1 = -1

self.top2 = n

def push1(self, x):

if self.top1 < self.top2 - 1:

self.top1 += 1

self.arr[self.top1] = x

else:

print("Stack Overflow")

def push2(self, x):

if self.top1 < self.top2 - 1:

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

iven a queue of integers and Q queries. The task is to perform operations on


queue according to the query.

Queries are as:

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


2. r : (Removes the front element of queue).
3. h : (Returns the front element).
4. f y : (check if the element y is present or not in the queue). Return "Yes"
if present, else "No".
Example 1:

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 {

//Function to push an element in queue.


void enqueue(Queue<Integer> q, int x)
{
//inserting x using add operation.
q.add(x);
}

//Function to remove front element from queue.


void dequeue(Queue<Integer> q)
{
//removing front element using poll operation.
q.poll();
}

//Function to find the front element of queue.


int front(Queue<Integer> q)
{
//returning the front element using peek operation.
return (q.peek());
}

//Function to find an element in the queue.


String find(Queue<Integer> q, int x)
{
//using an iterator over queue.
Iterator<Integer> it = q.iterator();

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)

Expected Time Complexity: O(N)


Expected Auxiliary Space : O(1)

Constraints:
2 ≤ N ≤ 10000
1 ≤ petrol, distance ≤ 1000
class Solution

//Function to find starting point where the truck can start to get through

//the complete circle without exhausting its petrol in between.

int tour(int petrol[], int distance[])

int n = petrol.length;

//considering first petrol pump as a starting point.

int start = 0;

int end = 1;

int cur_pet = petrol[start] - distance[start];

//we run a loop while all petrol pumps are not visited and we have

//reached first petrol pump again with 0 or more petrol.

while((end != start || cur_pet<0) && end <n )

//if current amount of petrol in truck becomes less than 0,

//then remove the starting petrol pump from tour.

while(cur_pet<0 && start != end && start < n )

//removing starting petrol pump and changing starting point.

cur_pet -= petrol[start] - distance[start];

start = (start+1)%n;

//if 0 is being considered as start again, then there

//is no possible solution.

if(start == 0)

return -1;
}

//adding a petrol pump to current tour.

cur_pet += petrol[end] - distance[end];

end = (end+1)%n;

//returning starting point.

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.

Expected Time Complexity: O(N)


Expected Auxiliary Space: O(N)

Constraints:
1 <= hashSize <= 1000
1 <= sizeOfArray <= 10000
0 <= Array[] <= 105
class Solution{

//Function to fill the array elements into a hash table

//using Linear Probing to handle collisions.

int[] linearProbing(int hash_size, int arr[], int array_size)

int hash_table[] = new int[hash_size];

//storing -1 at all indexes in the hash table.

for(int i = 0; i < hash_size; i++)

hash_table[i] = -1;

//iterating over the array.

for(int i=0;i<array_size;i++)

//if the value of hash table at index (arr[i]%hashSize) is -1

//which means empty then, we insert arr[i] at that place.

if(hash_table[arr[i]%hash_size]==-1)

hash_table[arr[i]%hash_size]=arr[i];

//else we move linearly from the filled position

//to find an index with -1 in hash table.

else

int counter=0;

int k=(arr[i])%hash_size;

int flag=0;

//using a loop which runs until we find an index with -1

//in hash table which means empty.


while(counter<hash_size&&hash_table[k]!=-1)

if(hash_table[k]==arr[i])

flag=1;

break;

k=(k+1)%hash_size;

counter++;

if(flag==1)

continue;

//if we find a position where arr[i] can be inserted

//then we insert the element.

if(counter<hash_size)

hash_table[k]=arr[i];

//returning the hash table.

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.

public static int sumExists(int arr[], int N, int sum) {

// using HashSet to store the elements.

HashSet<Integer> st = new HashSet<Integer>();

// inserting all elements in the HashSet.

for (int i = 0; i < N; i++) st.add(arr[i]);

// iterating over the array.

for (int i = 0; i < N; i++) {

// taking care of cases like 4-2=2 as two 2's cannot exist in

// distinct

// array so we continue iteration over next element.

if (sum - arr[i] == arr[i])

continue;

else {

// if (sum-arr[i]) exists in HashSet, we return 1.

if (st.contains(sum - arr[i])) {

return 1;

// if no such pair is present, we return 0.

return 0;

You might also like