Hackerrank Coding Problems With Solutions: Question 1 - Maximum Passengers
Hackerrank Coding Problems With Solutions: Question 1 - Maximum Passengers
Problem Statement -: A taxi can take multiple passengers to the railway station at the same
time.On the way back to the starting point,the taxi driver may pick up additional passengers for
his next trip to the airport.A map of passenger location has been created,represented as a
square matrix.
The Matrix is filled with cells,and each cell will have an initial value as follows:
● The Taxi driver starts at (0,0) and the railway station is at (n-1,n-1).Movement towards
● After reaching (n-1,n-1) the taxi driver travels back to (0,0) by travelling left or up through
up.once the rider is picked up the cell becomes an empty path cell.
● If there is no valid path between (0,0) and (n-1,n-1),then no passenger can be picked.
● The goal is to collect as many passengers as possible so that the driver can maximize
his earnings.
0 1
HackerRank Coding Problems with Solutions
-1 0
Start at top left corner.Move right one collecting a passenger. Move down one to the
destination.Cell (1,0) is blocked,So the return path is the reverse of the path to the airport.All
Returns:
Sample Input 0
4 -> size n = 4
4 -> size m = 4
0 0 0 1 -> mat
1000
0000
0000
Output 0
2
HackerRank Coding Problems with Solutions
Explanation 0
The driver can contain a maximum of 2 passengers by taking the following path (0,0) → (0,1) →
(0,2) → (0,3) → (1,3) → (2,3) → (3,3) → (3,2) → (3,1) → (3,0) → (2,0) → (1,0) → (0,0)
Sample Input 1
STD IN Function
———— ————-
3 → size n=3
3 → size m=3
0 1 -1 → mat
1 0 -1
111
Sample Output 1
Explanation 1
HackerRank Coding Problems with Solutions
The driver can contain a maximum of 5 passengers by taking the following path (0,0) → (0,1) →
C++ Code
#include <bits/stdc++.h>
using namespace std;
int n, m;
int mat[105][105];
map<pair<int, pair<int, int>>, int> dp;
bool isValid(int i, int j)
{
if (mat[i][j] == –1)
return false;
if (i < 0 || i >= n)
return false;
if (j < 0 || j >= m)
return false;
return true;
}
int solve(int i, int j, int x, int y)
{
if (!isValid(i, j))
{
return INT_MIN;
}
if (!isValid(x, y))
{
return INT_MIN;
}
if (i == n – 1 && x == n – 1 && j == m – 1 && y == m – 1)
{
if (mat[i][j] == 1)
{
return 1;
}
else
{
return 0;
}
}
if (dp.find({i, {j, x}}) != dp.end())
return dp[{i, {j, x}}];
HackerRank Coding Problems with Solutions
int cur = 0;
if (i == x && j == y)
{
if (mat[i][j] == 1)
cur = 1;
}
else
{
if (mat[i][j] == 1)
cur++;
if (mat[x][y] == 1)
cur++;
}
return 0;
}
end time and profit value. The manager has asked his employee Anirudh to pick jobs of
HackerRank Coding Problems with Solutions
his choice. Anirudh being greedy wants to select jobs for him in such a way that would
Given a list of jobs how many jobs and total earning are left for other employees once
Anirudh
Input format:
Each Job has 3 pieces of info – Start Time,End Time and Profit
The first line contains the number of Jobs for the day. Say ‘n’. So there will be ‘3n lines
Each of the next ‘3n’ lines contains jobs in the following format:
○ start_time
○ end-time
○ Profit
start-time and end-time are in HHMM 24HRS format i.e. 9am is 0900 and 9PM is 2100
HackerRank Coding Problems with Solutions
Constraints
● The number of jobs in the day is less than 10000 i.e. 0<_n<_10000
Output format :-
Program should return an array of 2 integers where 1st one is number of jobs left and
Sample Input 1 :
0900
1030
100
1000
1200
500
HackerRank Coding Problems with Solutions
53
1100
1200
300
Sample Output 1:
400
Sample Explanation 1
Anirudh chooses 1000-1200 jobs. His earnings is 500. The 1st and 3rd jobs i.e.
0900-1030 and 1100-1200 respectively overlap with the 2nd jobs. But profit earned from
them will be 400 only. Hence Anirudh chooses 2nd one. Remaining 2 Jobs & 400 cash
Sample Input 2:
0805
0830
HackerRank Coding Problems with Solutions
100
0835
0900
100
0905
0930
100
0935
1000
100
1005
1030
100
Sample output 2:
0
HackerRank Coding Problems with Solutions
Sample Explanation 2:
Anirudh can work on all appointments as there are none overlapping. Hence 0
C++
#include <bits/stdc++.h>
using namespace std;
class job
{
public:
int st, ed, cost;
};
int getTime(string s)
{
int hr = (s[0] – ‘0’) * 10 + (s[1] – ‘0’);
int min = (s[2] – ‘0’) * 10 + (s[3] – ‘0’);
return hr * 60 + min;
}
bool compare(job A, job B)
{
return A.ed < B.ed;
}
int searchJob(job arr[], int st, int ed, int key)
{
int ans = –1;
while (st <= ed)
{
int mid = (st + ed) / 2;
if (arr[mid].ed <= key)
{
ans = mid;
st = mid + 1;
}
else
{
ed = mid – 1;
}
}
return ans;
HackerRank Coding Problems with Solutions
}
pair<int, int> solve(job arr[], int n)
{
int dp[n] = {0};
int numOfJobs[n] = {0};
dp[0] = arr[0].cost;
numOfJobs[0] = 1;
if (idx != cur)
{
cur += dp[idx];
num += numOfJobs[idx];
}
if (cur > dp[i – 1])
{
dp[i] = cur;
numOfJobs[i] = num;
}
else
{
dp[i] = dp[i – 1];
numOfJobs[i] = numOfJobs[i – 1];
}
}
return {numOfJobs[n – 1], dp[n – 1]};
}
int main()
{
int n;
cin >> n;
job arr[n];
int cost;
string st, ed;
int total = 0;
return 0;
}
Problem Statement -: Street Lights are installed at every position along a 1-D road of
length n. Locations[] (an array) represents the coverage limit of these lights. The ith light
has a coverage limit of locations[i] that can range from the position max((i –
locations[i]), 1) to min((i + locations[i]), n ) (Closed intervals). Initially all the lights are
switched off. Find the minimum number of fountains that must be switched on to cover
the road.
Example
n=3
For the entire length of this road to be covered, only the light at position 2 needs to be
activated.
Returns:
Constraints :
● 1<_n<_ 10^5
3 ->locations[] size n = 3
1 ->locations[] [1, 1, 1]
1 ->Sample Output
Sample Output :
HackerRank Coding Problems with Solutions
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
bool compare(pair<int, int> A, pair<int, int> B)
{
if (A.first = B.first)
return A.second < B.second;
return A.first < B.first;
}
int solve(int location[], int n)
{
int i = 0;
int ans = 0;
while (i < n)
{
pair<int, int> p = range[i];
ans++;
while (i + 1 < n && range[i].first == range[i + 1].first)
{
p.second = max(p.second, range[i + 1].second);
i++;
}
//cout<<p.second<<” “<<i<<endl;
while (i < n && range[i].second <= p.second)
i++;
//cout<<p.second<<” “<<i<<endl;
}
return ans;
HackerRank Coding Problems with Solutions
}
int main()
{
int n;
cin >> n;
int location[n];
for (int i = 0; i < n; i++)
cin >> location[i];
Problem Statement – A stream of n data packets arrives at a server. This server can
only process packets that are exactly 2^n units long for some non-negative integer value
of n (0<=n).
All packets are repackaged in order to the 1 largest possible value of 2^n units. The
remaining portion of the packet is added to the next arriving packet before it is
repackaged. Find the size of the largest repackaged packet in the given stream.
Example :
Returns:
Constraints :
● 1<=n<=10^5
● 1<=arriving Packets[i] size<=10^9
Sample case :
Sample input :
5 → number of packets=5
12 → size of packets=[13,25,12,2,8]
25
10
Sample output :
16
Phython
def largeRepackagedPacket(arr):
HackerRank Coding Problems with Solutions
x=0
ans=0
for i in arr:
i=i+x
for j in range(31):
if i<twoP[j]:
break
x=i-twoP[j-1]
if ans<=twoP[j-1]:
ans=twoP[j-1]
return ans
Packets=[]
for i in range(int(input())):
HackerRank Coding Problems with Solutions
Packets.append(int(input()))
print(largeRepackagedPacket(Packets))
very strict asks students to write a program to print the trapezium pattern using stars
and dots as shown below . Since Anirudh is not good in astronomy can you help him?
Sample Input:
N=3
Output:
**.**
*…*
…..
HackerRank Coding Problems with Solutions
*…*
**.**
C++
#include <stdio.h>
int main()
{
int i,j,n;
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(j<n-i-1)
printf(“*”);
else
printf(“.”);
}
for(j=0;j<n-1;j++)
{
if(j<i)
printf(“.”);
else
printf(“*”);
}
printf(“\n“);
}
for(i=2;i<=n;i++)
{
for(j=0;j<n;j++)
HackerRank Coding Problems with Solutions
{
if(j<i-1)
printf(“*”);
else
printf(“.”);
}
for(j=0;j<n-1;j++)
{
if(j<n-i)
printf(“.”);
else
printf(“*”);
}
printf(“\n“);
}
return 0;
}
Problem Statement -: You are given an array, You have to choose a contiguous subarray
of length ‘k’, and find the minimum of that segment, return the maximum of those
minimums.
Sample input 0
1 → Length of segment x =1
5 → size of space n = 5
1 → space = [ 1,2,3,1,2]
3
HackerRank Coding Problems with Solutions
Sample output
Explanation
The subarrays of size x = 1 are [1],[2],[3],[1], and [2],Because each subarray only contains
1 element, each value is minimal with respect to the subarray it is in. The maximum of
these values is 3. Therefore, the answer is 3
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> arr;
int prevmin=-1;
int flag=0;
int x,n,q;
int main()
{
cin>>x>>n;
int ans=0;
for(int i=0;i<n;i++)
{cin>>q;arr.push_back(q);}
for(int i=0;i<n;i++)
{
ans=max(ans,func(i,i+x-1));
}
cout<<ans;
}
with his friends and played a game called “Guess the Word”.
● Computer displays some strings on the screen and the player should pick one
string / word if this word matches with the random word that the computer picks
then the player is declared as Winner.
● Kochouseph Chittilappilly’s friends played the game and no one won the game.
This is Kochouseph Chittilappilly’s turn to play and he decided to must win the
game.
● What he observed from his friend’s game is that the computer is picking up the
string whose length is odd and also that should be maximum. Due to system
failure computers sometimes cannot generate odd length words. In such cases
HackerRank Coding Problems with Solutions
you will lose the game anyways and it displays “better luck next time”. He needs
your help. Check below cases for better understand
Sample input :
5 → number of strings
Sample output :
morning
Explanation:
● Hello → 5
● Good → 4
● Morning → 7
● Welcome → 7
● You → 3
Sample input 2 :
HackerRank Coding Problems with Solutions
Go to hell
Sample output 2:
Explanation:
Here no word with odd length so computer confuses and gives better luck next time
Java
import java.util.*;
public class OddLength
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String arr[]=new String[n];
for(int i=0;i<n;i++)
arr[i]=sc.next();
int len=0;
ArrayList<String> oddLength=new ArrayList<String>();
for(int i=0;i<n;i++)
HackerRank Coding Problems with Solutions
{
len=arr[i].length();
if(len%2==1)
oddLength.add(arr[i]);
}
if(oddLength.size()==0)
System.out.println("Better luck next time");
else
{
Iterator itr=oddLength.iterator();
int max=-1;
String res="";
while(itr.hasNext())
{
String temp=(String)itr.next();
if(temp.length()>max)
{
res=temp;
max=temp.length();
}
}
System.out.println(res);
}
}
}
Problem Statement -: Raman was playing a game, in starting he has x coins at some
point of the game he has to pay some coins to get into the next level of the game, during
each game he can collect some coins. If at anypoint of the game numbers of coins of
Raman is less than one he will lose the game. Find the minimum value of x such that
Raman wins.
HackerRank Coding Problems with Solutions
C++
#include <iostream>
using namespace std;
int main() {
int n; cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[i];
int sum=0,ans=0;
for(int i=0;i<n;i++)
{
sum+=a[i];
if(sum<1)
{
sum=-sum;
ans+=sum+1;
sum=1;
}
}
cout<<ans<<endl;
}
Problem Statement – The math assignment says you will be given numbers, mostly with
imaginary additions, that means complex numbers, and you need to add them and tell
the answer in your answer script. You told your friend John that you don’t know the
addition of complex numbers, so John will write a program, which you can write in order
Input Format:
Output format:
Sample Input:
452
Sample Output:
4 + 5i
6 + 5i
HackerRank Coding Problems with Solutions
10 + 10i
C++
#include <bits/stdc++.h>
using namespace std;
class Complex //Writing the variables and the functions together, but cant be changed
globally -> Encapsulation
{
private:
int r,i; //Data Abstraction
public:
Complex(){r=i=0;}
Complex(int f,int k)
{
r=f;i=k;
}
void show()
{
cout<<r<<" + "<<i<<"i"<<endl;
}
Complex operator+(Complex obj)
{
Complex temp;
temp.r=r+obj.r;
temp.i=i+obj.i;
return temp;
}
Complex operator+(int a)
{
Complex temp;
temp.r=r+a;
return temp;
}
HackerRank Coding Problems with Solutions
};
int main()
{
int a,b,c;
cin>>a>>b>>c;
Complex i1(a,b);
i1.show();
Complex i2;
i2=i1+c; //Operator Overloading -> Polymorphism
i2.show();
(i1+i2).show();
Problem Statement – Given a sting , return the character that appears the minimum
number of times in the string. The string will contain only ascii characters, from the
ranges (“a”-”z”,”A”-”Z”,0-9), and case matters . If there is a tie in the minimum number of
times a character appears in the string return the character that appears first in the
string.
Input Format:
OutputFormat:
Constraints:
HackerRank Coding Problems with Solutions
Sample Input:
cdadcda
Sample Output:
Explanation:
C and A both are with minimum frequency. So c is the answer because it comes first
C++
#include <bits/stdc++.h>
using namespace std;
map<char,int> ma;
int main()
{
string s;int m=INT_MAX;
cin>>s;
for(int i=s.length()-1;i>=0;i--)
{
ma[s[i]]++;
m=min(m,ma[s[i]]);
}
for(int i=0;i<s.length();i++)
if(ma[s[i]]==m) {cout<<s[i];break;}
HackerRank Coding Problems with Solutions
Problem Statement –
There are some groups of devils and they splitted into people to kill them. Devils make
People to them left as their group and at last the group with maximum length will be
killed. Two types of devils are there namely “@” and “$”
Input Format:
Output Format:
Constraints:
2<=Length of string<=10^9
HackerRank Coding Problems with Solutions
Input string
PPPPPP@PPP@PP$PP
Output
Explanation
● PPPPPP@
● PPP@
● PP$
● PP
C++
#include <bits/stdc++.h>
int main()
string s;
cin>>s;
int a=0,mx=0;
for(int i=0;i<s.length();i++)
a++;
if(s[i]=='@'||s[i]=='$')
{mx=max(a,mx);a=0;}
HackerRank Coding Problems with Solutions
cout<<mx;
Problem Statement – Stephan is a vampire. And he is fighting with his brother Damon.
Vampires get energy from human bloods, so they need to feed on human blood, killing
the human beings. Stephan is also less inhuman, so he will like to take less life in his
hand. Now all the people’s blood has some power, which increases the powers of the
Vampire. Stephan just needs to be more powerful than Damon, killing the least human
possible. Tell the total power Steohan will have after drinking the bloods before the
battle.
● Note that: Damon is a beast, so no human being will be left after Damon drinks
Input Format:
Second line with a string with n characters, denoting the one digit power in every blood.
Output Format:
Constraints:
● n<=10^4
Sample input :
093212
Sample output :
Explanation:
HackerRank Coding Problems with Solutions
Stephan riches the town, drinks the blood with power 9. Now Damon cannot reach 9 by
https://www.freshersnow.com/placement-papers-download/
C++
#include <bits/stdc++.h>
int main()
string s;
cin>>s;
sort(s.begin(),s.end(),greater<char>());
for(auto i:s)
HackerRank Coding Problems with Solutions
cout<<sum1;