0% found this document useful (0 votes)
2K views119 pages

Solved Questions Competitive Programming

This document provides solutions to 50 coding questions for top tech companies. The questions cover a range of topics including arrays, sorting, two pointer techniques, and bit manipulation. Specific questions summarized include: 1. Calculating the product array of a given array without using division. 2. Finding the kth element in two sorted arrays merged together. 3. Computing the factorial of a large number by storing each digit in an array. 4. Determining the number of trailing zeros in a factorial by counting factors of 5 and 10. 5. Minimizing the number of bit flips needed to make the bitwise OR of two numbers equal a third number.

Uploaded by

amandeep651
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2K views119 pages

Solved Questions Competitive Programming

This document provides solutions to 50 coding questions for top tech companies. The questions cover a range of topics including arrays, sorting, two pointer techniques, and bit manipulation. Specific questions summarized include: 1. Calculating the product array of a given array without using division. 2. Finding the kth element in two sorted arrays merged together. 3. Computing the factorial of a large number by storing each digit in an array. 4. Determining the number of trailing zeros in a factorial by counting factors of 5 and 10. 5. Minimizing the number of bit flips needed to make the bitwise OR of two numbers equal a third number.

Uploaded by

amandeep651
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 119

50 Must Do

Coding Questions
for Top Tech giants Solved

P
1. Product Array

Problem Statement
In this problem, we are given an array of size N and we are asked to calculate the product of the
array except for that element. This is a pretty straightforward problem although, with a twist, we
cannot use the division operator.

Example

arr=[1 2 3 4 5], for each of these elements our product array will look like –
prod=[120 60 40 30 24 ] .
Product of whole array is 120.
Prod0=2*3*4*5= 120
Prod[0] =(1*3*4*5) = 60
Prod0=1*2*4*5= 40
Prod[0] =(1*2*3*5) = 30
Prod[0] =(1*2*3*4) = 24

Logic
The idea is to store the products till the left side and till the right side of the current index and
then we will simply have to multiply these two left and right products to get our answer.

2
Code
#include <bits/stdc++.h>

using namespace std;

