InfyTQ Exam Coding Questions 2022: 100+ Coding and Programming Questions with Solutions
It is a certification exam organized by Infosys. This will get you a professional certification in python programing from Infosys that will be valid for a lifetime. The candidate has to score a minimum of 75% to get the certificate. And candidates who scored more than 65% were eligible for the spot interview for the role of System Engineer. Furthermore, rounds will be conducted for the Power Programmer profile.
Round 1: It was an online round consisting of 20 MCQs and 2 Handson questions(coding). MCQs were based on the database, Python, OOPS. And Handson questions were quite easy but the coding has to be done in Python 3.
Candidates who scored more than 65% were shortlisted for round 2.
Round 2: In this round basic HR questions were asked like why do you want to join Infosys? What are your hobbies? The situationconflict questions, etc.
Join Telegram Channel 

Infytq coding questions and answers
1. Concatenation
Input: a string of comma separated numbers. The numbers 5 and 8 are present in the listAssume that 8 always comes after 5.
Case 1: num1 = add all numbers which do not lie between 5 and 8 in the input.
Case 2: num2= numbers formed by concatenating all numbers from 5 to 8.
Output: sum of num1 and num2
Example: 1) 3,2,6,5,1,4,8,9
Num1 : 3+2+6+9 =20
Num2: 5148
output: 5248+20 = 5168
Answer: 13
# input the array array = list(map(int,input().split(","))) # add all numbers which do not lie between 5 and 8 input number1 = sum(array[:array.index(5)]) + sum(array[array.index(8) + 1:]) # numbers lie between 5 and 8 l = array[array.index(5):array.index(8) + 1] # Initialization the number2 number2 = "" # concatenate all number present in array 1 for i in l: number2 += str(i) # output: number1 + number2 print(int(number2) + number1)
Note: Please recheck and compare the code after copying it.
2. Distinct subarray
Number of odd sub arrays. Find the number of distinct subarrays in an array of position integers such that the sum of the subarray is an odd integer, two subarrays are considered different if they either start or end at different index.
Input:
1
3
1 2 3
Output:4
Explanation: subarrays [[1, [1, 2) [1, 2, 3], [2], [2, 3], [3]]
Answer: 16
#itertools library is use for Permutation and Combination import itertools n1 = int(input()) n2 = int(input ()) #generate array from n1 to n2 array = [i for i in range(n1,n2+1)] print(array) ll = [array[i:j+1] for i in range(lem(array)) for j in range(i,len(array))] print(ll) c=0 for i in ll: if sum(i)%2!=0: c+=1 print(c)
Note: Please recheck and compare the code after copying it.
3. Palindrome
Write a python function nearest_palindrome ()
Which can accepts a number and return the nearest greater palindrome number.
Input: 12300 > output: 12321
Input: 12331 > output: 12421
Answer: 13
#define function def nearest_palindrome(n): while True: rev = int(str(n)[::1]) if rev==n: return int(n) n+=1 #give input n = int(input()) nearest_palindrome(n)
Note: Please recheck and compare the code after copying it.
4. Parenthesis matching
A non empty string instr containing only parenthesis (,),{.},[,] it return outstr based on following,
– instr is properly nested and return 0
– instr not properly nested, return position of element in instr
– position start from 1
Input: {([])} Output: 0
Input: (])()] Output: 3
Input: [[()] Output: n+1 for last element i.e 5+1=6
Answer: 24
st=[] ope =['[','{','('] close =[']',"}",")"] # define function def check(s): for i in range(len(s)): if s[i] in ope: st.append(s[i]) elif s[i] in close: last = close.index(s[i]) if (len(st) > 0) and (ope[last] == st[len(st)  1]) : st.pop() else: return("at position ",i+1) if len(st) == 0: return 0 else: return len(s)+1 #give the input s = input () print(check(s))
Note: Please recheck and compare the code after copying it.
5. Sum of factor
For a given list of numbers find the its factors and add the factors then if the sum of all factor is present in original list, sort it and print it
Ex:
Input: 0,1,6
Factors: 0 = 0, sum =0
1 = 1, sum =1
6 =1,2,3 = sum =6
Output: 1,6
If the sum is not present in the list then return 1.
Answer: 20
#define function def factor(n): s=0 if n==1: return 1 for i in range(1,n): if n%i==0: s+=i return s #give input list1 = list(map(int,input().split (","))) flag=0 for i in list1: if factor (i) in list1: flag=1 print(i) #if sum is not present if flag==0: print(1)
Note: Please recheck and compare the code after copying it.
6. Maximum subarray
An array is given suppose a =[3,5,8,2,19,12,7,11]
One have to find the largest subarray that the element satisfy the following condition
x[i]=x[i1]+x[i2]
If more than one substring if found then largets one has to print the array which starts with the minimum elements and if they are also same then the array with minimum second element and so on.
Here the subarrays 2,3,5,8],[3,8,11],[5,7,12,19]
Expected is [2,3,5,8]
Answer: 14
#input the array array = list(map(int,input(). split(","))) array=sorted(array) j = [] j.append(array[0]) j.append(array[1]) for i in range(2,len(array)): if j[i1]+j[i2] in array: j.append(j[i1]+j[i2]) else: break print(j)
Note: Please recheck and compare the code after copying it.
Got the Top MNC’s Previous Year Question Papers with Detailed Solution
Check the 300+ Most Common Interview Questions & Answers
7. Special string reverse
special string reverse
Input Format: b@rd
output Format: d@rb
Explanation:
We should reverse the alphabets of the string by keeping the special characters in the same position.
Answer: 15
#s is input string s = input() # d is dictionary d = dict() rev="" for i in range(len(s)): if s[i].isalnum()==False: d.update({i:s[i]}) else: rev+=s[i] rev = list(rev[::1]) for i ,j in d.items(): rev.insert(i,j) print("".join(rev))
Note: Please recheck and compare the code after copying it.
8. Special character out
Write a python program that it should consist of special charnumbers and chars. if there are even numbers of special chars Then the series should start with even followed by odd
Input: 19@a42&516
Output: 492561
If there are odd numbers of special chars then the output will be starting with odd followed by even
Input: 5u6@25g7#@
Output: 56527
If there are any number of additional digits append them at last
Answer: 36
#s is input of string s = input () c=0 even = [] odd = [] for i in s: if i.isalnum(): c+=1 if i.isdigit(): if int(i)%2==0: even.append(i) else: odd.append(i) if c%2==0: if len(even) > len(odd): t = len(odd) out = even else: t=len(even) out=odd for i in range(t): print("{}{}".format(even[i],odd[i],end="") for j in out[t:]: print(j,end="") else: if len(even) > len(odd): t = len(odd) out = even else: t=len(even) out = odd for i in range(t): print("{}{}".format(odd[i],even[i]),end="") for j in out[t:]: print(j,end="")
Note: Please recheck and compare the code after copying it.
9. Password generation
Given input of array of string in format <emnp name> <emp number> separated by comas ,Emp
should contain only alphabets and employee number. You have to generate password for
Ex:
input: Robert: 36787, Tina: 68721, Jo:56389
Output: tiX
Conditions: len of robert is 6 and 6 is present in emp number
robert (36787), so return the alphabet at position 6 that is t.
Now len of tina is 4 and 3 is not present in the 68721 so select the number which is max and less than the len of tina so select 2 return the alphabet that is at position 2 that is i.
Now In of Jo is 2 it is not present in 56389 and there is not present any number which is less than 2 so return X.
Answer: 21
#s is string s = input().split (",") print(s) stt=[] numm=[] for i in s: s1,n = i.split(":") stt.append(s1) numm.append(n) print(stt) print(numm) def pas(ss,n): l=len(ss) while l!=0: if str(1) in n: return ss[l1] else: l=1 return "X" for i in range(len(numm)): print(pas(stt[i],numm[i]),end="")
Note: Please recheck and compare the code after copying it.
10. Even number
A string which is a mixture of letter and integer and special char from which find the largest even number from the available digit after removing the duplicates.
If an even number is not formed then return1.
Ex: infosys@337
O/p:1
Hello#81@21349
O/p:983412
Answer: 23
input1="infosys@335 " #initialization the set set1=set() for i in input1: if(i.isdigit()): set1.add(int(i)) s1=sorted(set1,reverse=True) def largestEven(list1): if s1[1]%2==0 or s1[1]==0 : return s1 else: for j in range(1,len(list1)+1): if s1[j]%2==0 or s1[j]==0: even=s1.pop(j) s1.append(even) return s1 else: return 1 gestEven(set1)
Note: Please recheck and compare the code after copying it.
InfyTQ Exam Coding Questions 2022
11. Number sequence
Input: a string of comma separated numbers. The numbers 5 and 8 are present in the list Assume
that 8 always comes after 5.
Case 1: num 1 = add all numbers which do not lie between 5 and 8 in the input.
Case 2: num2= numbers formed by concatenating all numbers from 5 to 8.
Output: sum of num1 and num2
Example: 1)3,2,6,5,1,4,8,9
Num1: 3+2+6+9 =20
Num2: 5148
O/p=5248+20=5168
Answer: 12
#give input to array array = list(map(int,input().split(","))) num1 = sum(array[:array.index(5)])+sum(array[array.index(8)+1:]) print(num1) l = array[array.index(5):array.index(8)+1] num2 = "" for i in l: num2+=str(i) #print sum of num2 & num1 print(int(num2)+num1)
Note: Please recheck and compare the code after copying it.
12. Matrix problem
Read m’m>4
N=m+!
Take m*n matrix
If any num is consecutive for 3 times either in a row, column, diagonals print the num, if there multiple num print min of those num
Ex: m=6 take 6*7 matrix
2 3 4 5 6 2 4 3
2 3 4 7 6 7 6 2
2 3 5 5 5 5 2 5
2 3 1 1 2 1 3 6
1 1 1 1 9 0 3 5
2 3 1 1 5 1 2 7
O/p=1
Answer: 26
#insert number of row row = int(input()) mat =[] #insert all value of each row for i in range(row): mat.append(list(map(int,input().split()))) print(mat) col= len (mat[0]) Out=[] for r in range (row): for c in range(col2): if mat[r]==mat[r]==mat[r]: out.append(mat[r]) for r in range(row2): for c in range(col): if mat[r]==mat[r+1]==mat[r+2]: out.append(mat[r]) for r in range(row2): for c in range(col2): if mat[r]==mat[r+1]==mat[r+2]: out.append(mat[r]) print(out) Print(min(out))
Note: Please recheck and compare the code after copying it.
13. String rotation
Input rhdt:246, ghftd:1246
Expl: here every string is associated with the number sep by : if sum of squares of digits is even then rotate the string by 1 if square of digits
is odd then rotate the string left by 2 position 2*2+4*4+6*6=56 which is even so rotate rhdt >trhd 1*1+2*2+4*4+6*6=57 which is odd then
rotate string by 2 at left ‘ghftd”
o/p: ftdgh
Answer: 20
#s is input of string s = input().split(",") stt=[] numm=[] for i in s: s1,n = i.split(":") stt.append(s1) numm.append(n) def rotate(ss,n): n = list(str(n)) s =0 print(n) for i in n: s+=int(i)**2 if s%2==0: return ss[1:]+ss[:1] #right rotation else: return ss[2:]+ss[:2] #left rotation for i in range(len(numm)): print(rotate(stt[i],numm[i]))
Note: Please recheck and compare the code after copying it.
14. Pronic number
Input: 93012630
Output2,6,12,30,930,
We should divide the total number into substrings and we should verify each num is pronic num or not if pronic we should print that num
Pronic: means it is a multiple of two consecutive integers
Ex: 6>2*3 it’s a pronic
12>3*4 it’s a pronic
Input: 12665042
Output: 2,6,12,42,650
Answer: 14
#define pronic function def pronic(n): for i in range(1,(n//2)+1): if i*(i+1)==n: return True return False x = input() ara = [x[i:j+1]for i in range(len(x)) for j in range(i,len(x))] final =set() for i in ara: if pronic(int(i)): final.add(int(i)) print(sorted(final))
Note: Please recheck and compare the code after copying it.
15. Longest palindrome
Find the longest palindrome from a string
Input: moomso
Possible cases
Moom, mom, oso, 000, omo
Longest is moom so output: moom
Answer: 12
# s is input of string s = input() #generating substring ara = [s[i:j+1] for i in range(len(s)) for j in range(i,len(s))] l=0 out="" for i in ara: rev= i[::1] if i == rev and len(i)>l: l=len(i) out=i print(out)
Note: Please recheck and compare the code after copying it.
16. OTP Generation
Input Format: 13456
Output Format:1925
Explanation:
Take the string of numbers and generate a four digit OTP such that
1. 1f the number is odd square it.
2.If the number is even ignore it.
Answer: 10
#otp generation n=input() s="" for i in n: if int(i)%2==0: continue else: s+=str(int(i)**2) print(s[:4])
Note: Please recheck and compare the code after copying it.
17. Unique substring
A string is given we have to find the longest substring which is unique (that has no repetition ) and min size is 3.
If more than one sub string is found with max length the we have to print one which appered first in thw string
If no substring is present which matches the condition then we have to print 1;
Ex input: A@bcd1abx”
Output: “A@bcd1
Answer: 9
# unique substring s = input() b="" for i in range(len(s)): if s[i].lower() in b or s[i].upper() in b: break else: b+=s[i] print(b)
Note: Please recheck and compare the code after copying it.
InfyTQ Exam Coding Questions
1) What will be the output of the code below?
class ClassA:
def _init_(self, val1) :
self.value = val1
def method_a(self) :
return 10+self.value
class ClassB:
def _init_(self, val2):
self. num=val2
def method_b(self, obj):
return obj.method_a()+self.num
obj1=ClassA(20)
obj2=ClassB(30)
print(obj2.method_b(obj1))
a) 60
b) 50
c) 30
d) 40
2) Consider the relational schema along with the functional dependencies given below:
gaming (garnename, gametype, amount, playerno, playername, playertype, discount, duration)
playerno > playername, playertype, discount
gamename > gametype, duration, amount
playertype > discount
How many tables will result when the relation is in 3NF?
a) 2
b) 4
c) 3
d) 1
3) Consider the Hashing methods given below:
i) h(key) = key%10
ii) h(key) = key%25
iii) h(key) = key%50
Which of the hashing methods would NOT lead to collision when the following values are to be stored in the hash table?
80, 20, 35, 45, 25, 90
a) Only
b) Both ii) and iii)
c) Both i) and iii)
d) All i), ii) and iii)
4) Number 14 needs to be searched using BINARY SEARCH in the following sorted list of numbers:
1, 3, 7.9, 14, 19, 45
How many comparisons will be required to conclude that the number 14 is found at the 5th position?
Note: We have used integer division for finding the middle element and the index starts with 0 (zero)
a) 2
b) 3
c) 4
d) 1
5) Consider a Patient table with attributes patientid (primary key), patientname, city, dateofbirth, and phone. Except patientid no columns are unique. The table has three indexes as follows:
IDX1 – patientid
IDX2 – patientname, dateofbirth
IDX3 – gateofbirth, phone
Which of the following queries will result in INDEX UNIQUE SCAN?
a) WHERE city <> ‘Mumbai’ AND dateofbirth > ’30Mar1995′
b) WHERE patientid = ‘P1007′ AND dateofbirth ’30Mar1995’
c) WHERE patientname = ‘Sam’ AND dateofbirth = ’30Mar1995′
d) WHERE patientname LIKE ‘R%’
6) Take a string as a input. Separate all the integers from it. Then take each integers only once and form the largest even number possible. Print the largest possible even number. And if even number can’t be made, then print 0.
Consider 0 as even number.
sample input:
QWert@821142
sample output:
8412
Explanation: integers present are 8,2,1,1,4,2. Distinct integers are 8214, therefore largest possible even number is 8412
7) Take m(number of rows) and n(number of column) as input. Then there will be m lines of input each consisting of n integers separated by space.
Check for contiguous present of an integers at least 4 times. They can be contiguous present in either row or column or diagonal. And then print the smallest integer other wise print 1 if above conditions not followed.
sample input:
6 8
4 5 6 4 4 4 4 1
2 3 3 1 6 9 7 4
2 1 3 4 7 9 4 2
2 2 4 3 7 8 9 6
2 8 4 5 3 1 9 7
2 4 2 1 7 2 2 2
sample output:
2
Explanation: integers 4,3,2 are contiguous present in row, diagonal,column at least 4 times. Among them 2 is the smallest.
Infytq previous coding questions
Coding Task 1:
Write a C program to print the first half of an array at last and last half of the array at first. Input format: Firstline contains the size of the array. The second line contains elements of array separated by space. Output Format: Modified Array Sample Input If n = odd 5 12345 Expected Output: 45312 Sample Input If n = even 6 146235 Expected Output: 235146

