0% found this document useful (0 votes)
7 views41 pages

Coding Qns

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views41 pages

Coding Qns

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Question-1

Problem Statement:

The binary number system only uses two digits, 0 and 1. Any string that
represents a number in the binary number system can be called a binary
string. You are required to implement the following function:
int OperationsBinaryString(char *str);
The function accepts a string 'str' as its argument. The string 'str'
consists of binary digits separated with an alphabet as follows:
'A' denotes AND operation
'B' denotes OR operation
'C' denotes XOR operation
You are required to calculate the result of the string 'str', scanning the
string left to right, taking one operation at a time, and return the
same.
Question-1

Problem Statement:
Note:
No order of priorities of operations is required.
Length of 'str' is odd
If 'str' is NULL or None(in case of python), return -1
Example
Input:
ICOCICIAOBI
Output:
1
Explanation:
The alphabet in 'str' when expanded becomes "1 XOR 0 XOR 1 XOR 1 AND 0 OR 1", the
result of the expression becomes 1, hence 1 is returned.
Solution

import java.util.*; {
import java.lang.*; ans = ans | (str[j]-'0');
class Main }
{ else if(str[i]=='C')
public static int OperationsBinaryString( {
char[] str) ans = ans ^ (str[j]-'0');
{ }
int len=str.length; }
int ans= str[0]-'0'; return ans;
for(int i=1;i<len-1;i+=2) }
{ public static void main(String[] args)
int j=i+1; {
if(str[i]=='A') Scanner sc=new Scanner(System.in);
{ String s=sc.nextLine();
ans = ans & (str[j]-'0'); char[] str=s.toCharArray();
} System.out.printf("%d",OperationsBina
else if(str[i]=='B') ryString(str));
}
}
Question-2

Problem Statement:

A palindrome is a sequence of characters that has the property of reading the same
in either direction. You are given a function,
char* ConvertToPalindrome(char*str);
The function accepts a string ‘str’. Implement the function to find and return the
minimum characters required to append at the end of string ‘str’ to make it
palindrome.
Assumption:
String will contain only lower case English alphabets.
Length of string is greater than equal to 1.
Note:
If string is already palindrome then return “NULL”.
You have to find the minimum characters required to append at the end of string to
make it palindrome
Question-2

Problem Statement:
Example:
Input:
abcdc
Output:
ba
Explanation:
If we append ‘ba’ at the end of the string ‘abcdc’ it becomes ‘abcdcba’(i.e A
palindrome string)
solution

import java.util.*; StringBuffer str=new StringBuffer(s.substrin


class Main g(0,count));
{ String st=str.toString();
public static char[] append(String s) char[] pali = st.toCharArray();
{ return pali;
int l =s.length(); }
int j=l-1,count=0; public static void main(String[] args)
for(int i =0;i<l;i++) {
{ Scanner sc =new Scanner(System.in);
while(s.charAt(i)!=s.charAt(j)) String s=sc.nextLine();
{ char[] ch=append(s);
i++; for (int i = ch.length-1; i >= 0 ; i-
count++; -)
} {
j--; System.out.print(ch[i]);
} }
}
}
Question-3

Problem Statement:

Cubic sum
You are given a function:
Int isCubicSumExist(long long int A[], int N);
The function accepts an array ‘A’ of size ‘N’ implement the function to return the
count of good integers in array ‘A’
An integer Z is said to be good if and only if there exist two integers x and y such
that x3 + y3 = z
Question-3

Problem Statement:
Example
Input:
N :3
A : [35,9,1]
Output:
2
Explanation:
35 is a good integer, there exist an answer with X=2,Y=3(23+3 3 = 8+27 = 35)
9 is a good integer,there exist an answer with X=1,Y=2(13 + 2 3 = 9)
1 is not a good integer, so total 2 integers are good in the given array A
The custom input format for the above case
3
35 9 1
(the first line represents ‘N’ the second line represents the elements of the array
‘A’)
solution