void prodarray(long long *arr,long long n){

long long *prefix = new long long[n];

for(long long i = 0;i<n;i++)

prefix[i] = 1;

long long *suffix = new long long[n];

for(long long i = 0;i<n;i++)

suffix[i] = 1;

for(long long i = 1;i<n;i++)

prefix[i] = prefix[i-1]*arr[i-1];

for(long long i = n-2;i>=0;i--)

suffix[i] = suffix[i+1]*arr[i+1];

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

cout<<prefix[i]*suffix[i]<<" ";

cout<<endl;

int main()

//write your code here

int t;

cin>>t;

while(t--){

long long n;

cin>>n;

long long *arr = new long long[n];

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

cin>>arr[i];

prodarray(arr,n);

return 0;

Time Complexity:O(n), where n is the size of the given array.


Space Complexity:O(n), where n is the size of the given array.
3
2. Kth Element in Two Sorted Arrays

Problem Statement
Given two sorted arrays A and B, we need to find the kth element in the resultant array
which will be formed when these two arrays will be merged.

Example

A = [1,4,7]
B = [5,6,8,9]
K=3
Res = [1,4,5,6,7,8,9]
3rd element is 5.

Logic
First of all, to observe here is the arrays are sorted, can we take advantage of this property. I
think we can use a two-pointer technique here as after each iteration we have a definitive
way to change our pointers.
We can have a variable say x to count the number of elements we have placed in the sorted
array just we do not really need to place them; we just need to move the pointers.

Algorithm
1. When Ai<Bj, this will mean we have to place A[i] in our resultant array and increment the
value of x by 1 and check if x==k, this means our current A[i] is out kth element. Also,
increment i by 1.

2. When Ai>Bj, this will mean we have to place B[j] in our resultant array and increment the
value of x by 1 and check if x==k, this means our current B[j] is out kth element. Also,
increment j by 1.

4
Code

#include <bits/stdc++.h>
using namespace std;
int Kthelement(vector<int> &A,vector<int> &B,int k){
int n = A.size();
int m = B.size();
int i = 0,j= 0,x = 0;
while(i < n && j<m){
if(A[i] < B[j]){
x++;
if(x == k)
return A[i];
i++;
}else{
x++;
if(x == k)
return B[j];
j++;
}
}
while(i<n){
x++;
if(x == k)
return A[i];
i++;
}
while(j<m){
x++;
if(x == k)
return B[j];
j++;
} return -1; }

int main()
{
//write your code here
int t;
cin>>t;
while(t--){
int n,m,k;
cin>>n>>m>>k;
vector<int> A(n);
vector<int> B(m);
for(int i = 0;i<n;i++)
cin>>A[i];
for(int i = 0;i<m;i++)
cin>>B[i];
cout<<Kthelement(A,B,k)<<endl;
}

return 0;
}
5
3. Large Factorial

Problem Statement
Ah! Factorials, pretty daunting right? When it comes to simple implementation it’s quite easy to
give an answer but in this question, we are asked to find out the factorial of a very large
number. What difference does it make? Well, we know the range of 32-bit Integer is 0 to
4294967295 and if we just look at the factorial of a small number like 50 is
30414093201713378043612608166064768844377641568960512000000000000 which is
very large to be stored in the datatype.

Logic
Factorialn=1*2*3*4*…*n-1*n , well mathematically we just have to multiply each of these
numbers smaller than and equal to n and store them somewhere. As the number is very large
we cannot store it together, so I think we can use an array to store individual digits of this
answer as we can obviously store even 4294967295 length number.

Algorithm

1. Maintain a res array and store each number and its multiplication value in the array

2. Take a carry to store the carry for the multiplication of two numbers

3. While carry is not zero, we keep on adding the rest of the carry to the res array and keep
adding the remaining digits in carry to our resultant array.

4. Print in reverse order the array as our answer is in reverse order.

6
Code

#include <bits/stdc++.h>
using namespace std;
int MAX;
long long int res_size;
long long int multiply(int *res,int x){
int carry = 0;
for(long long int i = 0;i<res_size;i++){
int prod = res[i]*x + carry;
res[i] = prod%10;
carry = prod/10;
}
while(carry){
res[res_size++] = carry%10;
carry = carry/10;
}
return res_size;
}
void factorial(int N){
int *res = new int[MAX];
res[0] = 1;
res_size = 1;
for(int x = 2;x<=N;x++)
res_size = multiply(res,x);
//cout<<res_size;
for(long long int i = res_size -1 ;i>=0;i--)
cout<<res[i];
}

int main()
{
//write your code here
int N;
cin>>N;
MAX = float(N * log10(N / 2.718281828459) + log10(2 * 3.141592 * N) / 2.0);
MAX = int(floor(MAX) + 1);
factorial(N);
return 0;
}

Time Complexity:O(MAX), where MAX = float(N * log10(N / 2.718281828459) + log10(2 *


3.141592 * N) / 2.0);

MAX = int(floor(MAX) + 1)

Space Complexity:O(MAX)
7
4. Trailing Zeros

Problem Statement
Factorials are always quite fun to play with and in this problem, we are given a number n
and are asked to find a number of trailing zeroes at the end of n!.

Example

12!=479001600
So, the answer would be 2.

Logic
Let’s take any number of examples, let n = 12;
n!=12!=1*2*3*4*5*6*7*8*9*10*11*12
Let’s look carefully, we need trailing zeroes, which means possible multiplication of 10, rather
2 X 5, isn’t it?
If we can somehow know how many factors of 10 are there in the factorial of a number, then I
suppose we can estimate the number of trailing zeroes. Sounds good?
Now logically in any factorial, we will always have a greater number of 2 as factors than 5,
and hence the number of 5 will decide the number of factors of 10. Essentially, we can say –

where k is chosen such that 5k+1>n.


Hence, we only need to find this summation to get our answer.

Algorithm

1. Keep on dividing our num by power of 5

2. If our num < 0 stop the iteration and return the answer.

8
Code

#include<iostream.h>

using namespace std;

int trailZero(int n){

int res = 0;

for(int i = 5;n/i>0;i *= 5){

res += (n/i);

return res;

int main(){

int n;

cin>>n;

cout<<trailZero(n)<<"\n";

Time Comlexity:O(logn), where n is the given number.


Space Complexity:O(1)

9
5. Flipping Bits

Problem Statement
In this problem, we are given three Integers A, B, C and we are asked to change a minimum
number of bits possible in A and B such that A OR B=C.

Example
Pos →4321
A=8 →1000
B=3 →0011
C=5 →0101
We need to flip 3 bits in total. A bit at position 4 in A and bits at position 3 and 2 in B will be flipped.
A→0000
B→0101
A or B = 0 1 0 1 = C

Logic
The idea is to flip bits in A or B or both to get our required bit. We need to traverse our numbers
bit by bit and check certain conditions and change them according to the conditions. Well, we
can definitely check for 32 bits for a 32-bit integer but when we are counting the changes in bits
for both the numbers, it may go out of bounds. We also need to take bits of the maximum number
only as in only that way we can ensure our count does not get out of bounds.

Algorithm
1. Take the maximum of the numbers for running the loop. (avoids overflow)
2. Take out each rightmost bit and divide the number by 2 (right shifting) as it will keep on
right shifting the bits to right hence for every iteration, we get the next left bit.
3. If if(bitC == 1 && bitA == 0 && bitB == 0) when bit of C is 1, we need at least one of the A
bit or B bit set as their OR will give 1.
count++;
4. if(bitC == 0 && ((bitA ==0 && bitB==1) || (bitA == 1 && bitB ==0))) count++;when bit c is not
set, then we can have only one condition from truth table i.e., both needs to be 0 and if any
of them is set we change, and if both of them is set we change in both (2 flips).
5. if(bitC == 0 && (bitA && bitB) count += 2; If both of them is set we change in both (2 flips).
10
Code

#include<bits/stdc++.h>
using namespace std;
int flipbits(int A, int B, int C) {
int count = 0;
int loop = max(A,max(B,C));
while(loop){
int bitC = C%2;
int bitA = A%2;
int bitB = B%2;
A = A>>1;B = B>>1;C = C>>1;loop = loop>>1;
if(bitC == 1 && bitA == 0 && bitB == 0)
//change is required
count++;
if(bitC == 0 && ((bitA ==0 && bitB==1) || (bitA == 1 && bitB ==0)))
//change is required
count++;
if(bitC == 0 && (bitA && bitB) )
//change is required
count += 2;
}
return count;
}
int main(){
int t;
cin>>t;
while(t--){
int A,B,C;
cin>>A>>B>>C;
cout<<flipbits(A,B,C)<<endl;
}
return 0;
}

Time Complexity:O(maximum number of bits)

Space Complexity:O(1)

11
6. Beautiful String

Problem Statement
We are given two strings and we have to return that if these two strings are permutations
of each other or not.

Example
S = bytesprep
P = prepbytes
S and P are permutations of each other, hence print YES.

Logic
The idea is that if two strings are permutations of each other then all the characters and their
frequencies in one string should be the same in another string too.

Algorithm

1. Traverse the first string and store the characters and their corresponding frequencies in a
map.

2. Traverse the second string and keep on decrementing the frequencies of characters that are
present in the map.

3. If the frequency of a character drops to 0 then delete the key present in the map.

4. Check if the map is empty then return true else false.

12
Code

#include <bits/stdc++.h>

using namespace std;

int main()

//write your code here

int t;

cin>>t;

while(t--){

string s,p;

cin>>s>>p;

map<char,int> m;

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

m[s[i]]++;

for(int j = 0;j<p.length();j++)

m[p[j]]--;

if(m[p[j]] == 0)

m.erase(p[j]);

if(m.empty())cout<<"YES\n";

else cout<<"NO\n";

return 0;

Time Complexity:O(lengthS,lengthP)

Space Complexity:O(lengthS,lengthP)

13
7. Strength of bits

Problem Statement
In this problem, we are given an array of integers and from this array, we have to calculate
a value that can be formed like –
Suppose arr=[2 4 5 3], their binary representation will be [0010 0100 0101 0011]. Now,
the number of set bits in each is given in an array as [1 1 2 2], we have to calculate the
value X=12+14+25+23=42. We have to return this value of X.

Logic
The idea is to calculate the number of set bits efficiently first. This can be done by using bit
masking and checking 32 bits of a number which will take O(log(A[i]) time. We will repeat this
for every integer A[i] and then we have to take the countAi . This exponentiation can be done
easily in logarithmic time.

Algorithm
1. Iterate over the array and for every A[i] we have to find the number of set bit. This can be
done by built-in functions in CPP but it’s more efficient if we define our own to check every
32 bits of the number.
a. For I in 0 to 32 if((1ll<<i)&n) increment count by 1

2. Once we have the count of each set bits, we take the power(count, A[i])
a. This power can be iteratively calculated as –
i. If the power is odd then x*ans
ii. Else power = power/2, and x = x*x – basically separating the squares.

14
Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ff first
#define ss second
#define pb push_back

const ll MOD = 1e9 +7;


ll power_mod(ll x, ll y, ll m){
ll arr = 1;
x%=m;
while(y){
if(y&1){
arr=(arr*x)%m;
}
y>>=1;
x=(x*x)%m;
}
return arr;
}
ll cntBits(ll n){
ll cnt = 0;
for(ll i=0;i<32;i++){
if((1ll<<i)&n){
cnt++;
}
}
return cnt;
}
int main(){
ll n;
cin>>n;

ll ans = 0;
ll a;
for(ll i = 0; i<n; i++){
cin>>a;

ll setBitCount = cntBits(a);
ll val = power_mod(setBitCount, a, MOD);

ans = (ans + val)%MOD;


}
cout<<ans<<endl;
return 0;
}

Time Complexity:O(N * ( log(bit_count) +log(A[i] )), where bit_count is the count of bits of
A[i].

Space Complexity:O(1), as no extra space is used. 15


8. String Matching

Problem Statement
In this problem, we are given 3 words/strings specifically A, AZ, AZZ, and a string. We have to
find whether these strings are made up of the above strings only or not. Let’s make this clear-
er. Suppose our string is AAZZ , will return true as it is made up of A and AZZ. Hence, we
return true. If our string does not satisfy the condition then we return false.

Logic

Naively I can think of to find out all the subsequence of the given string and for each check
of these matches with any of the 3 given strings. But we might have multiple occurrences of
a word in the string and this will lead to a biquadratic solution. We need to reduce this time
complexity and think of some other approach.

Each string if consists of a combination of the given strings then we can find out the match-
ing part and recur over the next part for other combinations. The idea is simple, we consider
each prefix and search it in a dictionary. If the prefix is present in the dictionary, we recur for
the rest of the string (or suffix).

We will run a loop for each character in the string and match if we have a string that matches
the particular character. If at any point the character present in both strings is different then
we will return false. This matching has to be done 3 times for 3 different strings.

16
Algorithm

1. Store the given strings in some container.

2. For the first position in the string, we check do we have a word having the same character or
not and hence we start from zero for the first case.

3. We store the answer of each iteration in a dp array. dp[i] will denote whether ith position
included in the string is true for the presence of any of the 3 words.

4. For the latter cases, if we have a true till i-1 th position this will mean the ith position will also
be true if the ith position matches.

5. If the i-1th position has false then it’s obviously false and we will continue for the next posi-
tion.

Code

#include <bits/stdc++.h>
using namespace std;
bool dp[100005];
bool match(string str,string s,int i)
{
int n=str.size();
int m=s.size();
for(int j=i,k=0;j<n&&k<m;j++,k++)
{
if(str[j]!=s[k])
return false;
}
return true;
}
bool check(string str)
{
int n=str.size();
vector<string> v(3);
v[0]="A";
v[1]="AZ";
v[2]="AZZ";
if(match(str,v[0],0))
{
dp[0]=true;

17
Code

}
if(match(str,v[1],0))
{
dp[1]=true;
}
if(match(str,v[2],0))
{
dp[2]=true;
}
for(int i=1;i<n;i++)
{
if(match(str,v[0],i))
{
if(dp[i-1])
dp[i]=true;
}
if(match(str,v[1],i))
{
if(dp[i-1])
dp[i+1]=true;
}
if(match(str,v[2],i))
{
if(dp[i-1])
dp[i+2]=true;
}
}
return dp[n-1];
}
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
for(int i=0;i<100005;i++)
dp[i]=false;
if(check(s))
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}

Time Complexity:O(n), as the length of the 3 strings given is constant.

Space Complexity:O(1), no extra space was used.

18
9. Missing and Repeating

Problem Statement
In this problem, we are given an array of size n and it contains all the numbers from 1 to n
except one number and it also contains a duplicate number. We have to find these two
missing and repeating numbers.

Example
Suppose we have n=6
arr=[4 3 6 2 1 1] then we can see the missing number is 5 and the repeating number is 1.

Logic
We can use a map to store frequencies of each element of the array and then find which
element has the frequency of 2. This will be our repeating element. Again, we know that sum
of 1 to n=n*(n+1)/2 , so using this, if we subtract our current sum of the array given then we
will get missing number-repeating number, and we already have found out the repeating
number. Hence missing number=currsum+repeating number.

Algorithm
1. Keep a sum variable initialized to n*(n+1)/2.

2. We keep subtracting the elements from the sum by iterating through the array and also insert
the element in the map and update its frequency.

3. We are left with sum= missing number-repeating number, from which we can simply add the
repeating number obtained at step 2 and we will get the missing number.

19
Code

#include <bits/stdc++.h>
using namespace std;
void missingnum(int *arr,int n){
int sum = (n*(n+1))/2;
map<int,int> m;
int rep = arr[0];
for(int i =0;i<n;i++){
sum -= arr[i];
m[arr[i]]++;
if(m[arr[i]] == 2)rep = arr[i];
}
cout<<sum + rep<<" "<<rep;
}
int main()
{
//write your code here
int n;
cin>>n;
int *arr = new int[n];
for(int i=0;i<n;i++)
cin>>arr[i];
missingnum(arr,n);
return 0;
}

Time Complexity:O(n), where n is the size of the array.

Space Complexity:O(n) since we used a map.

20
10. Reduce to 1
Problem Statement
In this problem, we are given a binary string, simply a string of 0 and 1, and we are asked
to reduce this number (which can be formed from this binary string) to 1 by following
operations –
If the number is even then divide it by 2.
If the number is odd then add 1 to it.

Return the number of steps required to perform the above-mentioned task.

Example
If we have our number as 101 in string form then
101(5) → 110(6) → 011(3) →100(4) → 010(2) → 001(1)

Logic
The idea is to traverse from LSB of the string, as we need to minimize it to 1, so we try to
reduce it from the left. Moreover, if a number is even its leftmost bit is 0 else 1. So, this
observation will help us decide what we want to do, i.e., divide or add.

Algorithm
1. We know if the size of the string is 1 then we do not have to change anything.

2. If the LSB is 0 that means we have an even number and if we right-shift this as dividing by 2
then this zero will be shifted, so we can remove this 0 and increase our steps.

3. Else we have an odd number, now the operation we have to perform is to add 1.

4. Essentially, we have to keep the carry of 1 to the position until we get a zero where we can
add it. As in Binary 1+1= 0 carry =1.

5. If we do not find any 0 then append the 1 to the last.

6. We repeat this for each bit of the string.

21
Code

#include <bits/stdc++.h>
using namespace std;
int steps(string s){
int step = 0;
while(s.size()>1){
if(s.back() == '0')//even
{
s.pop_back();
step++;
continue;
}
bool chk = false; //if we at all get any 0
for(int i = s.size()-1;i>=0;i--){
if(s[i] == '0'){
s[i] = '1';
chk = true;
break;
}
s[i] = '0';
}
if(!chk)s="1"+s;
step++;
}
return step;
}
int main()
{
//write your code here
string s;
cin>>s;
cout<<steps(s)<<endl;
return 0;
}

22
11. Find a number

Problem Statement
Finding a number has always been an interesting puzzle! Well in this problem we are given
a sorted array of some numbers in which every element is present twice except one
element. We have to find this element. Easy isn’t it?

Example
Arr = 1 1 3 3 4 5 5 7 7 8 8
Output = 4

Logic
Let us first observe a sorted array with such conditions and see if we can find anything
interesting.
Arr = 1 1 3 3 4 5 5 7 7 8 8
Look carefully in the above array the answer is 4 but before it, all the duplicate elements –
the first element is always at even position and the second element is at the odd position but
after the answer element first element is at the odd position and the second element is at
even position.
This gives us an idea that whenever we find that for a current element if the next element is
equal to it and the current position is even and the next position is odd that means our
answer is not encountered so we can search in the right half else in the left half.

Algorithm
1. Find the mid of the low and high index.
2. If (low == high) return ans = low.

3. If the mid element == mid + 1 element and check the index of the mid element. If mid is even
and mid+1 will be odd. Search in the right of mid else search in the left of mid.

4. If the mid element == mid - 1 element and check the index of the mid element. If mid is even
and mid-1 will be odd. Search in the right of mid else search in the left of mid.

23
Code

#include <bits/stdc++.h>
using namespace std;
void search(vector<int> &arr,int n,int &ans,int l,int r){
if(l>r)return;
if(l == r){ans = arr[l]; return;}
int mid = r + (l-r)/2;
if(mid%2 == 0){
if(arr[mid] == arr[mid+1])
search(arr,n,ans,mid+2,r);
else
search(arr,n,ans,l,mid);
}else{
if(arr[mid] == arr[mid-1])
search(arr,n,ans,mid+1,r);
else
search(arr,n,ans,l,mid-1);
}
return;
}
int main()
{
//write your code here
int n;
cin>>n;
vector<int> arr(n);
for(int i = 0;i<n;i++)cin>>arr[i];
int ans = -1;
search(arr,n,ans,0,n-1);
cout<<ans<<endl;
return 0;
}

Time Complexity:O(logn), where n is the number of elements in the array.

Space Complexity:O(1)

24
12. Largest Integer with digit cost K
Problem Statement
In this problem, we are given the cost of each integer from 1 to 9. We are also provided
with an integer k and are asked to form the largest possible number that can be formed
for which the cost is equal to k. This means, for each digit that we place in our array/string
will incur the cost provided corresponding to the cost array.
Let’s make this clearer, suppose we have cost=[9 1 4 6 7 8 2 4 1] and k=8, the maximum
possible number with cost equal to k is “99999999” as the cost of 9 is 1 so we can place
eight 9s in our answer which will also be the maximum.

Logic
We will be using the concept of knapsack here with some modifications. Well, the best idea is
to start with 1 and check for all possible values trying to maximize the answer. We also keep
a visited 2D array depending on the state where the state has index and target k as the
variables. For every state, we have two options, either we can include that digit or we can
skip it. If we include that digit, we might include it multiple times, hence we start the next
recursion in this case from the same digit only whereas for the case of skipping, we start
from the next digit. We keep our answer in a 2D dp of strings. At the last, we compare the
two strings obtained from the two options and return whichever is greater.

Algorithm
1. Start the recursion function from digit 1 and recur down till 9.
2. For each digit, we have two options either we keep on including that digit using recursion

until the target becomes zero or we skip this digit.

a. solve(i+1, target), skipping the current i

b. solve(i, target-w[ind]) including the current i.

3. If both these answers are zero then we return “0” as no such string/number can be formed.

4. If both are not “0” then we have to take the maximum of these two.

25
Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll MOD = 1e9+7;

string dp[12][5005];
int vis[12][5005];
int w[12];
string max_fun(string s1, string s2){
if(s1.length()!=s2.length()){
return s1.length()>s2.length()?s1:s2;
}
if(s1>s2){
return s1;
}
else{
return s2;
}
}
string solve(int i, int target){
if(target == 0){
return "";
}
if(target<0 or i == 10){
return "0";
}
if(vis[i][target] == 1){
return dp[i][target];
}
vis[i][target] = 1;
string ans1 = solve(i+1, target);
string ans2 = solve(i, target-w[ind]);
if(ans1 == "0" and ans2 == "0"){
return dp[i][target] = "0";
}
if(ans1 == "0"){
return dp[i][target] = (ans2 + to_string(i));
}
if(ans2 == "0"){
return dp[i][target] = ans1;
}
dp[i][target] = max_fun(ans1, ans2 + to_string(i));
return dp[i][target];
}
int main(){
int K;
cin>>K;
for(int i=1;i<=9;i++){
cin>>w[i];
}
memset(vis, 0, sizeof(vis));
string ans = solve(1, K);
cout<<ans<<endl;
return 0;
}

Time Complexity:≈O(9*k), where k is the given target.

Space Complexity:≈O(9*k), we have used two extra space for these.


26
13. Large Small Difference

Problem Statement
In this problem, we are given an array of N integers and we have exactly 3 moves that we
have to perform. In one move we can choose an element from the array and change its
value to anything we want and then we have to return the minimum difference between
the smallest and largest element in the array.

Example
arr[]=[1 5 6 13 14 15 16 17], then for this our answer is 4 which comes from changing smallest
3 elements to 13, 17-13 = 4.

Logic
The idea is to minimize the difference between the maximum and minimum elements. This
can be done after sorting; we can change 3 elements such that our minimum and maximum
elements come closer. So, let suppose we have 4 elements then, obviously we can pick all
the 3 elements and change them to the maximum or minimum, and hence their difference will
always be 0.
If we can do 0 move, return (max(A) - min(A))
If we can do 1 move, return
min(the second max(A) - min(A), the max(A) - second min(A)).

Algorithm
So basically, we will have 3 options for n>4

Change 3 biggest elements


Change 2 biggest + 1 smallest element
Change 1 biggest + 2 smallest element
Change 3 smallest elements

Take minimum of these 4 cases.

27
Code

#include <bits/stdc++.h>
using namespace std;

#define ll long long


const ll MOD = 1e9+7;

int minDifference(vector<int>& A, int n) {


if (n < 5){
return 0;
}
partial_sort(A.begin(), A.begin() + 4, A.end());
nth_element(A.begin() + 4, A.end() - 4, A.end());
sort(A.end() - 4, A.end());
return min({A[n - 1] - A[3], A[n - 2] - A[2], A[n - 3] - A[1], A[n - 4] - A[0]});
}

int main(){
int n;
cin>>n;
vector<int> A(n);
for(int i = 0; i<n;i++){
cin>>A[i];
}
int ans = minDifference(A, n);
cout<<ans<<endl;
return 0;
}

Time Complexity:O(nlogn) , where n is the size of the array.

Space Complexity:O(1), no extra space is used.

28
14. Marky and his subarray
Problem Statement
In this problem, we are given an array and basically, we have to find the counts of even
subarray sums and odd subarray sums.

Example
arr=1 2 3, n=3 , there will be total nn+12=342=6 subarrays i.e.,
1 = odd
1+ 2 = 3 odd
1 +2+ 3 = 6 even
2 = even
2 +3 =5 odd
3 = odd
Hence total of 4 sums are there which are odd and the other two are even. We have to return
these counts.

Logic

The idea is very simple in a naïve way, we can simply find out all the subarrays that have an
even sum and subtract that from the total. We will use two loops to get the subarray sums.

Algorithm
1. Take two loops and iterate through the array.

2. If subarray sum = even then increase the count.

3. For odd sum = total number of subarrays – even count

29
Code

#include <bits/stdc++.h>
using namespace std;
vector<int> solve(vector<int> &v,int n){
vector<int> ans;
int even = 0;
for(int i = 0;i<n;i++)
{
int sum = 0;
for(int j = i;j<=n-1;j++)
{
sum += v[j];
if(sum%2==0){even = (even + 1)%1000000007;}
}
}
int total = (n*(n+1))/2;
ans.push_back(total-even);
ans.push_back(even);
return ans;
}
int main()
{
//write your code here
int n;
cin>>n;
vector<int> v(n);
for(int i = 0;i<n;i++)
cin>>v[i];
vector<int> ans = solve(v,n);
for(auto ele : ans)
cout<<ele<<" ";
return 0;
}

Time Complexity:On2, where n is the size of the array.

Space Complexity:O(1) , no extra space is used.

Another approach I can think of is to store only the odd and even characteristic i.e., either 1 for
odd or 0 for even in a temporary variable which will keep on counting. Then we can actually find
the number of 0 and 1s appearing in the subarrays and hence can increment the count
accordingly.

30
Code

#include <bits/stdc++.h>
using namespace std;
vector<long long int> solve(vector<int> &v,int n){
vector<long long int> ans;
long long int temp[2] = {1, 0};

long long int even = 0, sum = 0;

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


{
sum = (sum + v[i]) % 2;
temp[sum] = (temp[sum]+1)%1000000007;
}

even = (even + (temp[0]*(temp[0]-1)/2))%1000000007;


even = (even + (temp[1]*(temp[1]-1)/2))%1000000007;

long long int total = (n*(n+1))/2;


ans.push_back(total-even);
ans.push_back(even);
return ans;
}
int main()
{
//write your code here
int n;
cin>>n;
vector<int> v(n);
for(int i = 0;i<n;i++)
cin>>v[i];
vector<long long int> ans = solve(v,n);
for(auto ele : ans)
cout<<ele<<" ";
return 0;
}

Time Complexity:On, where n is the size of the array.

Space Complexity:O(1) , no extra space is used.

31
15. Maximizing the Difficulty Coefficient
Problem Statement
In this problem, we are given an array called satisfaction which refers to the satisfaction
of N problems that we have to create. Now, we can create each problem in 1 unit of time.
The satisfaction coefficient is given by the total time taken for creating a problem includ-
ing the previous problem time multiplied by the satisfaction. Find the maximum value of
the coefficient.

Example
Suppose our satisfaction array is given as satisfaction=[1 -2 5], then we can say –
For 1st problem – coefficient = 1*1
For 2nd problem- coefficient = -2*2
For 3rd problem- coefficient= 5*3
So total is 12 but this is not the maximum, we have to find the maximum. We make some
arrangements in the satisfaction array, possibly removing elements also.
New arr = -2 1 5
For 1st problem – coefficient = -2*1
For 2nd problem- coefficient = 1*2
For 3rd problem- coefficient= 5*3
Total coefficient = 15, which will be our answer.

Logic
The idea is to make the positive satisfaction to the last, i.e., we either reject the negative
satisfaction problems or we include them first so that our positive satisfaction problems are
moved later on. If we sort the satisfaction array in increasing order then we will have maxi-
mum satisfaction at the end.
Now, we can simply start from the end of the array and keep adding positive elements direct-
ly to our sum, but only till we have satisfactioni+totalsum>0. Whenever our total coefficient
tends to become negative, we stop creating the problems.

32
Algorithm
1. First of all, sort the satisfaction array so that all the maximum satisfaction problems remain to
the right.

2. Take a loop and two variables total and res initialized to 0.

3. Run the loop till satisfactioni+total>0 and we keep on adding the satisfaction coefficient in
res.

Code

#include <bits/stdc++.h>
using namespace std;
int main()
{
long long n;
cin>>n;
vector<long long> satisfaction(n);
for(long long i = 0;i<n;i++)
cin>>satisfaction[i];
sort(satisfaction.begin(),satisfaction.end());
long long res = 0, total = 0;
for(long long i = n-1;i>=0 && satisfaction[i]+total>0;i--){
total += satisfaction[i];
res += total;
}
cout<<res<<endl;
return 0;
}

Time Complexity:O(n), where n is the size of the array.

Space Complexity:O(1), no extra space is used.

33
16. Minimum Increments

Problem Statement
This problem might seem quite hard but with proper observations, it becomes quite
simple. In this problem, we are given a target array, and we have to find the minimum
number of ways to form this target array from array of 0s i.e., [0,0,0….] with only one type
of operation which is we can increase a subarray with 1 in each operation.
Essentially, we can pick up any subarray and we have to increment all the elements by 1.
Using this operation multiple times, we have to return the minimum number of operations
required to form the target array.

Example
The target=1 2 3 2 1 then
0 0 0 0 01 1 1 1 11 2 2 2 1→[1 2 3 2 1], so this will require 3 operations where we pick up one
subarray and increment all its elements by 1.

Logic
1. Keep a totalmoves count to store the answer, initialize it with target[0] as it will always be
equal to at least the minimum size of an element present in the array.
2. Also, we keep track of the previous moves to reuse and add this to our answer after
subtracting from the target element if that element is bigger than the previous target
element.
totalmoves +=(targeti-moveswecanreuse)

34
Code

#include <bits/stdc++.h>
using namespace std;
int minimumIncrements(vector<int> &target,int n){
int moveswecanuse = target[0];
int totalmoves = target[0];
for(int i = 1;i<n;i++){
if(target[i] <= moveswecanuse){
moveswecanuse = target[i];
}
else{
totalmoves += (target[i] - moveswecanuse);
moveswecanuse = target[i];
}
}
return totalmoves;
}
int main()
{
//write your code here
int n;
cin>>n;
vector<int> target(n);
for(int i = 0;i<n;i++)
cin>>target[i];
cout<<minimumIncrements(target,n)<<endl;
return 0;
}

Time Complexity:O(n), where n is the size of the array.

Space Complexity:O(1) , no extra space was used.

35
17. String Partition
Problem Statement
This is a popular interview question. In this problem, we are given a string S and we are asked
to partition this string into substrings such that if a character appears in one part, it must not
appear in any other part. You need to print the length of each part in their relative order.

Example
Input
2
Ababcaczwrtz
abcdefaqrwsqtop

Output
75
75111

Explanation
For the first test case:
The string can be break into "ababca" and "zwrtz" that is of length 7 and 5
For the second testcase:
The string can be break into "abcdefa" , "qrwsq" ,"t" , "o" , "p".

Algorithm
1. Take an array of size 26, to store the last occurrence of each character by traversing the string.

charIdx26, 0 and initialize each value to 0. charIdx[S[i]-'a'] = i for each i in S.

2. We traverse the string again and check whether we get the max position of a character the
same or not.

3. Push this length which is given by maxindex – lastindex + 1 to the result vector.

36
Logic
The idea is to store the last occurrence of a character while traversing the string. The reason
for this intuition is we know a character if it appears in one part it won’t appear in any other.
So, if a character is present at ith index and it is the last occurrence of it, then we can try
making a partition at ith index.
In the next pass of the string, we already have the last occurrences so we will need to
compare current character position with this. For this purpose, we use maxIndex which will
compare our current character’s last occurrence with current occurrence. If both positions
are same this means our current character is already at its last position and hence, we can
create a partition at this point and hence we also take another pointer lastindex which keeps
track of the last partition point as the string might have multiple partition points.

Code
#include <bits/stdc++.h>
using namespace std;
vector<int> partition(string S) {
vector<int> charIdx(26, 0);
for(int i = 0; i < S.size(); i++){
charIdx[S[i]-'a'] = i;
}
vector<int> results;

int maxIdx = -1, lastIdx = 0;


for(int i = 0; i < S.size(); i++){
maxIdx = max(maxIdx, charIdx[S[i]-'a']);
if(i == maxIdx) {
results.push_back(maxIdx - lastIdx + 1);
lastIdx = i+1;
}
}
return results;
}
int main()
{
//write your code here
int t;
cin>>t;
while(t--){
string s;
cin>>s;
vector<int> ans = partition(s);
for(auto ele: ans )
cout<<ele<<" ";
cout<<endl;
}
return 0;
}

37
18. Single and Triple

Problem Statement
Tricky problem! In this problem, we are given an array of size N which contains N
elements out of which only one element occurs only once while other elements occur
thrice. We have to find this single element.
Suppose arr=[1 2 1 11 2 2 1] , our answer will return 11.
Solve this problem without using extra space and possibly in linear time.

Logic
For this question, we have to recall our knowledge of binary numbers. Let suppose we have
an array [2 2 2 5], and its binary representation is [0010 0010 0010 0101]. Can we observe
something? If we go bit by bit then we can sum those up, and if the sum is not divisible by 3
then that bit is different in our answer.

Algorithm
1. We take care of the size of iteration to 32-bits.

2. We iterate through 32 bits of each of these elements present in the array.

3. Assign mask which will give us our current bit position.

4. We traverse the array for each of these bits and keep their sum,

If sum%3! = 0 this means we have to set this bit in our answer.

5. We keep on doing OR operation with our result as whenever we need a bit in our answer, we
can do it by doing OR.

38
Code

#include <bits/stdc++.h>
using namespace std;
const int max_size = 32;
int solve(int *arr,int n){
int res = 0,sum=0;
for(int i = 0;i<max_size;i++){
sum = 0;
int mask = (1<<i);
for(int j = 0;j<n;j++){
if(arr[j]&mask)
sum++;
}
if(sum%3 != 0)
res |= mask;
}
return res;
}
int main()
{
int n;
cin>>n;
int *arr = new int[n];
for(int i = 0;i<n;i++)
cin>>arr[i];
cout<<solve(arr,n)<<endl;
return 0;
}

Time Complexity:O32*nO(n), where n is the size of the array.

Space Complexity:O(1), as we haven’t used any extra space.

39
19. K Sum Subarrays

Problem Statement
In this problem we are given an array and sum K and we are asked to find the number of
subarrays whose sum is equal to k.

Example
Suppose our arr=[3,4,7,2,-3,1,4,2] , and K = 7. There are 4 subarrays satisfying the condition.
3+4 = 7 , 7=7 , 7+2+(-3)+1 = 7, 1+4+2 = 7.

Logic
The idea is to keep a sum that can be treated as our prefixsum[j] and then we can try to find
if we have encountered a subarray with sum = sum – k, well the logic behind this is, we
assume that we have such a subarray with sum = sum – k, this will only mean that if
prefixsum[j] is the total sum and we can find sum – k , this will ensure the presence of k.

Algorithm
1. Maintain a map for frequency of sum subarray and also initialize our sum = 0.

2. For every iteration we try to find if we have encountered sum – k in our map, if we did then
add its frequency to our answer.

3. Push the sum obtained in our map.

40
Code

#include <bits/stdc++.h>
using namespace std;
int KSumSubarrays(vector<int> A,int n,int K){
int sum = 0, ans = 0;
unordered_map<int,int> m;
for(int i = 0;i<n;i++){
sum += A[i];
if(sum == K)ans++;
if(m.find(sum - K)!=m.end())
ans += m[sum-K];
m[sum]++;
}
return ans;
}
int main()
{
//write your code here
int n,k;
cin>>n>>k;
vector<int> A(n);
for(int i = 0;i<n;i++)
cin>>A[i];
cout<<KSumSubarrays(A,n,k)<<endl;
return 0;
}

Time Complexity:O(N), as we are iterating only once.

Space Complexity:O(N), we have used a hashmap to store the frequency of sums

41
20. Subarray XOR

Problem Statement
Subarray problems are always intimidating. In this problem we are given an array of size N
and an Integer k in which we have to find the number of subarrays such that the XOR of
each elements of these subarrays is equal to k.

Example
A = [5,6,7,8,9], N=5, k=6.
[6] is itself a subarray.
[7,8,9] = 7 ^ 8 ^ 9 = 6.
So answer = 2.

Logic
Let’s recall some properties of XOR –
x XOR 0=x
x XOR x=0
if a XOR b=c then a=b XOR c
Basically, the whole idea is based on these properties.
Let us consider that we have calculated XOR of all elements to a certain index as XR. Now,
we can say that y XOR k=XR and from which we can derive y=XR (XOR) k. In this equation, we
are given the value of k and we have calculated the value of XR, we only need to find the
value of y. But here y can have multiple values as y and k are interchangeably used here. So,
we also need to store the frequency of y.

The idea is to maintain a global xor (XR) which will keep on xor-ing the elements in the array
and for each index we will have to find the value of y such that we get the value of k as given
in the problem.

42
Algorithm
1. Initialize an ans=0 , XR=0 and take a map/HashMap.

2. Iterate over our array, take the global xor

XR=XR ^ k
Check if XR==k then ans++
If XR^k is present in the map, i.e., search for a valid y in the map – if present then add its
frequency(value) in our answer, ans+=m[XR^k].
Else insert this key in the map, mXR++.

Code

#include <bits/stdc++.h>
using namespace std;
int countSub(vector<int> &A,int n,int k){
int ans = 0;
int xr = 0;
map<int,int> m;
for(int i =0;i<n;i++){
xr = xr ^ A[i];
if(xr == k)ans++;
if(m.find(xr^k)!=m.end()){
ans += m[xr^k];
}
m[xr]++;
}
return ans;
}
int main()
{
//write your code here
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
vector<int> A(n);
for(int i = 0;i<n;i++)
cin>>A[i];
cout<<countSub(A,n,k)<<endl;
}
return 0;
}

43
21.Reverse Bits
Problem Statement
We are given a 32-bit integer, we just have to reverse the bit string obtained from this number
and get the integer number from this new bit string. Don’t Worry Bit string is just the string of
binary representation of the numbers containing only 0’s and 1’s.

Example
N = 694
Bit representation - 0 1 0 1 0 1 1 0 1 1 0
Answer = 874

Logic
The naïve idea which I can think of is to traverse the 32 bits for the given number and store it
in a reverse fashion in our answer i.e., we need to put the 2i position bit to 231-i position in
our answer bit.

Algorithm
1. Extract the leftmost bit and keep on placing this according to the power of 2.

2. We initialize power = 31

3. For every iteration, we also change N to N/2 for the next iteration and decrement the power
by 1.

44
Code

#include <bits/stdc++.h>
using namespace std;
int reverseBits(int n) {
int ans = 0, power = 31;
while(n){
ans += (n&1) << power;
n >>= 1;
power--;
}
return ans;
}

int main()
{
int n;
cin>>n;
cout<<reverseBits(n)<<endl;
return 0;
}

Time Complexity:O1, traversing constant 32 bits.


Space Complexity:O1

45
22. Equilibrium Points

Problem Statement
In this problem we are given N magnets which are kept in linear fashion. The magnets are
kept in such a way that each of the magnets experiences a repulsive force from both the
side and which has the force power equal to distance 1/d where d = abs(pos1-pos2). We
are given the position of magnets we have to find the positions between these magnets
where the force will be zero.

Example
Suppose arr=[0 10 20 30], for this we have positions 3.82,15.00, 26.18 between these integers
where the force will be zero.

Logic
The intuition here is our answer will always be between a range and also the position is
always in sorted increasing order. Hence, we can try to think of some binary search approach
here to find the required positions. After that for each region between any 2 coordinates the
answer always exists either on the left boundary or any point between $2$ consecutive
points taken at a time because for $1/d$ between $2$ points there are infinite points. You
need to print one such point where the answer becomes less than 10^{-12}.

Algorithm
1. Take low and high at the ends of the array positions.

2. For every mid, we try to use this mid and find if this mid is a position or not.
We also need to check that if the answer has the precision of 1e-9 or not.
If the value of x is positive then change low to mid and high is mid.

46
Code

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll MOD = 1e9+7;
double getVal(double arr[],double i,int n){
double x=0;
for(int j=0;j<n;j++){
x=x+(1/double(i-arr[j]));
}
return x;
}
double binarySearch(double arr[],int n,double l,double r){
double mid;
while(l<r){
mid = (r+l)/2;
double x = getVal(arr,mid,n);
if(abs(x)<1e-9){
return mid;
}
else if(x>0){
l = mid;
}
else{
r = mid;
}
}
return l;
}
int main(){

int n;
cin>>n;
double arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<fixed<<setprecision(2);
for(int i=1;i<n;i++){
cout<<binarySearch(arr,n,arr[i-1],arr[i])<<" ";
}

cout<<endl;

return 0;
}

Time Complexity:O(logn), where n is the size of the array.

Space Complexity:O(1) no extra space was used.

47
23. Large Factorial

Problem Statement
In this problem, we are given an array of integers and a value k. We are asked to find the
minimum lengths of non-overlapping subarrays.

Example
Suppose we have arr=[3 2 5 4 1 5] and k = 5 then we can say our subarrays are [5] and [5]
and their sum of lengths is 1+1 = 2.

Logic
We have to find a subarray and their sum should be k. We can use a prefix sum to make it
more efficient. Now if we want to see if we have a subarray with sum K then for a particular
prefixi-k is present in the prefix array or not. If it does then we have our subarray with such
sum. From this, we can also find their respective index which will be stored in map. We need
the map to store the prefix sum and corresponding index. Then we have to iterate over the
array to find the minimum length subarray.

Algorithm
1. Build the prefix sum array

2. Create a HashMap to store the position of the prefix sums.

3. Now we iterate through the array and find currsum-target in the map, if we get it this means
we have a subarray before the current index whose sum is k and we can take this as one
minimum.

48
Code

#include <bits/stdc++.h>
using namespace std;
int minSumOfLengths(vector<int>& arr, int target) {
int n = arr.size();
unordered_map<int, int>hm;
hm[0] = -1;
int sum = 0;

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


sum += arr[i];
hm[sum] = i;
}
sum = 0;
int msize = INT_MAX, res = INT_MAX;
for (int i = 0; i < n; i++) {
sum += arr[i];

if (hm.find(sum-target) != hm.end())
msize = min(msize, i-hm[sum-target]);

if (hm.find(sum+target) != hm.end() && msize != INT_MAX)


res = min(res, msize + hm[sum+target]-i);
}
return res == INT_MAX ? -1 : res;
}
int main()
{
//write your code here
int n,k;
cin>>n>>k;
vector<int> arr(n);
for(int i = 0;i<n;i++)
cin>>arr[i];
cout<<minSumOfLengths(arr,k);
return 0;
}

Time Complexity:O(n), where n is the size of the array.

Space Complexity:O(n), as we used hashmap here.

49
24. Fibonacci sum equal to S

Problem Statement
We all have come across the Fibonacci sequence, right? Do not worry if you haven’t. It’s
just a series of numbers following the property – Fib1=1, Fib2=1 , and Fibn=Fibn-1+Fibn-2
for all n>2. We can jot down this sequence as – 1, 1, 2, 3, 5, 8, 13… and so on. In this prob-
lem, we are basically given an Integer sum S and are asked to find out the minimum
number of Fibonacci numbers when summed up to get a target S. We can use the same
Fibonacci number multiple times.

Example

If we have
S=22
And all the Fibonacci numbers below this – 1, 1,2, 3,5, 8, 13, 21
Then S=1+21 or 8+13 hence minimum we require two elements – ans = 2

Logic
The idea is to find all the Fibonacci numbers below S and start iterating from the largest
Fibonacci number just less than or equal to S. For each of the Fibonacci numbers, we keep
on dividing S by the Fibonacci number until our S becomes zero. Each of these divisions is
one step.

Algorithm

1. Find all the Fibonacci numbers below S.

2. Start Iterating from largest Fibonacci number and divide S by that number (greedily choosing
the largest element)

3. count += (S / fibnum[j]);

S %= fibnumj;

4. Return count
50
Code

#include <bits/stdc++.h>
using namespace std;
long long nearestfibpos = 0;
vector<long long> fib(long long S)
{
vector<long long> fibnum;
int i = 3, next;
fibnum.push_back(0);
fibnum.push_back(1);
fibnum.push_back(1);
while (1) {
next = fibnum[i - 1] + fibnum[i - 2];
if (next > S)
break;
fibnum.push_back(next);
i++;
}
return fibnum;
}
long long minSteps(long long S){
long long count = 0;
vector<long long> fibnum = fib(S);
long long j = fibnum.size() - 1;
while (S > 0) {
count += (S / fibnum[j]);
S %= (fibnum[j]);
j--;
}
return count;
}
int main()
{
//write your code here
long long S;
cin>>S;
cout<<minSteps(S)<<endl;
return 0;
}

Time Complexity:OS, where S is the sum given.We run till we get a Fibonacci number that is
greater than S.
Space Complexity:O(≈S), for storing all the Fibonacci numbers below S.

51
25. Overlapping

Problem Statement
In this problem, we have been given with bottom-left and top-right coordinates of two
rectangles and we are asked to find whether these rectangles are overlapping or not.

Logic
Suppose we have two sets of coordinates –
Rectangle 1: (x1, y1) – bottom-left (x2, y2) – top-right
Rectangle 2: (x3, y3) – bottom-left (x4, y4) – top-right
x1<x4 & x3<x2 for the x co-ordinates
y1<y4 & y3<y2 for the y co-ordinates
If these conditions satisfy then we can return true for overlapping.

Code

#include <bits/stdc++.h>
using namespace std;
bool overlap(int x1, int y1, int x2, int y2,
int x3, int y3, int x4, int y4)
{
return (x1<x4 && x3<x2 && y1<y4 && y3<y2);
}
int main()
{
//write your code here
int t;
cin>>t;
while(t--){
int x1, y1, x2,y2, x3, y3, x4, y4;
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
if(overlap(x1,y1,x2,y2,x3,y3,x4,y4))
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}

52
Well, here’s a trick the above program is accepted most of the time but will fail for certain
negative coordinates and the orientation of the rectangles. Rather than comparing each, we
can compare the minimum of the edges of two rectangles with their corresponding maximum.
Let me make this clearer.
We simply take the max of lower edges and min of upper edges and compare them. If the
overlap this should hold.

Code

#include <bits/stdc++.h>
using namespace std;
bool overlap(int x1, int y1, int x2, int y2,
int x3, int y3, int x4, int y4)
{
return (min(x4,x2) > max(x1,x3) && (max(y1,y3) < min(y2,y4)));
}
int main()
{
//write your code here
int t;
cin>>t;
while(t--){
int x1, y1, x2,y2, x3, y3, x4, y4;
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
if(overlap(x1,y1,x2,y2,x3,y3,x4,y4))
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}

Time Complexity:O(1), we did not use any loops.

Space Complexity:O(1), no extra space was used.

53
26. Longest increasing subsequence

Problem Statement
You are given an array of N non-negative integers. The task is to find the length of the
longest increasing subsequence. The longest increasing subsequence is an increasing
subsequence such that all elements of the subsequence are sorted in increasing order.

Example
Suppose we have an array as arr=[1 8 3 14 5] then the length of the longest increasing
subsequence is 3 which includes - [1 3 5]. We need to return the length of the subsequence.

Logic
We can start with a recursive type solution. We create a recursive function that returns the
length of the LIS possible from the current element onwards (including the current element).
Inside each function call, we consider two cases
The current element is larger than the previous element included in the LIS. In this case, we
can include the current element in the LIS. Thus, we find out the length of the LIS obtained
by including it. Further, we also find out the length of LIS possible by not including the
current element in the LIS. The value returned by the current function call is, thus, the
maximum out of the two lengths.
The current element is smaller than the previous element included in the LIS. In this case, we
can't include the current element in the LIS. Thus, we find out only the length of the LIS
possible by not including the current element in the LIS, which is returned by the current
function call.
Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that
arr[i] is the last element of the LIS.
Then, L(i) can be recursively written as:
L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i] or
L(i) = 1, if no such j exists.

54
Code

#include <bits/stdc++.h>

using namespace std;

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 maximum = 0;

int dp[n];

dp[0]=1;

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

dp[i]=1;

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

if(arr[i]>arr[j] && dp[i]<dp[j]+1){

dp[i] = dp[j]+1;

maximum = max(maximum, dp[i]);

cout<<maximum<<"\n";

return 0;

55
27. K Closest Points to Origin

Problem Statement
You have been given N points placed in the X−Y plane and an integer K. You have to find the KK
closest points which are close to the origin i.e., (0,0) out of the given N points. Note -You have
to output these K-points after sorting them in the ascending order first with respect to X−
coordinate and the according to Y−coordinate.
The distance between two points on the X-Y plane is the Euclidean distance as

Logic
The idea is to calculate the Euclidean distance of the given points from the origin and store the
distances in an array. Now make a copy of the array and sort the array in ascending order. Now
we can see the orginal index of the first k minimum distances of the sorted array in the original
array of distances and print the first k closest points from the list.

Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,k;
cin>>n>>k;
vector<vector<long long>> arr(n, vector<long long> (2));
int dist[n];
for(int i = 0; i < n; i++)
{
int x, y;
cin>>x>>y;
arr[i][0] = x;
arr[i][1] = y;
dist[i]=x*x + y*y;
}
priority_queue<pair<int, int>>pq;
for(int i=0;i<n;i++){
pq.push(make_pair(dist[i],i));
if(pq.size()>k)
pq.pop();
}
vector<vector<long long>> ans(k, vector<long long> (2));
int p=0;
while(!pq.empty()){
int index = pq.top().second;
pq.pop();
ans[p][0]= arr[index][0];
ans[p][1] = arr[index][1];
p++;
}
sort(ans.begin(),ans.end());
for(int i=0;i<k;i++)
cout<<ans[i][0]<<" "<<ans[i][1]<<"\n";
return 0;
} 56
28. Sudoku Solver
Problem Statement
As we all know, you are quite interested in the politics of Prepland since childhood, here comes
the best opportunity for you as the contest for becoming Mayor of the city is just going to
start. In the contest, you will be given a partially filled sudoku. A sudoku solution must satisfy
all of the following rules:
Each of the digits 1 - 9 must occur exactly once in each row
Each of the digits 1 - 9 must occur exactly once in each column
Each of the digits 1 - 9 must occur exactly once in each of the 9 3 × 3 sub-boxes of the grid.

Example
...26.7.1
68..7..9.
19...45..
82.1...4.
..46.29..
.5...3.28
..93...74
.4..5..36
7.3.18...
Is the matrix then the output
435269781
682571493
197834562
826195347

Logic
The basic idea here is to try to fill the empty cells one by one using numbers 1 to 9 and check
whether placing a number at an empty cell violates the above rules or not. If placing a number
in the range of 1 to 9 does not violate the above rule then do the same for the next empty cell
and if it violates the above-mentioned rules then try filling the empty cell with the next number
in the range 1 to 9. Do it until the grid is filled. If the grid gets filled return the grid.

57
Code

#include <bits/stdc++.h>
using namespace std;
bool isValid(vector<vector<char>>& board, int a, int i, int j){

for(int c=0;c<9;++c)
if(board[i][c]-'0' == a)
return 0;

for(int r=0;r<9;++r)
if(board[r][j]-'0' == a)
return 0;

int br = i/3, bc = j/3;


for(int r=br*3; r<br*3+3;++r)
for(int c=bc*3; c<bc*3+3;++c)
if(board[r][c]-'0' == a)
return 0;
return 1;
}

bool sudoku(vector<vector<char>>& board, int i, int j){


if(i == 9) return 1;
if(j == 9) return sudoku(board,i+1,0);
if(board[i][j] != '.') return sudoku(board,i,j+1);
for(int a=1;a<=9;++a){
if(isValid(board,a,i,j)){
board[i][j] = a+'0';
if(sudoku(board,i,j+1))
return 1;
board[i][j] = '.';
}
}
return 0;
}
int main() {
vector<vector<char>> board;
for(int i=0;i<9;i++){
vector<char>row;
for(int j=0;j<9;j++){
char a;
cin>>a;
row.push_back(a);
}
board.push_back(row);

}
sudoku(board,0,0);
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
cout<<board[i][j];
}
cout<<"\n";

return 0;
}
58
29. Reverse in a Group

Problem Statement
You have to reverse the list in a group of nodes. If the list is
HEAD→2→3→7→4→1→6→NULL and K is 3, your modified list should be
HEAD→7→3→2→6→1→4→NULL.

Logic
We will take three-pointers like current, previous, and next to where the current is pointed to
the head. We will also take a count by which we will have the count of nodes to reverse at a
time in a group. For one iteration or group of k, we will use the normal algorithm to reverse
the group. In the end, we assign the head to the new previous.
Assign three-node pointers curr = head, & prev, next to null.
For every iteration till count is less than k,
Next = curr→next
Curr→next = prev
Prev = curr
Curr = next
In the end, we assign the new head to the prev as prev is the new head.

Code
SinglyLinkedListNode *reverseKnodes(SinglyLinkedListNode *head,int k)
{
//write your code here
SinglyLinkedListNode* current = head;
SinglyLinkedListNode* next = NULL;
SinglyLinkedListNode* prev = NULL;
int count = 0;
while (current != NULL && count < k)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}

if (next != NULL)
head->next = reverseKnodes(next, k);
return prev;
}
59
30. Sunset View
Problem Statement
You have been given an array B of buildings and a direction that all of the buildings face.
You have to find an array of the indices of the buildings that can see the sunset. A build-
ing can see the sunset if it's strictly taller than all of the buildings that come after it in the
direction it faces. All of the buildings face the same direction, and this direction is either
east or west, denoting by the input string named direction, which will always be equal to
either EAST or WEST.

Example
Suppose the given array B = 4 6 5 4 5 2, and EAST then output is 1 4 5.

Logic
The idea is to make use of stack data structure for an appropriate and efficient solution to
this problem. Take the input of the building heights and store them in an array. Take the input
direction, whether it is EAST or WEST. Iterate over this array of building heights and push
elements into the stack appropriately. If the top of the stack is greater than the current
element, then push it into the stack. Else pop out of stack until the stack is empty or top
element is greater than the current element. Using this approach, we can eliminate all the
buildings that do not have a sunset view.

60
Code

#include <bits/stdc++.h>
using namespace std;

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];
string str;
cin >> str;
stack<int> st;
int i = 0;
int j = 1;
if (str == "WEST")
{
i = n - 1;
j = -1;
}
while (i >= 0 && i < n)
{
if (st.empty() || arr[i] < arr[st.top()])
st.push(i);
else
{
while (!st.empty() && arr[i] >= arr[st.top()])
{
st.pop();
}
st.push(i);
}

i += j;
}
vector<int> res;
while (!st.empty())
{
res.push_back(st.top());
st.pop();
}
if (str == "EAST")
reverse(res.begin(), res.end());

for (auto ele : res)


cout << ele << " ";
cout << "\n";
}
return 0;
}

61
31. Sum Subarray

Problem Statement
You are given an array A of size N. You have to print the length of the smallest subarray that
has a sum at least equal to K.

Example
Suppose we have our array as [1 2 3 4 2 1] and k = 7, then we have many subarrays whose
sum is at least equal to 7 like – [4 2 1 ], [1 2 3 4], [1 2 3 4 2],..[3 4],…[3 4 2 ], etc, but out of
these many subarrays, we have only [3 4] whose size is the minimum. Hence, we return its
length 2.

Logic
Well, the idea here is to use a data structure that can store our subarray which has the sum
of more than ‘k’ only. If we have a subarray such in our ds then we will evict any of the
elements and try to minimize the size keeping the sum more thank. This can be done using a
map or queue. We will try to implement this logic using a queue. Take a sum variable that will
keep on adding the elements to it and when the sum is greater than k we will check if this
subarray is the smallest we can get. For the next element when the sum is greater than k, we
evict the element from the front of the queue and also update our sum. We keep on doing
this till we reach the end of the array. In this, we also keep track of the minimum length subar-
ray when the sum becomes greater than k.

62
Code

#include<bits/stdc++.h>
using namespace std;
int32_t main()
{
int n,k;
cin>>n>>k;
int A[n];
for(int i=0;i<n;i++)
{
cin>>A[i];
}
int sum=0;
int i=0;
queue<int>q;
int ans=INT_MAX;
while(i<n)
{
q.push(A[i]);
sum+=A[i];
if(sum>=k)
{
while(sum>=k)
{
if(sum>=k)
{
int temp=q.size();
ans=min(ans,temp);
}
sum-=q.front();
q.pop();
}
}
i++;
}
cout<<ans<<endl;
}

63
32. Painter Partition

Problem Statement
PrepBuddy has N boards of length A1, A2, A3...AN. He wants to paint these boards so he
hires P painters. Each painter takes 1 unit of time to paint 1 unit of the board. He is short
on time, so he asks for your help in determining the minimum time to complete the task
with the constraint that any painter can only paint continuous sections of boards.

Example
For example if the lengths are [1,2,3,4] then a painter can be assigned [1,2], [1,2,3], [1,2,3,4],
[2,3] etc, but not [1,2,4],[2,4] etc. Another example, let the board array be 9 6 7 10 5 and the
number of painters is 3. So the 3 painters can be assigned subarrays as [9,6], [7], [10,5].
They will work simultaneously, so the minimum time required to paint all the boards will be 15
units.

Logic
Take input and calculate the upper and lower bounds required for binary search.
In the binary search, we run a while loop till low <= high:
a. We calculate mid as low + (high - low) / 2.
b. Now we have to check for this mid-value if it is possible to paint all boards within this
time, with the given number of painters.
c. If it is possible, we check for values in the left half, if we can find a lesser time than this.
So we update high-value with mid.
d. Else we search in the right part and update the low value with mid+1.
e. In the end, we return lo from the function which will give us our answer.

64
Code
#include <bits/stdc++.h>
using namespace std;
long long getMax(int arr[], int n)
{
long long max = INT_MIN;
for (int i = 0; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
long long getSum(int arr[], int n)
{
long long total = 0;
for (int i = 0; i < n; i++)
total += arr[i];
return total;
}
long long numberOfPainters(int arr[], int n, int maxLen)
{
long long total = 0, numPainters = 1;
for (int i = 0; i < n; i++)
{
total += arr[i];
if (total > maxLen)
{
total = arr[i];
numPainters++;
}
}
return numPainters;
}
long long partition(int arr[], int n, int k)
{
long long lo = getMax(arr, n);
long long hi = getSum(arr, n);
while (lo < hi)
{
long long mid = lo + (hi - lo) / 2;
long long requiredPainters = numberOfPainters(arr, n, mid);
if (requiredPainters <= k)
{
hi = mid;
}
else
lo = mid + 1;
}
return lo;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n, p;
cin >> n >> p;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << partition(arr, n, p) << endl;
}
return 0;
}
65
33. Count the Provinces

Problem Statement
There are N cities in the country of Prepland. Some of them are connected, while some
are not. If city X is directly connected with city Y, and city Y is connected directly with city
Z, then city X is indirectly connected with city Z.
A group of cities that are connected directly or indirectly with each other are known as
ProvinceProvince Your task is to count the total number of provinces in the Prepland.

Example
Let suppose we have 3 cities, denoted as 1,2, and 3. There is an edge from 1 to 2 and hence
1 and 2 are connected, this makes 2 provinces.

Logic
The idea is to take a parent array that stores the root of each of the cities. Initially, each city
will be the parent of itself which is represented by -1. Now when we add an edge, we will see
that if they are in different groups then unite them by making the parent of one node parent
of another also. So, if 1 is connected to 2 then the parent of 2 is changed to 1 and this goes
on for every edge. In the end, we traverse the parent array and count the number of -1, which
represents the number of separate groups. This will also be our final answer.

66
Code

#include <bits/stdc++.h>
using namespace std;

void addEdge(vector<int> adj[], int u, int v)


{
adj[u].push_back(v);
adj[v].push_back(u);
}

void DFSRecur(vector<int> adj[], vector<bool> &visited,int u)


{

visited[u]=true;
for(int i=0;i<adj[u].size();i++)
{
if(visited[adj[u][i]]==false)
DFSRecur(adj,visited,adj[u][i]);
}
}
void DFS(vector<int> adj[], int n)
{
vector<bool> visited(n,false);
int count=0;
for(int i=0;i<n;i++)
{
if(visited[i]==false)
{
DFSRecur(adj,visited,i);
count+=1;
}
}
cout<<count<<"\n";

}
int main() {
int t;
cin>>t;
while(t--) {
int nodes, edges;
cin >> nodes >> edges;

vector<int> adj[nodes];
for (int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
addEdge(adj, u, v);
}
DFS(adj, nodes);
}
return 0;
}

67
34. Marky and his subarray
Problem Statement
You are given the time intervals of n meetings. Each time interval consist of the start time
x and end time
Y. The task is to determine the minimum number of conference rooms required to hold all
the meetings.

Example
In this problem, we are given the start time and end times of the meetings and are asked to
find the minimum number of rooms that will be required so that no two meetings are orga-
nized in the same room. Suppose we have our starting and ending time arrays as –
57
25
34
16
12
Then the minimum number of rooms that we will require is 3.
For the first test case:
Room 1: 5th meeting→ 2nd meeting
Room 2: 4th meeting
Room 3: 1st meeting

Logic
The idea is we sort the arrival and departure times in a non-decreasing fashion and then
check how many overlapping time intervals we are getting. The maximum of these numbers
will give me the final answer.
If a meeting has already started then if any other meeting starts before the current meeting
end time then those will overlap.

68
Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
//write your code here
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<pair<int,int> > vp;
for(int i = 0;i<n;i++){
int x,y;
cin>>x>>y;
vp.push_back(make_pair(x,y));
}

priority_queue<int,vector<int>,greater<int> > pq;


sort(vp.begin(), vp.end());
for(auto i : vp){
pq.push(i.second);
}
int ans = 0;
for(int i = 0 ; i < vp.size() ; ++i){
if(!pq.empty() && vp[i].first >= pq.top())
pq.pop();
else
++ans;
}
return ans;
}
return 0;
}

69
35. Longest Palindromic Substring

Problem Statement
You are given a string str, find the longest palindromic substring in str.
Longest Palindromic Substring of string strstr: LPS[i...j] where 0<=i<=j<len(LPS).

Example
Palindrome string: LPS is a palindrome if reverse(LPS) = LPS.
If multiple LPS is the same then return the Longest Palindromic Substring which occurs first (
with the least starting index )
Input : "bbbbbabbb"
Output : "bbbabbb".

Logic
The idea is quite simple and I call it the spreading hand technique. :) Well, what we know
about a palindrome is, if we reverse the next half of the string then it will be equal to the first
half for a palindrome.
We keep a variable longest which stores the current longest palindrome seen.
We start iterating from 1 till the end –

