0% found this document useful (0 votes)
58 views25 pages

Infosys QNs

Uploaded by

praneshm2002
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)
58 views25 pages

Infosys QNs

Uploaded by

praneshm2002
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

C2 - Restricted use

Infosys Exam Pattern

The Infosys Exam Pattern contains only one test which will contain all the topics like
logical ability, Verbal, Pseudo Code, etc. To be more specific it contains 5 sections
with the name:

 Mathematical Ability

 Reasoning Ability

 Verbal Ability

 Pseudo Code

 Puzzle Solving

Topic Name Time Questions

Logical 25 mins 15 Ques

Mathematical Ability 35 mins 10 Ques

Verbal 20 mins 20 Ques

Pseudo Code 10 mins 5 Ques

Puzzle Solving 10 mins 4 Ques

Total 100 mins 54 Ques

1. Write a program in C++ to quickly swap two arrays.


// Illustrating the use of swap function
// to swap two arrays
#include <iostream>
#include <utility>
using namespace std;
C2 - Restricted use

int main ()
{
int a[] = {11, 12, 13, 14};
int b[] = {15, 16, 17, 18};
int n = sizeof(a)/sizeof(a[0]);

swap(a, b);

cout << "a[] = ";


for (int i=0; i<n; i++)
cout << a[i] << ", ";

cout << "\nb[] = ";


for (int i=0; i<n; i++)
cout << b[i] << ", ";

return 0;
}

2. Write a Program to sort a string of characters


MAX_CHAR = 26

def sortString(str):

charCount = [0 for i in range(MAX_CHAR)]

for i in range(0, len(str), 1):

charCount[ord(str[i]) - ord('a')] += 1

for i in range(0, MAX_CHAR, 1):


for j in range(0, charCount[i], 1):
print(chr(ord('a') + i), end = "")

if __name__ == '__main__':
s = "prepbytes"
sortString(s)

3. Write a program to count the number of unique characters in a given string.


def cntDistinct(st):

s = set([])

for i in range(len(st)):
C2 - Restricted use

s.add(st[i])

return len(s)

if __name__ == "__main__":

st = "prepbytes"
print(cntDistinct(st))

4. Write a program to multiply two matrices and print the result through another
matrix.
def mulMat(mat1, mat2, R1, R2, C1, C2):
rslt = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

for i in range(0, R1):


for j in range(0, C2):
for k in range(0, R2):
rslt[i][j] += mat1[i][k] * mat2[k][j]

print("Multiplication of given two matrices is:")


for i in range(0, R1):
for j in range(0, C2):
print(rslt[i][j], end=" ")
print("\n", end="")

if __name__ == '__main__':
R1 = 2
R2 = 2
C1 = 2
C2 = 2

mat1 = [[4, 4],


[5, 3]]

mat2 = [[4, 7],


[6, 2]]

if C1 != R2:
print("The number of columns in Matrix-1 must be equal to the number of rows in " + "Matrix-2", end='')
print("\n", end='')
print("Please update MACROs according to your array dimension in #define section", end='')
print("\n", end='')
else:
C2 - Restricted use

mulMat(mat1, mat2, R1, R2, C1, C2)

5. Given a string find the next permutation of the given string in C++.
#include <iostream>

using namespace std;

void swap(char* a, char* b)


{
if (*a == *b)
return;
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
void rev(string& s, int l, int r)
{
while (l < r)
swap(&s[l++], &s[r--]);
}

int bsearch(string& s, int l, int r, int key)


{
int index = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (s[mid] <= key)
r = mid - 1;
else {
l = mid + 1;
if (index == -1 || s[index] >= s[mid])
index = mid;
}
}
return index;
}

