HackerRank Advanced Coding Questions

HackerRank Previously Asked Coding Questions 2021-22

HackerRank is one of the most visited coding platform by students and organizations. Students visit HackerRank to practice various different coding problems, to gain knowledge about coding. Whereas companies prefer HackerRank to hire coding proficient students.
 
Here we have provided various previously asked coding questions of hackerrank for practice purpose. So if you want to get placed in a company that hires through hackerrank make sure you practice these questions well.
HackerRank Advance Coding Questions

Hackerrank  Advance Coding Round Details

 

Details about HackerRank as a Hiring platform

TopicsDetails
Number of Questions asked by companies2 – 5
Time Limit2 – 4.5 hrs approx
Difficulty levelHigh
Package Offered6 LPA – 12 LPA

HackerRank conducts various coding competition in which students can participate, and show off their coding skills. If they perform really well, and their scores impresses the companies, they get opportunities to directly appear for the interview, and gets placed in top 500 companies. SO make sure if you are participating in any HackerRank Hackathon, you give your best. For which we have given below various different coding problems, which will help you in practicing different coding techniques.

List of HackerRank Advance Coding Questions

HackerRank Practice Coding Questions with Solutions

Question 1 : Crazy Share Holder

Problem Statement – Ratan is a crazy rich person. And he is blessed with luck, so he always made the best profit possible with the shares he bought. That means he bought a share at a low price and sold it at a high price to maximize his profit. Now you are an income tax officer and you need to calculate the profit he made with the given values of stock prices each day. You have to calculate only the maximum profit Ratan earned.

Note that:

  • Ratan never goes into loss.

Example 1

  • Price=[1,6,2]
  • Ratan buys it on the first day and sells it on the second. 

Example 2

  • Price=[9,8,6]
  • The Price always went down, Ratan never bought it.

Input Format:

  • First line with an integer n, denoting the number days with the value of the stack
  • Next n days, telling the price of the stock on that very day.

Output Format:

  • Maximum profit done by Ratan in a single line.

Constraints:

  • Number of days <=10^8

Sample Input for Custom Testing

 STDIN              

———–       

7

11

2

Sample Output

  10

 Explanation

  • The maximum profit possible is when Ratan buys it in 1 rupees and sells it in 11.
#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> v)
{
int n = v.size();
if (n == 0)
return 0;
int mx = v[0];
for (int i = 1; i < n; i++)
mx = max(mx, v[i]);
if (mx <= 0)
return 0;
int mxSum = 0;
int cSum = 0;
for (int i = 0; i < n; i++)
{
cSum += v[i];
if (cSum < 0)
cSum = 0;
mxSum = max(mxSum, cSum);
}
return mxSum;
}
int main()
{
int n;
cin >> n;
int price[n];
for (int i = 0; i < n; i++) cin >> price[i];
vector<int> diff;
for (int i = n-2; i >=0 ; i--) diff.push_back(price[i+1] - price[i]);
int ans = solve(diff);
if(ans<0) cout<<0<<endl;
else cout<<ans<<endl;
}
def func(diff):
n=len(diff)
if n==0:
return 0
mx=max(diff)
if mx<=0:
return 0
mxS=0
cS=0
for i in diff:
cS+=i
if cS<=0:
cS=0
mxS=max(cS,mxS)
return mxS



n=int(input())
arr=[]
diff=[]
ans=[0]
for i in range(n):
arr.append(int(input()))
for i in range(n-1):
diff.append(arr[i+1]-arr[i])
ans=func(diff)
if ans<0:
print("0")
else:
print(ans)
import java.util.*;
public class PrepInsta {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int price[] = new int[n];
for(int i=0;i<n;i++) {
price[i] = sc.nextInt();
}
Vector<Integer> diff = new Vector<>();
for(int i=n-2;i>=0;i--) {
diff.add(price[i+1]-price[i]);
}
int ans = solve(diff);
if(ans<0) {
System.out.println(0);
}else {
System.out.println(ans);
}

}
private static int solve(Vector<Integer> v) {
int n = v.size();
if(n==0) {
return 0;
}
int mx = v.get(0);
for(int i=1;i<n;i++) {
mx = Math.max(mx, v.get(i));
}
if(mx<=0) {
return 0;
}
int mxSum=0,csum=0;
for(int i=0;i<n;i++) {
csum+=v.get(i);
if(csum<0)
csum=0;
mxSum = Math.max(csum, mxSum);
}
return mxSum;
}
}

Question 2 : Repeating Characters

Problem Statement – Codu is given a string and he thinks the letters that are repeated do have more power. He gathers only the repeating characters and keeps them as the most powerful to least powerful manner. Now it is your turn to write a code that will help Codu to do that.

Note that: only lowercase alphabets are accepted in input.

Input Format:

  • A string in a single line

Output Format:

  • A string made of only the repeated characters as sorted their frequency reducin, if the same the lower ascii value comes before.

Constraints:

  • Length of string<=10^5

Sample Input:

abcdefghaabca

Sample Output:

abc

#include<bits/stdc++.h>
using namespace std;
map < char, int >m;
string ss;
bool cmp (pair < char, int >&a, pair < char, int >&b)
{
return a.second > b.second;
}

void sort (map < char, int >&M)
{
vector < pair < char, int >>A;
for (auto & it:M)
A.push_back (it);
sort (A.begin (), A.end (), cmp);
for (auto & it:A)
ss += it.first;
}

int main ()
{
string s;
getline (cin, s);
for (auto i:s)
m[i]++;
sort (m);

for (auto i:ss)
if (m[i] > 1)
cout << i;
}
import java.util.*;
class StringReduction
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
String str = sc.next ();
TreeSet < Character > list = new TreeSet < Character > ();
for (int i = 0; i + 1 < str.length (); i++)
{
String prefix = str.substring (0, i);
String suffix = str.substring (i + 1, str.length ());
char ch = str.charAt (i);
if (prefix.indexOf (ch) != -1 || suffix.indexOf (ch) != -1)
list.add (ch);
}
if (str.substring (0, str.length () - 1).
indexOf (str.charAt (str.length () - 1)) != -1)
list.add (str.charAt (str.length () - 1));
Iterator itr = list.iterator ();
while (itr.hasNext ())
{
System.out.print ((Character) itr.next ());
}
}
}

Question 3 : Password Hacker

Problem Statement – Elliot made a KeyLogger for his friend Romero, so that he can see the passwords of his friend. Keylogger is a software that can tell you the buttons pressed in the keyboard without the consent of the user, and hence unethical. Elliot made it to hack Romero’s passwords. The one problem is, Romero writes the passwords in lowercase characters only, and the keylogger only takes the values of the keys. Like, for a it takes 1, for b 2, and for z 26. For a given number Elliot produces all combinations of passwords in a dictionary and starts a dictionary based password attack. For a given number, print all the possible passwords in a lexicographic order.

  • Input Format:
    • One line, denoting the value given by the keylogger
  • Output Format:
    • All possible combinations of keyloggers in new lines are lexicographically ordered.
  • Constraints:
    • 2<=Number of digit in input<=1000

Sample Input:

1234

Sample Output:

abcd

axd

Mcd

Explanation:

For 12, you can take 1,2 that is ab, or you can take 1.

#include<bits/stdc++.h>
using namespace std;
string ss;
vector<string> v;

void fun(int i, string s)
{
//cout<<i<<s<<endl;
if(i==ss.length()) {v.push_back(s);return;}
if(i>ss.length()) return;
if(ss[i]=='0') return;
char c='a'+(ss[i]-'1');
fun(i+1,s+c);
if(i!=s.length()-1)
if( ss[i]<'3' && ss[i+1]<'7')
{
int a=(ss[i]-'1'+1),b=(ss[i+1]-'0');
c=('a'+(10*a+b-1));//cout<<a<<b<<endl;
fun(i+2,s+c);
}
}

int main()
{
cin>>ss;
fun(0,"");
sort(v.begin(),v.end());
for(auto i:v) cout<<i<<endl;
}

Question 4 : Book Shop

Problem Statement – Ramesh went to a bookshop to buy books. There is a list of books with their value and price. Now Ramesh has limited money but he wants maximum value possible. Now there are 2 kinds of books, one is denoted with 1, that is independent, another one is denoted as 2, which you have to buy in double, that means you can not buy a single or odd number of those books. 

Print the maximum value Ramesh can extract from the books. 

 

  • Input Format:
    • First line contains two integers, n (Number of books) and T, total money he has.
    • Then n lines, 4 variables in each line, 
    • The serial number of the book
    • The value of the book
    • The price of the book
    • The marking (1 or 2)
  • Output Format:
    • Maximum value possible to be bought.
  • Constraints:
    • Number of books: <=100
    • Maximum Money with Ramesh <=1000
    • Max price of a book<=1000

Sample Input:

5 20

1 3 7 0

3 9 10 1

2 4 3 1

7 3 2 0

22 7 7 0

Sample Output:

20

 

Explanation:

It will be the 1st book,2nd and the third book.

#include<bits/stdc++.h>
using namespace std;
int n,w;
int *a,*b,*c;

int fun(int i,int cb,int t,int ww)
{
if(i==n){
if(cb&1) return 0;
else return t;
}
if(ww+b[i]<=w) return max(fun(i+1,cb+c[i],t+a[i],ww+b[i]),fun(i+1,cb,t,ww));
return fun(i+1,cb,t,ww);
}

int main()
{
cin>>n>>w;
int tt;
a=new int(n);
b=new int(n);
c=new int(n);
for(int i=0;i<n;i++)
cin>>tt>>a[i]>>b[i]>>c[i];
cout<<fun(0,0,0,0);
}

Question 5 – Last Student’s ID