For each character in this iteration, we have two options: either search for a palindrome
taking the ith character as second middle or only middle.

This means, when a palindrome with even length like “baab”, we have two middles as a
whereas for palindromes with odd length like “bab”, we do not consider the middle a for
the mismatch.

We have two options to check as given above. For both the options, take the middle
character and start expanding the pointers towards the opposite direction till we reach
the end or different characters.

If both the characters keep on matching then we can say that there is a palindrome in
between these pointers and we keep track of this length and start position.

if high - low + 1 > longest then start=low and longest = high - low +1.

70
Code

#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
string st;
cin>>st;
int longest = 1;
int start=0;
int len = st.length();
int low,high;
for(int i=1;i<len;i++){
low = i-1;
high = i;
while(low>=0 && high<len && st[low]==st[high]){
if(high - low + 1 > longest){
start=low;
longest = high - low +1;
}
low--;
high++;
}
low = i-1;
high = i+1;
while(low>=0 && high<len && st[low] == st[high]){
if(high - low +1 > longest){
start = low;
longest = high - low +1;
}
low --;
high++;
}
}
for(int i=start; i<=start+longest-1;i++)
cout<<st[i]<<"";
cout<<"\n";

}
return 0;
}

71
36. Points Collision

Problem Statement
A segment of the line is defined as the line connecting two points in the Cartesian Coordinate
System. The segments are defined by start and endpoints
(Xi, Yi) and (Xj, Yj) (1<=i,j<=n). Coordinates of these points are integer numbers with a real
value smaller than 1000
The length of each segment is positive.
When 2 segments don't have a common point then it is said that segments don't collide. In any
other case, segments collide. Be aware that segments collide even if they have only one point
in common. The segment is said to be isolated if it doesn't collide with all the other segments
that are given, i.e.segmenti is isolated when for each 1<=j<=n (i!=j), segments i and j don't
collide. You are asked to find the number T – How many segments are isolated.

