TCS CODING QUESTIONS
TCS CODING QUESTIONS
Q1. Given an array of integers arr[], the task is to find the sum of all the Mersenne
numbers from the array. A number is a Mersenne number if it is greater than 0
and is one less than some power of 2. First few Mersenne numbers are 1, 3, 7, 15,
31, 63, 127, …
Examples:
Input: arr[] = {17, 6, 7, 63, 3}
Output: 73
Only 7, 63 and 3 are Mersenne numbers i.e. 7 + 63 + 3 = 73
Input: arr[] = {1, 3, 11, 45}
Output: 4
Q2. A party has been organised on a cruise. The party is organised for a limited
time(T). The number of guests entering (E[i]) and leaving (L[i]) the party at every
hour is represented as elements of the array. The task is to find the maximum
number of guests present on the cruise at any given instance within T hours.
Example 1: Input: 5 ---> Value of T [7,0,5,1,3] ---> E[], element of E[0] to E[N-1],
where input each element is separated by new line [1,2,1,3,4] -----> L[],element
of L[0] to L[N-1], where input each element is separated by new line Output: 8 ----
-> Maximum number of guests on cruise at an instance.
Explanation:
1st hour Entry: 7, Exit: 1 No. of guests on the ship: 6
2nd hour: 1 st hour Entry: 0, Exit: 2 No. of guests on the ship: 6 -2 = 4
Hour 3: Entry: 5, Exit: 1 No. of guests on the ship: 4 + 5 -1 = 8 Hour 4: Entry: 1,
Exit: 3 No. of guests on the ship: 8 + 1 - 3 = 6
Hour 5: Entry: 3, Exit: 4 No. of guests on the ship: 6 + 3 - 4 = 5 Hence, Maximum
Number of guests within 5 hours is 8.
Q3. Given an array Arr[] of size T, contains binary digits. Where 0 represents a
biker running to the north. 1 represents a biker running to the south.
The task is to count crossing bikers in such a way that each pair of crossing bikers
(N, S), where 0<=N<S<=N<S Number of elements i.e. T
0. -> Value of 1st element
1. -> Value of 2nd element
0. -> Value of 3rd element
1. -> Value of 4th element
1. -> Value of 5th element
Output: 5
Explanation: The 5 pairs are (Arr[0], Arr[1]), (Arr[0], Arr[3]), (Arr[0], Arr[4]),
(Arr[2], Arr[3]) and (Arr[2], Arr[4]).
Note that in all pairs first element is 0, second element is 1 and index of first
element is smaller than index of second element.
Q4. A family is about to break their piggy bank to use the money for different
purposes. The piggy bank here represents an array (arr[]) consisting of N coins.
The family has to split the coins of piggy bank into smaller stack (sub-array) of
coins such that the sum of the difference between the maximum value and the
minimum value of the coins for all the stacks (sub-arrays) is maximum.
Note: Each value of the array can be used only once that is only in one subarray.
Constraints: 1 <= N <= 500 1 <=arr[i] <= 100
Example 1:
Input: 5 → Value of N {8,1,7,9,2} → arr[] elements from arr[0] to arr [N-1], Where
each element is separated by new line.
Output: 14
Explanation: Let us break the array elements into following subarrays: 1. (8,1) →
Max:8 Min:1
2. (7,9,2) → Max:9 Min:2 So, the difference between the maximum and minimum
elements in each subarrays is
1. 8-1=7
2.9-2=7
Now, the sum of the differences of subarray is: 7+7=14 Hence, output is 14.
Q5. A carpet manufacturing industry has newly ventured into the carpet
installation business. All the carpets manufactured are large squares in shape. To
install, each carpet has to be cut into shapes of squares or rectangles. The number
of slits to be made is given as N. The task is to find the maximum number of equal
squares or rectangles that can be achieved using N slits. Note: The square carpet
can be cut only using horizontal or vertical slits. Cuttings are done on a single
carpet which should be rolled out completely i.e. no folding or stacking is allowed.
Squares or rectangles cut should be equal size.
Example 1:
Output:
Example 2:
Q6. A supermarket maintains a pricing format for all its products. A value N
printed on each product. When the scanner reads the value N on the item, the
product of all the digits in the value N is the price of the item. The task is to design
a software such that given the code of any item N the product(multiplication) of
all the digits of value should be computed(price).
Example 1:
Q7. Airport security officials have confiscated several items of the passenger at
the security checkpoint. All the items have been dumped into a huge box(array).
Each item possessed a certain amount of risk(0,1,2). Here is the risk severity of
the item representing an array[] of N number of integer values. The risk here is to
sort the item based on their level of risk values range from 0 to 2.
Example 1:
Example 2:
Q8. Given a non-negative integer array Arr having size N. Each element of the
array will carry a different value. This means no two elements can have the same
values. The candidate has to do this with minimal changes in the original value of
the elements, making every element as least as much value as it originally had.
Find the minimum sum of all elements that can be set the array for:
Example 1:
Output : 9
Explanation: As two elements have the same value, max value for the one of
them needs to be incremented to 3. He can set the array with 2+3+4=9
Explanation: Here N=2, so we need to provide value of only two elements but we
are providing value of three elements so result is “Wrong Input”
Q9. Joseph is learning digital logic subject which will be for his next semester. He
usually tries to solve unit assignment problems before the lecture. Today, he got
one tricky question. The problem statement is “A positive integer has been given
as an input. Convert decimal value to binary representation. Toggle all bits of it
after the most significant bit including the most significant bit. Print the positive
integer value after toggling all bits”.
Example 1
Example 2
Output: Wrong input → result - String Explanation: Given integer “101” is out of
range. Hence the output will print “Wrong input
Q10. Given a string S(input) consisting of * and #. The length of the string is
variable. The task is to find the minimum number of * and # required to make it a
valid string. The string is considered valid if the number of * and # are equal. The
* and # can be at any position in the string. Note: The output will be a positive or
negative integer based on number of * and # in the input string. (* > #) : Positive
integer (# > *) : Negative integer (#=*): 0
Example 1:
Example 2:
Example 3:
The input format for testing The candidate has to write the code to accept one
inputs separated by a new line. First input: Accept a string S without any spaces
(consisting of only * and #) The output format for testing The output should be a
positive integer number (check in e.g.s 1, 2 and 3). Additional messages in output
will cause the failure of test cases.
Q11. Gary is an avid hiker. He tracks his hikes meticulously, paying close attention
to small details like topography. During his last hike, he took exactly n steps. For
every step he took, he noted if it was an uphill or a downhill step. Gary’s hikes
start and end at sea level. We define the following terms:
Input Format
The first line contains an integer, , denoting the number of steps in Gary’s hike.
The second line contains a single string of characters. Each character belongs to
{U, D} (where U indicates a step up and D indicates a step down), and the i(th) cin
the string describes Gary’s i(th) step during the hike.
Constraints
Output Format
Print a single integer denoting the number of valleys Gary walked through during
his hike.
Sample Input
UDDDUDUU
Sample Output
Q12. Alex works at a clothing store. There is a large pile of socks that must be
paired by color for sale. Given an array of integers representing the color of each
sock, determine how many pairs of socks with matching colors there are.
For example, there are n=7 socks with colors ar = {1,2,1,2,1,3,2}. There is one pair
of color 1 and one of color 2. There are three odd socks left, one of each color.
The number of pairs is 2.
Function Description
Complete the sockMerchant function in the editor below. It must return an
integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers describing the
colors ar[i] of the socks in the pile.
Constraints
1 <= n <= 100
1 <= ar[i] <= 100 & 0 <= i < n
Output Format
Return the total number of matching pairs of socks that Alex can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
Explanation
Alex can match 3 pairs of socks i.e 10-10, 10-10, 20-20
while the left out socks are 50, 60, 20
Q13, Particulate b matters are the biggest contributors to Delhi pollution. The
main reason behind the increase in the concentration of PMs include vehicle
emission by applying Odd Even concept for all types of vehicles. The vehicles with
the odd last digit in the registration number will be allowed on roads on odd dates
and those with even last digit will on even dates.
Given an integer array a[], contains the last digit of the registration number of N
vehicles traveling on date D(a positive integer). The task is to calculate the total
fine collected by the traffic police department from the vehicles violating the
rules.
Example 1:
Input :
4 -> Value of N
{5,2,3,7} -> a[], Elements a[0] to a[N-1], during input each element is separated by
a new line
Explanation:
Find will be collected from 5,3 and 7 with an amount of 200 each.
The president and prime minister of India will always sit next to each other.
Example 1:
Input :
Output :
Explanation:
Rest of the members can be arranged in (4-1)! ways.(1 is subtracted because the
previously selected two members will be considered as single members now).
So total possible ways 4 members can be seated around the circular table 2*6=
12.
Q15. An intelligence agency has received reports about some threats. The reports
consist of numbers in a mysterious method. There is a number “N” and another
number “R”. Those numbers are studied thoroughly and it is concluded that all
digits of the number ‘N’ are summed up and this action is performed ‘R’ number
of times. The resultant is also a single digit that is yet to be deciphered. The task
here is to find the single-digit sum of the given number ‘N’ by repeating the action
‘R’ number of times.
Example 1:
Input :
99 -> Value of N
3 -> Value of R
Output :
Q16. There are two banks – Bank A and Bank B. Their interest rates vary. You have
received offers from both banks in terms of the annual rate of interest, tenure,
and variations of the rate of interest over the entire tenure.You have to choose
the offer which costs you least interest and reject the other. Do the computation
and make a wise choice.
Constraints:
Explanation:
Example 1
o Input
o 10000
o 20
o 3
o 5 9.5
o 10 9.6
o 5 8.5
o 3
o 10 6.9
o 5 8.5
o 5 7.9
Output: Bank B
Q17. At a fun fair, a street vendor is selling different colours of balloons. He sells
N number of different colours of balloons (B[]). The task is to find the colour (odd)
of the balloon which is present odd number of times in the bunch of balloons.
Note: If there is more than one colour which is odd in number, then the first
colour in the array which is present odd number of times is displayed. The colours
of the balloons can all be either upper case or lower case in the array. If all the
inputs are even in number, display the message “All are even”.
Example 1:
7 -> Value of N
[r,g,b,b,g,y,y] -> B[] Elements B[0] to B[N-1], where each input element is
sepārated by ṉew line.
Output :
r -> [r,g,b,b,g,y,y] -> “r” colour balloon is present odd number of times in
the bunch.
Explanation:
r: 1 balloon
g: 2 balloons
b: 2 balloons
y : 2 balloons
Example 2:
Input:
10 -> Value of N
[a,b,b,b,c,c,c,a,f,c] -> B[], elements B[0] to B[N-1] where input each element
is separated by new line.
Output :
b-> ‘b’ colour balloon is present odd number of times in the bunch.
Explanation:
a: 2 balloons
b: 3 balloons
c: 4 balloons
f: 1 balloons
Here, both ‘b’ and ‘f’ have odd number of balloons. But ‘b’ colour balloon occurs
first.
Q18. There is a JAR full of candies for sale at a mall counter. JAR has the capacity
N, that is JAR can contain maximum N candies when JAR is full. At any point of
time. JAR can have M number of Candies where M<=N. Candies are served to the
customers. JAR is never remain empty as when last k candies are left. JAR if
refilled with new candies in such a way that JAR get full.
Write a code to implement above scenario. Display JAR at counter with available
number of candies. Input should be the number of candies one customer can
order at point of time. Update the JAR after each purchase and display JAR at
Counter.
Output should give number of Candies sold and updated number of Candies in
JAR.
If Input is more than candies in JAR, return: “INVALID INPUT”
K =< 5, where k is number of minimum candies that must be inside JAR ever.
Input Value
o 3
Output Value
o NUMBER OF CANDIES SOLD : 3
o NUMBER OF CANDIES AVAILABLE : 7
Input Value
o 0
Output Value
o INVALID INPUT
o NUMBER OF CANDIES LEFT : 10
Q19. AA washing machine works on the principle of Fuzzy System, the weight of
clothes put inside it for washing is uncertain But based on weight measured by
sensors, it decides time and water level which can be changed by menus given on
the machine control area.
For low level water, the time estimate is 25 minutes, where approximately weight
is between 2000 grams or any nonzero positive number below that.
For medium level water, the time estimate is 35 minutes, where approximately
weight is between 2001 grams and 4000 grams.
For high level water, the time estimate is 45 minutes, where approximately
weight is above 4000 grams.
Write a function which takes a numeric weight in the range [0,7000] as input and
produces estimated time as output is: “OVERLOADED”, and for all other inputs,
the output statement is
“INVALID INPUT”.
<Integer>
Example:
Input value
2000
Output value
Q20. A chocolate factory is packing chocolates into the packets. The chocolate
packets here represent an array arrt of N number of integer values. The task is to
find the empty packets(0) of chocolate and push it to the end of the conveyor
belt(array)
For Example:
There are 3 empty packets in the given set. These 3 empty packets represented as
O should be pushed towards the end of the array
Example 1:
Input:
7 – Value of N
Output:
4519500
Example 2:
Input:
— Value of N.
Output:
618200
Q21. Among these, Varahamihira was an astrologer of eminence and his book
Brihat Jataak is recokened as the ultimate authority in astrology.
He was once talking with Amarasimha,another gem among the nava ratnas and
the author of Sanskrit thesaurus, Amarakosha.
Amarasimha wanted to know the final position of a person, who starts from the
origin 0 0 and travels per following scheme.
… And thus he travels, every time increasing the travel distance by 10 units.
Test Cases
Case 1
Input : 3
Expected Output :-20 20
Case 2
Input: 4
Expected Output: -20 -20
Case 3
Input : 5
Expected Output : 30 -20
Given a maximum of 100 digit numbers as input, find the difference between the
sum of odd and even position digits
Test Cases
Case 1
Input: 4567
Expected Output: 2
Explanation : Odd positions are 4 and 6 as they are pos: 1 and pos: 3, both have
sum 10. Similarly, 5 and 7 are at even positions pos: 2 and pos: 4 with sum 12.
Thus, difference is 12 – 10 = 2
Case 2
Input: 5476
Expected Output: 2
Case 3
Input: 9834698765123
Expected Output: 1
Q23. One programming language has the following keywords that cannot be used
as identifiers:
break, case, continue, default, defer, else, for, func, goto, if, map, range, return,
struct, type, var
Test cases
Case 1
Input – defer
Expected Output – defer is a keyword
Case 2
Input – While
Expected Output – while is not a keyword
Q24. 1. The program will recieve 3 English words inputs from STDIN
1. These three words will be read one at a time, in three separate line
2. The first word should be changed like all vowels should be replaced by *
3. The second word should be changed like all consonants should be replaced
by @
4. The third word should be changed like all char should be converted to
upper case
5. Then concatenate the three words and print them
Case 1
Input
how
are
you
Case 2
Input
how
999
you
Q25. A doctor has a clinic where he serves his patients. The doctor’s consultation
fees are different for different groups of patients depending on their age. If the
patient’s age is below 17, fees is 200 INR. If the patient’s age is between 17 and
40, fees is 400 INR. If patient’s age is above 40, fees is 300 INR. Write a code to
calculate earnings in a day for which one array/List of values representing age of
patients visited on that day is passed as input.
Note:
Q26. Consider the following se ries: 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729,
128, 2187 …
This series is a mixture of 2 series – all the odd terms in this series form a
geometric series and all the even terms form yet another geometric series. Write
a program to find the Nth term in the series.
The value N in a positive integer that should be read from STDIN. The Nth term
that is calculated by the program should be written to STDOUT. Other than value
of n th term,no other character / string or message should be written to
STDOUT. For example , if N=16, the 16th term in the series is 2187, so only value
2187 should be printed to STDOUT.
You can assume that N will not exceed 30.
Q27. Jack and Jill are playing a string game. Jack has given Jill two strings A and
B. Jill has to derive a string C from A, by deleting elements from string A, such that
string C does not contain any element of string B. Jill needs help to do this task.
She wants a program to do this as she is lazy. Given strings A and B as input, give
string C as Output.
Example 1:
Input:
tiger -> input string A
ti -> input string B
Output:
ger -> Output string C
Explanation:
After removing “t” and “i” from “tiger”, we are left with “ger”.
So, the answer is “ger”.
Example 2:
Input:
processed -> input string A
esd -> input string B
Output:
proc -> Output string C
Explanation:
After removing “e” “s” and “d” from “processed”, we are left with “proc”.
So, the answer is “proc”.
For example:
Suppose n1=11 and n2=15.
There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have
no repeated digits. So, the output is 4.
Example1:
Input:
11 — Value of n1
15 — value of n2
Output:
4
Example 2:
Input:
101 — value of n1
200 — value of n2
Output:
72
Q30. We want to estimate the cost of painting a property. Interior wall painting
cost is Rs.18 per sq.ft. and exterior wall painting cost is Rs.12 per sq.ft.
Take input as
1. Number of Interior walls
2. Number of Exterior walls
3. Surface Area of each Interior 4. Wall in units of square feet
Surface Area of each Exterior Wall in units of square feet
If a user enters zero as the number of walls then skip Surface area values as
User may don’t want to paint that wall.
6
3
12.3
15.2
12.3
15.2
12.3
15.2
10.10
10.10
10.00
Total estimated Cost : 1847.4 INR
Q31. Given an array of integers where every element appears even number of
times except one element which appears odd number of times, write a program
to find that odd occurring element in O(log n) time. The equal elements must
appear in pairs in the array but there cannot be more than two consecutive
occurrences of an element.
For example :
232
1122233
22311
Input Format :
The first line contains the number of test cases T, T lines follow.
Each line then contains an integer N, the total number of people attended that
meeting.
Output Format :
Constraints :
Sample Input :
Output :
Explanation :
Q34. You have write a function that accepts, a string which length is “len”, the string
has some “#”, in it you have to move all the hashes to the front of the string and return
the whole string back and
print it.
Example :
Input:
Move#Hash#to#Front
Output:
###MoveHashtoFront
Q35. You have two numbers number1 and number2, your job is to check the number of
borrow operations needed for subtraction of number1 from number2. If the subtraction
is not possible
then return the string not possible.
Example :
754
658
Answer :
2
654
666
Answer:
Not possible