Coding Task 2:
Write a program to remove the given word from the input string. If the substring is not present in the input string, then print the input string as is. Input Format: Firstline consists of the sentence. Second line consists of the words which we want to remove from the given sentence. Output Format: Sentence after the given word is removed. 
Infytq previous coding questions
Question on strings
First Program
Input will be given like 4365188 Example : seoerate odd place Integers :: 3,5,8 You have to return a 4 digit OTP by squaring the digits. Digits from above example is 3,5,8 Square of those numbers is 9,25,65 So the otp to be returned is first four digits 9256 “”” num = input(“enter Number:”) a = list(map(int,str(num))) b = a[1::2] c = [] for i in b: i=i*i c.append(i) s=[str(i) for i in c] k=int(“”.join(s)) q=list(map(int,str(k))) w=q[0:4] l=[str(i) for i in w] j=int(“”.join(l)) print(j) 
First program
Input will be given like 4365188
Example : seoerate odd place Integers :: 3,5,8 You have to return a 4 digit OTP by squaring the digits. Digits from above example is 3,5,8 Square of those numbers is 9,25,65 So the otp to be returned is first four digits 9256 
Second program
A string will be given combination of letters and special characters. You have to return a reversed string keeping the special characters at the same place
Example : sd&hg#j Answer to be returned is : jg&hd#s 
Q) Input type String. Output type number. Print out the maximum even number which can be generated by making combinations of numbers present in the given string. Each number can be used only once ie. No Redundancy.
Example 1
Input String = Infytq@218412 Intermediate step (List of numbers *//redundancy removed*) = [2,1,8,4] Output Number = 8412 
Example 2
Input String = someString&337 Intermediate step (List of numbers *//redundancy removed*) = [3,7] Output Number = 1 
Question on Matrix
Q) Input a matrix. Check if do we get the same number consecutively at least 4 times in any fashion (Vertical, Horizontal, Diagonal). Record those sets.
If we get such multiple sets then print the number which is the least one
If we get such a single set then print the same number
If we get such no set then print 1
Example 1
Input m x n. Let’s take 1 3 3 3 3 9 1 6 9 2 3 9 1 2 2 5 4 9 2 2 4 5 7 9 2 4 5 6 7 2 Sets we get here [3 3 3 3] horizontally in the first line, [9 9 9 9] vertically in the last column,[2 2 2 2] diagonally. Hence, we’ll print min(3,9,2) = 2 here. 
Example 2
Input m x n. Let’s take 1 2 3 7 4 5 5 8 6 6 6 6 9 1 3 4 Sets we get here [6 6 6 6] only horizontally in 3rd row. Hence, we’ll print 6 here. 
Example 3
Input m x n. Let’s take 1 2 3 4 5 6 7 8 9 1 2 3 3 2 1 4 So we get NO set here. Hence, we’ll print 1 here. 
Infytq Coding questions
Handson questions basically test your logic and basic data structures.
Study Lists, Tuples, Dictionaries, Regex and Arrays very thoroughly.
First program:
For a given list of numbers, find its factors and add the factors. Then if the sum of factors is present in the original list, sort it and print it. Example: Input: 0,1,6 Factors of 0 = 0. Thus sum = 0 Factors of 1 = 1. Thus sum = 1 Factors of 6 = 1,2,3. Thus sum = 6 Output = 1,6 If the sum numbers are not present in original list, then return 1. 
Second Program:
Maximum number of swaps will be given and a list of digits will be given. We have to swap numbers to get the lowest number possible by using all digits from the list. 
Question on Password Generation
Given input of array of string in format <employee name>:<employee number> separated by comas. Employee name should contain only alphabets and employee number should contain only number.
You have to generate password. For example, you give input Robert:36787, Tina:68721, Jo:56389 Output: tiX Condition: Length of robert is 6 and 6 is present in employee number of robert(36787), so return the alphabet at position 6 that is t. Now, the length of Tina is 4 and 4 is not present in 68721,so select the number which is maximum and less than length of Tina so select 2, return the alphabet that is at position 2, return i. Now the length of Jo is 2 and it is not in 56389, and there is not any number which is less than 2, so return “X”. The main confusion was about how to give input. The format was employeename:employeenumber, employeename:employeenumber. 
Sample Problems
Problem 1
Input – Non empty string containing only these characters – (,),[,],{,} Output – Check if the string is properly nested. If yes print ‘0’. If not, — If it is found before completely traversing the string, print the index at which it is wrong. — If it is found after completely traversing the string, print the ‘string length+1’ Important Note – String index starts from 1. Example test cases – 1. Input – {[()]{}} Output – 0 #As the string is properly nested, we print ‘0’ 2. Input – {[}() Output – 3 #At index 3 we encounter ‘}’ but it fails the condition, #hence the index is printed. 
Problem 2
Input – A nonempty string containing only alphabets Output – Check if there are any prefix and suffix in the string, such that, they are equal.The prefix and suffix should not overlap. If found, — Print the length of the largest prefix/suffix If not found, — Print ‘1’ Important Note – Problem is case sensitive. Example Test cases – 1. Input – xxAbxxAbxx Output – ‘2’ #we get 3 strings here, ‘x’, ‘xx’, ‘xxAbxx’. But as the last string overlaps, we consider ‘xx’, and print 2 2. Input – Racecar Output – ‘1’ #As there is no prefix we print ‘1’ 
Problem 3
Input – A string of numbers Output – Check if the number is palindrome. If it is, print it’s length. If not, ( get the reverse of the string, add it to the original string, and check again). Repeat until a palindrome is generated. Example Test cases – 1. Input – 145, Output – 3. #145 is not palindrome. Add 145+541=686, which is a palindrome. Hence print it’s length, 3 2. Input – 4, Output – 1. # 4 is a palindrome. 
Infytq upgrade test coding questions
In this exam 3 coding Questions are asked – Easy( 50 points), Medium (75 points) and, Hard (100 points), a total of 225 points, and the points are assigned according to the number of test cases you pass.
(EASY 50 points)
Question 1: Write a program to add all the natural numbers till N, but not In decimal, do it in binary.
Example1:
input: 2(value of N) output: 11 Explanation: binary of 1= 01 binary of 2= 10 01+10=11
Example2:
input: 3 output: 22 Explanation: binary of 1= 01 binary of 2= 10 binary of 3= 11 01+10+11=22
Example3:
input: 4 output: 122
(MEDIUM75 points)
Question 2: Calculate the sum of Ai/Aj, where A is an Array of N numbers?
Example1:
Input: 3 (N no. of elements) 1 3 2 Output: 9 Explain: 1/1 + 1/2 +1/3 =1+0+0=1 3/1 + 3/2 +3/3= 3+1+1=5 2/1 + 2/2 + 2/3= 2+1+0=3 1+3+5=9
My code was unable to pass 2 test cases due to the time limit, but the rest of the test cases successfully passes and from this question, I got 55 points.
I was unable to solve the 3rd question. Let see what happens(waiting for the result)
Infytq upgrade test Questions as per topic:
1. Special Prime
Given an integer N
N<=10^50
Output the no. of pairs (x,y) such that
0<=x<=n
0<=y<=n
F(x) +F(y) = Prime number
F(x) = sum of digits of x
Note : (x,y) and (y,x) are to be treated as same pair
Example
Input
3
Output
5
Explanation
5 pairs (0,2), (1,1), (0,3), (2,3), (1,2) give prime no.s
2. Break the Waffle
Charlie wants to divide a big piece of waffle which is made up of m*n square pieces. Each piece is of size 1*1. The shape of waffle is a rectangle of dimension m*n. However, Charlie can break the waffle either horizontally or vertically, along the lines such that the square pieces are not destroyed.
Each break along a line has a certain cost associated with it. The cost is only dependent on the line along which the waffle is being broken, and not on its length.
The total cost is obtained by summing up the costs of all the breaks.
Given the cost associated with each line, Charlie wants to know the minimum cost of breaking the waffle into single square pieces.
Input
First line contains two integers m and n denoting the number of rows and columns respectively.
This is followed by m1, each line contains an integer denoting the cost of breaking a waffle along a horizontal line.
This is followed by n1, each line contains an integer denoting the cost of breaking a waffle along a vertical line.
Output
Output should be a single line integer denoting the minimum cost to break the waffle into single square pieces.
Constraints
1<=n<=10^5
1<=m<=10^5
Sample Input
2 2
3
4
Sample Output
10
Explanation
Break the waffer along the column where the cost = 4, then break the two pieces along the row where the cost = 3*2 = 6. Otherwise, the cost would have been 3+(4*2) = 11.
3. Dangerous Script
If you have ever looked at an assembly language dump of an executable file, you know that commands come in the form of hexadecimal digits that are grouped by the processor into instructions. It is important that parsing can be done correctly or code will not be executed as expected. Wrong Parsing is the basis for Return Oriented Programming.
You have developed a program in a new scripting language. Of course, it requires accurate parsing in order to perform as expeced, and it is very cryptic. You want to determine how many valid commands can be made out of your lines of script. To do this, you count all of the substrings that make up a valid command. Each of the valid commands will be in the following format :
1. First letter is a lowercase English letter
2. Next, it contains a sequence of zero or more of the following characters : lowercase English letters, digits, and colons.
3. Next, it contains a forward slash ‘/’.
4. Next, it contains a sequence of one or more of the following characters : lowercase English letters, digits.
5. Next, it contains a backward slash ‘\’.
6. Next, it contains a sequence of one or more lowercase English letter.
Given some string s, we define the following :
s[i…j] is a substring containing of all the characters in the inclusive range between i and j.
For example, your command line is abc:/b1c\xy. Valid command substrings are :
abc:/b1c\xy
bc:/b1c\xy
c:/b1c\xy
abc:/b1c\x
bc:/b1c\x
c:/b1c\x
There are six valid commands that may be parsed from that one command string.
Sample Input 0
6
w\\//a/b
w\\//a\b
w\\/a\b
w:://a\b
w::/a\b
w:/a\bc::/12\xyz
Sample Output
0
0
0
0
1
8
4. Uniformity
You are given a string that is formed from only three characters ‘a’, ‘b’, ‘c’. You are allowed to change atmost ‘k’ characters in the given string while attempting to optimize the uniformity index.
Note : The uniformity index of a string is defined by the maximum length of the substring that contains same character in it.
Input
The first line of input contains two integers n (the size of string) and k. The next line contains a string of length n.
Output
A single integer denoting the maximum uniformity index that can be achieved.
Constraints
1 <= n <= 10^6
0 <= k <= n
String contains only ‘a’, ‘b’, ‘c’.
Sample Input 0
6 3
abaccc
Sample Output 0
6
Explanation
First 3 letters can be changed to ‘c’ and we can get the string ‘cccccc’
5. Tree Edges
Given a tree with N nodes we are required to seperate a connected component with exactly k nodes. You are given queries specifying this k. We need to find the minimum edges to be removed for each query.
Input
First line specifies N.
Next N1 lines specify edges.
Next line shows Q(number of queries).
Subsequent Q lines contain k for each query.
Constraint
N <= 3000
Q <= 3000
K <= N
Example
Input
5
1 2
1 3
1 4
1 5
3
1
2
4
Output
1
3
1
Infytq Programming Questions:
1. Which of the following cannot be a variable?
a. _init_
b. in
c. it
d. on
2. What will be the output of the following python code snippet?
[‘hello’, ‘morning’][bool(“)]
a. error
b. no output
c. hello
d. morning
3. What arithmetic operators cannot be used with strings?
a. +
b. *
c. –
d. all of the mentioned
4. What is the output when we execute the list(“hello”)?
a. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] b. [‘hello’] c. [‘llo’] d. [‘olleh’]
5. In Python, a class is____ for a concrete object.
a. a blueprint
b. a distraction
c. a nuisance
d. an instance
Infytq aptitude questions
6. If several elements are competing for the same bucket in the Hash table, what is it called?
a. Diffusion
b. Replication
c. Collision
d. Duplication
7. What is the worst case complexity of binary search using recursion?
a. O(nlogn)
b. O(logn)
c. O(n)
d. O(n2)
8. Which of the following is required to create a new Instance of the class?
a. A constructor
b. A class
c. Avaluereturning method
d. A None method
9. What is the complexity of adding an element to the heap?
a. O(log n)
b. O(h)
c. O(log n) & O(h)
d. O(n)
10. In Python, a function within a class definition is called a:
a. a method
b. a callable
c. an operation
d. a factory
Infytq exam questions
11. What is the time complexity of pop() operation when the stack is implemented using an array?
a. O(1)
b. O(n)
c. O(logn)
d. O(nlogn)
12. A linear list of elements in which deletion can be done from one end (front) and insertion can take place only at the other end (rear) is known as a?
a. Stack
b. Tree
c. Queue
d. Linked list
13. A Data structure in which elements can be inserted or delected at/from both ends but not in the middle is?
a. Queue
b. Circular queue
c. Dequeue
d. Priority queue
14. Which of the following property does not hold for matrix multiplication?
a. Associate
b. Distributive
c. Commutative
d. Additive inverse
15. What is the maximum height of an AVL tree with p nodes?
a. p
b. log(p)
c. log(p)/2
d. p/2
Infytq Exam Coding questions
16. What will be the output of the following python code snippet?
1. d1 = {“john”:40, “peter”:45}
2. d2 = {“john”:466, “peter”:45}
3. d1 == d2
a. True
b. False
c. None
d. Error
17. Which SQL function is used to count the number of rows in a SQL Query?
a. COUNT()
b. NUMBER()
c. SUM()
d. COUNT(*)
18. Which SQL keyword is used to retrieve a maximum value?
a. MOST
b. TOP
c. MAX
d. UPPER
19. Which of the following language is MongoDB written in?
a. JavaScript
b. C
c. C++
d. All of the mentioned
20. Which of the following format is supported by MongoDB?
a. SQL
b. XML
c. BSON
d. All of the mentioned
Infytq previous Programming questions
Q1.Given array(2,6,3,5,8,9)
Possible XSeries(2,3,5), (2,3,5,8)
OutputLongest XSeries (2,3,5,8)
#XSeries where sum of two numbers results in next number
Q2Find longest substring of unique characters which is case insensitive
Q3Reversing a string leaving the special characters in the same place.
Q4Input will be given like 4365188
Example: separate odd place Integers :: 3,5,8
You have to return a 4 digit OTP by squaring the digits.
Digits from above example is 3,5,8
Square of those numbers is 9,25,65
So the otp to be returned is first four digits 9256
Q5A string will be given combination of letters and special characters. You have to return a reversed string keeping the special characters at the same place
Example : sd&hg#j
Answer to be returned is : jg&hd#s
Q 6– For a given list of numbers, find its factors and add the factors. Then if the sum of factors is present in the original list, sort it and print it.
Example:
Input: 0,1,6
Factors of 0 = 0. Thus sum = 0
Factors of 1 = 1. Thus sum = 1
Factors of 6 = 1,2,3. Thus sum = 6
Output = 1,6
If the sum numbers are not present in original list, then return 1.
Q7Maximum number of swaps will be given and an list of digits will be given. We have to swap numbers to get the lowest number possible by using all digits from the list.
Q8Take a string as a input. Separate all the integers from it. Then take each integers only once and form the largest even number possible. Print the largest possible even number. And if even number can’t be made, then print 0.
Consider 0 as even number.
sample input:
QWert@821142
sample output:
8412
explanation: integers present are 8,2,1,1,4,2. Distinct integers are 8214, therefore largest possible even number is 8412
Q9Input – Non empty string containing only these characters – (,),[,],{,}
Output – Check if the string is properly nested. If yes print ‘0’.
If not, — If it is found before completely traversing the string, print the index at which it is wrong.
— If it is found after completely traversing the string, print the ‘string length+1’
Important Note – String index starts from 1.
Example test cases –
1. Input – {[()]{}} Output – 0 #As the string is properly nested, we print ‘0’
2. Input – {[}() Output – 3 #At index 3 we encounter ‘}’ but it fails the condition, #hence the index is printed.
Q10Input – Non empty string containing only these characters – (,),[,],{,}
Output – Check if the string is properly nested. If yes print ‘0’.
If not, — If it is found before completely traversing the string, print the index at which it is wrong.
— If it is found after completely traversing the string, print the ‘string length+1’
Important Note – String index starts from 1.
Example test cases –
1. Input – {[()]{}} Output – 0 #As the string is properly nested, we print ‘0’
2. Input – {[}() Output – 3 #At index 3 we encounter ‘}’ but it fails the condition, #hence the index is printed.
Infytq coding questions
Q11Input – A string of numbers
Output – Check if the number is palindrome.
If it is, print it’s length.
If not, ( get the reverse of the string, add it to the original string, and check again). Repeat until a palindrome is generated.
Example Test cases –
1. Input – 145, Output – 3. #145 is not palindrome. Add 145+541=686, which is a palindrome. Hence print it’s length, 3
2. Input – 4, Output – 1. # 4 is a palindrome.
Q12Given a string, find the longest length of a prefix which is also a suffix.
Q13– Given a string, find the substring based on the following conditions,
The substring must be the longest one of all the possible substring in the given string.
There must not be any repeating characters in the substring.
If there is more than one substring satisfying the above two conditions, then print the substring which occurs first.
Length of the substring must be a minimum 3.
If there is no substring satisfying all the aforementioned conditions then print 1.
Q14Given an array of integers, find the combination of integers forming a sequence that satisfies the below conditions:
The ith integer must satisfy the given equation in the sequence
2. The length of the sequence must be maximum possible
3. If there is more than one sequence satisfying above two conditions then print that sequence which contains least integers.
In case there is no combination of integers possible then print 1.
See the example below:
Example 1:
If the given integers are 4, 2, 7, 5, 3, 8, 10, 11, 19 then the possible combinations of integers satisfying above conditions are 2, 3, 5, 8 and 3, 8, 11, 19 and hence the output must be 2, 3, 5, 8. Here you cannot form any other combination of integers whose length is greater than 4 and satisfies the given equation.
Example 2:
If the given integers are 1,5,6,10 then print 1.
Infytq mcq questions
InfyTQ Exam Data Structure Questions:
Data Structure is the true essence of Computer Science. Equipping yourself with indepth knowledge of data structures is mandatory to work as a Software Engineer in leading companies like Infosys. Also, check our blog on the Advantages of taking the Infosys Certification Exam
Frequently used Data Structures
The commonly used Data Structures can be broadly classified into two categories:
Linear Data Structures: A data structure is said to be linear if its elements form a sequence or a linear list. For Example Array, Linked List, Stack, Queue
NonLinear Data Structure: A data structure is said to be nonlinear if the traversal of nodes is nonlinear. For Example Graph, Tree
Let us dive deep into some questions which can test your knowledge in data structures.
1. Array
Q. Which of the following operations is not O (1) for an array of sorted data assuming that array elements are distinct?
a. Find the ith largest element
b. Delete an element
c. Find the ith smallest element
d. All of the above
Explanation: The worstcase time complexity for deleting an element from the array can become O(n).
2. Linked List
Q. Which of the following points is/are true about Linked List data structure when it is compared with an array?
a. Arrays have better cache locality that can make them better in terms of performance.
b. It is easy to insert and delete elements in Linked List.
c. Random access is not allowed in a typical implementation of Linked Lists.
d. The size of the array has to be predecided, a linked list can change their size any time
e. All of the above
3. Stack
Consider the following pseudocode that uses a stack declare a stack of characters
while (there are more characters in the word to read)
{ read a character push the character on the stack } while (the stack is not empty) { pop a character off the stack write the character to the screen } 
InfyTQ Exam Coding Questions
Q. What is the output for input “Infosys”?
a. InfosysInfosys
b. sysofnI
c. Infosys
d. sysofnIsysofnI
Explanation: Since the stack data structure follows the LIFO (Last In First Out) order. When we pop() items from the stack, they are popped in reverse order of their insertion (or push())
4. Queues
Q. Which of the following is true about the linked list implementation of the queue?
a. In a push operation, if new nodes are inserted at the beginning of a linked list, then in pop operation, nodes must be removed from the end.
b. In a push operation, if new nodes are inserted at the end, then in pop operation, nodes must be removed from the beginning.
c. Both of the above
d. None of the above
Explanation: To keep the FIFO (First In First ut) order, a queue can be implemented using a linked list in any of the given two ways.
5. Circular Queue
Q. Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation is carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are
a. Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT
b. Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR
c. Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT
d. Full: (FRONT+1) mod n == REAR, empty: REAR == FRONT
Explanation: Suppose we start filling the queue.
Let the maxQueueSize (Capacity of the Queue) is 4.
So, the size of the array which is used to implement this circular queue is 5, i.e. n = 5.
In the beginning when the queue is empty, FRONT and REAR point to index 0 of the array.
REAR represents insertion at the REAR index.
FRONT represents deletion from the FRONT index.
enqueue(“a”); REAR = (REAR+1) %5; (FRONT = 0, REAR = 1)
enqueue(“b”); REAR = (REAR+1) %5; (FRONT = 0, REAR = 2)
enqueue(“c”); REAR = (REAR+1) %5; (FRONT = 0, REAR = 3)
enqueue(“d”); REAR = (REAR+1) %5; (FRONT = 0, REAR = 4)
Now the queue size is 4 which is equal to the maxQueueSize. Hence overflow condition is reached.
Now, we can check for the conditions.
When Queue is Full:
(REAR+1) %n = (4+1) %5 = 0
FRONT is also 0.
Hence (REAR + 1) %n is equal to FRONT.
When the Queue is Empty:
REAR was equal to FRONT when empty (because in the starting before filling the queue FRONT = REAR = 0)
6. Hash Table
Q. Let a hash function H(x) maps the value at the index x%10 in an Array. For example, if the list of values is [11,12,13,14,15] it will be stored at positions {1,2,3,4,5} in the array or Hash table respectively.
Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4) mod7. Assuming the hash table is initially empty, which of the following is the contents of the table when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note that ‘_’ denotes an empty location in the table.
a. 8, _, _, _, _, _, 10
b. 1, 8, 10, _, _, _, 3
c. 1, _, _, _, _, _,3
d. 1, 10, 8, _, _, _, 3
Explanation: Let us put values 1, 3, 8, 10 in the hash of size 7. Initially, the hash table is empty
– – – – – – –
0 1 2 3 4 5 6
The value of the function (3x + 4) mod 7 for 1 is 0, so let us put the value at 0
1 – – – – – –
0 1 2 3 4 5 6
The value of the function (3x + 4) mod 7 for 3 is 6, so let us put the value at 6
1 – – – – – 3
0 1 2 3 4 5 6
The value of the function (3x + 4) mod 7 for 8 is 0, but 0 is already occupied, let us put the value (8) at next available space (1)
1 8 – – – – 3
0 1 2 3 4 5 6
The value of the function (3x + 4) mod 7 for 10 is 6, but 6 is already occupied, let us put the value (10) at the next available space (2)
1 8 10 – – – 3
0 1 2 3 4 5 6
7. Binary Tree
A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.
A Binary Tree node contains the following parts.
Data (Root)
Pointer to left child (Left)
Pointer to right child (Right)
There are 3 types of tree traversals:
Preorder (Root, Left, Right)
Inorder (Left, Root, Right)
Postorder (Left, Right, Root)
Binary Search Tree
Binary Search Tree is a nodebased binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree must also be a binary search tree.
InfyTQ Exam Coding Questions
The Preorder traversal sequence of a binary search tree is 30, 20, 10, 15, 25, 23, 39, 35, 42. Which one of the following is the Postorder traversal sequence of the same tree?
a. 10, 20, 15, 23, 25, 35, 42, 39, 30
b. 15, 10, 25, 23, 20, 42, 35, 39, 30
c. 15, 20, 10, 23, 25, 42, 35, 39, 30
d. 15, 10, 23, 25, 20, 35, 42, 39, 30
Explanation: The following is the constructed tree
30
/ \
20 39
/ \ / \
10 25 35 42
\ /
15 23
Q. The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)?
a. 2
b. 3
c. 4
d. 6
Explanation: Constructed binary search tree will be.
10
/ \
1 15
\ / \
3 12 16
\
5
8. Heap
Q. What is the time complexity of the Build Heap operation? Build Heap is used to building a max (or min) binary heap from a given array. Build Heap is used in Heap Sort as a first step for sorting.
a. O (N log N)
b. O (N^2)
c. O (log N)
d. O (N)
Explanation: Following is the algorithm for building a Heap of an input array A.
BUILDHEAP(A)
heapsize := size(A);
for i := floor(heapsize/2) downto 1
do HEAPIFY (A, i);
end for
END
9. Graph
Q. What is the maximum number of edges in an acyclic undirected graph with n vertices?
a. n – 1
b. n
c. n + 1
d. 2n – 1
Explanation: n * (n – 1) / 2 when cyclic. But the acyclic graph with the maximum number of edges is a spanning tree and therefore, the correct answer is n1 edges.
Join Us on Social Media:
Follow Us On Facebook  Follow Now 
Follow Us On Twitter  Follow Now 
Follow Us On LinkedIn  Follow Now 