Example
Input
3
3
0020
1 -1 1 1
2233
2
0011
1001
2
0001
0203

Output
1
0
2

72
Logic

The algorithm first sorts the endpoints along the x-axis from left to right, then it passes a
vertical line through all points from left to right and checks for intersections.

Algorithm
Following are detailed steps in online programming practice.

1. Let there be n given lines. There must be 2n endpoints to represent the n lines. Sort all points
according to x coordinates. While sorting, maintain a flag to indicate whether this point is the
left point of its line or the right point.

2. Start from the leftmost point. Do following for every point

If the current point is a left point of its line segment, check for the intersection of its line
segment with the segments just above and below it. And add its line to active line
segments (line segments for which the left endpoint is seen, but the right endpoint is not
seen yet). Note that we consider only those neighbors which are still active.

If the current point is a right point, remove its line segment from the active list and check
whether its two active neighbors (points just above and below) intersect with each other.

Code

#include <bits/stdc++.h>
#define min(x, y) ((x) < (y) ? (x) : (y))
#define max(x, y) ((x) > (y) ? (x) : (y))
struct Point {
double x, y;
};
struct Segment {
Point s, t;
};
double in(double a, double b, double c) {
return c >= a && c <= b;
}
73
Code

int onLine(Segment a, Point c) {


static double minx, maxx, miny, maxy;
minx = min(a.s.x, a.t.x);
maxx = max(a.s.x, a.t.x);
miny = min(a.s.y, a.t.y);
maxy = max(a.s.y, a.t.y);
if(in(minx, maxx, c.x) != 0 && in(miny, maxy, c.y) != 0) {
if((a.s.x-a.t.x)*(c.y-a.s.y) == (a.s.y-a.t.y)*(c.x-a.s.x)) {
return 1;
}
}
return 0;
}
double cross(Point &o, Point &a, Point &b) {
return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x);
}
int intersection(Segment a, Segment b) {
if(onLine(a, b.s) || onLine(a, b.t) || onLine(b, a.s) || onLine(b, a.t))
return 1;
if(cross(a.s, a.t, b.s)*cross(a.s, a.t, b.t) < 0 &&
cross(a.t, a.s, b.s)*cross(a.t, a.s, b.t) < 0 &&
cross(b.s, b.t, a.s)*cross(b.s, b.t, a.t) < 0 &&
cross(b.t, b.s, a.s)*cross(b.t, b.s, a.t) < 0
)
return 1;
return 0;
}
int main() {
int t, n, i, j;
Segment line[1000];
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
for(i = 0; i < n; i++)
scanf("%lf %lf %lf %lf", &line[i].s.x, &line[i].s.y, &line[i].t.x, &line[i].t.y);
int ans = 0;
for(i = 0; i < n; i++) {
int flag = 0;
for(j = 0; j < n; j++) {
if(i == j)
continue;
if(intersection(line[i], line[j])) {
flag = 1;
break;
}
}
if(flag == 0)
ans++;
}
printf("%d\n", ans);
}
return 0;
}
74
37. CHEATING CLASS
Problem Statement
Let’s suppose when a person cheats from a person j, then we draw a line segment between
them. We need to find the number of ways in which N people giving the exam(in a circular
table) can cheat in pairs provided there is no crossover (Two lines intersecting each other).