import java.util.*;
class Main public static int cubicSum(int n, int arr[])
{ { int count = 0;
public static boolean sumOfTwoCubes(int n) for(int i = 0; i < n; i++)
{ {
int lo = 1, hi = (int)Math.cbrt(n); if (sumOfTwoCubes(arr[i]))
while (lo <= hi) {
{ count++;
int curr = (lo * lo * lo + hi * h } }
i * hi); return count;
if (curr == n) }
return true; public static void main (String[] args)
if (curr < n) {
lo++; Scanner sc = new Scanner(System.in);
else int N = sc.nextInt();
hi--; int arr[] = new int[N];
} for(int i = 0; i < N; i++)
return false; arr[i] = sc.nextInt();
} System.out.println(cubicSum(N, arr));
}}
Question-4

Problem Statement:

Implement the following function:


Int PlayList(int airtime, int songs[], int n);

The function accepts a positive integer ‘airTime’ and a positive integer array
‘songs’ of size ‘n’ as its argument. ‘ songs’ consists of length of songs (in
minutes). A radio jockey has to playlists of combination of exactly thre songs such
that the total length of playlists is equal to ‘airtime’ (in minutes). Implement the
function to find the count of playlist that can be find and return the same.
Assumption: ‘songs’ consists of unique elements
Note: Return -1 if ‘songs’ is null(None,in case of python) or n<3
Question-4
Problem Statement:
Example:
Input:
airTime : 40
Songs : 7 14 21 19 17 2 29 5
Output:
3
Explanation:
Playlists formed are
{14,21,5} = 14 + 21+ 5 = 40
{7,14,19} = 7 + 14 + 19 = 40
{21,17,2} = 21 + 17 + 2 = 40
Since, 3 playlists can be formed thus, output is 3
The custom input format for the above case:
40
8
7 14 21 19 17 2 29 5
(the first line represents ‘airTime’ the second line represents the size of ‘songs’,
The third line represents the element of ‘songs’)
Question-4
Problem Statement:
Sample Input:
airTime: 21
songs : 10 7 9 5 2
2
The custom input for the above case:
21

5
10 7 9 5 2
(the first line represents ‘airTime’ the second line represents the size of ‘songs’,
The third line represents the element of ‘songs’)
Instructions:
This is a template based question,DO NOT write the “main” function
Your code is judged by an automated system,do not write any additional welcome
/greeting messages
“Save and Test” only checks for basic test cases, more rigorous cases will be used
to judge your code while scanning
Additional score will be given for writing optimized code both in terms of memory
and execution time
Solution