Problem Statement – There is an id code that is supposed to be given to all the aspirants of an exam. It is actually a substring of a given string. That means, the authority takes a string and then assigns all the unique substrings to all the students. Suppose there is a string “abcde”, so the ids of the students will be “a”,”b”,”c”,”d”,”e”,’ab”,”abc”,”abcd”,”abcde”,”bc”,”bcd”,”bcde”,”cd”,”cde”,”de”.

The students are standing in a line according to the lexicographic order of their given ids. You have to find out the id of the last student for the given input string from which the ids are generated.

 

  • Input Format:
    • Single line with the id generating string
  • Output format:
    • The last id as per lexicographical order
  • Constraints:
    • Number of characters in the string<=10^9

Sample Input:

abdc

 

Sample output:

dc

 

Explanation:

The last student will be with the id dc. The order will be

abdc

a

ab

abd

abdc

b

bd

bdc

c

d

dc

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

int main()
{
string s;
cin>>s;
char c=s[0];int j=0;
for(int i=1;i<s.length();i++)
if(c<s[i]) {j=i;c=s[i];}
cout<<s.substr(j,s.length()-j);
}
import java.util.*;
class MaximumSubstring
{
public static String maxString (char set[])
{
int n = set.length;
String temp = "";
TreeSet < String > list = new TreeSet <> ();
for (int i = 0; i < n; i++)
{
temp = "";
for (int j = i; j < n; j++)
{
temp = temp + set[j];
list.add (temp);
}
}
return list.last ();
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
String str = sc.next ();
char arr[] = str.toCharArray ();
System.out.println (maxString (arr));
}
}

Question 6 : Coin Game

Problem Statement – Raman was playing a game,  he starts with x coins. Now in every step, he wins and loses and he has to get the money or pay the money as needed. He came in contact with a psychic who can see the future and the Psychic predicted the outcomes after each step. Now Raman wants to start the game with the minimum wage where he doesn’t run out of money.  Help Raman to find what money he should start with. The only rule to keep playing is not going in a credit situation.

 

  • Input Format:
    • First line with n, number of steps in the game
    • Next n lines, n integers denoting outcomes of every game. Positive means winning and negative means losing that money.
  • Output Format:
    • One single integer denoting the minimum amount to start with
  • Constraints:
    • Number of steps<=10^9-1000<=Money needed in each step<=1000

Sample Input:

4

2

-9

15

2

 

Sample Output:

7

Explanation:

If he starts with 7 rupees, then after steps : 7 ->9 -> 0-> 15 -> 17.

#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;
sum = 0;

}
}
cout << ans << endl;
}
import java.util.*;
class MinimumStart
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
int arr[] = new int[n];

for (int i = 0; i < n; i++)
arr[i] = sc.nextInt ();
int sum = 0, ans = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
if (sum < 1)
{
sum = -sum;
ans += sum + 1;
sum = 1;
}
}
System.out.println (ans);
}
}
n=int(input())
arr=[]
for i in range(n):
arr.append(int(input()))
s,a=0,0
for i in arr:
s=s+i
if(s<1):
a=a+(-1*s)
s=0
print(a)

Question 7 : Digit Game

Problem Statement – For the number given to you, your score is the average of the digits of the number. You can choose your number for a given set of numbers. You have to maximize your own score. If possible, you have to take the value as early as possible to keep a good impact on the judges. Write a code that prints out the number chosen by you.

 

  • Input Format:
    • First line an integer value n, the number of values given.
    • Next n lines the n number of integer values.
  • Output Format:
    • One single integer from the values that has the highest possible score.
  • Constraints:
    • 2<=Number of numbers<=10^5
    • 1<=Number of digits in a number<=10^3

Sample test case:

Sample input:

5

3456 

909

322 

99

32

 

Sample Output:

99

Explanation:

In 99, the average and hence the score is 99, i.e highest of all.

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

bool S(string s)
{
float sum=0;
for(auto i:s) sum+=(i-'0');
if(m<(sum/s.length())) {m=sum/s.length();return true;}
return false;
}

int main()
{
m=0;
int n;
cin>>n;string s,ans;
for(int i=0;i<n;i++)
{
cin>>s;
if(S(s)) {ans=s;}
}
cout<<ans;
}

Question 8 : Lexicographically Smallest Tree

Problem Statement – How will we represent a binary tree? We can use a bracket structure for all of the edges, like (Parentnode , Childnode). Now if we use a node in a child node more than once, the tree can not be valid. Same for the parent node, a node can not be taken more than twice in  a graph as a parent node.

Suppose we see this one graph :

  • (P,Q)(P,R)(Q,T)(R,W)(U,V)(Q,S)(R,U)(U,Z)(S,I)(W,Y)

A tree with those edges may be illustrated in many ways. Here are two:

HackerRank Is this a tree Question
HackerRank Is this a tree Question image 2