Example
n=4
In the first sample provided above, there are 2 chords and 4 points. Let us label them as A, B,
C, D in order. Now possible arrangements are chords AB and chords CD, the second possible
arrangement is chord AD and chord BC.
Note: we can’t take chord AC and chord BD because they will intersect and we only have to
consider non-intersecting chords.

Logic
In this approach, we select a point and a variable point and then make a chord using both
points to divide the circle into two halves then using dp matrix we will find the number of
ways to form the rest of the chords in both halves multiply them, and add them to the solu-
tion of the ith column. We will proceed with this with the same fixed point and different
variable point and store the answer in the ith column.

75
Code

#include<bits/stdc++.h>
using namespace std;
#define ld long long
int main() {
ld dp[61];
dp[0]=dp[1]=1;
for(int i=2;i<61;i++)
{
dp[i]=0;
for(int j=0;j<i;j++)
{
dp[i]+=dp[j]*dp[i-j-1];
}
}
int t;
cin>>t;
for(;t>0;t--)
{
int n;
cin>>n;
n/=2;
cout<<dp[n]<<endl;
}
return 0;
}

76
38. Number of Substrings Containing All Three Characters

Problem Statement
Print the number of substrings containing all three characters i.e. a,b,c at least once in a
given string.

Example
Input:
1
acbaa
Output:
5
Explanation:
The substrings containing at least one occurrence of the characters a, b, and c are acb,
acba, acbaa, cba and cbaa.