import java.util.*; {count++;


class Main }
{ s.add(songs[j]);
public static int playList(int airTime, i } }
nt songs[], int n ) if(count>0)
{ return count;
int count=0; return -1;
for (int i = 0; i < n - 2; i++) }
{ public static void main(String[] args)
HashSet<Integer> s = new HashSet< {
Integer>(); Scanner sc=new Scanner(System.in);
int curr_sum = airTime - int air_time=sc.nextInt();
songs[i]; int n=sc.nextInt();
for (int j = i + 1; j < n; j++) int[] songs =new int[n];
{ for(int i=0;i<n;i++)
if (s.contains(curr_sum - songs[i]=sc.nextInt();
songs[j])) System.out.println(playList(air_time,
songs, n));
}
}
Question-5

Problem Statement:

Find Smallest Character


You are given a function:
def SmallestCharacter(s):
The function accepts a string ‘s’. Implement the function to find the smallest
English character which ios not present in the given string ‘s’ and return the same.
Question-5
Problem Statement:
Example :
Input :
aidubudxd
Output :
c
Explanation :
Input string contains a and b. So now the smallest character that is not present in
the string is c.
The custom input format for the above case:
aidubndxd
(The line represents a string ‘s’)

Sample Input
bbbb
Sample Output
a
Solution

import java.util.*; {
class Main if(freq[i] == 0)
{ {
public static char smallestCharacter(Stri int num = 'a' + i;
ng str) char ch = (char) (num);
{ return ch;
int freq[] = new int[26]; }
int len = str.length();
}
for(int i = 0; i <len; i++) return 'a';
{ }
freq[str.charAt(i) - 'a']++; public static void main(String[] args)
} {
for(int i = 0; i < 26; i++) Scanner sc=new Scanner(System.in);
String str = sc.next();
System.out.print(smallestCharacter(str));
}
}
Question-6

Problem Statement:

Find the word average


Implement the following function:
Static float Average(String str){}
The function accepts a string ‘str’ of length ‘len’ as its arugment. Implement the
function to calculate the word average and return the same. Word Average is
calculated by finding the average of the ASCII values of all of the letters in a
word.
Note:
• ‘str’ is not null
• Input string will contain only lower case English alphabets
• The ASCII value of lower case ‘a’ is 97 while that of ‘z’ is 122
• Do not round off your results, it will be automatically rounded off up to 2
decimal places and then displayed
Question-6
Problem Statement:
Example :
Input :
Str: source
Output :
109.50
Explanation :
Char value
S 115
o 111
u 117
r 114
c 99
e 101
Question-6
Problem Statement:
Word Average =(115+111+117+114+99+101)/6=657/6=109.50
Thus Output is 109.50
The custom input format for the above case :
6 source
(The first line represents ‘len’, the second line represent the string ‘str’)
Sample Input
Str: asp
Sample Output
108.00
The custom input format for the above case:
3asp
(The first line represents ‘len’, the second line represents the string ‘str’).
Solution

import java.util.*;
class Main
{
public static float average(String str)
{
int sum = 0;
for(int i = 0; i < str.length(); i++)
{
sum = sum + (int)str.charAt(i);
}
return (float)sum/str.length();
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.printf("%.2f",average(str));
}
}
Question-7

Problem Statement:

Level order traversal


Given a binary tree, find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree
Your Task:
You don't have to take any input. Complete the function level Order() that takes the
root node as input parameter and returns a list of integers containing the level
order
traversal of the given Binary Tree.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 105
Question-7
Problem Statement:
Test Case #1
Input: 1
/ \
3 2
Sample Output:
1 3 2

Test Case #2
Input: 10
/ \
20 30
/ \
40 60
Sample Output:
10 20 30 40 60
Solution
import java.util.LinkedList; Node root = new
import java.util.Queue; Node(Integer.parseInt(ip[0]));
import java.io.*; Queue<Node> queue = new LinkedList<>();
import java.util.*; queue.add(root);
class Node{ int i = 1;
int data; while(queue.size()>0 && i < ip.length) {
Node left; Node currNode = queue.peek();
Node right; queue.remove();
Node(int data){ // Get the current node's value from the
this.data = data; string
left=null; String currVal = ip[i];
right=null; // If the left child is not null
} } if(!currVal.equals("N")) {
class LOT { // Create the left child for the current
static Node buildTree(String str){ node
if(str.length()==0 || str.charAt(0)=='N'){ currNode.left = new
return null; Node(Integer.parseInt(currVal));
} // Push it to the queue
String ip[] = str.split(" "); queue.add(currNode.left);
}
Solution
// For the right child printInorder(root.left);
i++; System.out.print(root.data+" ");
if(i >= ip.length) printInorder(root.right);
break; }
currVal = ip[i]; public static void main (String[] args)
// If the right child is not null throws IOException{
if(!currVal.equals("N")) { BufferedReader br = new BufferedReader(new
// Create the right child for the current InputStreamReader(System.in));
node int t=Integer.parseInt(br.readLine());
currNode.right = new while(t > 0){
Node(Integer.parseInt(currVal)); String s = br.readLine();
// Push it to the queue Node root = buildTree(s);
queue.add(currNode.right); Solution g = new Solution();
} ArrayList <Integer> res =
i++; g.levelOrder(root);
} for (Integer num : res) System.out.print(num
return root; + " ");
} System.out.println();
static void printInorder(Node root) t--;
{ } } }
if(root == null)
return;
Solution
// } Driver Code Ends ArrayList <Integer> a= new ArrayList
//User function Template for Java <Integer>();
/* Queue<Node> q= new LinkedList<Node>();
class Node q.add(node);
{ while(!q.isEmpty()){
int data; a.add(q.peek().data);
Node left, right; Node k=q.poll();
Node(int item) if(k.left!=null){
{ q.add(k.left);
data = item; }
left = right = null; if(k.right!=null){
} } q.add(k.right);
*/ } }
class Solution return a;
{ } }
//Function to return the level order
traversal of a tree.
static ArrayList <Integer> levelOrder(Node
node)
{
Question-8

Problem Statement:

Given an array of non-negative integers, and a value sum, determine if there is a


subset of the given set with sum equal to given sum.

Your Task:
You don't need to read input or print anything. Your task is to complete the
function
Is SubsetSum() which takes the array arr[], its size N and an integer sum as input
parameters and returns boolean value true if there exists a subset with given sum
and false otherwise.
The driver code itself prints 1, if returned value is true and prints 0 if returned
value is
false.
Expected Time Complexity: O(sum*N)
Expected Auxiliary Space: O(sum*N)
Question-8
Problem Statement:

Test Case #1
Input:
N = 6
arr[] = {3, 34, 4, 12, 5, 2}
sum = 9
Sample Output: 1
Explanation: Here there exists a subset with
sum = 9, 4+3+2 = 9.
Question-8
Problem Statement:

Test Case #2
Input:
N = 6
arr[] = {3, 34, 4, 12, 5, 2}
sum = 30
Sample Output: 0
Explanation: There is no subset with sum 30.
Solution
import java.io.*; if(ob.isSubsetSum(N, arr, sum))
import java.util.*; System.out.println(1);
class SSP else
{ System.out.println(0);
public static void main(String args[])throws }
IOException }
{ }
BufferedReader read = new BufferedReader(new // } Driver Code Ends
InputStreamReader(System.in)); //User function Template for Java
int t = Integer.parseInt(read.readLine()); class Solution{
while(t--> 0) static Boolean isSubsetSum(int N, int arr[],
{ int sum){ // code here
int N = Integer.parseInt(read.readLine()); int dp=new int[N+1][sum+1];
String input_line[] = for(int[] a:dp)
read.readLine().trim().split("\\s+"); Arrays.fill(a,-1);
int arr[]= new int[N]; return util(arr,N-1,sum,dp);
for(int i = 0; i < N; i++) }
arr[i] = Integer.parseInt(input_line[i]);
int sum = Integer.parseInt(read.readLine());
Solution ob = new Solution();
Solution

static boolean util(int[] arr,int ind,int sum,int☐☐ dp)


{
if(ind==0)
return sum==arr[ind];
if(sum<0)
return false;
if(dp[ind][sum]!=-1)
return dp[ind][sum]==1;
if(sum==0)
return true;
boolean take= util(arr,ind-1,sum,dp);
boolean notTake=util(arr,ind-1,sum-arr[ind],dp);
if(take==true || notTake==true)
dp[ind][sum]=1;
else
dp[ind][sum]=0;
return take||notTake;
}}
Question-9

Problem Statement:

The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate the span of stocks price for all n
days.

The span Si of the stocks price on a given day i is defined as the maximum number of
consecutive days just before the given day, for which the price of the stock on the
current day is less than or equal to its price on the given day.

For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85},
then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}