The following is a recursive definition for the S-expression of a tree.

  • S-exp(node)=(node->val(S-exp(node->first_child))(S-exp(node->second_child))), if node!=””

This tree can be represented in S-expression in multiple ways.The lexicographically smallest way of expressing it as follows: P(Q(S(I))(T))(R(U(V)(Z))(W(Y)))). Translate the node-pair representation into its lexicographically smallest S-expression or report any errors that do not conform to the definition of the binary tree. The List of errors with their codes is as follows: 

Error                               Reason

  • Code Stopped1                More than 2 children
  • Code Stopped2                Duplicate Edges
  • Code Stopped3                Cycle Present(node is direct descendant of more than one node)
  • Code Stopped4                Multiple Roots
  • Code Stopped5                Any other error

Constraints:

  • All node names are single characters in the range ascii[A-Z].
  • The maximum node count is 26.
  • There is no specific order to the input (parent,child) pairs.

Sample Input 1

  • (B,D) (D,E) (A,B) (C,F) (E,G) (A,C)

Sample output 

  • (A(B(D(E(G))))(C(F)))

Explanation : A representation of tree is as follows in the image :

Sample Case 2

Input:

  • (C,E)(D,F)(A,B)(A,C)(B,D)

Output:

  • A(B(K))(C(E)))D(F)
HackerRank Is this a tree Question image 3
#include <bits/stdc++.h>
using namespace std;
string s,ans="";
unordered_map<char,int> root,child,flag;//rootOf,childOf
map<pair<char,char>,int> duplicateedgecheck;//Duplicate edge check
unordered_map<char,char> par,ch[2],monitor;
char find(char c)
{
if(monitor[c]) return monitor[c];
if(root[c]==0) return monitor[c]=c;
return monitor[c]=find(par[c]);
}

void makeans(char c)
{
if(flag[c]==0){
ans+=c;flag[c]++;
if(child[c]==2){ans+='(';makeans(min(ch[0][c],ch[1][c]));ans+='(';makeans(max(ch[0][c],ch[1][c]));}
else
for(int i=0;i<child[c];i++)
{ans+='(';makeans(ch[i][c]);}
ans+=')';}
}

int main()
{
getline(cin,s);
for(int i=0;i<26;i++)
{
root['A'+i]=-5;
}
for(int i=0;i<s.length();i++)
if(s[i]=='(')
{
child[s[i+1]]++;root[s[i+3]]=root[s[i+3]]==-5?1:root[s[i+3]]++; duplicateedgecheck[{min(s[i+1],s[i+3]),max(s[i+1],s[i+3])}]++; root[s[i+1]]==-5?root[s[i+1]]=0:1;
ch[0][s[i+1]]=='\0'?ch[0][s[i+1]]=s[i+3]:ch[1][s[i+1]]=s[i+3];par[s[i+3]]=s[i+1];
if(child[s[i+1]]>2){cout<<"Code Stopped1";return 0;}
if(duplicateedgecheck[{min(s[i+1],s[i+3]),max(s[i+1],s[i+3])}]>1){cout<<"Code Stopped2";return 0;}
if(find(s[i+1])==find(s[i+3])&&s[i+1]!=par[s[i+3]]){cout<<"Code Stopped3";return 0;}
if(root[s[i+3]]>1){cout<<"Code Stopped4";return 0;}
if(s[i+4]!=')'||s[i+2]!=','){cout<<"Code Stopped5";return 0;}
//i+=5;
}
for(int i=0;i<26;i++)
{
if(root['A'+i]==0) makeans('A'+i);
}
cout<<ans;
}

Question 9 : Book Shop

Problem Statement – Ramesh went to a bookshop to buy books. There is a list of books with their value and price. Now Ramesh has limited money but he wants maximum value possible. Now there are 2 kinds of books, one is denoted with 1, that is independent, another one is denoted as 2, which you have to buy in double, that means you can not buy a single or odd number of those books. 

Print the maximum value Ramesh can extract from the books. 

Input Format:

  • First line contains two integers, n (Number of books) and T, total money he has.
  • Then n lines, 4 variables in each line, 
  • The serial number of the book
  • The value of the book
  • The price of the book
  • The marking (1 or 2)

Output Format:

  • Maximum value possible to be bought.

Constraints:

  • Number of books: <=100
  • Maximum Money with Ramesh <=1000
  • Max price of a book<=1000

Sample Input:

5 20

1 3 7 0

3 9 10 1

2 4 3 1

7 3 2 0

22 7 7 0

Sample Output:

20

Explanation:

It will be the 1st book,2nd and the third book.

#include<bits/stdc++.h>
using namespace std;
int n,w;
int *a,*b,*c;

int fun(int i,int cb,int t,int ww)
{
if(i==n){
if(cb&1) return 0;
else return t;
}
if(ww+b[i]<=w) return max(fun(i+1,cb+c[i],t+a[i],ww+b[i]),fun(i+1,cb,t,ww));
return fun(i+1,cb,t,ww);
}