Logic
1. You can see in the above approach, we were able to find the answer but it was taking longer
times. So we use the Sliding Window Algorithm with the use of two pointers start and end.

2. A window contains characters from the index start to end-1.

3. In each window, we calculate the number of appearances of each character. If all the charac-
ter is present in sliding window then all the substrings, substring(start, end), substring(start,
end + 1), …, substring(start, n) are valid substrings., and we increase the counter by N - end
+ 1 where N is the length of String.

4. Finally, the algorithm finishes when the end reaches the end of the string and the final count-
er is printed.

77
Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
int test;
cin>>test;
while(test--){
char S[100000];
cin>>S;
int start=0, end=0, count=0;
if(strlen(S)<3)
count = 0;
else{
while(end <= strlen(S)){
int hash[26] = {0};
for(int i=start; i<end; i++){
hash[ S[i] - 'a' ]++;
}
if(hash[0]>0 && hash[1]>0 && hash[2]>0){
count += strlen(S) - end + 1;
start++;
}else{
end++;
}
}
}
cout<<count<<endl;
}
return 0;
}

78
39. Majority Votes

Problem Statement
Given an array of size N, which contains the voting ID's of students that have stood up for
the elections for the class monitor, the candidate with votes greater than half the strength
of the class will become monitor, find the ID of candidate that can become monitor else
return -1 if no one can become.

Example
Input : A = [1, 3, 2, 2, 2]
Output : 2
Explanation: 2 got 3 votes which is greater than half the strength of the class i.e. 5/2 = 2.

Logic
The idea is to use Hashing. While traversing the array of ID's keep incrementing the count of
votes for that particular ID.
If the count of any ID becomes greater than Strength-of-class/2, simply return it. Else return
-1.

Code

#include <bits/stdc++.h>
using namespace std;
int main()
{
int t; cin>>t;
while(t--){
int n; cin>>n;
//storing frequency of votes in hash array
int hash[1000000] = {0};
int arr[n];
int winner = -1;
for(int i=0; i<n; i++){
cin>>arr[i];
hash[arr[i]]++;
/* if frequency of votes becomes greater than half
of total votes, this element is our winner */
if(hash[arr[i]] > n/2)
winner = arr[i];
}
cout<<winner<<"\n";
}
return 0;
}

79
40. Fair Distribution of Chocolates

Problem Statement
Given a number of chocolates in N different bags and M children. Every kid will get some
consecutive bags. The task is to distribute chocolates in such a way that the maximum
number of chocolates assigned to a kid is minimum.

Example
Input : chocolates[] = {12, 34, 67, 90}
M=2
Output: 113
Explanation:
There are 2 kids. Chocolates can be distributed in the following fashion :

1) [12] and [34, 67, 90]


Max number of chocolates is allocated to kid
2 with 34 + 67 + 90 = 191 chocolates

2) [12, 34] and [67, 90]


Max number of chocolates is allocated to kid
2 with 67 + 90 = 157 chocolates

3) [12, 34, 67] and [90]


Max number of chocolates is allocated to student
1 with 12 + 34 + 67 = 113 chocolates

Of the 3 cases, Option 3 has the minimum chocolates = 113.

80
Logic
The idea is to use Binary Search according to data structures in c++.

We initialize minimum and maximum as 0 and sum-of-all-chocolates respectively.


We fix a value for the number of chocolates as mid of current minimum and maximum.
If a current mid can be a feasible solution, then we search on the lower half, else we search in
the higher half.
Before that, we need to check if mid-value is feasible or not.
Basically, we need to check if we can distribute chocolates to all children in a way that the
maximum number doesn’t exceed the current value. To do this, we sequentially assign
chocolates to every kid while the current number of assigned chocolates doesn’t exceed the
value.
In this process, if the number of kids becomes more than M, then the solution is not feasible.
Else feasible.

Code

#include <bits/stdc++.h>
using namespace std;

//function for finding if the assumed minimum is possible or not


int isPossible(int *arr, int n, int m, long long curr_min){
long long curr_sum = 0;
int studentRequired = 1;
for(int i=0; i<n; i++){
/* if any value in array is greater than current minimum
value then it is not a valid value and therefore return */
if(arr[i] > curr_min)
return 0;

if(arr[i] + curr_sum > curr_min){

studentRequired++;
curr_sum = arr[i];
/* if at any point required student becomes greater
than actual student return false */
if(studentRequired > m)
return 0;

81
Code

}
else{
curr_sum += arr[i];
}
}
return 1;
}

int solution(int *arr, int n, int m){

long long sum = 0;


//finding sum of all elements
for(int i=0 ;i<n; i++)
sum += arr[i];

//if books are less than students


if(n < m)
return -1;

//assume minimum pages to be start and maximum pages to be end


int start = 0;
int end = sum;

long long result = INT_MAX;

while(start <= end){


//we assume that this mid value can be our minimum pages
long long mid = start + (end - start) / 2;

/* if mid value is possible, store it and


go on searching for a lower value of mid */
if(isPossible(arr, n, m, mid)){

result = min(result, mid);


end = mid - 1;
}
/* if not possible search in the right half
for a possible value */
else{
start = mid + 1;
}
}
return result;
}

int main()
{
int t; cin>>t;
while(t--){
int n, k; cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
cin>>k;
cout<<solution(arr, n, k)<<"\n";
}
return 0;
}

82
41. Copying Hero

Problem Statement
We need to find the total number of steps need to make the current array of size N the same
as an array containing 1 to N numbers as elements. Each decrement or increment is counted
as a step.

Example
Input:
1
5
84219
Output:
9
Explanation:
As our target array is [1,2,3,4,5], we already have 1, 2, and 4 in our array. We have 8 and 9 in
place of 3 and 5, so if convert 8 to 3, and 9 to 5, we can achieve the target array. Hence
minimum increments/decrements required will be (8-3)+(9-5) ways i.e. 9 ways.

Logic
We can see that size of the array goes from 1 to 10^6, in worse conditions let the size of the
array be 10^6 if we sort this array using any of the sorting techniques i.e. Bubble Sort,
Insertion Sort, Selection sort. They all takeO(N2) in the worst cases, which results in 10^12
iterations when the size of the array is 106. So we, can’t choose the above three sorting
algorithms. We use Merge Sort to sort the array as it sorts the array in linear time complexity
(O(nlogn)).

Algorithm
1. By sorting the given array in non-decreasing order, it will make sure that the difference
between the element at the current index and the Hero array’s (Target array) element is
minimum.

2. Thus we can take the absolute difference between both elements, an increment or
decrement, both will be taken as a step.

3. Sum of all absolute differences is our final answer.


83
Code

#include <bits/stdc++.h>
using namespace std;