prices = {100, 80, 60, 70, 60, 75, 85}


span = {1, 1, 1, 2, 1, 4, 6}.

Time Complexity: O(n)


Auxilliary Space Complexity: O(n)
Question-9
Problem Statement:

Test Case #1
Sample IO
Input
price[] = { 10, 4, 5, 90, 120, 80 };

Output
1 1 2 4 5 1
Solution
import java.util.Stack; st.pop();
import java.util.Arrays; // If stack becomes empty, then price[i] is
public class EthCode { // greater than all elements on left of it,
// A stack based efficient method to i.e.,
calculate // stock span values // price[0], price[1], ..price[i-1]. Else
static void calculateSpan(int price[], int price[i]
n, int S[]) { // is greater than elements after top of
// Create a stack and push index of first stack
element // to it S[i] = (st.empty()) ? (i + 1) : (i -
Stack <Integer> st = new Stack <>(); st.peek());
st.push(0); // Push this element to stack st.push(i);
// Span value of first element is always 1 static void printArray(int arr[]) {
S[0] = 1; System.out.print(Arrays.toString(arr));
// Calculate span values for rest of the }
elements public static void main(String[] args) {
for (int i = 1; i < n; i++) { int price[] = { 10, 4, 5, 90, 120, 80 };
// Pop elements from stack while stack is int n = price.length;
not int S[] = new int[n];
// empty and top of stack is smaller than calculateSpan (price, n, S);
// price[i] printArray(S);
while (!st.empty() && price[st.peek()] <=
price[i])
Question-10

Problem Statement:

Compute the nearest larger number by interchanging its digits updated. Given 2
numbers a and b find the smallest number greater than b by interchanging the digits
of a and if not possible print -1.
Question-10
Problem Statement:

Input Format
2 numbers a and b, separated by space.
Output Format
A single number greater than b.
If not possible, print -1
Constraints1 <= a,b <= 10000000
Question-10
Problem Statement:

Test Case #1
Sample 10-1
Input 459 500
Output 549
Test Case #2
Sample 10-2
Input
645757 457765
Output 465577
Solution
public static void main(String[] args)
import java.util.*; Scanner sc = new Scanner(System.in);
class Solution { int a = sc.nextInt();
public static TreeSet<Integer> list = new int b = sc.nextInt();
TreeSet <>(); static void smallestNumber String s = a + "'";
(String str, String ans) smallestNumber (s, "");
{ Iterator itr = list.iterator(); int res = -
if (str.length() == 0) 1;
{ while (itr.hasNext())
list.add (Integer.parseInt (ans)); {
return; int no = (Integer) itr.next();
} if (no > b)
for (int i = 0; i < str.length (); i++) {
char ch = str.charAt (i); res = no;
String ros = str.substring (0, i) + break;
str.substring (i + }
1); }
smallestNumber (ros, ans + ch); System.out.println (res);
} }
} }
Question-11

Problem Statement:

Given a string str, a partitioning of the string is a palindrome partitioning if every


sub-string of the partition is a palindrome. Determine the fewest cuts needed for
palindrome partitioning of the given string.

Your Task:
You do not need to read input or print anything, Your task is to complete the function
palindromicPartition() which takes the string str as the input parameter and returns
the minimum number of partitions required.

Expected Time Complexity: O(n*n) [n is the length of the string str]


Expected Auxiliary Space: O(n*n)

Constraints:
1 ≤ length of str ≤ 500
Question-11
Problem Statement:

Test Case #1

Input: str = "ababbbabbababa"


Output: 3
Explanation: After 3 partitioning substrings
are "a", "babbbab", "b", "ababa".

Test Case #2

Input: str = "aaabba"


Output: 1
Explanation: The substrings after 1
partitioning are "aa" and "abba".
Solution
Scanner sc = new Scanner(System.in);
import java.io.*; int a sc.nextInt();
import java.util.*; int b = sc.nextInt();
class Place{ String s = a + " ";
public static void main(String args[])throws smallclass Solution{
IOException static int palindromicPartition(String str)
} {
BufferedReader in = new BufferedReader(new int[][] dp = new
InputStreamReader(System.in)); int[str.length()+1][str.length()+1];
int t = Integer.parseInt(in.readLine()); for(int[] a: dp){
while(t-->0){ Arrays.fill(a,-1);
String str = in.readLine(); }
Solution ob = new Solution(); return solve(str, 0,str.length()-1, dp);
System.out.println(ob.palindromicPartition(s }
tr)); static int solve(String s, int i, int j,
} int[][] dp}{
} if(i>j)return 0;
} if(isPalindrome(s,i,j))return 0;
// Driver Code Ends if(dp[0]=-1)return dp[];
//User function Template for Java int res = Integer.MAX_VALUE;
public static void main(String[] args)
}
Solution
for(int k = i; k<j; k++){ return true;
int temp = 1+ solve(s,i,k,dp) + }
solve(s,k+1,j,dp); }
if(temp<res)res = temp; estNumber (s,"");
} Iterator itr = list.iterator();
return dp[][]=res; int res = -1; while (itr.hasNext())
} }
static boolean isPalindrome(String s, int i, int no =(Integer)itr.next();
int){ if (no> b)
if(i>j)return false; {
if(i == j)return true; res = no; break;
while(i<jX){ System.out.println(res);
if(s.charAt(i)!=s.charAt(j)){ }
return false; }
} }
i++; }
j--;
}

You might also like