int main()
{
cin>>n>>w;
int tt;
a=new int(n);
b=new int(n);
c=new int(n);
for(int i=0;i<n;i++)
cin>>tt>>a[i]>>b[i]>>c[i];
cout<<fun(0,0,0,0);
}

Question 10 : Salted Map

Problem Statement – Hash Functions turn the user’s Password to such a form where you can never come back from the encrypted way. This thing is called Salting. Proyag came up  with such a hash function and he encrypted strings with that. You have to design a reverse hash function that will undo the salting.

In Proyag’s work, if there is a lowercase letter after an uppercase letter, the letters will interchange position. And if there is any digit in the string, it will be replaced with (9-that digit) to the first of the string, where there will be a & sign instead of the digit. In the real string there will not be any & sign.

Input Format:

  • A string with alphanumeric characters

Output:

  • A decrypted string

Sample Input:

  • 678rPepnIsta&&&

Sample Output:

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

int main()
{
string s,s1="";
stack<int> st;
cin>>s;
if(s[0]>='0'&&s[0]<='9') st.push('9'-s[0]);
for( int j=0;j<s.length();j++)
{
auto i=s[j];//cout<<i<<" "<<s1<<endl;
if(i>='0'&&i<='9') {st.push('9'-i);}
else if (i=='&') {s1+=('0'+st.top());st.pop();}
else if (j<s.length()-1)
{ if(s[j+1] !='&' && s[j+1]<'a' && s[j]>'Z' )
{s1=s1.substr(0,s1.length());s1=s1+s[j+1]+s[j];j++;}
else s1+=i;
}
else s1+=i;
}
cout<<s1;
}
import java.util.*;
class SalterMap
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
String numbers="";
String res="";
for(int i=0;i<str.length()-1 && str.charAt(i)!='&';i++)
{
if(str.charAt(i)>='0' && str.charAt(i)<='9')
{
numbers=(9-Integer.parseInt(str.charAt(i)+""))+numbers;
continue;
}
else if(str.charAt(i+1)>='A' && str.charAt(i+1)<='Z')
{
res=res+str.charAt(i+1)+str.charAt(i);
i++;
continue;
}
res=res+str.charAt(i);
}
res=res+numbers;
System.out.println(res);
}
}

Question 11 : Password ASCII

Problem Statement – Aman, who is working at a software company forgot the password of his Linkedin id.But he knows the ASCII values of his password in reverse order. Help aman to find the password. To decode the password, first reverse the string of digits, then successively pick valid values from the string and convert them to their ASCII equivalents. Some of the values will have two digits, and others three. Use the ranges of valid values when decoding the string of digits.

Some of the ASCII values are given with their characters:

  •  The ASCII value of A to Z is 65 to 90.
  •  The ASCII value of a to z is 97 to 122.
  •  The ASCII value of space characters is 32.

Note: The password only has alphabets and blank spaces.

Given a string , decode the password by following the steps mentioned above.

Constraints:

  •    1<= |s| <=10^5
  •    s[i] is an ascii character in the range [A-Za-z] or a space character

Sample Input :

796115110113721110141108

Sample Output :

PrepInsta

Explanation 

The reversed string will be 801141011127311011511697, which if analysed as ascii will be “PrepInsta”

#include <bits/stdc++.h>
using namespace std;
string s1,s;
int n;
void fun(int i)
{

if(i>=s.length()) return;
string s2=s.substr(i,2);
int j=stoi(s2);
if(j==32) s1+=" ";
else if((j>=65&&j<=91)||(j>=97&&j<=99)) s1+=char(j);
else
{
s2=s.substr(i,3);s1+=char(stoi(s2));
fun(i+3);return;
}
fun(i+2);
}

int main()
{
s1="";cin>>s;
reverse(s.begin(),s.end());
fun(0);
cout<<s1;
}
s=input()
s=s[::-1]
i=0
res=""
while(i<len(s)-1):
x=s[i]+s[i+1]
if x=="32":
res+=" "
elif int(x) in range(65,91) or int(x) in range(97,100):
res+=chr(int(x))
elif i+2<len(s):
x=x+s[i+2]
res+=chr(int(x))
i+=1
i+=2
print(res)
import java.util.*;
public class PasswordDecryption
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
char arr[]=str.toCharArray();
String current="";
String result="";
for(int i=arr.length-1;i>0;i=i-2)
{
current="";
current=""+arr[i]+arr[i-1];
int n=Integer.parseInt(current);
if(n==32)
result +=" ";
else if((n>=65 && n<=90 )|| (n>=97 && n<=99))
result char)n;
else
{
if(i-2<0)
break;
current += arr[i-2];
n=Integer.parseInt(current);
result +=(char)n;
i--;

}
}
System.out.println(result);
}
}

Question 12 : Maximum Revenue

Problem Statement –  Amit is a salesman who wishes to know the maximum revenue received from a given item of the N products each day . Amit has a sales record of N products for M days.Helo amit to find the highest revenue received each day.

