First Naukri Coding Questions With Solutions
First Naukri Coding Questions for Practice 2024
First Naukri Practice Coding questions are present on this page. A lot of companies are conducting there placement drives through First Naukri. Coding Section of First Naukri is one of the important section of their placement drive, if you are appearing for any drive that is being conducted through First Naukri, make sure you are practicing these First Naukri Coding Questions.
First Naukri Coding Questions With Solutions
Question 1 – Reverse The Bits
Problem Statement :-Suresh knows binary numbers very well. Unfortunately ,he forgot his bank account password , but he remembered a number and if we reverse the binary digits of that number we will get his password.Help suresh to find his password. You will be given a variable name n which is a no of passwords to find followed by n space separated numbers.You are required to give as output and passwords showing for each number.
For Example , if n is 3 and numbers 35000,3467,94856 , you are expected to give as output 487653376, 3517972480 and 290357248.
Example
- Case 1:
For the input provided as follows :
3
35000
3467
94856
Output of the program will be :
487653376, 3517972480 , 290357248
Explanation :
when we reverse the binary digits of number 35000,3467,94856. we get 487653376,3517972480 , 290357248 as the result.
- Case 2:
For the input provided as follows :
2
32678
10
Output of the program will be :
65536,1342177280
Explanation :
when we reverse the binary digits of 32678 and 10. we get 65536 and 1342177280 as the result.
#include<bits/stdc++.h> using namespace std; int main() { int m;cin>>m; while(m--) { int n; cin>>n; string s=""; for(int i=0;i<32;i++) { if((n&1)) s+='1'; else s+='0'; n>>=1; } cout<<(stoull(s,0,2))<<", ";} cout<< "\b\b "; } }
import java.util.*; public class Main { public static long reverse (long digit) { long rev = 0; for (int i = 0; i < 32; i++) { rev <<= 1; if ((digit & (1 << i)) != 0) rev |= 1; } return rev; } 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 (); for (int i = 0; i < n - 1; i++) System.out.print (reverse (arr[i]) + ","); System.out.print (reverse (arr[n - 1])); } }
m=int(input()) while m: m-=1 n=int(input()) s="" for i in range(32): if (n&1): s+='1' else: s+='0' n>>=1 print(int(s,2),end=", ") print("\b\b ")
Question 2: Probability of getting heads
Problem Statement :-In a cricket match , the captain of team A is tossing the coin. If head comes, team A wins the toss and similarly if tail comes then team B will win the toss. They will do N tosses of a coin for N different matches. Your task is to complete a function “count_wins()” that takes two inputs N and R. The function should return the probability of getting exactly R head on N successive tosses of a fair coin i.e. you have to find the probability that team A won the toss. coin has a equal probability of landing a head or tail (i.e. 0.5) on each toss.
Example
- Case 1:
For the input provided as follows :
4 3
The output of the program will be:
0.250000
- Case 2:
For the input provided as follows :
1 1
The output of the program will be :
0.500000
#include<bits/stdc++.h> using namespace std; double comb(int n,int r) { if(r==0) return 1; return n*comb(n-1,r-1)/r; } int main() { int n,r;cin>>n>>r; cout<< comb(n,r)/(1<< n); }
import java.util.*; public class Main { public static int fact (int n) { if (n == 0) return 1; return n * fact (n - 1); } public static double count_wins (int n, int r) { double res; res = fact (n) / (fact (r) * fact (n-r)); res = res / (Math.pow (2, n)); return res; } public static void main (String[]args) { Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int r = sc.nextInt (); System.out.println (count_wins (n, r)); } }
def count_wins(N, R): def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1) def combinations(n, r): return factorial(n) // (factorial(r) * factorial(n-r)) probability = combinations(N, R) * (0.5 ** R) * (0.5 ** (N - R)) return probability
Question 3 – Ayushman And Books
Problem statement :- Ayushman has plenty of coins with value m. And he will get any specific amount for a single book from his parents. For a given number of books and their price, and the value of the coin, if Ayushman can choose any amount at first, you have to predict one of how many books can be bought by him, and also the values of those books. Given that, Ayushman will maximise the number of books he can buy possibly with the amount he got and the infinity number of coins he has.
Note that, Whichever book he buys, he must use the money he gets from his parents. And the price of the books will be given in a sorted order. And there will only be one set of books that can be maximised as per the needs.
Input Format:
First line with space separated n and m, number of books and the plenty coins’ value if each
Next n lines represent the books with their cost.
Output Format:
First line with k, the number of books out of which, he can buy one.
Next k lines, the cost of them.
Sample Test Case:
6 6
3
4
9
10
13
16
Sample Output:
3
4
10
16
Explanation:
If he chooses 3, then he can buy either 3 or 9 (3+6)
If he chooses 4, he can buy either 4, or 10 or 16.
#include <iostream> #include <vector> using namespace std; int main() { int n, m; cin >> n >> m; vectorbooks(n); for (int i = 0; i < n; i++) { cin >> books[i]; } vector selectedBooks; int currentAmount = 0; int maxBooks = 0; for (int i = 0; i < n; i++) { if (books[i] <= m) { selectedBooks.push_back(books[i]); m -= books[i]; maxBooks++; } else { break; } } cout << maxBooks << endl; for (int i = 0; i < maxBooks; i++) { cout << selectedBooks[i] << endl; } return 0; }
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read the number of books and the value of each coin int n = scanner.nextInt(); int m = scanner.nextInt(); List bookCosts = new ArrayList<>(); // Read the costs of the books for (int i = 0; i < n; i++) { int cost = scanner.nextInt(); bookCosts.add(cost); } int amount = m; int booksBought = 0; List booksToBuy = new ArrayList<>(); // Iterate over the book costs for (int cost : bookCosts) { if (cost <= amount) { amount -= cost; booksBought++; booksToBuy.add(cost); } else { break; } } // Print the number of books bought System.out.println(booksBought); // Print the costs of the books bought for (int cost : booksToBuy) { System.out.println(cost); } } }
n, m = map(int, input().split()) book_costs = [] for _ in range(n): book_costs.append(int(input())) amount = m books_bought = 0 books_to_buy = [] for cost in book_costs: if cost <= amount: amount -= cost books_bought += 1 books_to_buy.append(cost) else: break print(books_bought) for cost in books_to_buy: print(cost)
Question 4: Matrix Path
Problem Statement :- You are in a ground maze and you will have to reach the destination (n-1,n-1). In the maze , you start at the top left (0,0), and make your way down to (n-1,n-1). At each step , you can only allowed to move downwards or rightwards , but if you are on the left diagonal (row number and column number are same) , then you can move down and right in one move.However , you cannot move to the block if it is an obstacle. You can only move if there is a path. 1 denotes an obstacle and 0 denotes the path .You have to print the minimum number of steps to reach the destination from the starting position.
First line of input contains an integer n which represents the number of rows and columns of matrix (it is always a square matrix).This is followed by n space separated number in n lines.
Example
- Case 1:
For the input provided as follows :
4
0 1 1 1
0 0 0 1
0 1 0 0
0 0 0 0
The output of the program will be
3
Explanation :
Minimum number of steps required is 3 steps:
- Step 1: (0,0)->(1,1)
- Step 2: (1,1)->(2,2)
- Step 3: (2,2) ->(3,3)
- Case 2:
For the input provided as follows:
4
0 0 0 1
0 0 1 0
0 0 1 0
1 0 0 0
The output of the program will be:
5
Explanation :
Minimum number of steps required is 5 steps:
The steps are : (0,0)->(1,1); (1,1)->(2,1);(2,1)->(3,1);(3,1)->(3,2);(3,2)->(3,3)
#include <iostream> #include <vector> #include <climits> using namespace std; int minimumSteps(vector<vector<int>>& matrix) { int n = matrix.size(); vector<vector<int>> dp(n, vector<int>(n, INT_MAX)); dp[0][0] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 1) { // Obstacle, can't move here continue; } if (i - 1 >= 0 && dp[i - 1][j] != INT_MAX) { // Check if moving from top is a valid path dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1); } if (j - 1 >= 0 && dp[i][j - 1] != INT_MAX) { // Check if moving from left is a valid path dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1); } if (i - 1 >= 0 && j - 1 >= 0 && dp[i - 1][j - 1] != INT_MAX) { // Check if moving diagonally is a valid path dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + 1); } } } return dp[n - 1][n - 1]; } int main() { int n; cin >> n; vector<vector<int>> matrix(n, vector<int>(n)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> matrix[i][j]; } } int minSteps = minimumSteps(matrix); cout << minSteps << endl; return 0; }
import java.util.*; Public class Main { public static void main (String[]args) { Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int a[][] = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = sc.nextInt (); int res[][] = new int[n][n]; boolean visit[][] = new boolean[n][n]; visit[0][0] = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 && j == 0) continue; if (a[i][j] == 0) { if (i == 0 && j != 0 && a[i][j - 1] == 0 && visit[i][j - 1]) { res[i][j] = res[i][j - 1] + 1; visit[i][j] = true; } if (i != 0 && j == 0 && a[i - 1][j] == 0 && visit[i - 1][j]) { res[i][j] = res[i - 1][j] + 1; visit[i][j] = true; } if (i == j && a[i - 1][j - 1] == 0 && visit[i - 1][j - 1]) { res[i][j] = res[i - 1][j - 1] + 1; visit[i][j] = true; } else if (i != 0 && j != 0) { if (a[i - 1][j] == 0 && a[i][j - 1] == 0 && visit[i - 1][j] && visit[i][j - 1]) { res[i][j] = (res[i][j - 1] < res[i - 1][j] ? res[i][j - 1] : res[i - 1][j]) + 1; visit[i][j] = true; } else if (a[i - 1][j] == 0 && visit[i - 1][j]) { res[i][j] = res[i - 1][j] + 1; visit[i][j] = true; } else if (a[i][j - 1] == 0 && visit[i][j - 1]) { res[i][j] = res[i][j - 1] + 1; visit[i][j] = true; } } }} } System.out.println (res[n – 1][n – 1]); } }
def minimum_steps(matrix): n = len(matrix) dp = [[float('inf')] * n for _ in range(n)] dp[0][0] = 0 for i in range(n): for j in range(n): if matrix[i][j] == 1: # Obstacle, can't move here continue if i - 1 >= 0 and dp[i - 1][j] != float('inf'): # Check if moving from top is a valid path dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1) if j - 1 >= 0 and dp[i][j - 1] != float('inf'): # Check if moving from left is a valid path dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1) if i - 1 >= 0 and j - 1 >= 0 and dp[i - 1][j - 1] != float('inf'): # Check if moving diagonally is a valid path dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + 1) return dp[n - 1][n - 1] n = int(input()) matrix = [] for _ in range(n): row = list(map(int, input().split())) matrix.append(row) min_steps = minimum_steps(matrix) print(min_steps)
Question 5: Is Sum Possible
Problem statement :- In a shop there are n items with different prices for each item.You have total N Rs and you will have to purchase a pair of items with that amount. The function should return true, if there exists a pair of items in the shop and whose sum adds to N Rs, else return false. The items are NOT necessarily in sorted order. Your task is to write the body of isSumPossible function.
The input arguments for the function are:
Number of items in the shop (x)
The total amount of money to be compared (N)
Items prices separated by space
- For example
For the input provided to the program as follows:
10
77
11 20 33 40 55 60 66 70 75 80
The output of the program will be :
true
Explanation :
11+66=77 . There exists a pair of items whose sum is N.
- Another example
For the input provided to the program as follows:
9
27
4 7 15 8 6 22 1 3 11
The output of the program will be:
false
Explanation :
No possible combination of 2 items would lead to a sum 27.
#include <bits/stdc++.h> using namespace std; bool f; int n, m; void fun(int i, vectora, int s) { if (i == a.size()) { f |= (m == s); return; } if (s > m) return; fun(i + 1, a, s + a[i]); fun(i + 1, a, s); } int main() { cin >> n >> m; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; fun(0, a, 0); cout << f; }
import java.util.HashSet; public class Main { public static boolean isSumPossible(int x, int N, int[] prices) { HashSet set = new HashSet<>(); for (int i = 0; i < x; i++) { int remaining = N - prices[i]; if (set.contains(remaining)) { return true; } set.add(prices[i]); } return false; } public static void main(String[] args) { int x = 10; int N = 77; int[] prices = {11, 20, 33, 40, 55, 60, 66, 70, 75, 80}; boolean result = isSumPossible(x, N, prices); System.out.println(result); // Output: true x = 9; N = 27; int[] prices2 = {4, 7, 15, 8, 6, 22, 1, 3, 11}; result = isSumPossible(x, N, prices2); System.out.println(result); // Output: false } }
def fun(i,a,s): global f global m if i==len(a): f|=(m==s) return if s>m: return fun(i+1,a,s) fun(i+1,a,s+a[i]) f=False n=int(input()) m=int(input()) a=list(map(int,input().split())) fun(0,a,0) if f: print(1) else: print(0)
Question 6: Product Of Diagonals
Problem Statement :- Write a program that will print the product of elements of left diagonal or right diagonal whose product is Maximum.The program takes total n rows and n columns as input (n numbers will be inputed per line and each number will be separated by space).
- For example
For the input provided as follows:
3
1 2 3
4 5 6
7 8 9
The program will provide the following output:
105
Explanation :
The product of left diagonal is 45 and the right diagonal is 105. So the output is the greatest of these two which is 105.
- Another example,
5
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
The program will provide the following output :
120
Explanation :
The product of left diagonal is 1 and the product of right diagonal is 120. so the greatest of these two is 120.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;cin>>n;
vector<vector<int>> v(n,vector<int>(n));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>v[i][j];
int p1=1,p2=1;
for(int i=0;i<n;i++)
p1*=v[i][i];
for(int i=n-1;i>=0;i--)
p2*=v[i][n-i-1];
cout<<max(p1,p2);
}
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[][] = new int[n][n]; // Reading the matrix elements from user input for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = sc.nextInt(); } } int left = 1; for (int i = 0; i < n; i++) { // Calculating the product of the main diagonal elements left = left * arr[i][i]; } int right = 1; for (int i = 0; i < n; i++) { // Calculating the product of the opposite diagonal elements right = right * arr[i][n - 1 - i]; } // Printing the maximum value between the product of the main diagonal and the product of the opposite diagonal System.out.println(left > right ? left : right); } }
n=int(input())
L=[]
p1=1
p2=1
for i in range(n):
l=list(map(int,input().split()))
L.append(l)
p1*=L[i][i]
p2*=L[i][n-i-1]
print(max(p1,p2))
Question 7 – Vaibhav’s Password
Problem statement :- Vaibhav is setting a password for his facebook account. He want that password to be a absolute unique one, so that it becomes nearly impossible for the hackers or his friends or foe’s to crack it. He came up with a idea, that first he will write a string of 14 characters of his choice, and then after that he will change the adjacent occurrences of characters of english alphabet with #.Like in a string “abskl” , ‘a’ and ‘b’ are adjacent to each other so we have to change them to # symbol i.e. our string becomes #skl. Help him to write a code for doing the same
For example ,
- Case 1:
For the input provided as follows:
acdgelskelvnuv
Output of the program will be :
a#gelskelvn#
- Case 2:
For the input provided as follows:
jkasdoghqwerty
Output of the program will be :
#asdo#qwerty
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,s1;
cin>>s;
for(int i=0;i<s.length()-1;i++)
if(s[i+1]==s[i]+1)
{s1+='#';i++;}
else
s1+=s[i];
if(s[s.length()-1]!=s[s.length()-2]+1) s1+=s[s.length()-1];
cout<<s1;
}
import java.util.*;
public class Password
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
String res="";
for(int i=1;i<str.length();i++)
{
int diff=(int)Math.abs(str.charAt(i)-str.charAt(i-1));
if(diff!=1)
res+=str.charAt(i);
else
res+="#";
}
System.out.println(res);
}
}
s=input()
s1=""
n=len(s)
i=0
while i<n-1:
if ord(s[i+1])==(ord(s[i])+1):
s1+='#'
i+=2
else:
s1+=s[i]
i+=1
if ord(s[n-1])!=ord(s[n-2])+1:
s1+=s[n-1]
print(s1)
Question 8: Balanced Parentheses
The Mathematics teacher gave his students a task to check if the arithmetic equation has balanced parentheses in it or not. An equation is said to be balanced if all the left parenthesis ‘(’ has a matching right parenthesis ‘)’ and the count of both should be equal.If so , the program will print 0 else the program will print 1.
- For example ,
For the input provided as follows:
((a+b)*c-d/e)
The output of the program will be :
0
Explanation :
All the parentheses of this equation are balanced . Hence the output is 0.
- Another example ,
For the input provided as follows :
(9*(7-2)*(1*5)
The output of the program will be :
1
Explanation :
All the parentheses of this equation are not balanced . Hence the output is 1.
#include <bits/stdc++.h> using namespace std; bool f; int n, m; void fun(int i, vectora, int s) { if (i == a.size()) { f |= (m == s); return; } if (s > m) return; fun(i + 1, a, s + a[i]); fun(i + 1, a, s); } int main() { cin >> n >> m; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; fun(0, a, 0); cout << f; }
import java.util.*;
public class BalanceParanthesis
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
String str = sc.next ();
Stack < Character > stack = new Stack < Character > ();
int flag = 0;
char temp;
for (int i = 0; i < str.length (); i++)
{
switch (str.charAt (i))
{
case '(':
stack.push ('(');
break;
case ')':try
{
temp = stack.pop ();
if (temp != '(')
flag = 1;
}
catch (Exception e)
{
flag = 1;
}
break;
}
if (flag == 1)
break;
}
if (flag == 1)
System.out.println ("1");
else if (stack.isEmpty ())
System.out.println ("0");
else
System.out.println ("1");
}
}
s=input()
c=0
for i in s:
if i =='(':
c+=1
elif (i==')') and c>0 :
c-=1
print(int(c>0))
Question 9 – Sum Of Non-Prime
Problem Statement :- Write a program to display the sum of all non-prime numbers from the given list of integers. A prime number is a number which is divisible by 1 or itself.
First line contains a number indicating the total number of integers and the second line contains integers separated by spaces.
- For example ,
For the input provided as follows:
5
4 6 9 3 7
The output of the program will be:
19
Explanation :
Non-prime number in the list are 4,6,9. So by adding these numbers we get 4+6+9=19.
- Another Example ,
For the input provided as follows
10
4 30 7 23 5 99 3 45 19 17
The output of the program will be :
178
Explanation :
Non-prime number in the list are 4,30,99,45 and the sum of all these number is 178.
#include<bits/stdc++.h>
using namespace std;
map<int,int> m;
bool ifPrime(int a)
{
if(m[a]==2||m[a]==1) return m[a]-1;
if((a&1)==0) {m[a]=1;return false;}
for(int i=3;i<=sqrt(a);i+=2)
if(a%i==0) {m[a]=1;return 0;}
m[a]=2;
return 1;
}
int main()
{
m[2]=2;
int n,sum=0,a;cin>>n;
for(int i=0;i<n;i++)
{
cin>>a;
if(!ifPrime(a)) sum+=a;
}
cout<<sum;
}
import java.util.*;
public class PrimeNumber
{
public static boolean isPrime (int n)
{
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i <= Math.sqrt (n); i = i + 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
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 ();
ArrayList nonprime = new ArrayList <> ();
for (int i = 0; i < n; i++)
if (!isPrime (arr[i]))
nonprime.add (arr[i]);
Iterator itr = nonprime.iterator ();
int sum = 0;
while (itr.hasNext ())
{
sum = sum + (Integer) itr.next ();
}
System.out.println (sum);
}
}
from collections import defaultdict
import math
d=defaultdict(int)
def ifPrime(a):
if d[a]==2 or d[a]==1:
return d[a]-1
if ((a&1)==0):
d[a]=1
return 0
for i in range(3,int(math.sqrt(a))+1):
if a%i==0:
d[a]=1
return 0
d[a]=2
return 1
d[2]=2
n=int(input())
a=list(map(int,input().split()))
sum=0
for i in a:
if ifPrime(i)==0:
sum+=i
print(sum)
Question 10 – Percentage in Fraction
Problem Statement :- Ankit got his 12th board examination result , but in result only subject names and marks are mentioned, there are 5 subjects in total with total 100 marks each. You have to calculate his percentage in fraction like if the percentage are 72.5% then you have to write it as 72 ½ .Ankit is asking for your help.Write a program to calculate his percentage in fraction.
First five lines of input contain marks of five subjects and you have to calculate the percentage in fraction.
- For example ,
For the input provided as follows:
70 77 73 72 80
The output of the program will be:
74 2/5
Explanation:
The percentage of above five subject is (70+77+73+72+80)/5 = 74.4 which in fraction is represented as 74 2/5
- Another Example ,
For the input provided as follows
33 45 67 89 38
The output of the program will be :
54 2/5
Explanation :
The percentage of above five subject marks is (33+45+67+89+38)/5=54.4 which in fraction is represented as 54 2/5
#include<bits/stdc++.h>
using namespace std;
int main()
{
int v,sum=0;
for(int i=0;i<5;i++) {cin>>v;sum+=v;}
cout<<sum/5<<" "<<sum%5<<"/"<<5;
}
import java.util.*;
class Percentage
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int subject;
int sum=0;
for(int i=0;i<5;i++)
{
subject=sc.nextInt();
sum=sum+subject;
}
System.out.println(sum/5+" "+sum%5+"/"+"5");
}
}
sum=0
L=list(map(int,input().split()))
for v in L:
sum+=v
print(sum//5,sum%5,"\b/",end="")
print(5)
Question 11 – Search For Cube Root’s
Problem Statement :- Write a program to find the sum of all the numbers whose cube roots are available in the list.If the number is not available then display “Not Found” as an output.
- For example ,
1,8,7,125,5,211,343,25,400,512
The output of the program will be:
981
Explanation :
The numbers whose cube roots is present in the list are 1+125+343+512=981
- Another example ,
4,9,343,25,78,512
The output of the program will be:
Not Found
Explanation:
No cube root is present in the list . Hence the answer is “Not Found”.
#include<bits/stdc++.h>
using namespace std;
map<int,int> m;
int main()
{
string s,s1;cin>>s;
vector<int> v;
for(auto i:s)
if(i==',')
{
v.push_back(stoi(s1));m[stoi(s1)]++;
s1="";
}
else s1+=i;
int sum=0;
v.push_back(stoi(s1));m[stoi(s1)]++;
for(auto i:v)
if(m[i*i*i]) sum+=(i*i*i);
if(sum)cout<<sum;
else cout<<"Not Found";
}
import java.util.*;
public class CubeRoot
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
String str = sc.next ();
String[] arr = str.split (",");
double sum = 0;
ArrayList list = new ArrayList ();
TreeSet result = new TreeSet <> ();
for (int i = 0; i < arr.length; i++)
list.add (Double.parseDouble (arr[i]));
for (int i = 0; i < list.size (); i++)
{
double cbrt = Math.cbrt (list.get (i));
if (list.contains (cbrt))
{
sum = sum + list.get (i);
}
}
if (sum == 0)
System.out.println ("Not Found");
else
System.out.println ((int) sum);
}
}
import math
L=list(map(int,input().split(",")))
sum=0
for i in L:
g=math.ceil(i**(1./3.))
if int(g**3)==int(i) and g in L:
sum+=i
if sum!=0:
print(sum)
else:
print("Not Found")
Question 12 – Sorted String
Problem Statement :- There are n number of words in the string separated by space.Your task is to arrange all these words according to their ASCII value, if let’s say there are three words in string i.e “I am good” then then the output of the program according to their ASCII value is “am good I”.It is given that all the letters of the string is in lowercase.
First line of input contains n which is the number of words in the string followed by a string.
- For example ,
5
abc hki gho hkc xyz
The output of the program will be
abc gho hkc hki xyz
- Another example
i am coding in java
The output of the program will be
am coding i in java
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
vector<string> v;
istringstream ss(s);
while(ss)
{
string word;ss>>word;
if(word=="") break;
v.push_back(word);
}
sort(v.begin(),v.end());
for(auto i:v)cout<<i<<" ";
}
import java.util.*;
public class Solution
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
String str = sc.nextLine ();
String[] arr = str.split (" ");
TreeSet < String > res = new TreeSet < String > ();
for (int i = 0; i < arr.length; i++)
res.add (arr[i]);
Iterator itr = res.iterator ();
while (itr.hasNext ())
{
System.out.print (itr.next () + " ");
}
}
}
l=list(map(str,input().split()))
l=sorted(l)
for i in l:
print(i,end=" ")
Question 13 – Occurrences Count
Problem Statement :- Write a program to read a sentence and output the number occurrences of each word in a sentence.The output of the program should be sorted into ascending order. It is given that all the letters of the words are in lowercase only and separated by spaces (“ ”). Display all the words in ascending order with their count.
Example
- Case 1:
For the input given below
you are good when your thoughts are good and your deeds are good
The output of the program will be
and – 1
are – 3
deeds – 1
good – 3
thoughts – 1
when – 1
you – 1
your – 2
- Case 2:
For the input given below
if you fail to plan you are planning to fail.
The output of the program will be
are – 1
fail – 2
if – 1
plan -1
planning – 1
to – 2
you – 2
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
map<string,int> m;
getline(cin,s);
vector<string> v;
istringstream ss(s);
while(ss)
{
string word;ss>>word;
if(word=="") break;
m[word]++;
}
for(auto &i:m)cout<<i.first<<" - "<<i.second<<endl;
}
import java.util.*;
public class Solution
{
static int countOccurences (String str, String word)
{
String a[] = str.split (" ");
int count = 0;
for (int i = 0; i < a.length; i++)
{
if (word.equals (a[i]))
count++;
}
return count;
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
String str = sc.nextLine ();
String[]arr = str.split (" ");
TreeMap < String, Integer > map = new TreeMap < String, Integer > ();
for (int i = 0; i < arr.length; i++)
{
map.put (arr[i], countOccurences (str, arr[i]));
}
Set s = map.entrySet ();
Iterator itr = s.iterator ();
while (itr.hasNext ())
{
Map.Entry m = (Map.Entry) itr.next ();
System.out.println (m.getKey () + "-"+m.getValue ());
}
}
}
from collections import defaultdict
d=defaultdict(set)
l=list(map(str,input().split()))
l=sorted(l)
a={}
for i in l:
if i in a:
a[i]+=1
else :
a[i]=1
for i in a:
print(i,"-",a[i])
Question 14 – Count Set Bits
Problem Statement :- Write a program to count the number of sets bits in the binary representation of an integer. First line of input contains an integer n .The output of the program should be the number of set bits of a binary representation of a number.
Examples:
- Case 1:
For the input provided as follows
7
The output of the program will be
3
Explanation
Binary representation of 7 is 111 and has 3 set bits.
- Case 2:
For the input provided as follows
17
The output of the program will be
2
Explanation
Binary representation of 17 is 10001 and has 2 set bits.
#include <iostream> int countSetBits(int n) { int count = 0; while (n > 0) { // Check if the least significant bit is set (i.e., equal to 1) if (n & 1) { count++; } // Right shift the number by 1 to check the next bit n >>= 1; } return count; } int main() { int n; std::cin >> n; int setBitCount = countSetBits(n); std::cout << setBitCount << std::endl; return 0; }
import java.util.*;
public class CountBits
{
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(countSetBits(n));
}
}
def count_set_bits(n): count = 0 while n > 0: # Check if the least significant bit is set (i.e., equal to 1) if n & 1: count += 1 # Right shift the number by 1 to check the next bit n >>= 1 return count n = int(input()) set_bit_count = count_set_bits(n) print(set_bit_count)
Question 15 – Maximum Difference
Given below the heights of students according to their standing order in a queue, find the maximum difference between heights of two students such that the smaller student stands before the larger student.The first line of input contain and integer n which is the number of elements in the array followed by n space separated elements of array.The output of the program should be the maximum difference of two array elements that satisfies the above condition.
- Example ,
For the input given below
7
3 8 10 6 2 4 6
The output of the program will be
7
Explanation:
The maximum difference between 3 and 10 is 7.
- Another Example,
9
3 5 2 9 5 8 6 12 7
The output of the program will be
10
Explanation:
The maximum difference between 2 and 12 is 10.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,a,mn=INT_MAX,mx=INT_MIN;cin>>n;
for(int i=0;i<n;i++)
{
cin>>a;
mn=min(mn,a);
mx=max(mx,a-mn);
}
cout<<mx;
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read the number of elements in the array int n = scanner.nextInt(); int[] heights = new int[n]; // Read the elements of the array for (int i = 0; i < n; i++) { heights[i] = scanner.nextInt(); } int maxDifference = findMaxDifference(heights); System.out.println(maxDifference); } private static int findMaxDifference(int[] heights) { int maxDiff = 0; int minElement = heights[0]; // Iterate over the array for (int i = 1; i < heights.length; i++) { int diff = heights[i] - minElement; maxDiff = Math.max(maxDiff, diff); // Update the minimum element if found if (heights[i] < minElement) { minElement = heights[i]; } } return maxDiff; } }
def find_max_difference(heights): max_diff = 0 min_element = heights[0] # Iterate over the array for height in heights[1:]: diff = height - min_element max_diff = max(max_diff, diff) # Update the minimum element if found if height < min_element: min_element = height return max_diff n = int(input()) heights = list(map(int, input().split())) max_difference = find_max_difference(heights) print(max_difference)
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment