Coding Questions (Accenture and Cognizant)
Coding Questions (Accenture and Cognizant)
1.Problem Description:
The Binary number system only uses two digits, 0 and 1 and the number system can be called 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 to right taking one
operation at a time, and return the same.
Input:
1C0C1C1A0B1
Output:
1
Python code:
def OperationsBinaryString(str):
a=int(str[0])
i=1
while i<len(str):
if str[i]=='A':
a&=int(str[i+1])
elif str[i]=='B':
a|=int(str[i+1])
else:
a^=int(str[i+1])
i+=2
return a
str=input()
print(OperationsBinaryString(str))
2.Problem Description:
The function accepts two positive integers ‘r’ and ‘unit’ and a positive integer array ‘arr’ of size ‘n’ as
its argument ‘r’ represents the number of rats present in an area,
‘unit’ is the amount of food each rat consumes and each ith element of array ‘arr’ represents the
amount of food present in ‘i+1’ house number, where 0 <= i.
Note:
Return -1 if the array is null.
Return 0 if the total amount of food from all houses is not sufficient for all the rats.
Computed values lie within the integer range.
Example:
Input:
r: 7
unit: 2
n: 8
arr: 2 8 3 5 7 4 1 2
Output:
4
Python code:
def calculate(r,unit,arr,n):
if n==0:
return -1
totalFoodRequired=r*unit
foodTillNow=0
house=0
foodTillNow+=arr[house]
break
return 0
return house+1
r = int(input())
unit = int(input())
n = int(input())
arr = list(map(int,input().split()))
print(calculate(r,unit,arr,n))
3.Problem Statement:
Note: In case there is no element in ‘arr’ whose absolute difference with ‘num’ is less than or equal
to ‘diff’, return -1.
Example:
Input:
arr: 12 3 14 56 77 13
num: 13
diff: 2
Output:
3
Python code:
count=0
for i in range(n):
if(abs(arr[i]-num)<=diff):
count+=1
if count:
return count
return 0
n=int(input())
arr=list(map(int,input().split()))
num=int(input())
diff=int(input())
Note:
Return -1 if array is empty or if n < 2
Return 0, if no such pairs found.
All computed values lie within integer range.
Example:
Input
sum:9
Arr:5 2 4 3 9 7 1
Output
2
Python code:
n = int(input())
sum1 = int(input())
if n < 2:
print('-1')
arr = sorted(arr)
for i in range(n-1):
print(arr[i] * arr[i+1])
break
else:
print('0')
5.Problem Statement:
N-base notation is a system for writing numbers that uses only n different symbols. These symbols
are the first n symbols from the given notation list(Including the symbol for o)
Decimal to n base notation are (0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:A,11:B and so on upto
35:Z).
Implement the following function
Char* DectoNBase(int n, int num):
The function accept positive integer n and num Implement the function to calculate the n-base
equivalent of num and return the same as a string
Steps:
Divide the decimal number by n,Treat the division as the integer division
The n-base value is the sequence of the remainders from last to first
Assumption:
1 < n < = 36
Example
Input
n: 12
num: 718
Output
4BA
Python code:
n = int(input())
num = int(input())
reminder = []
quotient = num // n
reminder.append(num%n)
while quotient != 0:
reminder.append(quotient%n)
quotient = quotient // n
reminder = reminder[::-1]
equivalent = ''
for i in reminder:
if i > 9:
a=i-9
a = 64 + a
equivalent+=chr(a)
else:
equivalent+=str(i)
print(equivalent)
6.Problem Statement:
A carry is a digit that is transferred to left if sum of digits exceeds 9 while adding two numbers from
right-to-left one digit at a time.
You are required to implement the following function.
Int NumberOfCarries(int num1 , int num2);
The function accepts two numbers ‘num1’ and ‘num2’ as its arguments. You are required to calculate
and return the total number of carries generated while adding digits of two numbers ‘num1’ and ‘
num2’.
Example:
Input
Num 1: 451
Num 2: 349
Output
2
Python code:
def NumberOfCarries(n1,n2):
count=0
carry = 0
l= len(n1)-1
else:
l = len(n2)-1
for i in range(l+1):
temp = int(n1[l-i])+int(n2[l-i])+carry
if len(str(temp))>1:
count+=1
carry = 1
else:
carry = 0
return count+carry
n1=input()
n2=input()
print(NumberOfCarries(n1,n2))
7.Problem Statement:
The function accepts a string ‘ str’ of length n and two characters ‘ch1’ and ‘ch2’ as its argument.
Implement the function to modify and return the string ‘ str’ in such a way that all occurrences of
‘ch1’ in the original string are replaced by ‘ch2’ and all occurrences of ‘ch2’ in the original string are
replaced by ‘ch1’.
Note:
Return null if the string is null.
If both characters are not present in the string or both of them are the same , then return the string
unchanged.
Example:
Input:
Str: apples
ch1:a
ch2:p
Output:
paales
Python code:
result = ''
if user_input != None:
return result
return 'Null'
user_input = input()
8.Problem Statement:
Loop between ‘a’ and ‘b’. Let the looping variable be ‘i’.
Find the exponent (power) of 2 for each ‘i’ and store the number with maximum exponent of
2 so far in a variable , let say ‘max’. Set ‘max’ to ‘i’ only if ‘i’ has more exponent of 2 than
‘max’.
Return ‘max’.
Assumption: a < b
Note: If two or more numbers in the range have the same exponents of 2 , return the small
number.
Example
Input:
7
12
Output:
8
Python code:
def countExponents(i):
count = 0
count+=1
i = i//2
return count
maximum, number = 0, a
for i in range(a,b):
temp = countExponents(i)
if temp>maximum:
return number
a, b = map(int,input().split())
print(maxExponents(a, b))
9.Problem Statement:
You are required to input the size of the matrix then the elements of matrix, then you have to divide
the main matrix in two sub matrices (even and odd)
in such a way that element at 0 index will be considered as even and element at 1st index will be
considered as odd and so on.
Then you have sort the even and odd matrices in ascending order then print the sum of second
largest number from both the matrices.
Example:
enter the size of array : 5
enter element at 0 index : 3
enter element at 1 index : 4
enter element at 2 index : 1
enter element at 3 index : 7
enter element at 4 index : 9
Sorted even array : 1 3 9
Sorted odd array : 4 7
7
Python code:
array = []
evenArr = []
oddArr = []
for i in range(0,n):
number = int(input("Enter Element at {} index:".format(i)))
array.append(number)
if i % 2 == 0:
evenArr.append(array[i])
else:
oddArr.append(array[i])
evenArr = sorted(evenArr)
oddArr = sorted(oddArr)
print(evenArr[1] + oddArr[1])
10.Problem Statement:
Note:
0 < m <= n
Example
Input:
m : 12
n : 50
Output
90
Python code:
m = int(input("M:"))
n = int(input("N:"))
sum = 0
for i in range(m,n+1,1):
print(sum)
calculate(m,n)
11.Problem Statement – Write a program to calculate the fuel consumption of your truck.The
program should ask the user to enter the quantity of diesel to fill up the tank and the distance
covered till the tank goes dry.Calculate the fuel consumption and display it in the format (liters per
100 kilometers).
Convert the same result to the U.S. style of miles per gallon and display the result. If the quantity or
distance is zero or negative display ” is an Invalid Input”.
[Note: The US approach of fuel consumption calculation (distance / fuel) is the inverse of the
European approach (fuel / distance ). Also note that 1 kilometer is 0.6214 miles, and 1 liter is 0.2642
gallons.]
The result should be with two decimal place.To get two decimal place refer the below-mentioned
print statement :
float cost=670.23;
Sample Input 1:
20
150
Sample Output 1:
Liters/100KM
13.33
Miles/gallons
17.64
Python code:
import sys
ltt =int(input())
lt= (ltt*1.00)
if(ltt<1):
sys.exit()
diss =int(input())
dis= (diss*1.00)
if(diss<1):
sys.exit()
hundred = ((lt/dis)*100)
print("Liters/100KM")
print(round(hundred,2))
miles = (dis*0.6214);
gallons =(lt*0.2642);
mg = miles/gallons;
print("Miles/gallons")
print(round(mg,2))
12.Problem Statement – Vohra went to a movie with his friends in a Wave theatre and during break
time he bought pizzas, puffs and cool drinks. Consider the following prices :
Rs.100/pizza
Rs.20/puffs
Rs.10/cooldrink
Sample Input 1:
Sample Output 1:
Bill Details
No of pizzas:10
No of puffs:12
No of cooldrinks:5
Total price=1290
Python code:
print("Bill details")
print("No of pizzas:{}".format(pizza_count))
print("No of puffs:{}".format(puffs_count))
print("No of cooldrinks:{}".format(drinks_count))
print("Total price={}".format(bill))
13.Problem Statement – Ritik wants a magic board, which displays a character for a corresponding
number for his science project. Help him to develop such an application.
For example when the digits 65,66,67,68 are entered, the alphabet ABCD are to be displayed.
[Assume the number of inputs should be always 4 ]
Sample Input 1:
Sample Output 1:
65-A
66-B
67-C
68-D
Python code:
a=int(input())
b=int(input())
c=int(input())
d=int(input())
print(str(a)+"-"+chr(a))
print(str(b)+"-"+chr(b))
print(str(c)+"-"+chr(c))
print(str(d)+"-"+chr(d))
14.Problem Statement – FOE college wants to recognize the department which has succeeded in
getting the maximum number of placements for this academic year. The departments that have
participated in the recruitment drive are CSE,ECE, MECH. Help the college find the department
getting maximum placements. Check for all the possible output given in the sample snapshot
Note : If any input is negative, the output should be “Input is Invalid”. If all department has equal
number of placements, the output should be “None of the department has got the highest
placement”.
Sample Input 1:
Sample Output 1:
Highest placement
CSE
Python code:
import sys
print("Input is Invalid")
sys.exit()
print("Highest placement")
m=max(cse,ece,mech)
if(cse==m):
print("CSE")
if(ece==m):
print("ECE")
if(mech==m):
print("MECH")
15.Problem Statement – In a theater, there is a discount scheme announced where one gets a 10%
discount on the total cost of tickets when there is a bulk booking of more than 20 tickets, and a
discount of 2% on the total cost of tickets if a special coupon card is submitted. Develop a program to
find the total cost as per the scheme. The cost of the k class ticket is Rs.75 and q class is Rs.150.
Refreshments can also be opted by paying an additional of Rs. 50 per member.
Hint: k and q and You have to book minimum of 5 tickets and maximum of 40 at a time. If fails
display “Minimum of 5 and Maximum of 40 Tickets”. If circle is given a value other than ‘k’ or ‘q’
the output should be “Invalid Input”.
Sample Input 1:
Sample Output 1:
Ticket cost:4065.25
Python code:
import sys
sys.exit(0)
if(circle== 'k'):
cost=75*noTicket
elif(circle== 'q'):
cost=150*noTicket
else:
print("Invalid Input")
sys.exit(0)
total=cost
if(noTicket>20):
total=cost
if(co== 'y'):
total= cost - ((0.02)*cost)
if(ref== 'y'):
total += (noTicket*50);
print("Ticket cost:{}".format(round(total,2)))
16.Problem Statement – Rhea Pandey’s teacher has asked her to prepare well for the lesson on
seasons. When her teacher tells a month, she needs to say the season corresponding to that month.
Write a program to solve the above task.
Month should be in the range 1 to 12. If not the output should be “Invalid month”.
Sample Input 1:
Sample Output 1:
Season:Autumn
Python code:
mon=int(input("Enter month"))
print("Season:Winter")
print("Season:Spring")
print("Season:Summer")
else:
print("Invalid month")
Write a java program to print all prime numbers in the interval [a,b] (a and b, both inclusive).
Note
Input 1 should be lesser than Input 2. Both the inputs should be positive.
If any of the condition mentioned above fails, then display “Provide valid input”
Sample Input 1:
15
Sample Output 1:
2 3 5 7 11 13
Python code:
a=int(input())
b=int(input())
else:
while(a<=b):
if(a==2):
print(a,end=" ");
elif(a==1):
a+=1
continue
else:
flag=0
for i in range(2,a//2+1):
if(a%i==0):
flag=1
break
if flag==0:
print(a,end=" ")
a+=1
18.Problem Statement – Goutam and Tanul plays by telling numbers. Goutam says a number to
Tanul. Tanul should first reverse the number and check if it is same as the original. If yes, Tanul
should say “Palindrome”. If not, he should say “Not a Palindrome”. If the number is negative, print
“Invalid Input”. Help Tanul by writing a program.
Sample Input 1 :
21212
Sample Output 1 :
Palindrome
Sample Input 2 :
6186
Sample Output 2 :
Not a Palindrome
Python code:
n=input()
if(int(n)<0):
print("Invalid Input")
elif(n==n[::-1]):
print("Palindrome")
else:
print("Not a Palindrome")
19.Problem Statement – XYZ Technologies is in the process of increment the salary of the
employees. This increment is done based on their salary and their performance appraisal rating.
1. If the appraisal rating is between 1 and 3, the increment is 10% of the salary.
2. If the appraisal rating is between 3.1 and 4, the increment is 25% of the salary.
3. If the appraisal rating is between 4.1 and 5, the increment is 30% of the salary.
Help them to do this, by writing a program that displays the incremented salary. Write a class
“IncrementCalculation.java” and write the main method in it.
Note : If either the salary is 0 or negative (or) if the appraisal rating is not in the range 1 to 5
(inclusive), then the output should be “Invalid Input”.
Sample Input 1 :
8000
Enter the Performance appraisal rating
Sample Output 1 :
8800
C code:
#include<stdio.h>
#include<stlib.h>
int main ()
int salary;
float rating;
exit (0);
else if (rating >= 1 && rating <= 3) { salary = salary + (10 * salary / 100); printf ("%d", salary); } else if
(rating > 3 && rating <= 4) { salary = salary + (25 * salary / 100); printf ("%d", salary); } else if (rating >
4 && rating <= 5)
{
salary = salary + (30 * salary / 100);
return 0;
20.Problem Statement – Chaman planned to choose a four digit lucky number for his car. His lucky
numbers are 3,5 and 7. Help him find the number, whose sum is divisible by 3 or 5 or 7. Provide a
valid car number, Fails to provide a valid input then display that number is not a valid car number.
Note : The input other than 4 digit positive number[includes negative and 0] is considered as invalid.
Sample Input 1:
Sample Output 1:
Lucky Number
C++ code:
#include <iostream>
#include<bits/stdc++.h>
int main ()
int n;
cin >> n;
if (n <= 0 or ! (digit == 4)) cout << n << " is not a valid car number";
else {
int sum = 0;
while (n > 0)
sum += n % 10;
n /= 10;
else
return 0;
21.Problem Statement –
IIHM institution is offering a variety of courses to students. Students have a facility to check whether
a particular course is available in the institution. Write a program to help the institution accomplish
this task. If the number is less than or equal to zero display “Invalid Range”.
Sample Input 1:
Enter no of course:
Java
Oracle
C++
Mysql
Dotnet
C++
Sample Output 1:
Python code:
import sys
n = int(input("Enter no of course"))
print("Invalid Range")
exit()
course=[]
for i in range(n):
course.append(input())
if search in course:
else:
22.Problem Statement – Mayuri buys “N” no of products from a shop. The shop offers a different
percentage of discount on each item. She wants to know the item that has the minimum discount
offer, so that she can avoid buying that and save money.
[Input Format: The first input refers to the no of items; the second input is the item name, price and
discount percentage separated by comma(,)]
Assume the minimum discount offer is in the form of Integer.
Note: There can be more than one product with a minimum discount.
Sample Input 1:
mobile,10000,20
shoe,5000,10
watch,6000,15
laptop,35000,5
Sample Output 1:
shoe
python code:
items = int(input())
itemList=[]
for i in range(items):
itemList.append(input().split(","))
list2=[]
for i in itemList:
i.append((int(i[1])*int(i[2]))//100)
list2.append(i[3])
result=[]
minimum = min(list2)
for i in itemList:
if i[3] == minimum:
result.append(i[0])
for i in result:
print(i)
23.Problem Statement – Raj wants to know the maximum marks scored by him in each semester.
The mark should be between 0 to 100 ,if goes beyond the range display “You have entered invalid
mark.”
Sample Input 1:
Enter no of semester:
90
98
76
67
89
76
Sample Output 1:
Python code:
list1=list()
for i in range(no_of_sem):
list1.append(list(range(int(input()))))
for i in range(no_of_sem):
for j in range(len(list1[i])):
list1[i][j]=int(input())
exit()
count = 1
for i in list1:
24.Problem Statement – Bela teaches her daughter to find the factors of a given number. When
she provides a number to her daughter, she should tell the factors of that number. Help her to do
this, by writing a program. Write a class FindFactor.java and write the main method in it.
Note :
If the input provided is negative, ignore the sign and provide the output. If the input is zero
Sample Input 1 :
54
Sample Output 1 :
1, 2, 3, 6, 9, 18, 27, 54
Python code:
x = abs(int(input()))
if x == 0:
print("No Factors")
exit()
if x % i == 0:
if i != x:
print(i,end=", ")
else:
print(i)
25.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:
Constraints:
Sample Input:
1234
Sample Output:
abcd
awd
lcd
c++ output:
#include<bits/stdc++.h>
string ss;
vector v;
//cout<<i<<s<ss.length()) return;
if(ss[i]=='0') return;
char c='a'+(ss[i]-'1');
fun(i+1,s+c);
if(i!=s.length()-1)
int a=(ss[i]-'1'+1),b=(ss[i+1]-'0');
c=('a'+(10*a+b-1));
//cout<<a<<b<>ss;
fun(0,"");
sort(v.begin(),v.end());
for(auto i:v)