Input Format : 

  • The first line of the input consists of two space-separated integers- day(M) and item(N) representing the days and the products in the sales record.
  • The next M lines consist of N space separated integers representing the sales revenue from each product each day.

Output Format: 

  • Print m space-separated integers representing the maximum revenue received each day .

Sample Testcases :

Input:

3 4

101 123 234 344

143  282 499 493

283 493 202 304

Output:

344 499 493

Explanation:

The maximum revenue received on the first day is 344 , followed by a maximum revenue of 499 on the second day and a maximum revenue of 493 on the third day.

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

int main()
{
int m,n, i,j;
cin >> m;
cin >> n;
int arr [m][n];
for(i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
cin >> arr[i][j];
}
}
for (i=0;i<m;i++)
{
int max = INT_MIN;
for(j=0;j<n;j++)
{
if(arr[i][j]>max)
{
max = arr[i][j];
}
}
cout << max << " ";
}
return 0;
}
import java.util.*;
class MaximumRevenue
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int arr[][]=new int[m][n];
int i,j;
for(i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
arr[i][j]=sc.nextInt();
}
}
for (i=0;i<m;i++)
{
int max = Integer.MIN_VALUE;
for(j=0;j<n;j++)
{
if(arr[i][j]>max)
{
max = arr[i][j];
}
}
System.out.println(max);
}

}
}

Question 13 : Order Check

Problem Statement – In an IT company there are n number of Employees , they are asked to stand in ascending order according to their heights.But some employees are not currently standing in their correct position. Your task is to find how many employees are there who are not standing in their correct positions.

Example:

height=[1,2,1,3,3,4,3]

The 4 employees at indices 1,2,5 and 6 are not in the right positions. The correct positions are (1,1,2,3,3,3,4).Return 4.

Function Description :

Complete the function countEmployees in the editor below.

  • count Employee has the following parameter(s):
  • int height[n]:an array of heights in the order the employees are standing

Returns: 

Int : the number of employees not standing in the correct positions 

Constraints

  •    1<=n<=10^5
  •    1<=height[i]<=10^9

Sample case 0

Sample input 0

1

2

1

3

3

4

3

Sample output 0:

4

Explanation 

The four employees who are  not standing in the correct positions are at indices [1,2,5,6] return 4. The correct positions are [1,1,2,3,3,3,4].

def countEmployees(n,arr):
dup_arr=arr[:]
dup_arr.sort()
count=0
for i in range(n):
if arr[i]!=dup_arr[i]:
count+=1
else:
pass
return count

n=int(input())
arr=[ ]
for i in range(n):
arr.append(int(input()))
print(countEmployees(n,arr))

Question 14 : Array Subarray

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.

Input Format:

  • First line will be Length of Segment.
  • Second line will be n, Size of array.
  • next n lines will be with the elements of array.

Output Format:

  • The maximumof those minimums.

Sample input :

  • 5
  • 1

Sample output :

3

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

#include <bits/stdc++.h>
using namespace std;
vector<int> arr;
int prevmin=-1;
int flag=0;
int x,n,q;

int sorting(int start,int end)
{
if(start+1==n) {start=0;end=end-n;}
if(start==end) return arr[start];
return min(arr[start],sorting(start+1,end));
}

int func(int start,int end)
{
if(flag==0) {flag++;return prevmin=sorting(start,end);}
if(arr[start-1]==prevmin) return prevmin;
return prevmin=(arr[end]<=prevmin)?prevmin:sorting(start,end);

}

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;
}
s=int(input())
n=int(input())
a=[]
for i in range(n):
a.append(int(input()))


def min_in_segment(start,end,prev,s,prev_min):
if s==1:
return a[start]
else:
if prev==-1 or prev_min==-2:
return min(a[start:end+1])
elif prev_min!=-2:
if prev!=prev_min:
if a[end]<prev_min:
return a[end]
else:
return prev_min
else:
return min(a[start:end+1])

msf=-1
prev=-1
prev_min=-2
for i in range(n-s+1):
new_min=min_in_segment(i,i+s-1,prev,s,prev_min)
msf=max(msf,new_min)
prev=a[i]
prev_min=new_min
print(msf)

import java.util.*;
public class DiskSpace
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();

int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;

for(int i=0;i<=n-x;i++)
{
min=Integer.MAX_VALUE;
for(int j=i;j<(i+x);j++)
min=Math.min(min,arr[j]);
max=Math.max(min,max);
}
System.out.println(max);
}
}

Question 15 : Can Ajay reach on time?

Problem Statement –  Ajay has a flight to catch in an hour. So he has to reach the airport as fast at possible. He hires a taxi and promises the taxi driver that if he reaches the airport within k minutes he would pay the taxi driver double the amount.

