Mygfg PDF
Mygfg PDF
45.62%
Problems
Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the
cells of ith row and jth column as 1.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is r and c, r is the number of rows and c is the number of columns.
The second line of each test case contains all the elements of the matrix in a single line separated by a single space.
Output:
Print the modified array.
Constraints:
1 ≤ T ≤ 100
1 ≤ r, c ≤ 1000
0 ≤ A[i][j] ≤ 1
Example:
Input:
3
22
10
00
23
000
001
43
100
100
100
000
Output:
11
10
001
111
111
111
100
Explanation:
Testcase1: Since only first element of matrix has 1 (at index 1,1) as value, so first row and first column are modified to 1.
int main() {
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
bool arr[n][m];
bool arr2[n][m]={0};
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>arr[i][j];
int row[n]={0};
int col[m]={0};
int i=0;
int j=0;
while(i<n)
{j=0;
int count=0;
if(!row[i]&1)
while(j<m)
if(arr[i][j]==1)
{count++;
if(!(row[i]&1))
for(int k=0;k<m;k++)
arr2[i][k]=1;
row[i]=1;
if(!(col[j]&1))
for(int k=0;k<n;k++)
{
arr2[k][j]=1;
col[j]=1;
j++;
else
j++;
if(count==m)
for(int l=0;l<n;l++)
row[l]=1;
i++;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cout<<arr2[i][j]<<" ";
cout<<endl;
return 0;
41.08%
Problems
Given a boolean 2D array where each row is sorted. Find the row with the maximum number of 1s.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case contains n and m, where n is the number of rows and m is the number of columns. The
second line of each test case contains the array elements.
Output:
Print the row with the maximum number of 1s.
Constraints:
1 ≤ T ≤ 50
1 ≤ n,m ≤ 103
Example:
Input:
2
44
0111001111110000
22
0011
Output:
2
1
Explanation :
Testcase 1 : Row 2 is having maximum number of 1s (0-based indexing).
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
int arr[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin>>arr[i][j];
int max=0;
int row=-1;
for(int i=0;i<n;i++)
vector<int> v(arr[i],arr[i]+m);
//for(int j=0;j<m;j++)
//cout<<v[j]<<" ";
//cout<<endl;
int index=upper_bound(v.begin(),v.end(),0)-v.begin();
//cout<<index<<endl;
if((m-index)>max)
{max=m-index;
row=i;
cout<<row<<endl;
return 0;
Relative Sorting
42.53%
Problems
Given two arrays A1[] and A2[] of size N and M respectively. The task is to sort A1 in such a way that the relative
order among the elements will be same as those in A2. For the elements not present in A2, append them at last in sorted
order. It is also given that the number of elements in A2[] are smaller than or equal to number of elements in A1[] and A2[]
has all distinct elements.
Note: Expected time complexity is O(N log(N)).
Input:
First line of input contains number of testcases. For each testcase, first line of input contains length of arrays N and M and
next two line contains N and M elements respectively.
Output:
Print the relatively sorted array.
Constraints:
1 ≤ T ≤ 100
1 ≤ N,M ≤ 106
1 ≤ A1[], A2[] <= 106
Example:
Input:
1
11 4
21257193688
2183
Output:
22118835679
Explanation:
Testcase 1: Array elements of A1[] are sorted according to A1[].
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
int arr1[n];
int arr2[m];
for(int i=0;i<n;i++)
cin>>arr1[i];
for(int i=0;i<m;i++)
cin>>arr2[i];
unordered_map<int,int> ma;
for(int i=0;i<n;i++)
{
ma[arr1[i]]++;
for(int i=0;i<m;i++)
while(ma[arr2[i]]>0)
cout<<arr2[i]<<" ";
ma[arr2[i]]--;
ma.erase(arr2[i]);
//itr=ma.begin();
vector<int> v;
for(itr=ma.begin();itr!=ma.end();itr++)
{ while(itr->second!=0)
{v.push_back(itr->first);
itr->second--;
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<endl;
return 0;
30.43%
The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so
that in between those days your profit is maximum.
Input:
First line contains number of test cases T. First line of each test case contains an integer value N denoting the number of
days, followed by an array of stock prices of N days.
Output:
For each testcase, output all the days with profit in a single line. And if there is no profit then print "No Profit".
Constraints:
1 <= T <= 100
2 <= N <= 103
0 <= Ai <= 104
Example
Input:
2
7
100 180 260 310 40 535 695
10
23 13 25 29 33 19 34 45 65 67
Output:
(0 3) (4 6)
(1 4) (5 9)
Explanation:
Testcase 1: We can buy stock on day 0, and sell it on 3rd day, which will give us maximum profit.
Ans.
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
int n;
cin>>n;
int arr[n];
for(int j=0;j<n;j++)
cin>>arr[j];
int j=0;
int start=0;
if(arr[0]<arr[1])
start=0;
else
start=1;
int end=0;
bool flag=false;
while(j<n-1)
if(arr[j]<=arr[j+1])
{flag=true;
end++;
else
{if(start<end)
start=j+1;
end=j+1;
j++;
if(start<end)
cout<<"("<<start<<" "<<end<<")";
if(flag==false)
cout<<"No Profit";
cout<<endl;
return 0;
49.92%
Problems
The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case
consists of a single line containing two space separated integers m and n.
Output:
For every test case print all prime numbers p such that m <= p <= n, space separated. Separate the answers for each test
case by a new line.
Constraints:
1<=T<=60
1 <= m <= n <= 100000,
n - m <= 100000
Example:
Input:
1 10
35
Output:
2357
35
Ans.
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
bool arr[m+1];
for(int i=0;i<m+1;i++)
arr[i]=true;
arr[1]=false;
for(int i=2;i*i<m+1;i++)
if(arr[i]==true)
for(int j=i*i;j<m+1;j=j+i)
arr[j]=false;
}
}
for(int i=n;i<=m;i++)
if(arr[i]==true)
cout<<i<<" ";
cout<<endl;
return 0;
49.09%
Problems
There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2
stairs at a time. Count the number of ways, the person can reach the top (order does not matter).
Note: Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, an integer N will be given.
Output:
For each testcase, in a new line, print number of possible ways to reach Nth stair.
Constraints:
1 <= T <= 1000
1 <= N <= 106
Example:
Input:
2
4
5
Output:
3
3
Ans.
#include<bits/stdc++.h>
// {
// if(n==1)
// return 1;
// else if(n==2)
// return 2;
// else
// {
// if(v[n]==-1)
// {
// if(n%2==0)
// {
// v[n]=stairs(n-1)+1;
// }
// else
// {
// v[n]=stairs(n-1);
// }
// }
// return v[n];
// }
// }
int main() {
int t;
cin>>t;
v[1]=1;
v[2]=2;
for(int i=3;i<1000001;i=i+2)
v[i]=v[i-2]+1;
for(int i=4;i<1000000;i=i+2)
v[i]=v[i+1];
}
v[1000001]=v[1000000]+1;
while(t--)
int n;
cin>>n;
cout<<v[n]<<endl;
return 0;
30.61%
Problems
There are N stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at
a time. Count the number of ways, the person can reach the top (order does matter).
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, an integer N will be given.
Output:
For each testcase, in a new line, print number of possible ways to reach Nth stair. Answer your output % 10^9+7.
Constraints:
1<=T<=105
1<=N<=105
Example:
Input:
3
4
10
24
Output:
5
89
75025
Ans.
#include<bits/stdc++.h>
if(n==1)
return 1;
else if(n==2)
return 2;
else
{ if(v[n]==-1)
v[n]=stairs(n-2)+stairs(n-1);
int main() {
int t;
cin>>t;
for(int i=0;i<100001;i++)
v[i]=-1;
while(t--)
int n;
cin>>n;
//if(n==1)
//cout<<1<<endl;
//else if(n==2)
//cout<<2<<endl;
//else
//{
// for(int i=3;i<=n;i++)
// {
// b=ans;
// }
//
//}
cout<<ans<<endl;
return 0;
Maximum Index
31.25%
Problems
Given an array A[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] <= A[j].
Input:
The first line contains an integer T, depicting total number of test cases. Then T test case follows. First line of each test
case contains an integer Ndenoting the size of the array. Next line contains N space separated integeres denoting the
elements of the array.
Output:
Print the maximum difference of the indexes i and j in a separtate line.
Constraints:
1 ≤ T ≤ 1000
1 ≤ N ≤ 107
0 ≤ A[i] ≤ 1018
Example:
Input:
1
9
34 8 10 3 2 80 30 33 1
Output:
6
Explanation:
Testcase 1: In the given array A[1] < A[7] satisfying the required condition(A[i] <= A[j]) thus giving the maximum difference
of j - i which is 6(7-1).
Ans.
int main() {
int t;
cin>>t;
for(int p=0;p<t;p++)
int n;
cin>>n;
int arr[n];
for(int j=0;j<n;j++)
cin>>arr[j];
int max=0;
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
if(arr[i]<=arr[j])
if((j-i)>max)
{ max=j-i;
if(max>(n-1-i))
break;
cout<<max<<endl;
return 0;
32.72%
Problems
Find out the maximum sub-array of non negative numbers from an array.
The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping
the third element is invalid.
Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array
B if sum(A) > sum(B).
Example:
A : [1, 2, 5, -7, 2, 3]
The two sub-arrays are [1, 2, 5] [2, 3].
The answer is [1, 2, 5] as its sum is larger than [2, 3]
NOTE 1: If there is a tie, then compare with segment's length and return segment which has maximum length
NOTE 2: If there is still a tie, then return the segment with minimum starting index
Input:
The first line contains an integer T, depicting total number of test cases.
Then following T lines contains an integer N depicting the size of array and next line followed by the value of array.
Output:
Print the Sub-array with maximum sum.
Constraints:
1 ≤ T ≤ 40
1 ≤ N ≤ 100
-100 ≤ A[i] ≤ 100
Example:
Input
2
3
123
2
-1 2
Output
123
2
Ans
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
int n;
cin>>n;
int arr[n];
for(int j=0;j<n;j++)
cin>>arr[j];
}
int max=0;
int sum=0;
int front=0;
int end=0;
int maxfront=0;
for(int j=0;j<n;j++)
{ int prevsum=sum;
sum=sum+arr[j];
if(sum>=max)
{max=sum;
end=j;
maxfront=front;
//cout<<"end "<<end<<endl;
//cout<<"maxfront "<<maxfront<<endl;
if(sum<prevsum)
sum=0;
front=j+1;
//cout<<"front "<<front<<endl;
for(int j=maxfront;j<=end;j++)
cout<<arr[j]<<" ";
cout<<endl;
return 0;
48.21%
Difficulty: Medium Marks: 4
Show Topic Tags
Problems
Given an unsorted array of size N of positive integers. One number 'A'from set {1, 2, …N} is missing and one number
'B' occurs twice in array. Find these two numbers.
Note: If you find multiple answers then print the Smallest number found. Also, expected solution is O(n) time and constant
extra space.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The
first line of each test case contains a single integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print B, the repeating number followed by A which is missing in a single line.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 106
1 ≤ A[i] ≤ N
Example:
Input:
2
2
22
3
133
Output:
21
32
Explanation:
Testcase 1: Repeating number is 2 and smallest positive missing number is 1.
Testcase 2: Repeating number is 3 and smallest positive missing number is 2.
Ans
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
int n;
cin>>n;
int arr[n+1]={0};
for(int j=0;j<n;j++)
{ int temp;
cin>>temp;
arr[temp]++;
int left=0,repeat=0;
for(int j=1;j<n+1;j++)
{ //cout<<arr[j]<<" ";
if(arr[j]==2)
repeat=j;
else if(arr[j]==0)
left=j;
cout<<repeat<<" "<<left<<endl;
return 0;
Kadane's Algorithm
32.92%
Problems
Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The
first line of each test case contains a single integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print the maximum sum of the contiguous sub-array in a separate line for each test case.
Constraints:
1 ≤ T ≤ 110
1 ≤ N ≤ 106
-107 ≤ A[i] <= 107
Example:
Input
2
5
1 2 3 -2 5
4
-1 -2 -3 -4
Output
9
-1
Explanation:
Testcase 1: Max subarray sum is 9 of elements (1, 2, 3, -2, 5) which is a contiguous subarray.
Ans
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int temp=0;
int max=0;
int maxele=arr[0];
for(int i=0;i<n;i++)
{ if(maxele<arr[i])
maxele=arr[i];
temp=temp+arr[i];
if(max<temp)
max=temp;
if(temp<0)
temp=0;
}
if(max==0)
cout<<maxele<<endl;
else
cout<<max<<endl;
return 0;
Coin Change
46.07%
Company Tags Accolite Amazon Microsoft Morgan Stanley OYO Rooms Paytm
Problems
Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. ,
Sm} valued coins. The order of coins doesn’t matter. For example, for N = 4 and S = {1,2,3}, there are four solutions:
{1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2},
{2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an
integer 'M' denoting the size of array. The second line contains M space-separated integers A1, A2, ..., AN denoting the
elements of the array. The third line contains an integer 'N' denoting the cents.
Output:
Print number of possible ways to make change for N cents.
Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 300
1 ≤ A[i] ≤ 300
Example:
Input:
2
3
123
4
4
2536
10
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n+1];
for(int i=1;i<n+1;i++)
cin>>arr[i];
sort(arr+1,arr+(n+1));
int c;
cin>>c;
int m[n+1][c+1];
int val=min(n+1,c+1);
int i;
for( i=0;i<val;i++)
m[i][0]=0;
m[0][i]=0;
// i=val;
while(i<c+1)
m[0][i]=0;
i++;
i=val;
while(i<n+1)
m[i][0]=0;
i++;
// int k=0;
//for(int i=1;i<n+1;i++)
//cout<<arr[i]<<" ";
//cout<<endl;
for(int i=1;i<n+1;i++)
{
for(int j=1;j<c+1;j++)
{ if(arr[i]<=j)
m[i][j]=m[i][j-arr[i]]+m[i-1][j];
else
m[i][j]=m[i-1][j];
if(arr[i]==j)
m[i][j]=m[i][j]+1;
// else
// {
// m[i][j]=0;
// }
// for(int i=0;i<n+1;i++)
// {
// for(int j=0;j<c+1;j++)
// {
// cout<<m[i][j]<<" ";
// }
// cout<<endl;
// }
cout<<m[n][c]<<endl;
return 0;
37.05%
Problems
Given an array of integers A and a sum B, find all unique combinations in A where the sum is equal to B.
Note:
All numbers will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The combinations themselves must be sorted in ascending order.
If there is no combination possible the print "Empty" (without qoutes).
Example,
Given A = 10,1,2,7,6,1,5 and B(sum) 8,
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Input:
First is T , no of test cases. 1<=T<=500
Every test case has three lines.
First line is N, size of array. 1<=N<=12
Second line contains N space seperated integers(x). 1<=x<=9.
Third line is the sum B. 1<=B<=30.
Output:
One line per test case, every subset enclosed in () and in every set intergers should be space seperated.(See example)
Example:
Input:
2
7
10 1 2 7 6 1 5
8
5
81868
12
Output:
(1 1 6)(1 2 5)(1 7)(2 6)
Empty
A.
#include <iostream>
set<string> p;
string print(vector<int> q)
{ string s="(";
for(int i=0;i<q.size()-1;i++)
s=s+to_string(q[i])+" ";
s=s+to_string(q[q.size()-1])+")";
//cout<<")";
return s;
if(s==k)
r=true;
p.insert(print(q));
return;
for(int i=j;i<v.size();i++)
if(s>k)
return;
q.push_back(v[i]);
sum(v,q,s+v[i],k,i+1,r);
if(!q.empty())
q.pop_back();
int main()
int t;
cin>>t;
while(t--)
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++)
int temp;
cin>>temp;
v.push_back(temp);
sort(v.begin(),v.end());
vector<int> q;
bool r=false;
int k;
cin>>k;
int s=0;
int j=0;
// cout<<k<<"VAL "<<endl;
sum(v,q,s,k,j,r);
if(!r)
cout<<"Empty";
else
//itr=s.begin();
for(itr=p.begin();itr!=p.end();itr++)
cout<<*itr;
cout<<endl;
p.clear();
return 0;
Combination Sum
28.77%
Problems
Given an array of integers A and a sum B, find all unique combinations in A where the sum is equal to B. The same
repeated number may be chosen from A unlimited number of times.
Note:
1. All numbers will be positive integers.
2. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
3. The combinations themselves must be sorted in ascending order.
Input:
First line of input contains number of testcases T. For each testcase, there will be three lines of input, first of which
contains N, size of array. Next line contains N space seperated integers, and the last line contains B.
Output:
For each testcase, print the sets enclosing a backet "(" and ")". No space between two sets. If no set can be formed with
the given set, then print "Empty" (without quotes).
Constraints:
1 <= T <= 500
1 <= N <= 12
1 <= A[i] <= 9
1 <= B <= 30
Example:
Input:
3
4
7265
16
11
65718299779
6
4
2468
8
Output:
(2 2 2 2 2 2 2 2)(2 2 2 2 2 6)(2 2 2 5 5)(2 2 5 7)(2 2 6 6)(2 7 7)(5 5 6)
(1 1 1 1 1 1)(1 1 1 1 2)(1 1 2 2)(1 5)(2 2 2)(6)
(2, 2, 2, 2)(2, 2, 4)(2, 6)(4, 4)(8)
Explanation:
Testcase 1: Required sets with sum equal to B (8) are as follows:
[2, 2, 2, 2]
[2, 2, 4]
[2, 6]
[4, 4]
[8]
A.
#include<bits/stdc++.h>
void print(vector<int> q)
{ cout<<"(";
for(int i=0;i<q.size()-1;i++)
cout<<q[i]<<" ";
cout<<q[q.size()-1]<<")";
if(s==k)
{r=true;
print(q);
//r=true;
return;
for(int i=j;i<v.size();i++)
if(s>k)
return;
// cout<<"*"<<v[i]<<endl;
q.push_back(v[i]);
sum(v,q,s+v[i],j,k,r);
j++;
if(q.size()==0)
return;
q.pop_back();
return;
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
set<int> s;
for(int i=0;i<n;i++)
int temp;
cin>>temp;
s.insert(temp);
vector<int> v;
for(;itr!=s.end();itr++)
v.push_back(*itr);
sort(v.begin(),v.end());
int k;
cin>>k;
int su=0;
bool r=false;
vector<int> q;
sum(v,q,su,0,k,r);
if(!r)
cout<<"Empty";
cout<<endl;
return 0;
33.32%
Problems
Given an array A of size N having distinct elements, the task is to find the next greater element for each element of the
array in order of their appearance in the array. If no such element exists, output -1
Input:
The first line of input contains a single integer T denoting the number of test cases.Then T test cases follow. Each test
case consists of two lines. The first line contains an integer N denoting the size of the array. The Second line of each test
case contains N space separated positive integers denoting the values/elements in the array A.
Output:
For each test case, print in a new line, the next greater element for each array element separated by space in order.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1018
Example:
Input
2
4
1324
4
4321
Output
3 4 4 -1
-1 -1 -1 -1
Explanation:
Testcase1: In the array, the next larger element to 1 is 3 , 3 is 4 , 2 is 4 and for 4 ? since it doesn't exist hence -1.
A.
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>arr[i];
s.push(arr[n-1]);
for(int i=n-2;i>=0;i--)
{next=arr[i];
while(s.empty()==false&&s.top()<next)
s.pop();
if(s.empty()!=true)
v.push_back(s.top());
}
else
v.push_back(-1);
s.push(next);
for(int i=v.size()-1;i>=0;i--)
cout<<v[i]<<" ";
cout<<-1<<endl;
//cout<<endl;
return 0;
34.64%
Problems
Given a binary number, write a program that prints 1 if given binary number is a multiple of 3. Else prints 0. The given
number can be big upto 2^100. It is recommended to finish the task using one traversal of input binary string.
Input:
The first line contains T denoting the number of testcases. Then follows description of testcases.
Each case contains a string containing 0's and 1's.
Output:
For each test case, output a 1 if string is multiple of 3, else 0.
Constraints:
1<=T<=100
1<=Length of Input String<=100
Example:
Input:
2
011
100
Output:
1
0
A.
int main() {
int t;
cin>>t;
while(t--)
string s;
cin>>s;
int c_even=0,c_odd=0;
for(int i=0;i<s.size();i=i+2)
if((s[i]-'0')==1)
c_even++;
for(int i=1;i<s.size();i=i+2)
if((s[i]-'0')==1)
c_odd++;
// cout<<c_odd<<" "<<c_even<<endl;
if(abs(c_odd-c_even)%3==0)
cout<<1<<endl;
else
cout<<0<<endl;
return 0;
Palindromic Array
56.94%
Difficulty: Medium Marks: 4
Associated Course(s): Sudo Placement 2019
Problems
You are given an array A of size N. Your task is to find the minimum number of operations needed to convert the given
array to 'Palindromic Array'.
Palindromic Array:
[23,15,23] is a ‘Palindromic Array’ but [2,0,1] is not.
The only allowed operation is that you can merge two adjacent elements in the array and replace them with their sum.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N, where N is the size of array.
The second line of each test case contains N space separated integers which is the input for the array.
Output:
Output the minimum number of operations required to make the given array a palindromic array.
Constraints:
1<=T<=100
1<=N<=100
Example:
Input:
2
5
32335
4
5334
Output:
1
3
Explanation:
For Test Case 1: [3 2 3 3 5] after merging the 1st two elements 3 and 2, we get the array as [5 3 3 5] which is a palindrome,
hence only 1 operation is needed.
A.
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
int i=0;
int j=n-1;
int count=0;
while(i<j)
if(arr[i]==arr[j])
i++;
j--;
else if(arr[i]<arr[j])
arr[i+1]=arr[i]+arr[i+1];
i++;
count++;
else
arr[j-1]=arr[j]+arr[j-1];
j--;
count++;
cout<<count<<endl;
return 0;
Tic-Tac-Toe
24.5%
A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach
this board position after some moves or not.
Note that every arbitrary filled grid of 9 spaces isn’t valid e.g. a grid filled with 3 X and 6 O isn’t valid situation because
each player needs to take alternate turns.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is given as a 1D array of size 9.
Output:
Constraints:
1 ≤ T ≤ 100
Example:
Input:
2
XXOOXOOOO
XXOOOXXOX
Output:
Invalid
Valid
A.
int t;
cin>>t;
for(int p=0;p<t;p++)
{ char a[3][3];
int countx=0;
int counto=0;
bool flagx=false;
bool flago=false;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
cin>>a[i][j];
//cout<<a[i][j]<<" ";
if(a[i][j]=='X')
countx++;
else if(a[i][j]=='O')
counto++;
//cout<<endl;
//cout<<counto<<" "<<countx<<endl;
//cout<<flagx<<" "<<flago<<endl;
if(countx==counto||countx==counto+1)
{//cout<<"in"<<endl;
if(a[0][0]==a[1][1]&&a[1][1]==a[2][2])
{ //cout<<flagx<<" "<<flago<<endl;
if(a[0][0]=='X')
flagx=true;
else if(a[0][0]=='O')
flago=true;
}
//cout<<flagx<<" "<<flago<<endl;
if(a[2][0]==a[1][1]&&a[1][1]==a[0][2])
if(a[2][0]=='X')
flagx=true;
else if(a[2][0]=='O')
flago=true;
// cout<<flagx<<" "<<flago<<endl;
for(int i=0;i<3;i++)
if(a[i][0]==a[i][1]&&a[i][1]==a[i][2])
if(a[i][0]=='X')
flagx=true;
else if(a[i][0]=='O')
flago=true;
//cout<<flagx<<" "<<flago<<endl;
for(int i=0;i<3;i++)
if(a[0][i]==a[1][i]&&a[1][i]==a[2][i])
if(a[0][i]=='X')
flagx=true;
else if(a[0][i]=='O')
flago=true;
//cout<<flagx<<" "<<flago<<endl;
if(flagx==true&&flago==true)
cout<<"Invalid"<<endl;
else if(flagx==true&&countx==counto+1)
cout<<"Valid"<<endl;
else if(flago==true&&counto==countx)
cout<<"Valid"<<endl;
else if(flagx==false&&flago==false)
cout<<"Valid"<<endl;
else
cout<<"Invalid"<<endl;
else
cout<<"Invalid"<<endl;
return 0;
Handshakes
42.56%
Problems
We have N persons sitting on a round table. Any person can do a handshake with any other person.
2 3
In how many ways these N people can make handshakes so that no two handshakes crosses each other. N would be
even.
For example, in above diagram, there are two non-crossing ways to handshake {{1, 2}, {3, 4}} and {{1, 3}, {2, 4}}.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N.
Output:
Constraints:
1 ≤ T ≤ 20
2 ≤ N ≤ 30
Example:
Input:
2
2
8
Output:
1
14
A.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
class GFG {
if(n==0||n==1)
return arr[n];
else
for(int i=0;i<=(n-1);i++)
v1=catalan(i,arr);
v2=catalan(n-1-i,arr);
v3=v1.multiply(v2);
val=val.add(v3);
}
arr[n]=val;
return val;
int t=sc.nextInt();
for(int i=0;i<t;i++)
int n=sc.nextInt();
for(int j=0;j<(n/2)+1;j++)
arr[j]=new BigInteger("0");
System.out.println(catalan(n/2,arr));
56.04%
Problems
Given an array with n distinct elements, convert the given array to a reduced form where all elements are in range from 0
to n-1. The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest
element, … n-1 is placed for largest element.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N, where N is the size of array.
The second line of each test case contains N input arr[i].
Output:
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 200
1 ≤ arr[i] ≤ 1000
Example:
Input:
2
3
10 40 20
5
5 10 40 30 20
Output:
021
01432
A.
#include<bits/stdc++.h>
struct C
int rank;
int index;
int val;
};
return (temp1.val<temp2.val);
return (temp1.index<temp2.index);
int main() {
int t;
cin>>t;
while(t--)
vector<struct C> v;
int n,x;
cin>>n;
for(int i=0;i<n;i++)
struct C temp;
cin>>x;
temp.val=x;
temp.index=i;
temp.rank=-1;
v.push_back(temp);
// cout<<v.size()<<"***\n";
sort(v.begin(),v.end(),exchange);
for(int i=0;i<v.size();i++)
v[i].rank=i;
sort(v.begin(),v.end(),indexfunc);
// cout<<"Hello"<<endl;
for(int i=0;i<v.size();i++)
cout<<v[i].rank<<" ";
cout<<endl;
return 0;
49.37%
Problems
Given an array arr[] of positive integers. Find the length of the longest sub-sequence such that elements in the
subsequence are consecutive integers, the consecutive numbers can be in any order.
Input:
The first line of input contains T, number of test cases. First line of line each test case contains a single integer N.
Next line contains N integer array.
Output:
Print the output of each test case in a seprate line.
Constraints:
1 <= T <= 100
1 <= N <= 105
0 <= a[i] <= 105
Example:
Input:
2
7
2619453
7
1 9 3 10 4 20 2
Output:
6
4
Explanation:
Testcase 1: The consecutive numbers here are 1, 2, 3, 4, 5, 6. These 6 numbers form the longest consecutive subsquence.
A.
#include <bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++)
int temp;
cin>>temp;
v.push_back(temp);
sort(v.begin(),v.end());
int count=1;
int max=1;
for(int i=0;i<n-1;i++)
if(v[i]+1==v[i+1])
count++;
else
if(max<count)
{max=count;
}
count=1;
if(max<count)
cout<<count<<endl;
else
cout<<max<<endl;
return 0;
Special Keyboard
39.09%
Problems
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N, N is the
number of key.
Output:
Print maximum number of A's. Print -1, if N is greater than 75.
Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 75
Example:
Input:
2
3
7
Output:
3
9
Explanation:
Testcase 1: We can at most get 3 A's on screen by pressing following key sequence.
A, A, A.
Testcase 2: We can at most get 9 A's on screen by pressing following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl
A.
#include <bits/stdc++.h>
if(x>y)
return x;
else
return y;
ll dp[76];
int main()
int t;
cin>>t;
dp[0]=0;
dp[1]=1;
dp[2]=2;
dp[3]=3;
for(int i=4;i<=75;i++)
{ dp[i]=dp[i-1]+1;
for(int j=i-3;j>0;j--)
dp[i]=max(dp[i],dp[j]*(i-j-1));
while(t--)
int n;
cin>>n;
if(n<=75)
cout<<dp[n]<<endl;
else
cout<<-1<<endl;
return 0;
50.14%
Problems
Given a set of N nuts of different sizes and N bolts of different sizes. There is a one-one mapping between nuts and bolts.
Match nuts and bolts efficiently.
Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt
and bolt can only be compared with nut to see which one is bigger/smaller.
Input:
The first line contains 'T' denoting the number of testcases. Then follows description of T testcases:
Each case begins with a single positive integer N denoting the number of nuts/bolts. Then follows the array of nuts, each
element separated by a space. And finally the bolts array, again, each element is separated by a space here. Array of
Nuts/Bolts can only consist of the following elements:{'@', '#', '$', '%', '^', '&', '~', '*', '!'}. And no element can be repeated.
Output:
For each test case, output the matched array of nuts and bolts in separate lines, where each element in the array is
separated by a space. Print the elements in the following order ! # $ % & * @ ^ ~
Constraints:
1 <= T <= 70
1 <= N <= 9
Example:
Input:
2
5
@%$#^
%@#$^
9
^&%@#*$~!
~#@%&*$^!
Output:
#$%@^
#$%@^
!#$%&*@^~
!#$%&*@^~
A.
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
vector<char> nut;
vector<char> bolt;
for(int i=0;i<n;i++)
char temp;
cin>>temp;
nut.push_back(temp);
for(int i=0;i<n;i++)
char temp;
cin>>temp;
bolt.push_back(temp);
sort(nut.begin(),nut.end());
sort(bolt.begin(),bolt.end());
for(int i=0;i<n;i++)
cout<<nut[i]<<" ";
cout<<endl;
for(int i=0;i<n;i++)
cout<<bolt[i]<<" ";
cout<<endl;
return 0;
37.02%
Problems
Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher
frequency come first. If frequencies of two elements are same, then smaller number comes first.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The
first line of each test case contains a single integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
For each testcase, in a new line, print each sorted array in a seperate line. For each array its numbers should be seperated
by space.
Constraints:
1 ≤ T ≤ 70
30 ≤ N ≤ 130
1 ≤ Ai ≤ 60
Example:
Input:
2
5
55464
5
99925
Output:
44556
99925
Explanation:
Testcase1: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are same then
smaller element comes first. So 4 4 comes first then comes 5 5. Finally comes 6.
The output is 4 4 5 5 6.
Testcase2: The highest frequency here is 3. The element 9 has the highest frequency. So 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.
A.
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
map<int,int> m;
int n;
cin>>n;
for(int j=0;j<n;j++)
int temp;
cin>>temp;
m[temp]++;
for(int j=0;j<m.size();j++)
{itr=m.begin();
int max=itr->second;
int val=itr->first;
itr++;
for(;itr!=m.end();itr++)
if(itr->second>max)
{max=itr->second;
val=itr->first;
m[val]=-1;
while(max--)
cout<<val<<" ";
cout<<endl;
return 0;
Rotten Oranges
Submissions: 12861 Accuracy:
47.28%
Problems
Given a matrix of dimension r*c where each cell in the matrix can have values 0, 1 or 2 which has the following meaning:
0 : Empty cell
1 : Cells have fresh oranges
2 : Cells have rotten oranges
So, we have to determine what is the minimum time required to all oranges. A rotten orange at index [i,j] can rot other
fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right) in unit time. If it is impossible to rot every
orange then simply return -1.
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case contains two integers r and
c, where r is the number of rows and c is the number of columns in the array a[]. Next line contains space separated r*c
elements each in the array a[].
Output:
Print an integer which denotes the minimum time taken to rot all the oranges (-1 if it is impossible).
Constraints:
1 <= T <= 100
1 <= r <= 100
1 <= c <= 100
0 <= a[i] <= 2
Example:
Input:
2
35
210211012110021
35
210210012110021
Output:
2
-1
Explanation:
Testcase 1:
2|1|0|2|1
1|0|1|2|1
1|0|0|2|1
Oranges at positions {0,0}, {0, 3}, {1, 3} and {2, 3} will rot oranges at {0, 1}, {1, 0}, {0, 4}, {1, 2}, {1, 4}, {2, 4} during 1st unit
time. And, during 2nd unit time, orange at {1, 0} got rotten and will rot orange at {2, 0}. Hence, total 2 unit of time is
required to rot all oranges.
A.
struct rnode{
int i;
int j;
int layer;
};
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
int arr[n][m];
queue<rnode> q;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{ visit[i][j]=false;
cin>>arr[i][j];
if(arr[i][j]==2)
temp.i=i;
temp.j=j;
temp.layer=0;
q.push(temp);
visit[i][j]=true;
count++;
else if(arr[i][j]==0)
visit[i][j]=true;
count++;
int level=0;
del.j=-100;
del.layer=-10;
q.push(del);
while(!q.empty())
q.pop();
if(temp.layer==-10)
if(!q.empty())
{level++;
del.i=-100;
del.j=-100;
del.layer=-10;
q.push(del);
else
int i=temp.i;
int j=temp.j;
if(i-1>=0&&visit[i-1][j]==false)
{ visit[i-1][j]=true;
count++;
if(arr[i-1][j]==1)
node.i=i-1;
node.j=j;
node.layer=level;
q.push(node);
}
if(j-1>=0&&visit[i][j-1]==false)
{ visit[i][j-1]=true;
count++;
if(arr[i][j-1]==1)
node.i=i;
node.j=j-1;
node.layer=level;
q.push(node);
if(i+1<n&&visit[i+1][j]==false)
{ visit[i+1][j]=true;
count++;
if(arr[i+1][j]==1)
node.i=i+1;
node.j=j;
node.layer=level;
q.push(node);
if(j+1<m&&visit[i][j+1]==false)
{ visit[i][j+1]=true;
count++;
if(arr[i][j+1]==1)
node.i=i;
node.j=j+1;
node.layer=level;
q.push(node);
}
}
if(count<n*m)
cout<<-1<<endl;
else
cout<<level<<endl;
//cout<<count<<" <-:"<<endl;
return 0;
29.41%
Problems
You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the
array.
Note: Expected solution in O(n) time using constant extra space.
Input:
First line consists of T test cases. First line of every test case consists of N, denoting the number of elements in array.
Second line of every test case consists of elements in array.
Output:
Single line output, print the smallest positive number missing.
Constraints:
1 <= T <= 100
1 <= N <= 106
-106 <= arr[i] <= 106
Example:
Input:
2
5
12345
5
0 -10 1 3 -20
Output:
6
2
Explanation:
Testcase 1: Smallest positive missing number is 6.
Testcase 2: Smallest positive missing number is 2.
A.
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
int n;
cin>>n;
int arr[n];
map<int,int> m;
for(int j=0;j<n;j++)
int temp;
cin>>temp;
arr[j]=temp;
m[temp]++;
int minval=1;
int j=1;
while(m[j]!=0)
minval++;
j++;
cout<<minval<<endl;
return 0;
65.33%
Given an array of n elements, where each element is at most k away from its target position. The task is to print array in
sorted form.
Input:
First line consists of T test cases. First line of every test case consists of two integers N and K, denoting number of
elements in array and at most k positions away from its target position respectively. Second line of every test case
consists of elements of array.
Output:
Single line output to print the sorted array.
Constraints:
1<=T<=100
1<=N<=100
1<=K<=N
Example:
Input:
2
33
213
63
2 6 3 12 56 8
Output:
123
2 3 6 8 12 56
A.
class compare
public:
return a>b;
};
int main() {
int t;
cin>>t;
while(t--)
int n,k;
cin>>n>>k;
int arr[n];
int i;
priority_queue<int,vector<int>,compare> pq;
for(i=0;i<n;i++)
{ cin>>arr[i];
// pq.push(temp);
for( i=0;i<k;i++)
{// cin>>arr[i];
pq.push(arr[i]);
while(pq.empty()!=true)
cout<<pq.top()<<" ";
pq.pop();
if(i<n)
{pq.push(arr[i]);
i++;
cout<<endl;
return 0;
Huffman Encoding
26.53%
Problems
Given An array of Alphabets and their frequency. Your task is to print all the given alphabets Huffman Encoding.
Note: If two elements have same frequency, then the element which if at first will be taken on left of Binary Tree and other
one to right.
Input:
First line consists of test cases T. First line of every test case consists of string of alphabets and second line consists of
its frequencies.
Output:
Print the HuffmanCodes in single line, with n spaces of each alphabet's HuffmanCodes respectively. In PreOrder form of
Binary Tree.
Constraints:
1<=T<=100
1<=|String length|<=26
Example:
Input:
1
abcdef
5 9 12 13 16 45
Output:
0 100 101 1100 1101 111
Explanation:
For the above test case.
HuffmanCodes will be
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Print in the PreOrder of Binary Tree.
A.
struct node{
int freq;
char val;
};
class compare{
public:
if(a->freq>b->freq)
return true;
else
return false;
};
if (!root)
return;
if (root->val!= '$')
int main() {
int t;
cin>>t;
while(t--)
string s;
cin>>s;
//int arr[s.size()];
for(int i=0;i<s.size();i++)
{ int freq;
cin>>freq;
temp->freq=freq;
temp->val=s[i];
temp->left=NULL;
temp->right=NULL;
pq.push(temp);
while(pq.size()!=1)
pq.pop();
pq.pop();
parent->val='$';
parent->freq=l->freq+r->freq;
parent->left=l;
parent->right=r;
pq.push(parent);
}
pq.pop();
traverse(p,"");
cout<<endl;
return 0;
41.95%
Problems
Given n Magnets which are placed linearly, with each magnet to be considered as of point object. Each magnet suffers
force from its left sided magnets such that they repel it to the right and vice versa. All forces are repulsive. The force being
equal to the distance (1/d , d being the distance). Now given the positions of the magnets, the task to find all the points
along the linear line where net force is ZERO.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. The second line of each
test case contains an integer N. Then in the next line are N space separated values of the array M[], denoting the positions
of the magnet.
Output:
For each test case in a new line print the space separated points having net force zero till precised two decimal places.
Constraints:
1<=T<=100
1<=N<=100
1<=M[]<=1000
Example:
Input:
2
2
12
4
0 10 20 30
Output:
1.50
3.82 15.00 26.18
A.
using namespace std;
double arr[101];
{ double net=0;
for(int i=0;i<n;i++)
net=net+(1/(mid-arr[i]));
return net;
double mid=(l+(r-l)*0.50);
double val=force(mid,n);
if(val<0.0000000000001&&val>(-0.0000000000001))
return mid;
else if(val<0)
return find(l,mid,n);
else
return find(mid,r,n);
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
int n;
cin>>n;
//double arr[n];
for(int j=0;j<n;j++)
{
cin>>arr[j];
for(int j=0;j<n-1;j++)
double zero=find(arr[j],arr[j+1],n);
printf("%.2f ",zero);
cout<<endl;
return 0;
47.01%
Problems
You are given an array A of size N. You need to print the total count of sub-arrays having their sum equal to 0
Input:
First line of the input contains an integer T denoting the number of test cases. Each test case consists of two lines.
First line of each test case contains an Integer N denoting the size of the array, and the second line contains N space
separated integers.
Output:
For each test case, in a new line, print the total number of subarrays whose sum is equal to 0.
Constraints:
1 <= T <= 100
1<= N <= 107
-1010 <= Ai <= 1010
Example:
Input:
2
6
005500
10
6 -1 -3 4 -2 2 4 6 -12 -7
Output:
6
4
A.
int t;
cin>>t;
while(t--)
{int n;cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int sum = 0;
int count=0;
sum += arr[i];
if (sum == 0)
// out.push_back(make_pair(0, i));
count++;
// 0 sum
if (map.find(sum) != map.end())
{
// vector<int> vc = map[sum];
// out.push_back(make_pair(*it + 1, i));
count=count+map[sum];
// Important - no else
map[sum]++;
cout<<count<<endl;
return 0;
40.04%
Problems
Consider a matrix with N rows and M columns, where each cell contains either a ‘0’ or a ‘1’ and any cell containing a 1 is
called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or
diagonally. If one or more filled cells are connected, they form a region. The task is to find the unit area of the largest
region.
Input:
The first line of input will be the number of testcases T, then T testcases follow. The first line of each testcase contains 2
space separated integers n and m. Then in the next line are the n x m inputs of the matrix A separated by space.
Output:
The output in the expected output will be the length of the largest region formed.
Constraints:
1 <= T <= 100
1 <= N, M <= 50
0 <= A[][] <= 1
Example:
Input:
2
33
110001101
13
111
Output:
4
3
Explanation:
Testcase 1: Matrix can be shown as follows:
110
001
101
A.
visited[i][j]=true;
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int seven=0;
int eight=0;
if(i+1<N&&visited[i+1][j]==false&&A[i+1][j]==1)
one= check(i+1,j,A,visited,N,M);
if(j+1<M&&visited[i][j+1]==false&&A[i][j+1]==1)
two= check(i,j+1,A,visited,N,M);
if(i-1>=0&&visited[i-1][j]==false&&A[i-1][j]==1)
three= check(i-1,j,A,visited,N,M);
if(i+1<N&&j+1<M&&visited[i+1][j+1]==false&&A[i+1][j+1]==1)
four= check(i+1,j+1,A,visited,N,M);
if(j-1>=0&&visited[i][j-1]==false&&A[i][j-1]==1)
five= check(i,j-1,A,visited,N,M);
if(i-1>=0&&j-1>=0&&visited[i-1][j-1]==false&&A[i-1][j-1]==1)
six=check(i-1,j-1,A,visited,N,M);
if(i-1>=0&&j+1<M&&visited[i-1][j+1]==false&&A[i-1][j+1]==1)
seven= check(i-1,j+1,A,visited,N,M);
if(i+1<N&&j-1>=0&&visited[i+1][j-1]==false&&A[i+1][j-1]==1)
eight= check(i+1,j-1,A,visited,N,M);
return one+two+three+four+five+six+seven+eight+1;
bool visited[N][50];
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
visited[i][j]=false;
int max=INT_MIN;
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
if(visited[i][j]==false&&A[i][j]==1)
int val=check(i,j,A,visited,N,M);
if(val>max)
max=val;
return max;
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
int arr[n][50];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>arr[i][j];
int count=findIslands(arr,n,m);
cout<<count<<endl;
return 0;
37.32%
Problems
Given a number N, the task is to find the largest prime factor of that number.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case
contains an integer N.
Output:
For each test case, in a new line, print the largest prime factor of N.
Constraints:
1 <= T <= 100
2 <= N <= 1010
Example:
Input:
2
6
15
Output:
3
5
A.
#include<math.h>
int prime(int n)
for(int i=2;i<=sqrt(n);i++)
if(n%i==0)
return 0;
return 1;
if(x>=y)
return x;
else
return y;
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++)
{ int max=2;
int n;
cin>>n;
if(prime(n))
cout<<n<<endl;
else
int j=2;
while(j<=sqrt(n))
if(n%j==0)
{ //cout<<n/j<<" "<<prime(n/j)<<endl;
if(prime(n/j))
{max=max_(max,n/j);
else if(prime(j))
max=max_(max,j);
j++;
cout<<max<<endl;
return 0;
/*#include <iostream>
#include <string>
#include <cmath>
#include <bits/stdc++.h>
#include <vector>
if(n==1) // exception
return false;
if(n%i==0)
return false;
return true;
if (a>b)
return a;
return b;
int max_factor = 2;
if(number%i==0) // is it a factor
max_factor = max(max_factor,number/i);
max_factor = max(max_factor,i);
return max_factor;
}
int main() {
int t;
cin >> t;
while(t--)
int number;
else
return 0;
}*/
48.96%
Problems
Given a N X N matrix (M) filled with 1, 0, 2, 3. The task is to find whether there is a path possible from source to destination,
while traversing through blank cells only. You can traverse up, down, right and left.
Output:
For each test case in a new line print 1 if the path exist from source to destination else print 0.
Constraints:
1 <= T <= 20
1 <= N <= 20
Example:
Input:
2
4
3000033001030233
3
032300100
Output:
1
0
Explanation:
Testcase 1: The matrix for the above given input is:
3000
0330
0103
0233
From the matrix we can see that there exists a path from to reach destination 2 from source 1.
Testcase 2: The matrix for the above given input is:
032
300
100
From the matrix we can see that there does not exists any path to reach destination 2 from source 1.
A.
visited[i][j]=true;
if(A[i][j]==2)
return true;
bool one=false;
bool two=false;
bool three=false;
bool four=false;
if(i+1<N&&visited[i+1][j]==false&&(A[i+1][j]==3||A[i+1][j]==2))
one= check(i+1,j,A,visited,N,M);
if(j+1<M&&visited[i][j+1]==false&&(A[i][j+1]==3||A[i][j+1]==2))
two= check(i,j+1,A,visited,N,M);
if(i-1>=0&&visited[i-1][j]==false&&(A[i-1][j]==3||A[i-1][j]==2))
three= check(i-1,j,A,visited,N,M);
if(j-1>=0&&visited[i][j-1]==false&&(A[i][j-1]==3||A[i][j-1]==2))
four= check(i,j-1,A,visited,N,M);
return (one||two||three||four);
bool visited[N][50];
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
visited[i][j]=false;
// int max=INT_MIN;
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
if(A[i][j]==1)
// for(int m=0;m<N;m++)
// {
// for(int n=0;n<M;n++)
// {
// cout<<visited[m][n]<<" ";
// }
// cout<<endl;
// }
return val;
// return max;
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
int arr[n][50];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>arr[i][j];
bool count=false;
count=findIslands(arr,n,n);
if(count==true)
cout<<1<<endl;
else
cout<<0<<endl;
}
return 0;
16.59%
Problems
Given an array A of size N, find all combination of four elements in the array whose sum is equal to a given value K. For
example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and K = 23, one of the quadruple is “3 5 7 8” (3 + 5 + 7 + 8 = 23).
The output should contain only unique quadrples For example, if input array is {1, 1, 1, 1, 1, 1} and K = 4, then output
should be only one quadrple {1, 1, 1, 1}
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains
two lines. The first line of input contains two integers N and K. Then in the next line are N space separated values of the
array.
Output:
For each test case in a new line print all the quadruples present in the array separated by space which sums up to value of
K. Each quadruple is unique which are separated by a delimeter "$" and are in increasing order.
Constraints:
1 <= T <= 100
1 <= N <= 100
-1000 <= K <= 1000
-100 <= A[] <= 100
Example:
Input:
2
53
00211
7 23
10 2 3 4 5 7 8
Output:
0012$
2 3 8 10 $2 4 7 10 $3 5 7 8 $
A.
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
int sum;
cin>>sum;
/*set<int> s;
for(itr=s.begin();itr!=s.end();itr++)
v.push_back(*itr);
}*/
vector<int> v;
for(int i=0;i<n;i++)
int temp;
cin>>temp;
v.push_back(temp);
sort(v.begin(),v.end());
bool flag=false;
//vector<int> v1;
//vector<int> v2;
//vector<int> v3;
//vector<int> v4;
//map<string> s;
// string prevval="";
//string val="";
map<string,int> m;
for(int i=0;i<v.size()-3;i++)
{ if(v[i]<sum)
{
for(int j=i+1;j<v.size()-2;j++)
{ if(v[i]+v[j]<sum)
for(int k=j+1;k<v.size()-1;k++)
{ if(v[i]+v[k]+v[j]<sum)
for(int l=k+1;l<v.size();l++)
if(v[i]+v[j]+v[l]+v[k]==sum)
{flag=true;
//if(val!=prevval)
if(m[val]==0)
{cout<<val;
m[val]++;
// prevval=val;
if(flag==false)
cout<<-1;
cout<<endl;
return 0;
}
46.83%
Problems
Given a string, the task is to count all palindromic sub-strings present in it.
Input:
The first line of input will contain no of test cases T . Then T test cases follow . Each test case contains 2 lines. The first
line of each test case contains an integer N denoting the length of the string, next line of test case contains the string
Output:
For each test case output a single line depecting the number of palindromic substrings present.
Constraints:
1<=T<=100
2<=N<=500
Example:
Input
2
5
abaab
7
abbaeae
Output
3
4
Explanation:
Test Case 1
Input : str = "abaab"
Output: 3
All palindrome substring are : "aba" , "aa" , "baab"
Test Case 2
Input : str = "abbaeae"
Output: 4
All palindrome substring are : "bb" , "abba" ,"aea","eae"
A.
int main() {
int n;
cin>>n;
for(int i=0;i<n;i++)
{int count=0;
// stack<int> s;
int k=3;
int l;
cin>>l;
string str;
cin>>str;
//cout<<str;
int j=0;
while(j<=l-2)
{string v=str.substr(j,2);
if(v[0]==v[1])
{count++;
//cout<<count<<endl;
j++;
// cout<<" ";
for(int a=k;a<=l;a++)
{ for(int j=0;j<=l-a;j++)
string v=str.substr(j,a);
int p=0;
while(p<a/2)
if(!(v[p]==v[a-1-p]))
break;
p++;
if(p==a/2)
{count++;
// cout<<count<<endl;
cout<<count<<endl;
return 0;
58.64%
Problems
Given an array arr[] and a number K where K is smaller than size of array, the task is to find the Kth smallest element in the
given array. It is given that all array elements are distinct.
Input:
The first line of input contains an integer T, denoting the number of testcases. Then T test cases follow. Each test case
consists of three lines. First line of each testcase contains an integer N denoting size of the array. Second line contains N
space separated integer denoting elements of the array. Third line of the test case contains an integer K.
Output:
Corresponding to each test case, print the kth smallest element in a new line.
Constraints:
1 <= T <= 100
1 <= N <= 105
1 <= arr[i] <= 105
1 <= K <= N
Example:
Input:
2
6
7 10 4 3 20 15
3
5
7 10 4 20 15
4
Output:
7
15
Explanation:
Testcase 1: 3rd smallest element in the given array is 7.
A.
using namespace std;
int n;
int temp=*a;
*a=*b;
*b=temp;
int i=l+1;
int j=r;
int p=arr[l];
while(i<=j)
while(arr[i]<p)
i++;
while(arr[j]>p)
j--;
if(i>j)
break;
else
swap(&arr[i],&arr[j]);
swap(&arr[j],&arr[l]);
return j;
int s=partition(arr,l,r);
if(s+1==k)
return arr[s];
}
else if(s+1<k)
return kthsmall(arr,s+1,r,k);
else
return kthsmall(arr,l,s-1,k);
int main() {
int t;
cin>>t;
while(t--)
// int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int k;
cin>>k;
int kval=kthsmall(arr,0,n-1,k);
cout<<kval<<endl;
return 0;
47.93%
Max. Score:
100
Problems
Given an unsorted array A[] of size N of positive integers. One number 'a'from set {1, 2, …N} is missing and one number
'b' occurs twice in array. The task is to find the repeating and the missing.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The
first line of each test case contains a single integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
For each testcase, in a new line, print b, which is the repeating number, followed by a, which is the missing number, in a
single line.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 106
1 ≤ A[i] ≤ N
Example:
Input:
2
2
22
3
133
Output:
21
32
Explanation:
Testcase 1: Repeating number is 2 and smallest positive missing number is 1.
Testcase 2: Repeating number is 3 and smallest positive missing number is 2.
My Submissions Editorial
A.
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
int arr[n+1];
int sum=0;
for(int i=0;i<n+1;i++)
arr[i]=0;
}
for(int i=1;i<n+1;i++)
int temp;
cin>>temp;
arr[temp]++;
sum=sum+temp;
int miss=-1;
int rep=-1;
for(int i=1;i<=n;i++)
if(arr[i]==2)
{rep=i;
break;
if(arr[i]==0)
miss=i;
break;
if(miss!=-1)
cout<<sum-(((n*(n+1))/2)-miss)<<" "<<miss<<endl;
else
cout<<rep<<" "<<((n*(n+1))/2)-(sum-rep)<<endl;
return 0;
30.47%
Max. Score:
100
Problems
You are given a number N. You need to convert it to 1 in minimum number of operations.
Using the above operations, find the minimum number of operations require to convert N to 1.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains 1 line of
input containing N.
Output:
For each testcase, in a new line, print the minimum number of steps required.
Constraints:
1 <= T <= 100
1 <= N <= 107
Examples:
Input:
4
1
2
3
4
Output:
0
1
2
2
Explanation:
Testcase1: 1 can be converted into 1 in 0 steps.
Testcase2: 2 can be converted into 1 in 1 step: 2-1
A.
int count(int n)
if(n==1)
return 0;
else
if(n&1)
int c1=count(n+1)+1;
int c2=count(n-1)+1;
return min(c1,c2);
else
{
int c=count(n/2)+1;
return c;
int main() {
int t;
cin>>t;
while(t--)
cin>>n;
int c=count(n);
// if(n==3)
// cout<<2<<endl;
// else
// {
// while(n!=1)
// {
// if(n&1)
// {
// if((n&(n+1))==0)
// {
// n=n+1;
// }
// else
// n=n-1;
// count++;
// }
// else
// {
// if(n&(n-1)==0)
// {count=count+(int)(log2((double)n));
// n=1;
// }
// else
// {n=n/2;
// count++;
// }
// }
// if(n==3)
// {
// count=count+2;
// break;
// }
// }
cout<<c<<endl;
return 0;
30.79%
Problems
Given an array arr[] of N positive integers, where elements are consecutive (sorted). Also, there is a single element which
is repeating X(any variable) number of times. Now, the task is to find the element which is repeated and number of times it
is repeated.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the
array N. Next line contains the array elements.
Output:
For each testcase, there will be a single line containing the element which is repeated and the number of times it is
repeated, seperated by space.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= arr[i] <= 1015
Input:
2
5
12334
5
23455
Output:
32
52
Example:
Testcase 1: In the given array, 3 is occuring two times.
A.
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
//map<int,int> m;
//for(int i=0;i<n;i++)
//{
// int t;
// cin>>t;
// m[t]++;
//}
//for(itr=m.begin();itr!=m.end();itr++)
//{
// if(itr->second>1)
// {
// cout<<itr->first<<" "<<itr->second<<endl;
// }
//}
//
int i=0;
int count=1;
while(i<n-1)
{ if(arr[i]==arr[i+1])
{count++;
break;
i++;
int j=n-1;
while(j>=0&&arr[j]!=arr[i])
j--;
cout<<arr[i]<<" "<<j-i+1<<endl;
return 0;
31.46%
Problems
Dilpreet wants to paint his dog- Buzo's home that has n boards with different lengths[A1, A2,..., An]. He hired k painters for
this work and each painter takes 1 unit time to paint 1 unit of the board.The problem is to find the minimum time to get this
job done under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only
board {1} or nothing but not board {2, 4, 5}.
Input:
The first line consists of a single integer T, the number of test cases. For each test case, the first line contains an
integerk denoting the number of painters and integer n denoting the number of boards. Next line contains n- space
separated integers denoting the size of boards.
Output:
For each test case, the output is an integer displaying the minimum time for painting that house.
Constraints:
1<=T<=100
1<=k<=30
1<=n<=50
1<=A[i]<=500
Example:
Input:
2
24
10 10 10 10
24
10 20 30 40
Output:
20
60
Explanation:
1. Here we can divide the boards into 2 equal sized partitions, so each painter gets 20 units of the board and the total time
taken is 20.
2. Here we can divide first 3 boards for one painter and the last board for the second painter.
A.
if(m[n][k]!=-1)
return m[n][k];
else
{ m[n][k]=sum;
int x=sum;
for(int i=1;i<n;i++)
x=x-arr[i];
m[n][k]=min(m[n][k],val);
return m[n][k];
int main() {
int t;
cin>>t;
while(t--)
int k,n;
cin>>k>>n;
int arr[n+1];
for(int i=1;i<n+1;i++)
{
cin>>arr[i];
if(k==1)
int sum=0;
for(int i=1;i<n+1;i++)
sum=sum+arr[i];
cout<<sum<<endl;
else if(n==1)
cout<<arr[1]<<endl;
else if(k>=n)
int max=arr[1];
for(int i=2;i<n+1;i++)
if(max<arr[i])
max=arr[i];
cout<<max<<endl;
else
int m[n+1][31];
for(int i=0;i<n+1;i++)
for(int j=0;j<k+1;j++)
m[i][j]=-1;
}
}
for(int i=1;i<k+1;i++)
m[1][i]=arr[i];
int sum=arr[1];
for(int i=2;i<n+1;i++)
{ sum=sum+arr[i];
m[i][1]=sum;
int ans=T(n,k,arr,m,sum);
cout<<ans<<endl;
return 0;
15.29%
Problems
Given a number N, the task is find the number of ways to represent this number as a sum of 2 or more consecutive natural
numbers.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case
contains an integer N as input.
Output:
For each test case, print the total number of ways In new line. If the number can not be represent in the required way, print
"0" without quotes.
Constraints:
1<=T<=6000
2<=N<=109
Example:
Input:
2
10
15
Output:
1
3
A.
int main() {
int t;
cin>>t;
for(int p=0;p<t;p++)
int n;
cin>>n;
int count=0;
int i=2;
if(n==1)
cout<<0<<endl;
else
while(1)
if((n-((i-1)*(i))/2)%i==0)
count++;
i++;
else
i++;
if((n-((i-1)*(i))/2)/i<=0)
break;
}
cout<<count<<endl;
return 0;
28.38%
Problems
Determine the row index with minimum number of ones. The given 2D matrix has only zeroes and ones and also the matrix
is sorted row wise. If two or more rows have same number of 1's than print the row withsmallest index.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case consists of
two integer n and m. The next line consists of n*m spaced integers.
Output:
Print the index of the row with minimum number of 1's. If there is 0 number of '1' in the matrix then, print '-1'.
Constraints:
1 <= T <= 103
1 <= n, m <= 100
Example:
Input:
2
33
000000000
44
0001011100110011
Output:
-1
0
Explanation:
Testcase 2: The matrix formed for the given input will be as such
0001
0111
0011
0011
First row is having minimum number of 1 i.e. answer is 0.
A.
#include <bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
int min=m;
int index=0;
bool flag=false;
for(int i=0;i<n;i++)
{int count=0;
for(int j=0;j<m;j++)
{int temp;
cin>>temp;
if(temp)
count++;
if(count!=0)
{ flag=true;
if(count<min)
{min=count;
index=i;
if(flag==false)
cout<<-1<<endl;
else
cout<<index<<endl;
return 0;
}
34.29%
Problems
Given two arrays A and B of positive integers. Your task is to find numbers which are present in the first array, but not
present in the second array.
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case contains space separated
integers N and M which denotes the number of elements in the array A and B. Next two line contains space separated
array elements.
Output:
Print space separated numbers present in the first array but not in the second.
Constraints:
1 <= T <= 100
1 <= N, M <= 107
1 <= Ai,Bi <= 1018
Example:
Input:
2
65
1 2 3 4 5 10
23105
55
4 3 5 9 11
4 9 3 11 10
Output:
4 10
5
Explanation:
Testcase 1: 4 and 10 are present in first array while not in second array.
A.
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n1,n2;
cin>>n1>>n2;
map<long long int,int> m;
for(int i=0;i<n1;i++)
cin>>temp;
m[temp]++;
arr[i]=temp;
for(int i=0;i<n2;i++)
cin>>temp;
m[temp]=0;
for(int i=0;i<n1;i++)
if(m[arr[i]]>0)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
37.62%
Problems
We are given a row wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is
always odd.
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case contains two integers r and
c, where r is the number of rows and c is the number of columns in the array a[]. Next r line contains space separated c
elements each in the array a[].
Output:
Print an integer which is the median of the matrix.
Constraints:
1<= T <=100
1<= r,c <=150
1<= a[i][j] <=1000
Example:
Input:
1
33
135
269
369
Output:
5
A.
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
vector<int> v;
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
int temp;
cin>>temp;
v.push_back(temp);
sort(v.begin(),v.end());
cout<<v[(n*m)/2]<<endl;
return 0;
Without Adjacent
Submissions: 1481 Accuracy:
9.2%
Max. Score:
100
Problems
Given an array arr[] of N positive integers. The task is to find a subsequence with maximum sum such that there should be
no adjacent elements from the array in the subsequence.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains size of array N. Next line
contains N elements of the array space seperated.
Output:
For each testcase, print the maximum sum of the subsequence.
Constraints:
1 <= T <= 100
1 <= N <= 106
1 <= arr[i] <= 106
Example:
Input:
2
3
123
3
1 20 3
Output:
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent
in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum.
A.
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>arr[i];
}
long long ic=arr[0];//include_current(max sum including current)
for(int i=1;i<n;i++)
ec=max(ip,ep);
ic=ep+arr[i];
ep=ec;
ip=ic;
cout<< max(ic,ec)<<endl;
return 0;
45.83%
Problems
Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list.
Input:
First line of input contains number of testcases T. For each testcase, first line contains length of linked list and next line
contains the linked list elements.
Output:
For each testcase, there will be a single line of output which contains the linked list with every k group elements reversed.
Example:
Input:
1
8
12245678
4
Output:
42218765
Explanation:
Testcase 2: Since, k = 4. So, we have to reverse everty group of two elements. Modified linked list is as 4, 2, 2, 1, 8, 7, 6, 5.
A.
/*Please note that it's Function problem i.e.
/*
Return the node which points to the head of the new LinkedList
Node is defined as
struct node
int data;
*/
cur=head;
prev=NULL;
temp=NULL;
head1=NULL;
int g=k;
while(g!=0)
next=cur->next;
cur->next=prev;
prev=cur;
cur=next;
g--;
head1=prev;
while(prev->next!=NULL)
{
prev=prev->next;
//cout<<prev->data<<"***"<<cur->data<<"***\n";
while(cur!=NULL)
{ g=k;
temp=prev;
prev=NULL;
next=cur->next;
cur->next=prev;
prev=cur;
cur=next;
g--;
temp->next=prev;
while(prev->next!=NULL)
prev=prev->next;
return head1;
69.01%
Company Tags Amazon Goldman Sachs Kritikal Solutions Microsoft Samsung Visa
Problems
You are given a pointer/ reference to the node which is to be deleted from the linked list of N nodes. The task is to delete
the node. Pointer/ reference to head node is not given.
Note: No head reference is given to you.
Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains length of linked list and
next line contains the data of the linked list. The last line contains the node to be deleted.
Output Format:
For each testcase, in a newline, print the linked list after deleting the given node.
Your Task:
This is a function problem. You only need to complete the function deleteNode that takes reference to the node that needs
to be deleted. Theprinting is done automatically by the driver code.
Constraints:
1 <= T <= 100
1 <= N <= 103
Example:
Input:
2
2
12
1
4
10 20 4 30
20
Output:
2
10 4 30
Explanation:
Testcase 1: After deleting 20 from the linked list, we have remaining nodes as 10, 4 and 30.
A.
struct Node
int data;
Node* next;
}*/
// This function should delete node from linked list. The function
// may assume that node exists in linked list and is not last node
node->data=(node->next)->data;
node->next=(node->next)->next;
}
Intersection Point in Y Shapped Linked Lists
49.55%
Problems
There are two singly linked lists of size N and M in a system. But, due to some programming error the end node of one of
the linked list got linked into one of the node of second list, forming a inverted Y shaped list. Write a program to get the
point where two linked lists intersect each other.
Above diagram shows an example with two linked list having 15 as intersection point. Expected time complexity is O(m +
n) where m and n are lengths of two linked lists.
Input:
First line of input is the number of test cases T. Every test case has four lines. First line of every test case contains three
numbers, x (number of nodes before merge point in 1st list), y (number of nodes before merge point in 11nd list)
and z (number of nodes after merge point). Next three lines contain x, y and z values.
Output:
Print the data of the node in the linked list where two linked lists intersects.
Your Task:
The task is to complete the function intersetPoint() which finds the point of intersection of two linked list. The function
should return data value of a node where two linked lists merge. If linked list do not merge at any point, then it shoudl
return -1.
Constraints:
1 <= T <= 50
1 <= N <= 100
1 <= value <= 1000
Example:
Input:
2
232
10 20
30 40 50
5 10
232
10 20
30 40 50
10 20
Output:
5
10
Explanation:
Testcase 1: The point of intersection of two linked list is 5, means both of them get linked (intersects) with each other at
node whose value is 5.
A.
int data;
Node(int x) {
data = x;
next = NULL;
}; */
Node* temp1=head1;
Node* temp2=head2;
int c1=0;
int c2=0;
while(temp1!=NULL)
temp1=temp1->next;
c1++;
while(temp2!=NULL)
temp2=temp2->next;
c2++;
if(c1>c2)
int d=c1-c2;
int i=0;
temp1=head1;
temp2=head2;
while(temp1!=NULL&&i<d)
temp1=temp1->next;
i++;
while(temp1!=NULL&&temp2!=NULL&&temp1!=temp2)
temp1=temp1->next;
temp2=temp2->next;
return temp1->data;
else
int d=c2-c1;
int i=0;
temp1=head1;
temp2=head2;
while(temp2!=NULL&&i<d)
temp2=temp2->next;
i++;
while(temp1!=NULL&&temp2!=NULL&&temp1!=temp2)
temp1=temp1->next;
temp2=temp2->next;
return temp1->data;
43.56%
Company Tags Adobe Amazon BankBazaar D-E-Shaw MakeMyTrip Microsoft Morgan Stanley Ola Cabs OYO
Rooms Walmart
Problems
You are given a Linked List with N nodes with M nodes having random pointers pointing to any other node consisting of
two pointers in each node, with one pointer of each node pointing to the next node just like in a single linked list and the
second pointer which is arbitary pointer can point to any node in the list and not just the previous node.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains two integers N and M. Next
line of input contains values of N nodes of the linked list and last line contains the nodes, for which each ith node is
connected to any jth node.
Output:
For each testcase, clone the given linked list.
Your Task:
The task is to complete the function copyList() which takes one argument the head of the linked list to be cloned and
should return the head of the cloned linked list.
Constraints:
1 <= T <= 100
1 <= N <= 100
1 <= Q <= 100
1 <= a, b <= 100
Example:
Input:
1
42
1234
1224
Output:
1
Explanation:
Testcase 1: In this test case, there are 4 nodes in linked list. Among these 4 nodes, 2 nodes have arbit pointer set, rest
two nodes have arbit pointer as NULL. Third line tells us the value of four nodes. The fourth line gives the information
about arbitrary pointers. The first node with set arbit pointer is 1, its arbit pointer is pointing to node 2. The second node
with set arbit pointer is 2, its arbit pointer is pointing to node 4.
A.
struct Node
int data;
Node* next;
Node* arb;
};*/
Node* tempres=res;
Node* temp=head->next;
while(temp!=NULL)
Node* temp2=newNode(temp->data);
temp=temp->next;
tempres->next=temp2;
tempres=tempres->next;
Node* p1=head;
Node* p2=head;
Node* pres=res;
while(p1!=NULL)
{ if(p1->arb!=NULL)
while(p2!=NULL&&p1->arb!=p2)
p2=p2->next;
pres->arb=p2;
// else
//{
// cout<<"arb is null\n";
//}
p1=p1->next;
pres=pres->next;
p2=head;
/*Node* tempprint=res;
// cout<<"Node working"<<endl;
while(tempprint!=NULL)
cout<<tempprint->data<<" ";
if(tempprint->arb!=NULL)
{ //cout<<"Hello "<<endl;
cout<<"--"<<tempprint->arb->data<<"--"<<" ";
tempprint=tempprint->next;
cout<<endl;*/
return res;
33.91%
Problems
Given a Linked List of size N, where every node represents a linked list and contains two pointers of its type:
(i) a next pointer to the next node,
(ii) a bottom pointer to a linked list where this node is head.
You have to flatten the linked list to a single linked list which is sorted.
| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 45
and after flattening it, the sorted linked list looks like:
5-> 7-> 8- > 10 -> 19-> 20-> 22-> 28-> 30-> 35-> 40-> 45-> 50.
The node structure has 3 fields as mentioned. A next pointer, abottom pointer and a data part.
There are multiple test cases. For each test case, this function will be called individually.
Output:
Return a pointer to the flattened linked list.
Constraints:
1 <= T <= 50
0 <= N <= 50
1 <= Mi <= 20
1 <= Element of linked list <= 1000
Example:
Input
1
4
4234
5 7 8 30 10 20 19 22 50 28 35 40 45
Output:
5 7 8 10 19 20 22 28 30 35 40 45 50
A.
struct Node{
int data;
}; */
temp->data=data;
temp->bottom=NULL;
temp->next=NULL;
return temp;
if(head1==NULL&&head2==NULL)
return NULL;
else if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
else
Node* temp=NULL;
if(head1->data<head2->data)
temp=createNode(head1->data);
temp->bottom=merge(head1->bottom,head2);
else
temp=createNode(head2->data);
temp->bottom=merge(head1,head2->bottom);
return temp;
vector<Node* > v;
Node* temp=root;
while(temp!=NULL)
// Node* t=temp;
// t->next=NULL;
v.push_back(temp);
// Node* p=t;
// while(p!=NULL)
// {
// cout<<p->data<<" ";
// p=p->bottom;
// }
// cout<<endl;
temp=temp->next;
Node* t=v[0];
t->next=NULL;
for(int i=1;i<v.size();i++)
{ v[i]->next=NULL;
t=merge(t,v[i]);
return t;
39.46%
Company Tags Amazon Fab.com Flipkart Google Microsoft One97 United Health Group Zoho
Problems
You are in a party of N people, where only one person is known to everyone. Such a person may be present in the party, if
yes, (s)he doesn’t know anyone in the party. Your task is to find the stranger (celebrity) in party.
You will be given a square matrix M[][] where if an element of row i and column j is set to 1 it means ith person knows
jth person. You need to complete the function getId() which finds the id of the celebrity if present else return -1. The
function getId() takes two arguments, the square matrix M and its size N.
Input:
The first line of input contains an element T denoting the number of test cases. Then T test cases follow. Each test case
consist of 2 lines. The first line of each test case contains a number denoting the size of the matrix M. Then in the next line
are space separated values of the matrix M.
Output:
For each test case output will be the id of the celebrity if present (0 based index). Else -1 will be printed.
User Task:
The task is to complete the function getId() which returns the Id of celebrity if present, else -1.
Constraints:
1 <= T <= 50
2 <= N <= 501
0 <= M[][] <= 1
Example:
Input (To be used only for expected output) :
2
3
010000010
2
0110
Output :
1
-1
Explanation :
For the above test case the matrix will look like
010
000
010
Here, the celebrity is the person with index 1 ie id 1
A.
// int row=0;
// int index;
// int count=0;
// vector<int> v;
// for(int i=0;i<MAX;i++)
// { row=0;
// for(int j=0;j<MAX;j++)
// {
// row=row+M[i][j];
// if(row==1)
// index=j;
// }
// if(row==1)
// {
// // M[i][j]=1;
// // v.push_back(i);
// for(int k=0;k<MAX;i++)
// {
// count=count+M[k][index];
// }
// if(count==MAX)
// return i;
// }
// else if(row==0)
// {
// for(int i=0;i<MAX;i++)
// {
// int count=0;
// for(int j=0;j<MAX;j++)
// {
// count=count+M[j][i];
// }
// if(count==MAX)
// return i;
// count=0;
// }
// }
// }
// // for(int i=0;i<v.size();i++)
// // { int count=0;
// // for(int j=0;j<MAX;j++)
// // {
// // count=count+M[v[i]][j];
// // }
// // if(count==MAX)
// // return i;
// // }
// return -1;
int a = 0;
int b = n - 1;
while (a < b)
if (M[a][b])
a++;
else
b--;
// Check if a is actually
// a celebrity or not
if ( (i != a) &&
(M[a][i] ||
!M[i][a]))
return -1;
return a;
Topological sort
40%
Company Tags Accolite Amazon Flipkart Microsoft Moonfrog Labs OYO Rooms
Problems
Given a directed graph, you need to complete the function topoSort which returns an array having the topologically sorted
elements of the array and takes two arguments. The first argument is the Graph graph represented as adjacency list
and the second is the number of vertices N.
Note : There can be multiple topological sorts of a Graph. The driver program that calls your function doesn't match your
output element by element, but checks whether the output produced by your function is a valid topological sort or not.
Input:
The first line of input takes the number of test cases then T test cases follow . Each test case contains two lines. The
first line of each test case contains two integers E and N representing no of edges and the number of vertices. Then in
the next line are E pairs of integers u, v representing an edge from u to v in the graph.
Output:
For each test case output will be 1 if the topological sort is done correctly else it will be 0 .
Constraints:
1 <= T <= 50
1 <= E, N <= 50
0 <= u, v
Example:
Input
2
66
505223404113
44
30102001
Output:
1
0
Explanation:
Testcase 1: The output 1 denotes that the order is valid. So, if you have implemented your function correctly, then output
would be 1 for all test cases.
A.
* N: number of vertices
*/
visited[i]=true;
//cout<<i<<" ";
for(int j=0;j<adj[i].size();j++)
if(visited[adj[i][j]]==false)
dfs(adj[i][j],adj,visited,rev);
rev.push_back(i);
{ vector<int> rev;
bool visited[V];
for(int i=0;i<V;i++)
{
visited[i]=false;
// cout<<"adj list"<<endl;
// for(int i=0;i<V;i++)
// { cout<<i<<" ";
// for(int j=0;j<adj[i].size();j++)
// {
// cout<<adj[i][j]<<" ";
// }
// cout<<endl;
// }
for(int i=0;i<V;i++)
if(visited[i]==false)
dfs(i,adj,visited,rev);
//cout<<endl;
// v[0]=0;
// v[1]=2;
// v[2]=1;
// v[3]=5;
// v[4]=4;
// v[5]=3;
for(int i=0;i<V;i++)
v[V-1-i]=rev[i];
// cout<<endl;
return v;
32.45%
Difficulty: Medium Marks: 4
Associated Course(s): Geeks Classes in Noida Geeks Classes in Noida- (Summer-Weekdays)More
Company Tags Amazon BrowserStack Dell Flipkart Grofers MakeMyTrip Netskope Walmart
Problems
You are given a binary tree for which you have to print its vertical order traversal. your task is to complete the
function verticalOrder which takes one argument the root of the binary tree and prints the node of the binary tree
in vertical order as shown below.
If there are multiple nodes passing through a vertical line, then they should printed as they appear in level order traversal.
Input Format:
The first line of input contains T denoting the number of testcases. Ttestcases follow. Each testcase contains 2 lines of
input. The first line contains number of operations to insert the nodes. The second line contains the nodes and their
position during the insertion.
Output Format:
For each testcase, the vertical order traversal of the tree is to be printed. The nodes' data are to be separated by spaces.
Your Task:
This is a function problem. Your task is to just complete the verticalOrder() function and you don't have to take any input
or output. The newline is automatically appended by the driver code.
Constraints:
1 <= T <= 100
1 <= Number of nodes <= 5000
Example:
Input:
4
3
12L13R35L
2
12R13L
4
10 20 L 10 30 R 20 40 L 20 60 R
4
12L13R24R45R
Output:
2153
312
40 20 10 60 30
21435
Explanation:
Testcase1:
1
/ \
2 3
/
5
As it is evident from the above diagram that during vertical traversal 2 will come first, then 1 and 5, and then 3. So output
is 2 1 5 3
Testcase2:
1
/ \
3 2
As it is evident from the above diagram that during vertical traversal 3 will come first, then 1 and then 2. So output is 3 1 2
A.
struct Node
int data;
Node* left;
Node* right;
}; */
map<int,vector<int>> m;
if(root==NULL)
return ;
else
m[i].push_back(root->data);
preorder(root->left,i-1);
preorder(root->right,i+1);
preorder(root,0);
for(itr=m.begin();itr!=m.end();itr++)
for(int i=0;i<itr->second.size();i++)
cout<<itr->second[i]<<" ";
m.clear();
}
38.68%
Problems
Given K sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a
single sorted linked list.
Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains number of linked lists N
and next line contains data of nodes of all K linked lists, with first element as M, the length of linked list and next M
elements for the same linked list.
Output Format:
For each testcase, in a new line, print the merged linked list.
Your Task:
The task is to complete the function mergeKList() which merges the K given lists into a sorted one. The printing is
done automatically by thedriver code.
Constraints
1 <= T <= 50
1 <= N <= 103
Example:
Input:
2
4
3123245256278
3
213345618
Output:
123455678
1234568
Explanation :
Testcase 1: The test case has 4 sorted linked list of size 3, 2, 2, 2
1st list 1 -> 2-> 3
2nd list 4->5
3rd list 5->6
4th list 7->8
The merged list will be 1->2->3->4->5->5->6->7->8.
A.
struct Node
int data;
Node* next;
};*/
/* arr[] is an array of pointers to heads of linked lists
Node* node=(Node*)malloc(sizeof(Node));
node->data=data;
node->next=NULL;
return node;
if(head1==NULL&&head2==NULL)
return NULL;
else if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
else
Node* temp=NULL;
if(head1->data<head2->data)
temp=createNode(head1->data);
temp->next=merge(head1->next,head2);
else
temp=createNode(head2->data);
temp->next=merge(head1,head2->next);
return temp;
{
Node* head=arr[0];
for(int i=1;i<N;i++)
head=merge(head,arr[i]);
return head;
38.66%
Company Tags Amazon Citrix D-E-Shaw Informatica Intuit Microsoft Ola Cabs One97 Opera OYO
Rooms Paytm Samsung Snapdeal Streamoid Technologies Visa
Problems
A group of connected 1's forms an island. The task is to complete the method findIslands() which returns the number of
islands present. The function takes three arguments the first is the boolean matrix A and then the next two arguments
are N and M denoting the size(N*M) of the matrix A .
Input:
The first line of input will be the number of testcases T, then T test cases follow. The first line of each testcase contains
two space separated integers N and M. Then in the next line are the NxM inputs of the matrix A separated by space .
Output:
For each testcase in a new line, print the number of islands present.
User Task:
Since this is a functional problem you don't have to worry about input, you just have to complete the
function findIslands().
Constraints:
1 <= T <= 100
1 <= N, M <= 50
0 <= A[i][j] <= 1
Output
2
2
Explanation:
Testcase 1: The graph will look like
110
001
101
Here, two islands will be formed
First island will be formed by elements {A[0][0] , A[0][1], A[1][2], A[2][2]}
Second island will be formed by {A[2][0]}.
A.
*/
visited[i][j]=true;
if(i+1<N&&visited[i+1][j]==false&&A[i+1][j]==1)
check(i+1,j,A,visited,N,M);
if(j+1<M&&visited[i][j+1]==false&&A[i][j+1]==1)
check(i,j+1,A,visited,N,M);
if(i-1>=0&&visited[i-1][j]==false&&A[i-1][j]==1)
check(i-1,j,A,visited,N,M);
if(i+1<N&&j+1<M&&visited[i+1][j+1]==false&&A[i+1][j+1]==1)
check(i+1,j+1,A,visited,N,M);
if(j-1>=0&&visited[i][j-1]==false&&A[i][j-1]==1)
check(i,j-1,A,visited,N,M);
if(i-1>=0&&j-1>=0&&visited[i-1][j-1]==false&&A[i-1][j-1]==1)
check(i-1,j-1,A,visited,N,M);
if(i-1>=0&&j+1<M&&visited[i-1][j+1]==false&&A[i-1][j+1]==1)
check(i-1,j+1,A,visited,N,M);
if(i+1<N&&j-1>=0&&visited[i+1][j-1]==false&&A[i+1][j-1]==1)
check(i+1,j-1,A,visited,N,M);
bool visited[N][50];
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
{
visited[i][j]=false;
int count=0;
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
if(visited[i][j]==false&&A[i][j]==1)
check(i,j,A,visited,N,M);
count=count+1;
return count;
40.94%
Problems
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the
given 2D array.Your task is to complete the function kthSmallest which takes two arguments the first is a matrix (mat) and
sec argument is the order of the matrix (n) and the function returns the kth smallest element in the matrix.
Input:
The first line of input is an integer T denoting the no of test cases . Then T lines follow . The first line of each test case
contains an integer N denoting the size of the matrix then in the next line are N*N space separated values of the matrix .
The third line contains an integer k.
Output:
For each test case print in a new line the kth smallest element of the matrix .
Constraints:
1<=T<=100
1<= N<=20
1<= M[][]<=100
Example
Input
1
4
16 28 60 64 22 41 63 91 27 50 87 93 36 78 87 94
3
Output
27
A.
struct node{
int val;
int row;
int col;
};
class compare{
public:
return a->val>b->val;
};
temp->val=val;
temp->row=row;
temp->col=col;
return temp;
for(int i=0;i<n;i++)
pq.push(temp);
}
while((k-1)!=0)
pq.pop();
if(temp->row+1<n)
pq.push(next);
k--;
return ans->val;
34.13%
Problems
Given a singly linked list of size N, and an integer K, you need to swap theKth node from beginning and Kth node from
end in linked list.
Note: You need to swap the nodes and not change the content of the nodes.
Input Format:
First line of input contains the number of testcases T. The first line of every testacase contains N, number of nodes in
linked list and K, the nodes to be swapped and the second line of contains the elements of the linked list.
Output Format:
If nodes are swapped correctly, the output will be 1, else 0.
User Task:
The task is to complete the function swapkthnode(), which has arguments head, num and K, and it should return new
head. The validation is doneinternally by the driver code to ensure that the swapping is done by changing
references/pointers only. A correct code would always cause output as 1.
Constraints:
1 <= T <= 100
1 <= N <= 103
1 <= K <= 103
Example:
Input:
3
41
1234
53
12345
34
1234
Ouput:
1
1
1
Explanation:
Testcase1: Here K = 1, hence after swapping the 1st node from beginning and end the new list will be 4 2 3 1.
A.
struct Node {
int data;
Node *next;
Node(int x) {
data = x;
next = NULL;
*/
{ if(head==NULL)
return head;
if(head->next==NULL)
return head;
if(K>num)
return head;
Node *temp1=head;
Node *temp2=head;
Node *prev1=NULL;
Node *prev2=NULL;
int i=1;
while(temp1!=NULL&&i<K)
{ prev1=temp1;
temp1=temp1->next;
i++;
i=1;
while(temp2!=NULL&&i<num-K+1)
{ prev2=temp2;
temp2=temp2->next;
i++;
if(K==1)
{ temp2->next=head->next; //free(head);
prev2->next=temp1;
temp1->next=NULL;
return temp2;
if(K==num)
temp1->next=head->next; //free(head);
prev1->next=temp2;
temp2->next=NULL;
// temp1->next=NULL;
//temp2=head;
return temp1;
if(prev1!=NULL)
prev1->next=temp2;
// else
// {
// temp2=head;
// }
if(prev2!=NULL)
prev2->next=temp1;
// else
// {
// temp1=head;
// }
//temp1=head;
Node* temp3=temp2->next;
temp2->next=temp1->next;
temp1->next=temp3;
// temp1->next=temp3->next;
return head;
54.58%
Problems
Given a binary tree containing N+1 with N edges nodes and an integer X. Your task is to complete the
function countSubtreesWithSumX() that returns the count of the number of subtress having total node’s data sum equal to
a value X.
5
/ \
-10 3
/ \ / \
9 8 -4 7
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains number of edges in the
tree. Next line contains information as X Y L or X Y R which means Y is on the left of X or Y is on the right of X
respectively. Last line contains sum.
Output:
For each test case count the number of subtrees with given sum.
Your Task:
The task is to complete the function countSubtreesWithSumX() which check if there exists a subtree with sum x.
Constraints:
1 <= T <= 103
1 <= N <= 103
-103 <= Node Value <= 103
Example:
Input:
2
6
5 -10 L 5 3 R -10 9 L -10 8 R 3 -4 L 3 7 R
7
2
12L13R
5
Output:
2
0
Explanation:
Testcase 1: Subtrees with sum 7 are [9, 8, -10] and [7].
A.
/*
struct Node
int data;
Node(int x){
data = x;
};
*/
{
if(!root)
return 0;
else
int sum=treesum(root->left,x,arr)+treesum(root->right,x,arr)+root->data;
if(sum==x)
arr[0]++;
return sum;
if (!root)return 0;
int arr[1]={0};
int sum=treesum(root->left,x,arr)+treesum(root->right,x,arr)+root->data;
if(sum==x)
arr[0]++;
return arr[0];
Leaves to DLL
55.42%
Problems
Given a Binary Tree with N edges. The task is to extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL
need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and
right pointers are different. In DLL, left means previous pointer and right means next pointer. Head of DLL should point to
the left most leaf and then in inorder traversal and so on.
Input:
First line of input contains number of testcases T. For each testcase, there will be two lines, first of which containing the
number of edges (between two nodes) in the tree. Next line contains N pairs (considering a and b) with a 'L' (means node b
on left of a) or 'R' (means node b on right of a) after a and b.
Output:
For each testcase, there will be two lines containing the nodes of DLL, first in reverse order and next in order of inorder
traversal of tree.
Constraints:
1 <= T <= 100
1 <= N <= 103
Example:
Input:
2
2
12L13R
3
12L13R24L
Output:
23
32
43
34
Explanation:
Testcase 2: After extracting leaves, 3 and 4 from the tree, we have doubly linked list as 3 <-> 4.
A.
Node is as follows:
struct Node{
int data;
Node *left,*right;
};
*/
temp->data=data;
temp->left=NULL;
temp->right=NULL;
if(head==NULL)
return temp;
else
Node* cur=head;
while(cur->right!=NULL)
cur=cur->right;
}
cur->right=temp;
temp->left=cur;
return head;
if(root==NULL)
return root;
else if(root->left==NULL&&root->right==NULL)
*head_ref=root;
root=NULL;
return *head_ref;
else
stack<Node* > s;
s.push(root);
while(s.empty()!=true)
Node * temp=s.top();
s.pop();
if(temp->left==NULL&&temp->right==NULL)
*head_ref=insertDLL(*head_ref,(temp->data));
temp=NULL;
else
if(temp->right!=NULL)
s.push(temp->right);
if(temp->left!=NULL)
s.push(temp->left);
}
}
return *head_ref;
33.59%
Problems
Given an array arr[] of size N and an element k. The task is to find all elements in array that appear more than n/k times.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case
contains an integer n denoting the size of the array. Then the next line contains n space separated integers forming the
array. The last line of input contains an integer k.
Output:
Print the count of elements in array that appear more than n/k times.
User Task:
The task is to complete the function countOccurence() which returns count of elements with more than n/k times
appearance.
Constraints:
1 <= T <= 102
1 <= N <= 106
1 <= a[i] <= 106
1 <= k <= N
Example:
Input:
2
8
31221233
4
4
2332
3
Output:
2
2
Explanation:
Testcase 1: In the given array, 3 and 2 are the only elements that appears more than n/k times.
A.
float r=(float)n/(float)k;
// map<int,int> m;
// for(int i=0;i<n;i++)
// {
// m[arr[i]]++;
// }
int count=0;
// for(itr=m.begin();itr!=m.end();itr++)
// {
// if((float)itr->second>r)
// {
// count++;
// }
// }
int largest=arr[0];
for(int i=1;i<n;i++)
if(arr[i]>largest)
largest=arr[i];
int arr2[largest+1]={0};
// for(int i=0;i<largest+1;i++)
// {
// cout<<arr2[i]<<" ";
// }
for(int i=0;i<n;i++)
arr2[arr[i]]++;
for(int i=0;i<largest+1;i++)
if((float)arr2[i]>r)
count++;
// for(int i=0;i<largest+1;i++)
// {
// cout<<arr2[i]<<" ";
// }
return count;
63.89%
Problems
Given Pointer/Reference to the head of a doubly linked list of N nodes, the task is to Sort the given doubly linked list using
Merge Sort in both non-decreasing and non-increasing order.
Input Format:
There are be multiple test cases, for each test case function mergeSort() will be called separately. The only input to the
function is the pointer/reference to the head of the doubly linked list.
Output Format:
For each test, print the sorted doubly linked list in both order i.e. in non-decreasing and non-increasing order.
Your Task:
The task is to complete the function sortDoubly() which sorts the doubly linked list. The printing is done automatically by
the driver code.
Constraints:
1 <= T <= 100
1 <= N <= 105
Example:
Input:
2
8
73526418
5
9 15 0 -1 0
Ouput:
12345678
87654321
-1 0 0 9 15
15 9 0 0 -1
Explanation:
Testcase 1: After sorting the given linked list in both ways, resultant matrix will be as given in the first two line of output,
where first line is the output for non-decreasing order and next line is for non-increasing order.
A.
/*
struct Node
int data;
struct Node *next, *prev;
data = x;
}; */
temp->data=data;
temp->prev=NULL;
temp->next=NULL;
if(head1==NULL&&head2==NULL)
return NULL;
else if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
else
if(head1->data<head2->data)
temp=createNode(head1->data);
temp->next=merge(head1->next,head2);
// t=t->next;
// while(t!=NULL&&t->prev==NULL)
// {
// t->prev=pre;
// t=t->next;
// pre=pre->next;
// }
else
temp=createNode(head2->data);
temp->next=merge(head1,head2->next);
// t=t->next;
// while(t!=NULL&&t->prev==NULL)
// {
// t->prev=pre;
// t=t->next;
// pre=pre->next;
// }
//return temp;
return temp;
if(head==NULL)
return NULL;
else if(head->next==NULL)
return head;
else
while(fast!=NULL)
{
fast=fast->next;
if(fast!=NULL)
{ pre=slow;
fast=fast->next;
slow=slow->next;
temp->prev=NULL;
pre->next=NULL;
return temp;
if(head==NULL)
return NULL;
else if(head->next==NULL)
return head;
else
return merge(l,h);
if(head==NULL)
return NULL;
else if(head->next==NULL)
return head;
else
temp=temp->next;
while(temp!=NULL&&temp->prev==NULL)
temp->prev=pre;
temp=temp->next;
pre=pre->next;
return dohead;
32.3%
Problems
Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes
visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Input Format:
The first line of the input contains a single integer T denoting the number of test cases. T testcases follow. Each testcase
contains two lines of input. The first line contains number of edges. The second line contains relation between nodes.
Output Format:
For each test case, in a new line, print top view of the binary tree level wise. The nodes should be separated by space.
Your Task:
Since this is a function problem. You don't have to take input. Just complete the function printTopView() that takes root
node as parameter.
Constraints:
1 <= T <= 100
1 <= N <= 50
Example:
Input:
2
2
12L13R
5
10 20 L 10 30 R 20 40 L 20 60 R 30 90 L
Output:
123
10 20 30 40
Explanation:
Testcase 1:
/ \
2 3
10
/ \
20 30
/ \ /
40 60 90
A.
/*struct Node
int data;
};*/
//map<int,vector<int>> m;
if(root==NULL)
return;
else
m[i].push_back(root->data);
preorder(root->left,i-1);
preorder(root->right,i+1);
}*/
/* preorder(root,0);
stack<int> s;
queue<int> q;
//m.erase(0);
for(itr=m.begin();itr!=m.end();itr++)
q.push(itr->second[0]);
//s.push(itr->second[itr->second.size()-1]);
vector<int> p;
while(!q.empty())
p.push_back(q.front());
q.pop();
sort(p.begin(),p.end());
for(int i=0;i<p.size();i++)
cout<<p[i]<<" ";
//cout<<root->data<<" ";
while(!s.empty())
cout<<s.top()<<" ";
s.pop();
}
m.clear();*/
map<int,int> m;
que.push(make_pair(root,0));
while(!que.empty())
que.pop();
if(m.find(cur.second)==m.end())
cout<<cur.first->data<<" ";
m[cur.second]=cur.first->data;
if(cur.first->left)
que.push(make_pair(cur.first->left,cur.second-1));
if(cur.first->right)
que.push(make_pair(cur.first->right,cur.second+1));
39.66%
Problems
Given a linked list, the task is to complete the functionmaxPalindrome which returns an integer denoting the length of the
longest palindrome list that exist in the given linked list.
Examples:
Output : 5
Output : 2
Input:
The first line of input contains an integer T denotingo the no of test cases. Then T test cases follow. The first line of each
test case contains an integer N denoting the size of the linked list . Then in the next line are N space separated values of
the given linked list.
Output:
For each test case output will be the required max length of the palindrome present in the given linked list.
Constraints:
1<=T<=100
1<=N<=100
A.
struct Node
int data;
Node *next;
} */
{ int count=0;
while(head1!=NULL&&head2!=NULL)
if(head1->data==head2->data)
{count++;
head1=head1->next;
head2=head2->next;
else
break;
}
return count;
Node* cur=head;
Node* prev;
Node* next;
int count=0;
while(cur!=NULL)
next=cur->next;
cur->next=prev;
count=max(count,2*countcommon(prev,next)+1);
count=max(count,2*countcommon(cur,next));
prev=cur;
cur=next;
return count;
46.83%
Problems
Given K sorted arrays arranged in form of a matrix. The task is to merge them. You need to complete mergeKArrays()
function which takes 2 arguments, an arr[k][k] 2D Matrix containing k sorted arrays and an integer k denoting the number
of sorted arrays. The function should return a pointer to the merged sorted arrays.
Input:
The first line of input contains the number of test cases, then T test cases follows. Each test case will contain an integer N
denoting the number of sorted arrays. Then in the next line contains all the elements of the array separated by space.
Output:
The output will be the sorted merged array.
User Task:
The task is to complete the function mergeKArrays() which takes two arguments, and returns pointer to the modified array.
Constraints:
1 <= T <= 50
1 <= N <= 103
1 <= K <= 10
Example:
Input:
1
3
123456789
Output:
123456789
Explanation:
Testcase 1:
Above test case has 3 sorted arrays of size 3, 3, 3
arr[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
The merged list will be [1, 2, 3, 4, 5, 6, 7, 8, 9].
A.
// of size k*k
int t=0;
for(int i=0;i<k;i++)
for(int j=0;j<k;j++)
output[t]=arr[i][j];
t++;
sort(output,output+k*k);
return output;
45.89%
Given an array of N distinct elementsA[ ]. The task is to find the minimum number of swaps required to sort the array. Your
are required to complete the function which returns an integer denoting the minimum number of swaps, required to sort
the array.
Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow . Each test case
contains an integer N denoting the no of element of the array A[ ]. In the next line are N space separated values of the array
A[ ] .
Output:
For each test case in a new line output will be an integer denoting minimum umber of swaps that are required to sort the
array.
Constraints:
1 <= T <= 100
1 <= N <= 103
1 <= A[] <= 104
User Task: Your task is to complete minSwaps() which should return number of swaps required to make the array
elements sorted.
Output:
2
2
Explanation:
Testcase 1: We need two swaps, swap 1 with 4 and 3 with 2 to make it sorted.
A.
int count=0;
for(int i=0;i<N;i++)
{int max=A[0];
int index=0;
for(int j=1;j<N-i;j++)
if(max<A[j])
{
max=A[j];
index=j;
if(index!=(N-1-i))
{int temp=A[index];
A[index]=A[N-1-i];
A[N-1-i]=temp;
count++;
return count;
26.16%
Problems
Given two numbers as stings s1 and s2 your task is to multiply them. You are required to complete the
function multiplyStrings which takes two strings s1 and s2 as its only argument and returns their product as strings.
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow . Each test case
contains two strings s1 and s2 .
Output:
For each test case in a new line the output will be a string denoting the product of the two strings s1 and s2.
Constraints:
1 <= T <= 100
1 <= length of s1 and s2 <= 103
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user
for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task
is to complete the function specified, and not to write the full code.
A.
/*Please note that it's Function problem i.e.
class GfG{
49%
Problems
Given a graph of V nodes represented in the form of adjacency matrix. The task is to find the shortest distance of all the
vertex's from the source vertex.
Input:
The first line of input contains an integer T denoting the number of test cases . Then T test cases follow .The first line of
each test case contains an integer V denoting the size of the adjacency matrix and in the next line are V space separated
values of the matrix (graph) . The third line of each test case contains an integer denoting the source vertex s.
Output:
For each test case output will be V space separated integers where the ith integer denote the shortest distance of ith
vertex from source vertex.
You task:
You are required to complete the function dijkstra() which takes 3 arguments. The first argument is the adjacency matrix
(graph), the second argument is the source vertex s and the third argument is V denoting the size of the matrix. The
function prints V space separated integers where i'th integer denotes the shortest distance of the i'th vertex from source
vertex.
Constraints:
1 <= T <= 20
1 <= V <= 20
0 <= graph[i][j] <= 1000
0 <= s
Example:
Input:
2
2
0 25 25 0
0
3
0 1 43 1 0 6 43 6 0
2
Output:
0 25
760
Explanation:
Testcase 1: Shortest distance of source node 0 to 1 is 25, and shortest distance of source to source is 0.
A.
* V: number of vertices
*/
int dist[V];
bool v[V];
for(int i=0;i<V;i++)
dist[i]=INT_MAX;
v[i]=false;
dist[src]=0;
// v[src]=true;
for(int i=0;i<V;i++)
{ int index=src;
int min=INT_MAX;
for(int j=0;j<V;j++)
if(min>dist[j]&&v[j]==false)
index=j;
min=dist[j];
v[index]=true;
for(int j=0;j<V;j++)
if(v[j]==false&&(dist[j]>(dist[index]+graph[index][j])))
{
dist[j]=dist[index]+graph[index][j];
for(int i=0;i<V;i++)
cout<<dist[i]<<" ";
//cout<<endl;
47.96%
Problems
You are given a linked list of N nodes. The task is to remove the loop from the linked list, if present.
Input:
First line of input contains number of testcases T. T testcases follow. For each testcase, first line of input contains
length N of the linked list and next line contains N data of the linked list. The third line contains the position of the
node(from head) to which the last node will get connected. If it is 0 then there is no loop.
Output:
For each testcase, in a new line, 1 will be printed if loop is removed(correct answer) else 0 will be printed(for wrong
answer).
User Task:
You don't have to read the input, or print the output. Just complete the function removeTheLoop() which has only
argument as head reference of the linked list. If you complete this function in correct way and loop gets removed, the
answer will be 1.
Constraints:
1 <= T <= 50
1 <= N <= 300
Example:
Input:
2
3
134
2
4
1834
0
Output:
1
1
Explanation:
Testcase 1: In the first test case N = 3.
The linked list with nodes N = 3 is given. Here, x = 2 which means last node is connected with xth node of linked list.
Therefore, there exists a loop.
Testcase 2: N = 4 and x = 0, which means lastNode->next = NULL, thus the Linked list does not contains any loop.
A.
/*
struct Node {
int data;
Node(int x) {
data = x;
next = NULL;
};
*/
/*The function removes the loop from the linked list if present
Node* slow=head;
Node* fast=head;
do
slow=slow->next;
fast=(fast->next)->next;
} while(fast->next!=NULL&&(fast->next)->next!=NULL&&slow!=fast);
if(slow!=fast)
return;
// cout<<slow->data<<endl;
//cout<<fast->data<<endl;
Node* prev=fast;
Node* cur=head->next;
fast=fast->next;
// Node* prevhead=NULL;
while(cur!=fast)
{
//prevhead=prev;
prev=fast;
cur=cur->next;
fast=fast->next;
// cout<<prevhead->data<<endl;
//cout<<cur->data<<endl;
// cout<<fast->data<<endl;
prev->next=NULL;
// Node* temp=head;
// while(temp!=NULL)
// {
// cout<<temp->data<<" ";
// temp=temp->next;
// }
//cout<<" jj"<<detectloop(head)<<endl;
35.29%
Problems
Given an array arr[] of positive integers. Find the length of the longest sub-sequence such that elements in the
subsequence are consecutive integers, the consecutive numbers can be in any order.
Input Format:
The first line of input contains T, number of test cases. First line of line each test case contains a single integer N.
Next line contains N integer array.
Output Format:
Print the output of each test case in a seprate line.
Your Task:
This is a function problem. You only need to complete the functionfindLongestConseqSubseq that takes arr and
n as parameters and retunsthe length.
Constraints:
1 <= T <= 100
1 <= N <= 105
0 <= a[i] <= 105
Example:
Input:
2
7
2619453
7
1 9 3 10 4 20 2
Output:
6
4
Explanation:
Testcase 1: The consecutive numbers here are 1, 2, 3, 4, 5, 6. These 6 numbers form the longest consecutive subsquence.
A.
// map<int,int> m;
// for(int i=0;i<n;i++)
// {
// m[arr[i]]++;
// }
// int max=0;
// itr=m.begin();
// int temp=0;
// itr2=m.begin();
// itr2++;
// itr=m.begin();
// // for(itr=m.begin();itr!=m.end();itr++)
// // {
// // cout<<itr->first<<endl;
// // }
// // itr=m.begin();
// //cout<<endl;
// while(itr!=m.end()&&itr2!=m.end())
// {
// while((itr2!=m.end())&&((itr2->first-itr->first)==1))
// { //cout<<itr2->first<<" "<<itr->first<<endl;
// temp=temp+itr->second;
// itr2++;
// itr++;
// }
// temp=temp+itr->second;
// if(max<temp)
// {max=temp;
// }
// temp=0;
// if(itr2==m.end())
// break;
// if(itr==m.end())
// break;
// itr2++;
// itr++;
// }
sort(arr,arr+n);
int i=0;
int j=1;
int max=0;
int temp=0;
while(i<n&&j<n)
while(j<n&&i<n&&((arr[j]-arr[i])==1))
{temp=temp+1;
i++;
j++;
temp=temp+1;
if(max<temp)
max=temp;
temp=0;
i++;
j++;
}
if(max==0)
return 1;
return max;
45.92%
Problems
Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher
frequency come first. If frequencies of two elements are same, then smaller number comes first.
Input Format:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The
first line of each test case contains a single integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Output Format:
For each testcase, in a new line, print each sorted array in a seperate line. For each array its numbers should be seperated
by space.
Your Task:
This is a function problem. You only need to complete the function sortByFreq that takes arr, and n as parameters
and prints the sorted elements. Endline is provided by the driver code.
Constraints:
1 ≤ T ≤ 70
30 ≤ N ≤ 130
1 ≤ Ai ≤ 60
Example:
Input:
2
5
55464
5
99925
Output:
44556
99925
Explanation:
Testcase1: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are same then
smaller element comes first. So 4 4 comes first then comes 5 5. Finally comes 6.
The output is 4 4 5 5 6.
Testcase2: The highest frequency here is 3. The element 9 has the highest frequency. So 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.
A.
if(a.second>b.second)
return true;
else if(a.second==b.second)
// return (a.first<b.first);
if(a.first<b.first)
return true;
else
return false;
else
return false;
unordered_map<int,int> m;
for(int i=0;i<n;i++)
m[arr[i]]++;
//itr=m.begin();
vector<pair<int,int>> v;
for(itr=m.begin();itr!=m.end();itr++)
pair<int,int> temp;
temp.first=itr->first;
temp.second=itr->second;
v.push_back(temp);
}
sort(v.begin(),v.end(),freq);
int i=0;
while(i<v.size())
{ while(v[i].second!=0)
{cout<<v[i].first<<" ";
v[i].second--;
i++;
//cout<<endl;
24.44%
Problems
Given an array arr[] of size N containing 0s and 1s only. The task is to count the subarrays having equal number of 0s and
1s.
Input Format:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case
consists of two lines. First line of each test case contains an Integer N denoting size of array and the second line
contains N space separated 0 and 1.
Output Format:
For each test case, in a new line, print the count of required sub arrays in new line
Your Task:
This is a function problem. You only need to complete the functioncountSubarrWithEqualZeroAndOne that takes arr, and n
as parametersand returns count of required subarrays.
Constraints:
1 <= T <= 100
1 <= N <= 106
0 <= A[i] <= 1
Example:
Input:
2
7
1001011
5
11110
Output:
8
1
Explanation:
Testcase 1: The index range for the 8 sub-arrays are:
(0, 1), (2, 3), (0, 3), (3, 4), (4, 5)
(2, 5), (0, 5), (1, 6)
A.
// cumulative sum
int curr_sum = 0;
um[curr_sum]++;
int count = 0;
if (itr->second > 1)
if (um.find(0) != um.end())
count += um[0];
return count;
}
26.95%
Problems
Given a boolean matrix mat[r][c] of size r X c, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells
of ith row and jth column as 1.
Input Format:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is r and c, r is the number of rows and c is the number of columns.
The next r lines contain c elements having either 0 or 1 and separated by spaces.
Output Format:
Print the modified array.
Your Task:
This is a function problem. You only need to complete the functionbooleanMatrix that takes r, c, and matrix as parameters
and prints themodified array. You need to append a newline to separate ouput of individual testcases.
Constraints:
1 ≤ T ≤ 100
1 ≤ r, c ≤ 1000
0 ≤ A[i][j] ≤ 1
Example:
Input:
3
22
10
00
23
000
001
43
100
100
100
000
Output:
11
10
001
111
111
111
100
Explanation:
Testcase1: Since only first element of matrix has 1 (at index 1,1) as value, so first row and first column are modified to 1.
A.
{
int row[1000]={0};
int col[1000]={0};
int b[SIZE][SIZE];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
b[i][j]=a[i][j];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
if(b[i][j]==1)
{ if(row[i]==0)
{for(int k=0;k<c;k++)
a[i][k]=1;
row[i]++;
if(col[j]==0)
for(int k=0;k<r;k++)
a[k][j]=1;
col[j]++;
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
cout<<a[i][j]<<" ";
cout<<endl;
64.07%
Problems
Given a Square matrix mat[] of size NxN. Your task is to find minimum number of operation(s) that are required to make the
matrix Beautiful.
A Beautiful matrix is a matrix in which sum of elements in each row and column is equal. In one operation you can only
increment any value of cell of matrix by 1.
Input Format:
First line of the input contains an integer T denoting the number of test cases. Then T test case follows. First line of each
test case contains an integer N denoting the size of the matrix. Next line contains NxN space separated integers denoting
the elements of the matrix.
Output Format:
For each test case print a single integer in a new line denoting the minimum number of operations required that needed to
be performed.
Your Task:
This is a function problem. You need to complete the functionfindMinOpeartion() that takes matrix and
n as parameters and returns count of minimum number of operations.
Constraints:
1 <= T <= 150
1 <= N <= 100
1 <= mat[i][j] <= 150
Example:
Input:
2
2
1234
3
123423321
Output:
4
6
Explanation:
TestCase 1:
43
34
1. Increment value of cell(0, 0) by 3
2. Increment value of cell(0, 1) by 1
Hence total 4 operation are required.
A.
//Complete this function
{ int maxrow=0;
int maxcol=0;
int maxsum=0;
//rowmax
int row=1;
int col=0;
//int tempsum=0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
maxrow=maxrow+matrix[i][j];
maxcol=maxcol+matrix[j][i];
if(maxsum<maxcol||maxsum<maxrow)
if(maxcol>maxrow)
maxsum=maxcol;
col=1;
row=0;
else
maxsum=maxrow;
col=0;
row=1;
maxcol=0;
maxrow=0;
// cout<<"Max "<<maxsum<<endl;
//cout<<"Col "<<col<<endl;
//cout<<"Row "<<row<<endl;
int count=0;
int tempsum=0;
if(col==1)
{ // cout<<"Hello col\n";
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
tempsum=tempsum+matrix[j][i];
count=count+(maxsum-tempsum);
tempsum=0;
else
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
tempsum=tempsum+matrix[i][j];
count=count+(maxsum-tempsum);
tempsum=0;
return count;
Closer to sort
Submissions: 381 Accuracy:
46.99%
Problems
Given an array arr[] of N integers which is closer sorted (defined below)and an element x. The task is to find index of the
element x if it is present. If not present, then print -1.
Closer Sorted: First array is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e, may
be to the arr[i+1] orarr[i-1].
Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the
array. Next line contains the array elements. Last line contains the element to be searched.
Output Format:
Output the index at which the element is present (0-based), if present, else print "-1".
Your Task:
This is a function problem. You only need to complete the function closer() that arr, N, and x as parameters and returns the
index. If element is not present, return -1.
Constraints:
1 <= T <= 100
1 <= N <= 106
1 <= arr[i] <= 106
Example:
Input:
1
5
3 2 10 4 40
2
Output:
1
Explanation:
Testcase 1: 2 is present at index 1 (0-based indexing) in the given array.
A.
// n: size of array
int i=0;
int j=n-1;
int mid;
while(i<=j)
mid=i+(j-i)/2;
if(arr[mid]==x)
return mid;
else
if(mid+1<n&&arr[mid+1]==x)
return mid+1;
if(mid-1>=0&&arr[mid-1]==x)
return mid-1;
if(arr[mid]>x)
j=mid-2;
else
i=mid+2;
return -1;
45.32%
Problems
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.
Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains size of three arrays N, M
and P. Next three lines contains N, M and P elements for arrays.
Output Format:
Output the merged sorted array.
Your Task:
This is a function problem. You only need to complete the functionmergeThree() that takes A,B,C as parameters. The
function returns anarray or vector.
Constraints:
1 <= T <= 100
1 <= N, M, P <= 106
1 <= A[i], B[i], C[i] <= 106
Example:
Input:
2
456
1234
12345
123456
234
12
234
4567
Output:
111222333444556
122344567
A.
Vector d;
int i=0;
int j=0;
int n=A.size();
int m=B.size();
while(i<n&&j<m)
if(A[i]<B[j])
d.push_back(A[i]);
i++;
else
d.push_back(B[j]);
j++;
}
while(i<n)
d.push_back(A[i]);
i++;
while(j<m)
d.push_back(B[j]);
j++;
i=0;
j=0;
Vector e;
n=d.size();
m=C.size();
while(i<n&&j<m)
if(d[i]<C[j])
e.push_back(d[i]);
i++;
else
e.push_back(C[j]);
j++;
while(i<n)
e.push_back(d[i]);
i++;
while(j<m)
e.push_back(C[j]);
j++;
return e;
Kadane's Algorithm
41.55%
Problems
Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The
first line of each test case contains a single integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print the maximum sum of the contiguous sub-array in a separate line for each test case.
User Task:
The task is to complete the function maxSubarraySum() which finds subarray with maximum sum.
Constraints:
1 ≤ T ≤ 110
1 ≤ N ≤ 106
-107 ≤ A[i] <= 107
Example:
Input:
2
5
1 2 3 -2 5
4
-1 -2 -3 -4
Output:
9
-1
Explanation:
Testcase 1: Max subarray sum is 9 of elements (1, 2, 3, -2, 5) which is a contiguous subarray.
A.
// n: size of array
int maxsum=0;
for(int i=0;i<n;i++)
tempsum=tempsum+arr[i];
if(maxsum<tempsum)
maxsum=tempsum;
if(tempsum<0)
tempsum=0;
if(maxsum==0)
{maxsum=arr[0];
for(int i=1;i<n;i++)
if(maxsum<arr[i])
maxsum=arr[i];
return maxsum;
27.42%
Problems
Given an array arr[] of N distinct integers, check if this array is Sorted (non-increasing or non-
decreasing) and Rotated counter-clockwise. Note that input array may be sorted in either increasing or decreasing order,
then rotated.
A sorted array is not considered as sorted and rotated, i.e., there should be at least one rotation.
Input:
The first line of input contains number of testcases T. Each testcase contains 2 lines, the first line contains N, the number
of elements in array, and second line contains N space separated elements of array.
Output:
Print "Yes" if the given array is sorted and rotated, else Print "No", without Inverted commas.
User Task:
The task is to complete the function checkRotatedAndSorted() which checks if an array is sorted and rotated clockwise.
Constraints:
1 <= T <= 100
1 <= N <= 106
1 <= A[i] <= 106
Example:
Input:5
4
3412
3
123
4
10 20 30 14
5
30 20 10 50 35
5
30 20 10 50 25
Output:
Yes
No
No
Yes
No
Explanation:
Testcase 1: The array is sorted (1, 2, 3, 4) and rotated twice (3, 4, 1, 2).
Testcase 2: The array is sorted (1, 2, 3) is not rotated.
Testcase 3: The array is sorted (10, 20, 30, 14) is not sorted and rotated as 14 is greater than 10.
A.
int drop=0;
//int dec=0;
//int inc=0;
if(arr[0]>arr[1])
{//dec=1;
int val=arr[0];
int i=1;
while(i<num-1)
{ if(drop==1)
while(i<num-1)
if(arr[i]<arr[i+1]||arr[i]<val)
return false;
i++;
if(arr[i]>val)
return true;
else
return false;
if(arr[i]<arr[i+1])
drop=1;
i++;
return false;
else //increasing
{int val=arr[0];
int i=1;
while(i<num-1)
{ if(drop==1)
while(i<num-1)
if(arr[i]>arr[i+1]||arr[i]>val)
return false;
i++;
if(arr[i]<val)
return true;
else
return false;
if(arr[i]>arr[i+1])
drop=1;
i++;
}
return false;
38.95%
Problems
Given an array arr[] of N non-negative integers representing height of blocks at index i as Ai where the width of each block
is 1. Compute how much water can be trapped in between blocks after raining.
Structure is like below:
| |
|_|
We can trap 2 units of water in the middle gap.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case contains an integer N denoting the size of the array, followed by N space separated numbers to be stored in
array.
Output:
Output the total unit of water trapped in between the blocks.
User Task:
The task is to complete the function trappingWater() which returns the total amount of water that can be trapped.
Constraints:
1 <= T <= 100
3 <= N <= 107
0 <= Ai <= 108
Example:
Input:
2
4
7409
3
699
Output:
10
0
Explanation:
Testcase 1: Water trapped by block of height 4 is 3 units, block of height 0 is 7 units. So, total unit of water trapped is 10
units.
A.
// n: size of array
int left[n];
int right[n];
left[0]=arr[0];
for(int i=1;i<n;i++)
left[i]=max(left[i-1],arr[i]);
right[n-1]=arr[n-1];
for(int i=n-2;i>=0;i--)
right[i]=max(right[i+1],arr[i]);
int trap=0;
for(int i=1;i<n-1;i++)
if(arr[i]==0)
trap=trap+min(left[i],right[i]);
else
if(arr[i]<min(left[i],right[i]))
trap=trap+min(left[i],right[i])-arr[i];
return trap;
Maximum Index
25.87%
Problems
Given an array A[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] <= A[j].
Input:
The first line contains an integer T, depicting total number of test cases. Then T test case follows. First line of each test
case contains an integer Ndenoting the size of the array. Next line contains N space separated integeres denoting the
elements of the array.
Output:
Print the maximum difference of the indexes i and j in a separtate line.
User Task:
The task is to complete the function maxIndexDiff() which finds and returns maximum index difference. Printing the output
will be handled by driver code.
Constraints:
1 ≤ T ≤ 1000
1 ≤ N ≤ 107
0 ≤ A[i] ≤ 1018
Example:
Input:
2
2
1 10
9
34 8 10 3 2 80 30 33 1
Output:
1
6
Explanation:
Testcase 1: In the given array A[1] < A[7] satisfying the required condition(A[i] <= A[j]) thus giving the maximum difference
of j - i which is 6(7-1).
A.
// n: size of array
int diff;
int maxdiff;
int j=n-1;
while(arr[j]<arr[0])
j--;
maxdiff=j;
for(int i=1;i<n;i++)
{
j=n-1;
while(arr[j]<arr[i])
j--;
diff=j-i;
if(maxdiff<diff)
maxdiff=diff;
return maxdiff;
76.73%
Problems
Given an array arr[] of size N where every element is in range from 0 to n-1. Rearrange the given array so
that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space.
Input Format:
First line contains an integer denoting the test cases 'T'. First line of each test case contains an integer value depicting
size of array 'N' and next line contains N space separated integers denoting the elements of the array.
Output Format:
Print all elements of the array after rearranging, each separated by a space, in separate line for each test case.
User Task:
The task is to complete the function arrange() which arranges the elements in the array. The printing is done automatically
done by the driver code.
Constraints:
1 <= T <= 100
1 <= N <= 107
0 <= Arr[i] < N
Example:
Input:
3
2
10
5
40213
4
3201
Output:
01
34201
1032
Explanation:
Testcase 1: arr[0] = 1 and arr[arr[0]] = 0. Also, arr[1] = 0 and arr[arr[1]] = 1. So, rearranging elements, we get array as, 0 1.
A.
// n: size of array
for(int i=0;i<n;i++)
arr2[i]=arr[arr[i]];
//cout<<arr[i]<<" ";
for(int i=0;i<n;i++)
arr[i]=arr2[i];
56.87%
Problems
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should
be max value, second should be min value, third should be second max, fourth should be second min and so on.
Note: O(1) extra space is allowed. Also, try to modify the input array as required.
Input:
First line of input conatins number of test cases T. First line of test case contain an integer denoting the array size N and
second line of test case contain N space separated integers denoting the array elements.
Output:
Output the modified array with alternated elements.
User Task:
The task is to complete the function rearrange() which rearranges elements and shouldn't print anything. Printing of the
modified array will be handled by driver code.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= arr[i] <= 107
Example:
Input:
2
6
123456
11
10 20 30 40 50 60 70 80 90 100 110
Output:
615243
110 10 100 20 90 30 80 40 70 50 60
Explanation:
Testcase 1: Max element = 6, min = 1, second max = 5, second min = 2, and so on... Modified array is : 6 1 5 2 4 3.
A.
// n: size of array
int arr2[n];
int j=n-1;
for(int i=0;i<n;i=i+2)
arr2[i] =arr[j];
j--;
j=0;
for(int i=1;i<n;i=i+2)
arr2[i]=arr[j];
j++;
for(int i=0;i<n;i++)
arr[i]=arr2[i];
}
42.15%
Problems
Given a keypad as shown in diagram, and an N digit number. List all words which are possible by pressing these numbers.
Input Format:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains
two lines of input. The first line of each test case is N, N is the number of digits. The second line of each test case contains
D[i], N number of digits.
Output Format:
Print all possible words from phone digits with single space.
Your Task:
This is a function problem. You just need to complete the functionpossibleWords that takes
an array as parameter and prints all the possible words. The newline is automatically added by the driver code.
Constraints:
1 <= T <= 10
1 <= N <= 10
2 <= D[i] <= 9
Example:
Input:
2
3
234
3
345
Output:
adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
dgj dgk dgl dhj dhk dhl dij dik dil egj egk egl ehj ehk ehl eij eik eil fgj fgk fgl fhj fhk fhl fij fik fil
A.
word[row]=arr[a[row]-2][col];
row++;
if((N-row)==0)
{
for(int k=0;k<N;k++)
cout<<word[k];
cout<<" ";
return;
int len=arr[a[row]-2].length();
for(int j=0;j<len;j++)
printpossible(N,word,row,j,arr,a);
string arr[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
char word[N];
int row=0;
int len=arr[a[row]-2].length();
for(int j=0;j<len;j++)
printpossible(N,word,row,j,arr,a);
33.22%
Problems
You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the
array.
Note: Expected solution in O(n) time using constant extra space.
Input:
First line consists of T test cases. First line of every test case consists of N, denoting the number of elements in array.
Second line of every test case consists of elements in array.
Output:
Single line output, print the smallest positive number missing.
User Task:
The task is to complete the function missingNumber() which returns the smallest positive missing number in the array.
Constraints:
1 <= T <= 100
1 <= N <= 106
-106 <= arr[i] <= 106
Example:
Input:
2
5
12345
5
0 -10 1 3 -20
Output:
6
2
Explanation:
Testcase 1: Smallest positive missing number is 6.
Testcase 2: Smallest positive missing number is 2.
A.
vector<int> v(1000);
for(int i=0;i<n;i++)
{ if(arr[i]>0)
v[arr[i]]++;
for(int i=1;i<v.size();i++)
if(v[i]==0)
return i;
return 1;
29.84%
Problems
Given two sorted arrays P[] and Q[] in non-decreasing order with size nand m. The task is to merge the two sorted arrays
into one sorted array (in non-decreasing order).
Note: Expected time complexity is O((n+m) log(n+m)). DO NOT use extra space.
Input Format:
First line contains an integer T, denoting the number of test cases. First line of each test case contains two space
separated integers X and Y, denoting the size of the two sorted arrays. Second line of each test case contains X space
separated integers, denoting the first sorted array P. Third line of each test case contains Y space separated integers,
denoting the second array Q.
Output Format:
For each test case, print (X + Y) space separated integer representing the merged array.
Your Task:
This is a function problem. You only need to complete the functionmerge() that takes n and m as parameters.
Constraints:
1 <= T <= 100
1 <= X, Y <= 5*104
0 <= Pi, Qi <= 109
Example:
Input:
1
45
1357
02689
Output:
012356789
Explanation:
Testcase 1: After merging two non-decreasing arrays, we have, 0 1 2 3 5 6 7 8 9.
a.
int temp=*a;
*a=*b;
*b=temp;
if (gap <= 1)
return 0;
// {
// int i, j, gap = n + m;
// {
// swap(arr1[i], arr2[j]);
// if (j < m)
// {
// }
// }
// }
int gap=nextGap(n+m);
while(gap!=0)
{ int i=0;
for( i=0;i+gap<n;i++)
if(arr1[i]>arr1[i+gap])
{
swap(&arr1[i],&arr1[i+gap]);
int j=0;
if(gap>n)
j=gap-n;
else
j=0;
for(;j<m&&i<n;j++,i++)
if(arr1[i]>arr2[j])
swap(&arr1[i],&arr2[j]);
if(j<m)
for(j=0;j+gap<m;j++)
if(arr2[j]>arr2[j+gap])
swap(&arr2[j],&arr2[j+gap]);
gap=nextGap(gap);
50.33%
Difficulty: Hard Marks: 8
Associated Course(s): Sudo Placement 2019
Problems
Given an even number (greater than 2), return two prime numbers whose sum will be equal to given number. There are
several combinations possible. Print only first such pair.
NOTE: A solution will always exist, read Goldbach’s conjecture. Also, solve the problem in linear time complexity, i.e.,
O(n).
Input:
The first line contains T, the number of test cases. The following T lines consist of a number each, for which we'll find two
prime numbers.
Output:
For every test case print two prime numbers space separated, such that the smaller number appears first. Answer for each
test case must be in a new line.
Constraints:
1 ≤ T ≤ 70
1 ≤ N ≤ 10000
Example:
Input:
5
74
1024
66
8
9990
Output:
3 71
3 1021
5 61
35
17 9973
A.
#include<bits/stdc++.h>
int main() {
int t;
cin>>t;
while(t--)
int n;
cin>>n;
bool arr[n+1];
for(int i=0;i<n+1;i++)
arr[i]=true;
arr[1]=false;
for(int i=2;i*i<n+1;i++)
if(arr[i]==true)
for(int j=i*i;j<n+1;j=j+i)
arr[j]=false;
vector<int> v;
for(int i=2;i<n+1;i++)
if(arr[i]==true)
v.push_back(i);
for(int i=0;i<v.size();i++)
int temp=v[i];
int index=lower_bound(v.begin(),v.end(),n-temp)-v.begin();
if(temp+v[index]==n)
{cout<<temp<<" "<<v[index]<<endl;
break;
return 0;
}
Allocate minimum number of pages
25.72%
Problems
You are given N number of books. Every ith book has Pi number of pages.
You have to allocate books to M number of students. There can be many ways or permutations to do so. In each
permutation one of the M students will be allocated the maximum number of pages. Out of all these permutations, the task
is to find that particular permutation in which the maximum number of pages allocated to a student is minimum of those in
all the other permutations, and print this minimum value.
Each book will be allocated to exactly one student. Each student has to be allocated atleast one book.
Note: Return -1 if a valid assignment is not possible, and allotment should be in contiguous order (see explanation for
better understanding).
Input:
The first line contains 'T' denoting the number of testcases. Then follows description of T testcases:
Each case begins with a single positive integer N denoting the number of books.
The second line contains N space separated positive integers denoting the pages of each book.
And the third line contains another integer M, denoting the number of students.
Output:
For each test case, output a single line containing minimum number of pages each student has to read for corresponding
test case.
Constraints:
1<= T <= 100
1 <= N <= 106
1 <= A [ i ] <= 106
1 <= M <= 106
Example:
Input:
2
4
12 34 67 90
2
3
15 17 20
Output:
113
32
A.
#include<bits/stdc++.h>
// is feasible or not.
bool isPossible(long int arr[], long int n,long int m, long int curr_min)
int studentsRequired = 1;
return false;
studentsRequired++;
// update curr_sum
curr_sum = arr[i];
if (studentsRequired > m)
return false;
else
curr_sum += arr[i];
}
return true;
long sum = 0;
// no. of students
if (n < m)
return -1;
sum += arr[i];
// total pages
if (isPossible(arr, n, m, mid))
// that means
end = mid - 1;
else
start = mid + 1;
return result;
// Drivers code
int main()
int t;
cin>>t;
while(t--)
long int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>arr[i];
long int m;
cin>>m;
return 0;
31.23%
Difficulty: Hard Marks: 8
Associated Course(s): Geeks Classes in Noida Geeks Classes in Noida- (Summer-Weekdays)More
Problems
Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that
cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.
Note : It is assumed that negative cost cycles do not exist in input matrix.
Input:
The first line of input will contain number of testcases T. Then T test cases follow. Each test case contains 2 lines. The first
line of each test case contains an integer N denoting the size of the grid. Next line of each test contains a single line
containing N*N space separated integers depecting cost of respective cell from (0,0) to (N,N).
Output:
For each test case output a single integer depecting the minimum cost to reach the destination.
Constraints:
1 <= T <= 50
1 <= N <= 50
Example:
Input:
2
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
2
42 93 7 14
Output:
327
63
Explanation:
Testcase 1:
Grid is:
31, 100, 65, 12, 18,
10, 13, 47, 157, 6,
100. 113, 174, 11, 33,
88, 124, 41, 20, 140,
99, 32, 111, 41, 20
A cost grid is given in below diagram, minimum
cost to reach bottom right from top left
is 327 (31 + 10 + 13 + 47 + 65 + 12 + 18 + 6 + 33 + 11 + 20 + 41 + 20)
A.
#define ROW n
#define COL n
int n;
struct cell
int x, y;
int distance;
};
if (a.distance == b.distance)
if (a.x != b.x)
else
return (i >= 0 && i < COL && j >= 0 && j < ROW);
int dis[row][col];
dis[i][j] = INT_MAX;
// direction arrays for simplification of getting
// neighbour
set<cell> st;
st.insert(cell(0, 0, 0));
dis[0][0] = grid[0][0];
while (!st.empty())
cell k = *st.begin();
st.erase(st.begin());
if (!isInsideGrid(x, y))
continue;
if (dis[x][y] != INT_MAX)
st.erase(st.find(cell(x, y, dis[x][y])));
// cell in set
st.insert(cell(x, y, dis[x][y]));
/*
*/
int main() {
int t;
cin>>t;
while(t--)
cin>>n;
int arr[n][50];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
if(n!=1)
{int count=shortest(arr,n,n);
cout<<count<<endl;
else
cout<<arr[0][0]<<endl;
return 0;
30.57%
Company Tags Adobe Amazon Apple Belzabar D-E-Shaw Facebook Flipkart Google Intuit Microsoft Morgan
Stanley Ola Cabs Oracle OYO Rooms Samsung SAP Labs Walmart Yahoo
Problems
Given an input stream of N integers. The task is to insert these numbers into a new stream and find the median of the
stream formed by each insertion of X to the new stream.
Input:
The first line of input contains an integer N denoting the number of elements in the stream. Then the next N lines contains
integer x denoting the number to be inserted into the stream.
Output:
For each element added to the stream print the floor of the new median in a new line.
Constraints:
Output:
5
10
5
4
Explanation:
Testcase 1:
A.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
int n=Integer.parseInt(bf.readLine());
int val=Integer.parseInt(bf.readLine());
a.add(val);
System.out.println(""+val);
int val2=Integer.parseInt(bf.readLine());
a.add(val2);
System.out.println((val+val2)/2);
for(int i=3;i<=n;i++)
a.add(Integer.parseInt(bf.readLine()));
Collections.sort(a);
if(i%2!=0)
System.out.println(a.get(i/2));
else
System.out.println((a.get(i/2)+a.get((i/2)-1))/2);
}catch(Exception e)
}}
46.88%
Problems
Given a string of lowercase ASCII characters, find all distinct continuous palindromic sub-strings of it.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case
contains a string.
Output:
Print the count of distinct continuous palindromic sub-strings of it.
Constraints:
1<=T<=10^5
1<=length of string<=10^5
Example:
Input:
2
abaaa
geek
Output:
5
4
A.
int n;
cin>>n;
for(int i=0;i<n;i++)
{int count=0;
// stack<int> s;
map<string,int> m;
int k=3;
int l;
string str;
cin>>str;
l=str.length();
string v;
//cout<<str;
int j=0;
while(j<l)
{v=str.substr(j,1);
m.insert(pair<string,int>(v,count));
count++;
j++;
j=0;
while(j<=l-2)
{ v=str.substr(j,2);
if(v[0]==v[1])
{ m.insert(pair<string,int>(v,count));
count++;
//cout<<v<<endl;
//cout<<count<<endl;
j++;
// cout<<" ";
for(int a=k;a<=l;a++)
{ for(int j=0;j<=l-a;j++)
v=str.substr(j,a);
int p=0;
while(p<a/2)
if(!(v[p]==v[a-1-p]))
break;
p++;
if(p==a/2)
{m.insert(pair<string,int>(v,count));
count++;
//cout<<v<<endl;
//cout<<count<<endl;
cout<<m.size()<<endl;
return 0;
19.94%
Problems
Given two sorted arrays arr[] and brr[] of sizes N and M respectively. The task is to find the median of the two arrays when
they get merged.
Input:
First line of input contains number of testcases T. First line of input contains number of elements in both arrays N and M
respectively. Next two lines contains the array elements.
Output:
For each testcase, print the median of two sorted arrays. If there are total even elements, we need to print floor of average
of middle two elements.
Constraints:
1 <= T <= 100
1 <= N, M <= 106
1 <= arr[i], brr[i] <= 107
Example:
Input:
3
56
12345
345678
23
12
234
44
1234
11 12 13 14
Output:
4
2
7
Explanation:
Testcase 1: After merging two arrays, elements will be as 1 2 3 3 4 4 5 5 6 7 8. So, median is 4.
A.
int main() {
int t;
cin>>t;
while(t--)
int n,m;
cin>>n>>m;
int arr1[n];
int arr2[m];
for(int i=0;i<n;i++)
cin>>arr1[i];
for(int i=0;i<m;i++)
cin>>arr2[i];
}
int arr3[n+m];
int i=0;
int j=0;
int k=0;
int val=(n+m)/2;
while(i<n&&j<m&&k<=val)
if(arr1[i]<arr2[j])
arr3[k]=arr1[i];
i++;
else
arr3[k]=arr2[j];
j++;
k++;
if(i==n)
while(k<=val)
arr3[k]=arr2[j];
k++;
j++;
if(j==m)
while(k<=val)
{
arr3[k]=arr2[i];
k++;
i++;
if(!((n+m)&1))
// if(i==n)
// {
// while(j<m)
// {
// arr3[k]=arr2[j];
// j++;
// k++;
// }
// }
// if(j==m)
// {
// while(i<n)
// {
// arr3[k]=arr1[i];
// i++;
// k++;
// }
// }
cout<<(arr3[val]+arr3[val-1])/2<<endl;
else
// while(i<=val&&j<=val)
// {
// if(arr1[i]<arr2[j])
// {
// arr3[k]=arr1[i];
// i++;
// }
// else
// {
// arr3[k]=arr2[j];
// j++;
// }
// k++;
// }
// if(i==n)
// {
// while(j<m)
// {
// arr3[k]=arr2[j];
// j++;
// k++;
// }
// }
// if(j==m)
// {
// while(i<n)
// {
// arr3[k]=arr1[i];
// i++;
// k++;
// }
// }
cout<<arr3[val]<<endl;
return 0;
74.57%
Problems
Given a string S and a pattern P of all lowercase characters. The task is to check if the pattern exists in the string or not.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains string S and next line
contains pattern P.
Output:
For each testcase, print "Yes" if pattern is found in the string, and "No" if pattern is not found in the string.
Your Task:
The task is to complete the function KMPSearch() which returns true or false depending on whether pattern is present in
the string or not, andcomputeLPSArray() which computes the longest prefix suffix for every index.
Constrsaints:
1 <= T <= 100
1 <= |S|, |P| <= 103
Example:
Input:
2
aabaacaadaabaaba
aaaab
aabaacaadaabaaba
caada
Output:
No
Yes
Explanation:
Testcase 1: Given pattern is found in the given string S.
Testcase 2: Given pattern is found in the given string S.
A.
int i=0;
lps[0]=0;
int j=i+1;
while(j<=pat.size()-1)
if(pat[i]==pat[j])
i=i+1;
lps[j]=i;
j=j+1;
else
while(i-1>=0&&pat[lps[i-1]]!=pat[j])
i=lps[i-1];
lps[j]=lps[i];
j=j+1;
// for(int i=0;i<M;i++)
// {
// cout<<lps[i]<<" ";
// }
// cout<<endl;
int n=txt.size();
int m=pat.size();
int i=0;
int j=0;
int lps[m];
computeLPSArray(pat,m,lps);
while(i<n)
if(pat[j]==txt[i])
i++;
j++;
if(j==m)
return true;
}
else if(i<n&&pat[j]!=txt[i])
if(j!=0)
j=lps[j-1];
else
i=i+1;
return false;
20.81%
Problems
Given an array arr[] of N integers arranged in a circular fashion. Your task is to find the maximum contigious subarray
sum.
Input:
First line of input contains a single integer T which denotes the number of test cases. First line of each test case contains
a single integer N which denotes the total number of elements. Second line of each test case contains N space separated
integers denoting the elements of the array.
Output:
For each test case print the maximum sum obtained by adding the consecutive elements.
User Task:
The task is to complete the function circularSubarraySum() which finds the circular subarray with maximum sum.
Constraints:
1 <= T <= 101
1 <= N <= 106
-106 <= Arr[i] <= 106
Example:
Input:
3
7
8 -8 9 -9 10 -11 12
8
10 -3 -4 7 6 5 -4 -1
8
-1 40 -14 7 6 5 -4 -1
Output:
22
23
52
Explanation:
Testcase 1: Starting from last element of the array, i.e, 12, and moving in circular fashion, we have max subarray as 12, 8, -
8, 9, -9, 10, which gives maximum sum as 22.
A.
if(a>b)
return a;
else
return b;
int tempsum=0;
int maxsum=0;
for(int i=0;i<num;i++)
tempsum=tempsum+arr[i];
if(tempsum>maxsum)
maxsum=tempsum;
if(tempsum<0)
tempsum=0;
if(maxsum==0)
{ maxsum=arr[0];
for(int i=1;i<num;i++)
if(maxsum<arr[i])
{
maxsum=arr[i];
return maxsum;
int tsum=0;
for(int i=0;i<num;i++)
tsum=tsum+arr[i];
arr[i]=-arr[i];
int maxsum=tsum+kadane(arr,num);
return maxsum;
int k = kadane(arr,num);
//wrapper
int rk = reversekadane(arr,num);
if(k==-1||rk==-1)
return -1;