bool nextpermutation(string& s)
{
int len = s.length(), i = len - 2;
while (i >= 0 && s[i] >= s[i + 1])
--i;
if (i < 0)
return false;
else {
int index = bsearch(s, i + 1, len - 1, s[i]);
swap(&s[i], &s[index]);
rev(s, i + 1, len - 1);
return true;
}
C2 - Restricted use

int main()
{
string s = { "prepbytes" };
bool val = nextpermutation(s);
if (val == false)
cout << "No Word Possible" << endl;
else
cout << s << endl;
return 0;
}

6. Write a program to find the area of the incircle of a right angles triangle.
PI = 3.14159265

def area_inscribed(P, B, H):


return ((P + B - H)*(P + B - H)*(PI / 4))

P=3
B=4
H=5
print(area_inscribed(P, B, H))

7. Write a program that will find the missing characters that are needed to make
the string a panagram.
MAX_CHAR = 26

def missingChars(Str):

present = [False for i in range(MAX_CHAR)]

for i in range(len(Str)):
if (Str[i] >= 'a' and Str[i] <= 'z'):
present[ord(Str[i]) - ord('a')] = True
elif (Str[i] >= 'A' and Str[i] <= 'Z'):
present[ord(Str[i]) - ord('A')] = True

res = ""

for i in range(MAX_CHAR):
if (present[i] == False):
res += chr(i + ord('a'))
C2 - Restricted use

return res

Str = "Welcome to prepbytes"

print(missingChars(Str))

8. Write a program that converts the given temperature of Fahrenheit into celsius.
def Cel_To_Fah(n):

return (n*1.8)+32
n = 40

print(int(Cel_To_Fah(n)))

9. Write a program that will find the sum of all the prime numbers between 1 and
N.
def sumOfPrimes(n):
prime = [True] * (n + 1)

p=2
while p * p <= n:
if prime[p] == True:
i=p*2
while i <= n:
prime[i] = False
i += p
p += 1

sum = 0
for i in range (2, n + 1):
if(prime[i]):
sum += i
return sum

n = 15
print(sumOfPrimes(n))

10. Write a program to make the largest number from the digits of the array.
def largestNumber(array):

if len(array)==1:
return str(array[0])
for i in range(len(array)):
C2 - Restricted use

array[i]=str(array[i])
for i in range(len(array)):
for j in range(1+i,len(array)):
if array[j]+array[i]>array[i]+array[j]:
array[i],array[j]=array[j],array[i]

result=''.join(array)
if(result=='0'*len(result)):
return '0'
else:
return result

a = [54, 546, 548, 60]


print(largestNumber(a))

11. Given an array form a triangle such that the last row of the triangle contains all
the elements of the array and the row above it will contain the sum of two
elements below it.

def printTriangle(arr, n):

tri = [[0 for i in range(n)]


for i in range(n)]

for i in range(n):
tri[n - 1][i] = arr[i]

i=n-2
while(i >= 0):
for j in range(0, i + 1, 1):
tri[i][j] = (tri[i + 1][j] +
tri[i + 1][j + 1])

i -= 1

for i in range(0, n, 1):


for j in range(0, i + 1, 1):
print(tri[i][j], end = " ")
print("\n", end = "")

arr = [4, 7, 3, 6, 7, 3]
n = len(arr)
printTriangle(arr, n)

12. Given the price of the stock on each day find the maximum profit you can earn
by selling them.
C2 - Restricted use

def maxProfit(price, start, end):

if (end <= start):


return 0

profit = 0

for i in range(start, end, 1):

for j in range(i+1, end+1):

if (price[j] > price[i]):

curr_profit = price[j] - price[i] +\


maxProfit(price, start, i - 1) + \
maxProfit(price, j + 1, end)

profit = max(profit, curr_profit)

return profit

if __name__ == '__main__':
price = [100, 180, 260, 310, 40, 535, 695]
n = len(price)

print(maxProfit(price, 0, n - 1))

13. You are given a matrix that contains only 0 and 1 find the maximum size of a
rectangle that contains only 1.
class Solution():
def maxHist(self, row):

result = []

# Top of stack
top_val = 0

max_area = 0

area = 0

i=0
while (i < len(row)):

if (len(result) == 0) or (row[result[-1]] <= row[i]):


result.append(i)
C2 - Restricted use

i += 1
else:

top_val = row[result.pop()]
area = top_val * i

if (len(result)):
area = top_val * (i - result[-1] - 1)
max_area = max(area, max_area)

while (len(result)):
top_val = row[result.pop()]
area = top_val * i
if (len(result)):
area = top_val * (i - result[-1] - 1)

max_area = max(area, max_area)

return max_area

def maxRectangle(self, A):

result = self.maxHist(A[0])

for i in range(1, len(A)):

for j in range(len(A[i])):

if (A[i][j]):
A[i][j] += A[i - 1][j]

result = max(result, self.maxHist(A[i]))

return result

if __name__ == '__main__':
A = [[0, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 0]]
ans = Solution()

print("Area of maximum rectangle is",


ans.maxRectangle(A))
C2 - Restricted use

14. Given the coordinates of the endpoints of two rectangles find whether they
overlap each other or not.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def do_overlap(l1, r1, l2, r2):

if l1.x == r1.x or l1.y == r1.y or r2.x == l2.x or l2.y == r2.y:


return False

if l1.x > r2.x or l2.x > r1.x:


return False

if r1.y > l2.y or r2.y > l1.y:


return False

return True

if __name__ == "__main__":
l1 = Point(0, 10)
r1 = Point(10, 0)
l2 = Point(5, 5)
r2 = Point(15, 0)

if(do_overlap(l1, r1, l2, r2)):


print("Rectangles Overlap")
else:
print("Rectangles Don't Overlap")

15. You are given two strings to find whether we can convert one string to another
by rotating in two places.
def isRotated(str1, str2):

if (len(str1) != len(str2)):
return False

if(len(str1) < 2):


return str1 == str2
clock_rot = ""
anticlock_rot = ""
l = len(str2)

anticlock_rot = (anticlock_rot + str2[l - 2:] +


str2[0: l - 2])
C2 - Restricted use

clock_rot = clock_rot + str2[2:] + str2[0:2]

return (str1 == clock_rot or


str1 == anticlock_rot)

str1 = "prep"
str2 = "eppr"
if isRotated(str1, str2):
print("Yes")
else:
print("No")

Given a sorted array arr and an integer k, find the position(0-based indexing) at
which k is present in the array using binary search.

Examples:

Input: k = 4, arr= [1, 2, 3, 4, 5]


Output: 3
Explanation: 4 appears at index 3.
Input: k = 445, arr= [11, 22, 33, 44, 55]
Output: -1
Explanation: 445 is not present.
Expected Time Complexity: O(logn)
Expected Space Complexity: O(long)

Note: Try to solve this problem in constant space i.e O(1)

Constraints:
1 <= arr.size() <= 105
1 <= arr[i] <= 106
1 <= k <= 106
class Solution:
def binarysearch(self, arr, k):
# Code Here
l=0
r=len(arr)-1
while l<=r:
mid = (l+r)//2
if arr[mid]==k:
C2 - Restricted use

return mid
elif arr[mid]<k:
l=mid+1
else:
r=mid-1

return -1

Given an array arr, the task is to find the largest element in it.
Examples:

Input: arr= [1, 8, 7, 56, 90]


Output: 90
Explanation: The largest element of given array is 90.
Input: arr = [5, 5, 5, 5]
Output: 5
Explanation: The largest element of given array is 5.
Input: arr = [10]
Output: 10
Explanation: There is only one element which is the largest
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

Constraints:
1 <= arr.size()<= 105
0 <= arri <= 105
arr may contain duplicate elements.

from typing import List

class Solution:
def largest(self, n : int, arr : List[int]) -> int:
C2 - Restricted use

max=arr[0]
for i in range(len(arr)):
if arr[i]>max:
max=arr[i]
return max

Given a number N, find the first N Fibonacci numbers. The first two number of the
series are 1 and 1.

Example 1:

Input:
N=5
Output: 1 1 2 3 5
Example 2:

Input:
N=7
Output: 1 1 2 3 5 8 13
Your Task:
Your task is to complete printFibb() which takes single argument N and returns a list
of first N Fibonacci numbers.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(N).
Note: This space is used to store and return the answer for printing purpose.

Constraints:
1<= N <=84
class Solution:
def printFibb(self, n):
if n <= 0:
return []
if n == 1:
return [1]
C2 - Restricted use

# Initialize the first two Fibonacci numbers


fib_sequence = [1, 1]

# Generate Fibonacci numbers until we reach the required count


for i in range(2, n):
next_fib = fib_sequence[i - 1] + fib_sequence[i - 2]
fib_sequence.append(next_fib)

return fib_sequence

solution = Solution()

You have n books, each with arr[i] a number of pages. m students need to be
allocated contiguous books, with each student getting at least one book.
Out of all the permutations, the goal is to find the permutation where the sum of
the maximum number of pages in a book allotted to a student should
be the minimum, out of all possible permutations.

Note: Return -1 if a valid assignment is not possible, and allotment should be in


contiguous order (see the explanation for better understanding).

Examples:

Input: n = 4, arr[] = [12, 34, 67, 90], m = 2


Output: 113
Explanation: Allocation can be done in following ways:
{12} and {34, 67, 90} Maximum Pages = 191
{12, 34} and {67, 90} Maximum Pages = 157
{12, 34, 67} and {90} Maximum Pages =113.
Therefore, the minimum of these cases is 113, which is selected as the output.
Input: n = 3, arr[] = [15, 17, 20], m = 5
Output: -1
Explanation: Allocation can not be done.
Expected Time Complexity: O(n logn)
Expected Auxilliary Space: O(1)
C2 - Restricted use

Constraints:
1 <= n, m <= 105
1 <= arr[i] <= 106

class Solution:
def findPages(self,N, A, M):
l = max(A); r = sum(A); ans = -1

if len(A) < M: return -1 # Number of books can not be lesser than number of of students as we have to
give atleast 1 book to a student

def isValid(A, M, mid):


pageSum = 0 # sum of pages of A that can be allocated to one student
requiredStudents = 1 # Number of students required if mid is the max capacity of student

for pages in A:
pageSum += pages
if pageSum > mid: # sum of pages allocated to one student exceed max capacity of the student
requiredStudents += 1 # We need one more student
pageSum = pages # start calculating sum of pages can be allocated to next student

if requiredStudents > M: return False


else: return True

while l <= r:
mid = l + (r - l) // 2

if isValid(A, M, mid):
ans = mid # Updating answer the the current mid as it is the most optimized(least) ans till now
r = mid - 1 # I will try to decrease mid
else:
l = mid + 1 # current mid NOT isValid so I will try to increase mid

return ans # Most Optimized ans is stored here


Implement the next permutation, which rearranges the list of numbers into
Lexicographically next greater permutation of list of numbers. If such arrangement is
not possible, it must be rearranged to the lowest possible order i.e. sorted in an
ascending order. You are given an list of numbers arr[ ] of size N.

Example 1:
C2 - Restricted use

Input: N = 6
arr = {1, 2, 3, 6, 5, 4}
Output: {1, 2, 4, 3, 5, 6}
Explaination: The next permutation of the
given array is {1, 2, 4, 3, 5, 6}.
Example 2:

Input: N = 3
arr = {3, 2, 1}
Output: {1, 2, 3}
Explaination: As arr[] is the last
permutation. So, the next permutation
is the lowest one.
Your Task:
You do not need to read input or print anything. Your task is to complete the
function nextPermutation() which takes N and arr[ ] as input parameters and returns
a list of numbers containing the next permutation.

Expected Time Complexity: O(N)


Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 10000

class Solution:
def nextPermutation(self, N, arr):
index=-1
for i in range(N-2,-1,-1):
if arr[i]<arr[i+1]:
index=i
break
if index==-1:
arr.reverse()
return arr
C2 - Restricted use

for i in range(N-1,index,-1):
if arr[i]>arr[index]:
arr[i],arr[index]=arr[index],arr[i]
break

arr[index+1:]=reversed(arr[index+1:])
return arr

SPEACIALIST PROGRAMMER

You are given an array a of N Integers and asked to split the array a into k consecutive segments such that
each element of a belongs to exactly one segment and the sum of the cost of all segments is minimum.
We define the cost of some segment t as the sum of distances between the first and last occurrence for each
unique element in the segment t.
Your task is to find the minimum possible total sum of the cost of all segments.
Input Format

 The first line contains an integer, n, denoting the number of elements in a.


 The next line contains an integer, k, denoting the Number of required consecutive segments..
 Each line i of the n subsequent lines (where 0 <=i<n) contains an integer describing a[i].
Constraints :

 1 <= n<= 35000


 1 <=k <=min(n,100)
 1 <=a[i] <=n
Sample Sample
Input Output Explanation
1 0 The only possible segment is [1] The cost is 1-1=0
1
1
7 3 We can divide the array into [1,6,6,4] and [6,6,6] Cost of [1,6,6, 4] will be (1-1)+(3-
2 2)+(4-4)=1 and cost of [6 ,6,6] will be 3-1=2. Total cost would be 1+2=3
1
6
6
4
6
6
6
C2 - Restricted use

#include<bits/stdc++.h>

using namespace std;


const int N = 4e5, M = 110, inf = 0x3f3f3f3f;
int a[N], dp[N][M], lst[N], pre[N], nxt[N], i, j, n, m, L, R, sum;

int cal(int l, int r) {


while (L < l) {
if (nxt[L] <= R)sum -= nxt[L] - L; L++; } while (L > l) {
--L;
if (nxt[L] <= R)sum += nxt[L] - L;
}
while (R < r) { ++R; if (pre[R] >= L)sum += R - pre[R];
}
while (R > r) {
if (pre[R] >= L)sum -= R - pre[R];
R--;
}
return sum;
}

void solve(int l, int r, int L1, int R1, int now)


{
if (l > r || L1 > R1)return;
int mid = (l + r) / 2, val = inf, pos;
for (int i = L1; i < mid && i <= R1; ++i)
{
int tmp = dp[i][now - 1] + cal(i + 1, mid);
if (tmp < val)pos = i, val = tmp;
}
dp[mid][now] = val;
solve(l, mid - 1, L1, pos, now);
solve(mid + 1, r, pos, R1, now);
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
for (i = 1; i <= n; ++i) cin >> a[i];
for (i = 1; i <= n; ++i) dp[i][0] = inf, pre[i] = lst[a[i]], lst[a[i]] = i;
for (i = 1; i <= n; ++i) lst[a[i]] = n + 1;
for (i = n; i; --i) nxt[i] = lst[a[i]], lst[a[i]] = i;
for (i = 1; i <= m; ++i) solve(1, n, 0, n, i);
cout << dp[n][m] << "\n";
}
C2 - Restricted use

Problem Statement :
Wael wants to play Santa this year, so he prepared gifts for all the children of the neighborhood. He decided
to pack the gifts in boxes and give each child a box. Let’s define the Value of the box as the number of distinct
types of gifts inside this box.
Wael has N gifts, such that the type of each gift i is A[i]. Wael wants to pack exactly K boxes, and he has to
put in each box a sub-array of consecutive gifts
Wael wants to maximize the total value of all boxes with gifts. Your task is to help him determine this
maximum possible total value
Notes

 Each gift should be put in exactly one box, and each box should contain a sub-array of consecutive
gifts.
 A box cannot be left empty
Input Format

 The first line contains an integer, N, denoting the number of elements in A


 The next line contains an integer, K, denoting the number of boxes.
 Each line i of the N subsequent lines (where 0≤i<N) contains an integer describing Ai
Constraints

 1 <= N <= 35000


 1 <= K <= Min (N,50)
 1 <= A[i] <= N

Sample Sample
Input Output Explanation
1 1 Wael will put the only gift in a box so the total value will be 1.
1
1
4 2 Wael has only one box he has to put all gifts in it, so that there are two types of gifts in the
1 box, so the value is equal to 2
1
2
2
1
7 5 It is optimal to put the first two gifts in the first box, and all the rest in the second There are
2 two distinct types in the first box, and three in the second box then, so the total value is 5.
1
3
3
C2 - Restricted use

1
4
4
4

#include <bits/stdc++.h>
using namespace std;
int ans = INT_MIN;

void solve(int a[], int n, int k, int index, int count, int maxval)
{

if (k == 1) {
maxval = max(maxval, count);
count = 0;
map<int, int>mp;
for (int i = index; i < n; i++) {
mp[a[i]]++;
}
count = mp.size();
mp.clear();

maxval = max(maxval, count);

ans = max(ans, maxval);


return;
}
count = 0;
map<int, int>mp;
for (int i = index; i < n; i++) {
mp[a[i]]++;
count = mp.size();

maxval = max(maxval, count);

solve(a, n, k - 1, i + 1, count, maxval);

}
}
// Driver Code
int main()
{
int arr[] = {1, 1};
int k = 2; // K divisions
C2 - Restricted use

int n = 2; // Size of Array


solve(arr, n, k, 0, 0, 0);
cout << ans << "\n";
}

Problem Statement :
A subarray of array A is a segment of contiguous elements in array A.
Given an array A of N elements, you can apply the following operations as many times as you like:
– Choosing a subarray [L, R] and subtracting 1 from each element in this subarray. The cost of this operation
is X.
– Choosing an index i such that A[i] is positive, and setting A[i] = 0. The cost of this operation in Y.
Your task is to make all the elements equal to 0 and find the minimum cost to do so.
Input Format

 The first line contains an integer, N., denoting the number of elements in A.
 The next line contains an integer, X, denoting the cost of the first operation.
 The next line contains an integer. Y, denoting the cost of the second operation
 Each line i of the N subsequent lines (where 1 <=i<= N) contains an Integer describing Ai.
Constraints

 1<=N<=10^5
 1<=X<=10
 1<=Y<=10^4
 1<=A[i]<=10^8

Sample Input 1
1
1
10
1
Sample Output 1
1
Explanation:
N=1 X=1 Y=10 A=[1]. The optimal solution is to perform one operation of the first type on the subarray [1,N].
Sample Input 2
3
1
1
1
C2 - Restricted use

1
1
Sample Output 2
1
Explanation:
N=3 X=1 Y=1 A=[1,1,1] The optimal solution is to perform one operation of the first type on the
subarray[1,N];

n=1
x=1
y = 10
arr = [1]
ans = 0
arrSize = len(arr)
for i in range(arrSize):
arr[i] = arr[i] - 1

ans = ans + x
for i in range(arrSize):
if arr[i] != 0:
arr[i] = 0
ans = ans + y
print(ans)

Problem Statement :

Given an array A of N elements. You should choose a value B such that (B>=0), and then for each element in A
set A[i]=A[i](+)B where is the bitwise XOR.
Print the minimum number of inversions in array A that you can achieve after choosing the value of B
optimally and setting A[i] = A[i] (+) B. Since the answer might be large, print it modulo (10^9+7)
Input Format

 The first line contains an integer, N. denoting the number of elements in A


 Then the next line contains N elements, denoting the elements in A.
Input :
4
1032
Output
1
C2 - Restricted use

#include <bits/stdc++.h>
#define sz(x) ((int)(x).size())
#define inf mod

using namespace std;

const int maxn = (int) 5e6 + 100;


int n, t[2][maxn], id = 1;
int dp[2][30];
vector < int >g[maxn];

void add (int x, int pos)


{
int v = 0;
for (int i = 29; i >= 0; i--)
{
int bit = ((x >> i) & 1);
if (!t[bit][v])
t[bit][v] = id++;
v = t[bit][v];
g[v].push_back (pos);
}
}

void go (int v, int b = 29)


{
int l = t[0][v], r = t[1][v];
if (l)
go (l, b - 1);
if (r)
go (r, b - 1);
if (!l || !r)
return;
int res = 0;
int ptr = 0;
for (auto x:g[l])
{
while (ptr < sz (g[r]) && g[r][ptr] < x)
ptr++;
res += ptr;
}
dp[0][b] += res;
dp[1][b] += sz (g[l]) * 1ll * sz (g[r]) - res;
}

int main ()
{
C2 - Restricted use

cin >> n;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
add (x, i);
}
go (0);
int inv = 0;
int res = 0;
for (int i = 0; i <= 29; i++)
{
inv += min (dp[0][i], dp[1][i]);
if (dp[1][i] < dp[0][i])
res += (1 << i);
}
cout << inv;
}