The city description is as follows –

  • The taxi is at point 0,0  & airport is at (n-1,m-1) in a 2 – D grid of n rows and m columns. The grid has some blocked (represented as’#’) and some unblocked (represented as’.’) cells. 
  • The starting position of the taxi is in the top – left corner of the grid. It is guaranteed that the starting position & ending positions are not blocked. Each cell of the grid is connected with its right ,left,top,bottom cells (if those cells exist ). It takes 1 second for a taxi to move from a cell to its adjacent cell. 
  • If the taxi can reach the bottom-right (airport) corner of the grid within  k seconds, return the string ‘Yes’. Otherwise , return the string ‘No’.

Example :

  • rows =3
  • grid =[‘..##’,’#.##’,’#…’]
  • maxTime =5

..##

#.##

#…

  • It will take the taxi 5 seconds to reach the bottom right corner. As long as k>_5,return  :  ‘Yes’.

Returns:

  • String;the final string; either ‘yes’ or ‘ No’

Constraints :

  • 1<_rows<_500
  • 0<_maxTime<_10^6

Input Format For Custom Testing

  • The first line contains an integer,rows that denotes the number of rows of the 2-D grid
  •  In each of the next rows lines, the i^th line contains a string denoting the configuration of the i^th row of the grid.
  • The last line contains an integer, maxTime ,that represents the maximum time in seconds the taxi has to reach the bottom right cell.

Sample Input :

2

.. 

..

3

Sample Output :

Yes

Explanation :

The grid has 2 rows and 2 columns and the time within which the taxi needs to reach the bottom-right cell in 3 seconds. Starting from the top-left cell, the taxi can either move to the top-right unblocked

#include <bits/stdc++.h>
#define INF 1000000000
#define ll long long
using namespace std;

char mat[505][505];
ll dp[505][505];

int main()
{
int n;
cin >> n;

for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> mat[i][j];

for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dp[i][j] = INF;

ll mxTime = 0;
cin >> mxTime;

dp[0][0] = 0;
for (int i = 1; i < n; i++)
{
if (mat[0][i] == '#')
break;

dp[0][i] = dp[0][i - 1] + 1;
}

for (int i = 1; i < n; i++)
{
if (mat[i][0] == '#')
break;

dp[i][0] = dp[i-1][0] + 1;
}

for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
if(mat[i][j]=='#')
continue;
dp[i][j] = min(dp[i-1][j],dp[i][j-1])+1;
}
}

if(dp[n-1][n-1]>mxTime)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
return 0;
}

Question 16 : Game Of Clicks

Problem Statement –  Sahil watches TV all day and gets bored. He started playing this dumb game of identifying minimum number of inputs needed to reach a channel. As his cousin, you have to help him, but you live far from his house. So you decide to write a code that will ask Sahil for some inputs and give outputs respectively.

Here are the problems you need to keep in mind,

  • There are 13 buttons on his remote: 10 buttons for the numbers (0-9) to form integers denoting respective channel index, “Up channel” button and  “ Down channel” button for going i +1th channel and i-1th channel from i respectively, and  a “Last viewed” button to see what’s the last channel before it. 
  • The number buttons allow you to jump directly to a specific channel  (Ex: to go to channel 172 by typing 1,7,2).
  • If the channel which you are in is ith and that is the max channel index possible, by Up channel, you will reach the first channel possible. Same goes for the down channel button. You can go to the highest channel possible if you go down from the lowest channel possible.

Sahil can get from one channel to the next in one of the two ways. Sahil’s parents have set some parental control on some channels on Aniruth’s television. The “Up Channel “ and “Down buttons” buttons skip these channels as these channels are not viewable. Given a list of channels to view, the lowest channel, the highest channel, and a list of blocked channels, your program should return the minimum number of clicks necessary to get through all the shows that Anirudh would like to match.

Input Format :

  • First line is the lowest Channel
  • Second-line is the highest Channel
  • Followed by a number of blocked channels B, 
  • and the next B lines contain the actual blocked channels.
  • Followed by the number of Channels to view V, and the next V lines contain the actual channels to view.

Constraints :

  • The lowest channel on the television will be greater than 0. and less than or equal to 10,000.
  • The highest channel on the television will be greater than or equal to the lowest channel. and less than or equal to 10.000. 
  • The list of channels that are blocked on Anirudh’s television. All the channels in this list will be valid channels (greater than or equal to lowest channel, less than or equal 1 to highest channel). Duplicates may be Ignored. The blocked list can be a maximum of 40 channels.  
  • The sequence that Sahil must view contains between 1 and 50 elements. inclusive. All channels in this sequence are not in the blocked list and are between lowest channel and highest channel. Inclusive.

Sample Input : 

  • 1
  • 20
  • 2
  • 18
  • 19
  • 5
  • 15
  • 14
  • 17
  • 1
  • 17

Sample output :

7

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

unordered_map<int,int> m;
int l,u;
int util(int a,int b)
{
if(a==b) return 0;
if(m[a]) return util(a+1,b);
return 1+util(a+1,b);
}

