Append two elements to make the array satisfy the given condition
Last Updated :
25 Jan, 2022
Given an array arr[] of non-negative integers, let’s define X as the XOR of all the array elements and S as the sum of all the array elements. The task is to find two elements such that when they are appended to the array S = 2 * X is satisfied for the updated array.
Examples:
Input: arr[] = {1, 7}
Output: 6 14
Initially S = 8, and X = 6. After appending 6
and 14, S_NEW = (8 + 6 + 14) = 28
and X_NEW = (6 ^ 6 ^ 14) = 14
Clearly, S_NEW = 2 * X_NEW
Input: arr[] = {1, 3}
Output: 2 6
Naive approach: Run two nested loops from 1 to S and check for each pair whether it satisfies the condition or not. This will take O(S2) time.
Efficient approach: It can be observed that if X and S + X are appended to the array then S_NEW = 2 * (S + X) and X_NEW = S + X which satisfy the given condition.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findNums( int arr[], int n)
{
int S = 0, X = 0;
for ( int i = 0; i < n; i++) {
S += arr[i];
X ^= arr[i];
}
cout << X << " " << (X + S);
}
int main()
{
int arr[] = { 1, 7 };
int n = sizeof (arr) / sizeof ( int );
findNums(arr, n);
return 0;
}
|
Java
class GFG
{
static void findNums( int arr[], int n)
{
int S = 0 , X = 0 ;
for ( int i = 0 ; i < n; i++)
{
S += arr[i];
X ^= arr[i];
}
System.out.println(X + " " + (X + S));
}
public static void main (String[] args)
{
int arr[] = { 1 , 7 };
int n = arr.length;
findNums(arr, n);
}
}
|
Python3
def findNums(arr, n) :
S = 0 ; X = 0 ;
for i in range (n) :
S + = arr[i];
X ^ = arr[i];
print (X, X + S);
if __name__ = = "__main__" :
arr = [ 1 , 7 ];
n = len (arr);
findNums(arr, n);
|
C#
using System;
class GFG
{
static void findNums( int []arr, int n)
{
int S = 0, X = 0;
for ( int i = 0; i < n; i++)
{
S += arr[i];
X ^= arr[i];
}
Console.WriteLine(X + " " + (X + S));
}
public static void Main()
{
int []arr = { 1, 7 };
int n = arr.Length;
findNums(arr, n);
}
}
|
Javascript
<script>
function findNums(arr , n) {
var S = 0, X = 0;
for (i = 0; i < n; i++) {
S += arr[i];
X ^= arr[i];
}
document.write(X + " " + (X + S));
}
var arr = [ 1, 7 ];
var n = arr.length;
findNums(arr, n);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...