void merge(int arr[], int start, int mid, int end){


int left[mid-start+1];
int right[end-mid];
for(int i=start; i<mid+1; i++){
left[i-start] = arr[i];
}
for(int i=mid+1; i<=end; i++){
right[i-(mid+1)] = arr[i];
}
int leftIndex=0, rightIndex=0, arrIndex=start;
for( ; leftIndex<=mid-start && rightIndex<end-mid; arrIndex++){
if(left[leftIndex]<right[rightIndex]){
arr[arrIndex] = left[leftIndex++];
}
else{
arr[arrIndex] = right[rightIndex++];
}
}

while(leftIndex<=mid-start){
arr[arrIndex++] = left[leftIndex++];
}

while(rightIndex<end-mid){
arr[arrIndex++] = right[rightIndex++];
}

void mergeSort(int arr[], int start, int end){


if(end==start)
return;
mergeSort(arr,start,(start+end)/2);
mergeSort(arr,((start+end)/2)+1,end);
merge(arr,start,(start+end)/2,end);
}

int main()
{

int test;
cin>>test;
while(test--){

int n;
cin>>n;

int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
mergeSort(a,0,n-1);

long long int cost=0;


for(int i=0;i<n;i++)
cost+=abs(a[i]-(i+1));

cout<<cost<<endl;
}
}

84
42. Check SumTree
Problem Statement
"A SumTree is a Binary Tree where the value of a node is equal to the sum of the nodes
present in the left subtree and right subtree."
Given a binary tree and the task is to return true if the given binary tree is SumTree else
return false.

Logic
In the above method, we are calculating the left & right subtrees for every node.
We can skip the recalculation of this sum for each subtree if we take care of the following
points:
If the current node is the leaf node, then the sum of the subtrees of this node is equal to the
value of the node itself.
If the current node is not a leaf node, then the sum of the subtrees of this node is double the
value of the node.

Code
#define REP(i, n) for (i = 0; i < n; i++)
#define pb(a) push_back(a)
#define vi vector<long>
#define ll long long
#include <bits/stdc++>
using namespace std;
struct node
{
ll value;
node *left;
node *right;
};
node *createNode(ll value)
{
node *t = new node();
t->value = value;
t->right = t->left = NULL;
return t;
}
void deleteNode(node *t)
85
Code
{
delete t;
}
node *replaceNegativeOne(node *root)
{
if (root == NULL || (root->value == -1 && root->left == NULL && root->right == NULL))
return NULL;
root->left = replaceNegativeOne(root->left);
root->right = replaceNegativeOne(root->right);
return root;
}
node *createTreeByLevelTree()
{
ll n, m;
queue<node> q;
node *root, *t;
root = NULL;
while (cin >> n)
{
if (q.empty())
{ root = createNode(n);
q.push(root);
continue;
}
cin << m;
t = q.front();
q.pop();
t->left = createNode(n);
t->right = createNode(m);
if (t->left->value != -1)
{
q.push(t->left);
}
if (t->right->value != -1)
{
q.push(t->right);
} if (q.empty())
{
break;
}
}
return root;
}
void deleteTree(node *node)
{
if (node == NULL)
return;
deleteTree(node->left);
deleteTree(node->right);
delete node;
}
int sum(struct node *root)
{
if(root == NULL)
return 0;
return sum(root->left) + root->value + sum(root->right);
}
bool checkSumTree(struct node* node)
{
if(node == NULL || (node->left == NULL && node->right == NULL))
return true;
return(node->value==sum(node->left)+sum(node->right)) &&checkSumTree(node->left)&&checkSumTree(node->right);
}
int main()
{
node *root = NULL;
root = createTreeByLevelTree();
root = replaceNegativeOne(root);
if(checkSumTree(root))
cout<<"true"<<endl;
else
cout<<"false"<<endl;
deleteTree(root);
return 0;
}

86
43. Mirror Tree

Problem Statement
Given a Binary Tree, convert it into its mirror.

Logic
We will use recursion to traverse our tree in Depth First Search manner to convert it into its
mirror image.
Starting from the root node we will swap left and right node pointers of our tree.
We will call the same function recursively for it’s left & right subtrees until we traverse all the
nodes.

Code

#define REP(i, n) for (i = 0; i < n; i++)


#define pb(a) push_back(a)
#define vi vector<long>
#define ll long long
#include <bits/stdc++.h>
using namespace std;
struct node
{ ll value;
node *left;
node *right;
};
node *createNode(ll value)
{
node *t = new node();
t->value = value;
t->right = t->left = NULL;
return t;
}
void deleteNode(node *t)
{ delete t;
}
node *replaceNegativeOne(node *root)
{
if (root == NULL || (root->value == -1 && root->left == NULL && root->right == NULL))
return NULL;
root->left = replaceNegativeOne(root->left);
root->right = replaceNegativeOne(root->right);
return root;
}
node *createTreeByLevelTree()
{

87
Code
ll n, m;
queue<node *> q;
node *root, *t;
root = NULL;
while (cin >> n) {
if (q.empty())
{
root = createNode(n);
q.push(root);
continue;
}
cin >> m;
t = q.front();
q.pop();
t->left = createNode(n);
t->right = createNode(m);
if (t->left->value != -1)
{
q.push(t->left);
}
if (t->right->value != -1)
{
q.push(t->right);
}
if (q.empty())
{
break;
}
}
return root;
}
void inOrderTraversal(node *t)
{
//write your code here;
if (t == NULL)
return;
inOrderTraversal(t->left);
cout << t->value << " ";
inOrderTraversal(t->right);
}
void deleteTree(node *node)
{ if (node == NULL)
return;
deleteTree(node->left);
deleteTree(node->right);
delete node;
}
void mirror(node *a)
{
stack<node *> s;
s.push(a);
while(!s.empty())
{
node *t = s.top();
s.pop();
node* temp = t->left;
t->left = t->right;
t->right= temp;
if(t->left)
s.push(t->left);
if(t->right)
s.push(t->right);
}
}
int main()
{
node *root = NULL;
root = createTreeByLevelTree();
root = replaceNegativeOne(root);
mirror(root);
inOrderTraversal(root);
deleteTree(root);
return 0;
}

88
44. One more GCD sum
Problem Statement
Calculate the sum for a given number n:
ΣΣ (i*j)/gcd(i,j)2 where the first summation has bounds from i = 1 to n and for next summa-
tion, j = i+1 to n.

Example
Let's assume N to be 10, the phi table for it would be:
Where, phi(8) will be 2 because, 3 and 5 both have gcd() 1 with 8.
Now , we have found the value of phi(k).
We find summation of all values from 1 to 10 with a derived formula.
Hence, gcd sum of 10 will be 923.

Logic
Let gcd(i,j) = d, where d can go from 1 to n. If gcd(i,j) is d, i and j can be represented as some
multiple of d, let i=k*d and j=l*d, where k<l because i 2) Our summation equation is , from
above step we can see it becomes,
⇒ (i=k*d and j=l*d)
⇒ (gcd(i,j) = d)
⇒ k*l
Now, we have one summation for one value of d ranging from 1 to N, internally we have
(k*l) summation over all pairs where l>k and gcd(l,k)=1. Total number of pairs such that
gcd(n,k)=1 where k lies between 1 and n can be found by using Euler Totient Function. An
array phi will be maintained for such values.
Also we know gcd(l,k) = gcd(l,l-k) where l>k and l>l-k, so in above received equation we
can change value of k to l-k, as they both will have same gcd(), so sum(k*l) =
sum(l*(l-k))).
We can make it further easy, as sum(kl) = sum( which is also equal to because we still
need to find summation over gcd(l,k)=1, where `k
Now we have only l as a variable to count ranging from 2 to () and d lies in range 1 to n,
which can be found in O() time for a given value of n.

89
Algorithm
Calculate phi() for all values between 1 to max range of numbers.
phi(n) returns the total number of values from 1 to n which have gcd() with n as 1.
Calculate (l*l*phi(l))/2 for all values of 2 to n with double summation as asked in the problem.

Code

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 1000000007
#define maxn 2000001

ll phi[maxn];
ll res[maxn];

void pre()
{
ll i,j;
for(i=1;i<maxn;i++)
phi[i] = i;
for(i=2;i<maxn;i++)
{
if(phi[i] == i)
{
for(j=i;j<maxn;j=j+i)
{
phi[j] = (phi[j]/i)*(i-1);
}
}
}
for(i=2;i<maxn;i++)
for(j=i;j<maxn;j=j+i)
res[j] = (res[j] + (((i*i)%N)*((phi[i]*500000004)%N))%N)%N;

for(i=2;i<maxn;i++)
res[i] = (res[i] + res[i-1])%N;
}
int main() {
pre();
int test;
cin>test;
int v[maxn] = {0};
int j=0;
while(test--){
int n;
cin>n;
ll ans = res[n];
ans = (ans+N)%N;
v[j++]=ans;
}
for(int i = 0;i<j;i++)
cout << v[i] << '\n';
}

90
45. Maximum Edges

Problem Statement
Given N number of vertices, M number of edges and relation between them to form an
undirected graph, our task is to find the maximum number of edges among all the connect-
ed components in the given graph.

Logic
DSU data structure is also sometimes called Union-Find Set. This data structure is used to
keep track of the different disjoint sets. It basically performs two operations :
Union : It takes two vertices and join them in a single set (if it is not already there).
Find : Determines in which subset the element is.
We are using an additional array size[] to keep the size of the edges for each root of our set.
ith index of size[] will give us the number of edges in the tree rooted with i.
We will perform union for every edge. After processing all the edges, iterate through size[]
and print the maximum value i.e maximum edge count.

Algorithm
Dfs()
union()
find()

91
Code
#include<bits/stdc++.h>
using namespace std;
vector<int>v[100005];
bool vis[100005];
int siz,edges;

int dfs(int i)
{
vis[i]=true;
//siz++;
for(int u:v[i])
{
edges++;
if(!vis[u])
dfs(u);
}
return edges;
}

int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;

for(int i=0;i<n;i++)
{
v[i].clear();
vis[i] = false;
}

for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}

siz=0,edges = 0;
int maxedges=0;
for(int i=0;i<n;i++)
{
if(!vis[i])
{
//dfs(i);
//cout<<edges/2<<"\n";
maxedges=max(maxedges,dfs(i)/2);
siz=0;edges=0;
}
}
cout<<maxedges<<"\n";
}
return 0;
}

92
46. Longest Palindromic Substring

Problem Statement
You are given a string str, and find the longest palindromic substring in str.
Longest Palindromic Substring of string str:LPS[i…j], where 0<=i<=j< len(LPS)
Palindrome string:LPS is palindrome if reverse(LPS) =LPS
If multiple LPS is the same then return the Longest Palindromic Substring which occurs first
( with the least starting index ).

Example
Input
3
aaa
bbabb
baa

Output
aaa
bbabb
aa

Logic
Consider the case "ababa". If we already knew that "bab" is a palindrome, it is obvious that
"ababa" must be a palindrome since the two left and right end letters are the same.
P(i,j) = {true,}if the substring Si …Sj is a palindrome;
{false,}otherwise
Therefore,
P(i, j) =(P(i+1,j−1) and Si==Sj)
The base cases are:
P(i, i) = true
P(i, i+1) = (Si==Si+1 )

This yields a straightforward DP solution, where we first initialize the one and two letter
palindromes, and work our way up finding all three letters palindromes, and so on…

93
Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
//write your code here
int t;cin>>t;
while(t--)
{
string s;cin>>s;
int n=s.length();
int dp[n][n];
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
{
dp[i][i]=1;
}
int ans=1,st=0;
for(int i=0;i<n-1;i++)
{
if(s[i]==s[i+1])
{
dp[i][i+1]=1;
if(ans<2)
{ans=2;
st=i;
}
}
}
for(int i=3;i<=n;i++)
{
for(int j=0;j<n-i+1;j++)
{
int k=j+i-1;
if(s[j]==s[k])
{
if(dp[j+1][k-1]==1)
{dp[j][k]=1;
if(ans<i)
ans=i;
st=j;
}
}
}
}
for(int i=st;i<st+ans;i++)
cout<<s[i];
cout<<"\n";
}
return 0;
}

94
47. FORM STRING
Problem Statement
Arnab is now given a String S. He is given N different types of pieces of sticks with strings
written on them(we have an infinite supply of each type). Now Arnab is asked whether he can
form the string S using the sticks by placing them one after another. If yes print "Yes” else
print "No" (without double quotes).

Example
1

prepBytes

pre

ab

pBy

cd

tes

we can form prepBytes using the strings pre+pBy+tes.

Logic
Iterate over all the strings, checking if the target string "begins" with any of them.
Take the longest string with which the target string begins, remove it from the list and trim it
from the main string.
Rinse, repeat.
Stop when you’re left with a 0 length target string.

95
Algorithm
Look at this function:
function Possible(array A, string s)
If s is empty, return true.
compute the array P of all strings in A that are a prefix of s.
If P is empty, return false.
for each string p in P:
if Possible(A with p removed, s with prefix p removed) return true
return false
Use a map to mark all the substrings encountered.If you end up with an empty string, print
"Yes" else print "No".

Code

#include <bits/stdc++.h>
using namespace std;
map<string,int> mp;
bool solve(string s)
{
if(mp[s])
{
if(mp[s]==1)
return true;
}
string w="";
int fl=2;
for(int i=0;i<s.length();i++)
{
w+=s[i];
if(mp[w]==1&&solve(s.substr(i+1)))
{
mp[s]=1;
return true;
}
}
mp[s]=2;
return false;
}
int main()
{
int t;
cin>>t;
while(t--)
{
mp.clear();
string s;
cin>>s;
int n;
cin>>n;
string st;
for(int i=0;i<n;i++)
{
cin>>st;
mp[st]=1;
}
cout<<(solve(s)?"Yes":"No")<<endl;
}
return 0;
}
96
48. DROP EGG

Problem Statement
Himanshu visited a building with N floors and he carried with him k eggs, he found out that the
eggs are rotten, so he plays a trick he wants to know the maximum floor from which the egg
can be dropped without breaking the egg.
1. An egg that survives the fall can be used again.

2. A broken egg cannot be used again.


3. You know Himanshu is very lazy, help him find the minimum number of moves required to
find the answer.
4. If the egg breaks when dropped from some floor then it will break if dropped from any
higher floor.

5. If the egg does not break when dropped from some floor then it will not break if dropped
from any lower floor.

Example
Input: 30 4
Output 5

Logic
Solve it in a bottom up manner, means start from the smallest sub problem possible (here it is
0 eggs 0 floors) and solve it. Store the result in some temporary storage.
Recursive equation will be the same as above. Start solving from the smallest sub problem
and move towards the final problem. Use the temporary result being stored instead of solving
the sub problems again.

Algorithm
getDrops (k,n) = 1 + Min(x = 1,2,….n) [(drops(k-1, n-1), drops(k, n-x)]

97
Code

#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,e;
cin>>n>>e;
int dp[e+1][n+1];
for(int i=0;i<=n;i++)
dp[1][i]=i;
for(int i=1;i<=e;i++)
dp[i][1]=1;
for(int i=2;i<=e;i++)
{
for(int j=2;j<=n;j++)
{
dp[i][j]=1000000000;
for(int k=1;k<=j;k++)
{
int res=1+max(dp[i-1][k-1],dp[i][j-k]);
if(res<dp[i][j])
dp[i][j]=res;
}
}
}
cout<<dp[e][n]<<"\n";
}
return 0;
}

98
49. Power Game

Problem Statement
Today, Bunny's father is doing work from home. But, Bunny is constantly annoying him and
makes it hard for him to complete his work. So, Bunny's father gave him two integers X and N,
and ordered him to find the value of XN. As the value of XN could be very large, he also orders
to mod the result by (109+7). Bunny is not so good with mathematical problems, so he asks
you for help. As a good friend of bunny, now it's your task to solve this problem.

Example
for the test case, 2^5= 2*2*2*2*2 = 32 and 32 % 109+7 = 32.

Logic
The idea is to use an iterative approach to find the product. Here we will use a trick, suppose
the power is even, that will mean x^4 can be broken into x^2 and x^2 and multiply these two
rather than continuously multiplying x. This will reduce the time complexity from O(n) to
O(logn).
Initialize our result = 1
If n is odd
res = (res * x)%1000000007
If n is even
n = n / 2;
x = (x * x)%1000000007;

99
Code

C++

#include <iostream>

using namespace std;

long long binaryExponentiation(long long a, long long b,long long m)

long long result=1;

while(b>0)

if(b&1)

result = (result*a)%m;

a=(a*a)%m;

b=b>>1;

return result;

int main() {

int t;

cin>>t;

while(t-->0) {

long long a, b, m;

cin >> a >> b;

m = 1000000007;

cout << binaryExponentiation(a, b, m)<<"\n";

return 0;

100
50. Missing in AP

Problem Statement
Given an array A, such that it is arranged in an Arithmetic Progression, but one element
from this A.P. is missing, find it.

Example
Input : A = [3, 6, 12, 15, 18]
Output : 9
Explanation : In the given A.P. series starting with initial element 3 and Common Difference 3,
9 is the element that is missing between 6 and 12.

Logic
Check whether the missing element lies near one of the corner points by taking the difference of
first and second elements and difference of last and second last elements and comparing these
differences with each other. If they are not equal, this implies that the missing number lies near
corner points and we can easily compute the missing number.
Else we will follow below approach –
 The idea is to use Binary Search.
 We initialize low and high as 0 and n-1, and calculate mid as mid = low + (high - low)/2
 If the element present at mid matches the calculated value at mid, this implies that
elements at the lower half are all positioned correctly, so we search in the right half.
• else we store the calculated value and search in the lower half till
low 6. In this way, we will have the last value that was not at its right position stored with us
which will be our result.

101
Code

#include <bits/stdc++.h>
using namespace std;
int MissingAP(int *arr, int low, int high, int diff, int missing_ele){
if(low <= high){
int mid = low + (high - low)/2;
/* if curr element is at its right place in AP
we will search in the lower half then */
if(arr[mid] == arr[0] + mid*diff)
return MissingAP(arr, mid+1, high, diff, missing_ele);

/* else save the value that should be here and further


search in the lower half */
else{
missing_ele = arr[0] + mid*diff;
return MissingAP(arr, low, mid - 1, diff, missing_ele);
}
}
//finally return the ele that was not found on its place
return missing_ele;
}
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];

//check if missing element lies at one of the ends or close to one of the ends
int left_diff = arr[1] - arr[0];
int right_diff = arr[n-1] - arr[n-2];
int diff, missing_ele;

//if left == right, missing element lies inside of the array


if(left_diff == right_diff){
diff = left_diff;
//we will go on checking inside the array
cout<<MissingAP(arr, 0, n-1, diff, -1)<<"\n";
continue; }
//else missing ele is at one of the corners or near corner
if(left_diff < right_diff){
missing_ele = arr[n-1] - left_diff;
cout<<missing_ele<<"\n";
}
else{
missing_ele = arr[0] + right_diff;
cout<<missing_ele<<"\n";
}
}
return 0;
}
102
MCQ
1. When overloading unary operators using the Friend function,it
requires_____ argument/s.
A.) Zero

B.) One

C.) Two

D.) None of these.

Answer - (B)

2) Which of the following is not a casting operator in CPP?

A.) explicit_cast

B.) static_cast

C.) dynamic_cast

D.) reinterpret_cast

Answer - (A)

3) Object oriented programming employs_________ programming approach.

A.) top-down

B.) 2-procedural

C.) bottom-up

D.) all of these.

Answer - (C)

103
MCQ
4) If a process fails, most operating systems write the error information
to a ______.
A.) log file

B.) another running process

C.) new file

D.) none of the mentioned

Answer - (A)

5) _____________is the OOP feature and mechanism that binds together


code and the data it manipulates, and keep both safes from the outside
world.
A.) -Data Binding

B.) Data Encapsulation

C.) Data Storing

D.) Data Abstraction

Answer - (B)

6) What is the size of a character literal in C and C++?

A.) 4 and 1

B.) 1 and 4

C.) 1 and 1

D.) 4 and4

Answer - (A)
104
MCQ
7) The depth of complete binary tree is given by_____________.
A.) Dn = n log2n

B.) Dn = n log2n +1

C.) Dn = log2n

D.) Dn = log2n + 1

Answer - (D)

8) How do you calculate the pointer difference in a memory-efficient


double linked list?

A.) head xor tail

B.) pointer to previous node xor pointer to next node

C.) pointer to the previous node – pointer to next node

D.) pointer to next node – pointer to the previous node

Answer - (B)

9) The default C Storage Class for a variable is__________.

A.) Static

B.) Auto

C.) Extern

D.) Register

Answer - (B)

105
MCQ
10) What happens if a class does not have a name?
A)-It will not have a constructor

B)-It will not have a destructor

C)-It is not allowed

D)-It will neither have a constructor or a destructor

Answer - (B)

11) What is the return type of the hashCode() method in the Object
class?

A)-Object

B)-int

C)-long

D)-void

Answer - (B)

12) Left Shift operation is equivalent to which operation?


A)-Division by 2

B)-Multiplying by 2

C)-Adding 2

D)-Subtracting 2

Answer - (B)

106
MCQ
13) When does Overloading not occur?
A)-More than one method with the same name, same signature but different number of signature

B)-More than one method with the same name, same signature, the same number of parameters

but a different type

C)-More than one method with the same name but different method signature and different

number or type of parameters

D)-None of the above

Answer - (B)

14) Which of the following statement is true about Left Shift Operator << ?

A)-Left shift operator shifts individual bits on the left side.

B)-When shifting the left side, overflow bits are ignored.

C)-Zeroes are filled on the right side.

D)-All the above

Answer - (D)

15) Which of the following is not an OOPs concept in Java?

A)-Abstraction

B)-Encapsulation

C)-Isolation

D)-Compilation

Answer - (D)
107
MCQ
16) Which of the following statements are true?
A)-Higher level of abstraction means higher details.

B)-Lower level of abstraction means higher details.

C)-level of abstraction is not related to details.

D)-None of the above

Answer - (B)

17) What does the right shift >> operator do?

A)-Right shift operator shift individual bits on to the right side.

B)-When shifting bits right side, overflow bits on the right are ignored or truncated.

C)-Zeroes are filled on the left side.

D)-All the above

Answer - (D)

18) What is the output of the program?

A)-10
int main()
{
B)-11
const int a=10;
a++;
C)-Compilation Error
cout<<a;
return 0;
D)-Linking Error
}

Answer - (C)
108
MCQ
19) Which of the following is true about 'this' keyword?
A)-this can be used to invoke the current class constructor

B)-this cannot be used to invoke the current class method

C)-both 1 and 2

D)-None of the above

Answer - (B)

Q-20) Find the output.


#include<iostream>
using namespace std;
A)-2 int x = 10;
void fun()
{
B)-1 int x = 2;
{
int x = 1;
C)-10 cout << ::x << endl;
}
}
D)-None of the above
int main()
{
fun();
Answer - (C) return 0;
}

21) Which one of the following is not a real-time operating system?

A)-VxWorks

B)-QNX

C)-RTLinux

D)-Palm OS

Answer - (D)
109
MCQ
22) What else is a command interpreter called?
A)-prompt

B)-kernel

C)-shell

D)-command

Answer - (C)

23) What will be the output of the following program?

public class Test2 {


A)-Complete
public static void main(String[] args)
{
B)-Iomplede StringBuffer s1 = new
StringBuffer("Complete");
s1.setCharAt(1,'i');
C)-Cimpletd s1.setCharAt(7,'d');
System.out.println(s1);
D)-Coipletd }
}

Answer - (C)

24) How many times PrepBytes is printed?

A)-Error int main()


{
int i=0;
B)-5 times lbl:
cout<<"PrepBytes";
i++;
if(i<5)
C)-4 times {
goto lbl;
}
D)-6 times return 0;

}
Answer - (B)
110
MCQ
25) Which module gives control of the CPU to the process selected by
the short-term scheduler?
A)-dispatcher

B)-interrupt

C)-scheduler

D)-None of the mentioned

Answer - (A)

26) Which of the following does not belong to queues for processes?

A)-Job Queue

B)-PCB Queue

C)-Device Queue

D)-Ready Queue

Answer - (B)

27) Which algorithm is defined in Time quantum?

A)-shortest job scheduling algorithm

B)-round-robin scheduling algorithm

C)-priority scheduling algorithm

D)-multilevel queue scheduling algorithm

Answer - (B)
111
MCQ
28) What is the output of the following Java code?

A)-24 class Person


{
private int age;

B)-Compilation error private Person()


{
age = 24;
}
C)-Runtime error }

public class Test


{
D)-None of the above public static void main(String[] args)
{
Person p = new Person();
System.out.println(p.age);
}
Answer - (B) }

29) Which one of the following is the deadlock avoidance algorithm?

A)-banker’s algorithm

B)-round-robin algorithm

C)-elevator algorithm

D)-Karn's algorithm

Answer - (A)

30) What will happen when a process terminates?

A)-It is removed from all queues

B)-It is removed from all, but the job queue

C)-Its process control block is de-allocated

D)-Its process control block is never de-allocated

Answer - (A)
112
MCQ
31) Which of the following is a problem that can occur in poorly planned,
unnormalized databases where all the data is stored in one table (a
flat-file database)?
A)-Anomalies

B)-Functional dependency

C)-Normalization

D)-Decomposition

Answer - (A)

32) Which of the following is not a transaction state?


A)-Active

B)-Partially committed

C)-Failed

D)-Compensated

Answer - (D)

33) Which dependency occurs when a non-prime attribute is functionally


dependent on part of a candidate key?

A)-Multivalued Dependency

B)-Join Dependency

C)-Partial Dependency

D)-Trivial Functional Dependency

Answer - (C)
113
MCQ
34) Which of the following join is also called an 'inner-join'?
A)-Non-Equijoin

B)-Self-Join

C)-Equijoin

D)-None of these

Answer - (C)

35) Which of the following statement is not true?

A)-A relation in 2NF must also be in 1NF

B)-A relation in 3NF must also abe in 2NF

C)-A relation in 3NF must also be in BCNF

D)-A relation in BCNF must also be in 3NF

Answer - (C)

36) Maximium no. of children a B-tree of order m can have is


_______________.

A)m

B)-m+1

C)-m-1

D)-m/2

Answer - (A)
114
MCQ
37) Which of the following is correct about the foreign key?
A)-A foreign key is a primary key of a relation which is an attribute in another relation

B)-A foreign key is a superkey of a relation which is an attribute in more than one other relations

C)-A foreign key is an attribute of a relation that is a primary key of another relation

D)-A foreign key is the primary key of a relation that does not occur anywhere

Answer - (C)

38) If the database buffer sizes are very large, what data structure would
be used for efficient search?

A)-B+ trees

B)-Hash tables

C)-Fibonacci heaps

D)-Red-Black trees

Answer - (B)

39) In which process, the details of the entities are hidden from the
user in the ER Model?

A)-generalization

B)-specialization

C)-abstraction

D)-none of these above

Answer - (C)
115
MCQ
40) An entity set which does not have enough attributes to form a
Primary key is _______________.
A)-Strong Entity Set

B)-Weak Entity Set

C)-Strong Relationship Set

D)-Weak Relationship Set

Answer - (B)

41) Which of the following is not a basic control structure?

A)-B+ trees

B)-Hash tables

C)-Fibonacci heaps

D)-Red-Black trees

Answer - (A)

42) Which of the following is a program planning tool?


A)-Sequential

B)-decision

C)-Pseudo Code

D)-Both A&B

Answer - (D)
116
MCQ
43) What will be the output of the following C code?

#include <stdio.h >


main()
A)-24 {
int n;
n=f1(4);
B)-4 printf("%d",n);
}
f1(int x)
C)-12
{
int b;
D)-10 if(x==1)
return 1;
else
b=x*f1(x-1);
return b;
}

Explanation-The above code returns the factorial of a given number using the
method of recursion. The given number is 4 in the above code, hence the
factorial of 4, that is, 24 will be returned.

Answer - (A)

44) In linear search with an array, how many comparisons are needed in
the best case?

A)-0

B)-1

C)-n

D)-n/2

Answer - (B)

117
MCQ
45) In the following scenarios, when will you use selection sort?
A)-The input is already sorted

B)-A large file has to be sorted

C)-Large values need to be sorted with small keys

D)-Small values need to be sorted with large keys

Answer - (C)
Explanation-Selection is based on keys, hence a file with large values and small
keys can be efficiently sorted with selection sort.

46) In which of the following type of searching key comparisons are


needed?
A)-Linear Search

B)-Non-Linear Search

C)-Address calculation search

D)-Both A&B

Answer - (D)

47) Which one of the following is an application of the backtracking


algorithm?
A)-Finding the shortest path

B)-Finding the efficient quantity to shop

C)-Ludo

D)-Crossword

Answer - (D) 118


MCQ
48) Consider the following C++ program.
int main()
A)x + y using repeated subtraction {
int x, y, m, n;
cin>>x>>y;
B)x mod y using repeated subtraction /* x > 0 and y > 0 */
m = x; n = y;
while (m != n)
{
C)the greatest common divisor of x and y if(m>n)
m = m - n;
else
D)the least common multiple of x and y n = n - m;
}
cout>>n;
}

Answer - (B)

49) Which of the following methods can be used to solve N-queen's


problem?
A)-Greedy algorithm

B)-Divide and conquer

C)-Iterative improvement

D)-Backtracking

Answer - (D)

50) What is a Greedy strategy for Optimal storage on tape?

A)-Arrange all programs in decreasing order of length

B)-Arrange all programs on a First in first come basis

C)-Arrange all programs in increasing order of length

D)-Arrange all programs in random order

Answer - (C)
119

You might also like