int func(int b,int prev)
{
if(b<prev) return min(util(prev,u)+util(l,b)+1,util(b,prev));
else return min(util(prev,b),util(l,b)+util(prev,u)+1);
}

int main()
{
int flag=0,ans=0,prev,prev2;
cin>>l>>u;
int bn,b; cin>>bn;
while(bn--){cin>>b;m[b]++;}
cin>>bn;
while(bn--)
{
cin>>b;
if(b>9 && flag==0) {ans+=2;flag++;prev=b;}
else if(flag==0) {ans+=1;flag++;prev=b;}
else if(prev2==b) {prev2=prev;prev=b;ans++;}
else
{
ans+=min(b>9?2:1,func(prev,b));prev2=prev;prev=b;
}
}

cout<<ans;
}
def prev(now,l,h,blocked):
if now!=l:
if (now-1) not in blocked:
return (now-1)
else:
return prev(now-1,l,h,blocked)

else:
if h not in blocked:
return h
else:
return prev(h,l,h,blocked)

def next(now,l,h,blocked):
if now!=h:
if (now+1) not in blocked:
return (now+1)
else:
return next(now+1,l,h,blocked)

else:
if l not in blocked:
return l
else:
return next(l,l,h,blocked)

def digits(n):
count=0
while n>0:
n=n//10
count+=1

return count

for i in range(2):
if i==0:
l=int(input())
else:
h=int(input())

b=int(input())
blocked=[]
for i in range(b):
blocked.append(int(input()))


back=-1
now=-1
c=int(input())
k=0
for i in range(c):
n=int(input())
n1=digits(n)
if now==-1:
now=n
k+=n1
continue

if back==n:
k+=1
back,now=now,back
continue

pf=0
pb=0
now1=now
prev1=now
for j in range(n1):
if j==(n1-1):
pf=n1
pb=n1
break
else:
now1=next(now1, l, h, blocked)
pf+=1
prev1=prev(prev1, l, h, blocked)
pb+=1
if now1==n:
break
if prev1==n:
break
k+=pf
back=now
now=n
print(k)
import java.util.*;
public class GameOfClicks
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int l=sc.nextInt();
int h=sc.nextInt();
int b=sc.nextInt();
List<Integer>bl=new ArrayList<>();
for(int i=0;i<b;i++){
bl.add(sc.nextInt());
}
int v=sc.nextInt();
List<Integer>vl=new ArrayList<>();
for(int i=0;i<v;i++){
vl.add(sc.nextInt());
}
Set<Integer>sl=new HashSet<>();
int res=0;
for(Integer i:vl){
if(bl.contains(i))
continue;
sl.add(i);
}
for(Integer i:sl){
String s=i+"";
res+=s.length();
}
System.out.println(res);

}
}

Question 17 : Help Anirudh

Problem Statement – Anirudh loves to play games but his father is very strict. But one day his father agreed to get him a new game if he solves the following problem –
Given an array of Integers, determine the number of moves to make all elements equal. Each move consists of choosing all but 1 element and Incrementing their values by 1. Can you help Anirudh?
Example :

  • numbers= [3, 4, 6, 6, 3]
  • Choose 4 of the 5 elements during each move and Increment each of their values by one. Indexing begins at 1. It takes 7 moves as follows:

iteration            array
0                     [3,4,6,6,3]
1                     [4,5,7,6,4]
2                     [5,6,7,7,5]
3                     [6,7,8,7,6]
4                     [7,8,8,8,7]
5                     [8,9,9,8,8]
6                     [9,9,10,9,9]
7                     [10,10,10,10,10]

Returns: long: the minimum number of moves required

Constraints

  • 1<=n<=10^5
  • 1<=numbers(i)<=10^6

Sample cases:
Sample input 0:
5 → size of numbers[]
3 → numbers[]=[3,4,6,6,3]
4
6
6
3
Sample output 0:
7

Sample input 1:
4
4
3
4

Sample Output 1:
2

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

int main() {
// your code goes here
int t;
t = 1;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n;i++) cin >> arr[i];
int min_element = INT_MAX;
long long int sum = 0;
for (int i = 0; i < n;i++) {
min_element = min(min_element,arr[i]);
sum += arr[i];
}
cout << sum - n * min_element << endl;

}
return 0;
}
def minMoves(n,nums):
s=0
i = nums.index(min(nums))
for j in range(n):
if(i==j):
continue
else:
s= s+nums[j]-nums[i]
return s

n=int(input())
numbers=[]
for i in range(n):
numbers.append(int(input()))
print(minMoves(n,numbers))
import java.util.*;
public class MinimumMoves
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];

for(int i=0;i<n;i++)
arr[i]=sc.nextInt();

int min=Integer.MAX_VALUE;
long sum=0;
for(int i=0;i<n;i++)
{
min=Math.min(min,arr[i]);
sum=sum+arr[i];
}
System.out.println(sum-n*min);
}
}