Problem Statement :
Wael is well-known for how much he loves the bitwise XOR operation, while kaito is well known for how
much he loves to sum numbers, so their friend Resli decided to make up a problem that would enjoy
both of them. Resil wrote down an array A of length N, an integer K and he defined a new function
called Xor- sum as follows

 Xor-sum(x)=(x XOR A[1])+(x XOR A[2])+(x XOR A[3])+…………..+(x XOR A[N])


Can you find the integer x in the range [0,K] with the maximum Xor-sum (x) value?
Print only the value.
Input format

 The first line contains integer N denoting the number of elements in A.


 The next line contains an integer, k, denoting the maximum value of x.
 Each line i of the N subsequent lines(where 0<=i<=N) contains an integer describing Ai.
Constraints

 1<=N<=10^5
 0<=K<=10^9
 0<=A[i]<=10^9
Sample Input 1
1
0
989898
Sample Output 1
C2 - Restricted use

989898
Explanation:
Xor_sum(0)=(0^989898)=989898
Sample Input 2
3
7
1
6
3
Sample Output 2
14
Explanation
Xor_sum(4)=(4^1)+(4^6)+(4^3)=14.
Sample Input 3
4
9
7
4
0
3
Sample Output 3
46
Explanation:
Xor_sum(8)=(8^7)+(8^4) +(8^0)+(8^3)=46.

def Xor_sum(x, arr):


xorSum = sum(arr)

for i in range(1, x):


s=0
for j in arr:
s += i ^ j
if s > xorSum:
xorSum = s
return xorSum

n=4
x=9
arr = [7, 4, 0, 3]
print(Xor_sum(x, arr))

You might also like