Check if it is possible to construct an Array of size N having sum as S and XOR value as X
Last Updated :
23 Jul, 2025
Given three numbers N, S and X the task is to find if it is possible to construct a sequence A of length N, where each A[i] >= 0 for 1<=i<=N and the sum of all numbers in a sequence is equal to S, and the bit-wise XOR of sequence equals to X.
Examples:
Input: N = 3, S = 10, X = 4
Output: Yes
Explanation: One of the sequence possible is {4, 3, 3} where sum equals 10 and XOR equals 4
Input: N = 1, S = 5, X = 3
Output: No
Approach: Lets consider the following test cases.
Case-1: When N equals 1 it can be easily seen that when (S equals X) then only return "Yes" otherwise "No".
Case-2: When N is greater than equal to 3, use the formula (a + b) = (a xor b) + 2(a and b) Here it can be seen that (a + b) = S and (a xor b) = X so equation becomes S = X + 2(a.b). Therefore, (S-X) should be even because on right side we have 2(a.b). So, it can be said that is S is odd then X is odd and if S is even then X is even then only, (S-X) is also even which can be checked by (S%2 == X%2) also S >= X otherwise A.B turns negative Which is not possible.
Case-3: For the case N equals 3, it is something like A + B + C = S and A^B^C = X. Use the property A^A = 0 and 0^A = A => X + ( S - X)/2 + (S - X)/2 = X + (S-X) => X + ( S - X)/2 + (S - X)/2 = S and also this way: X ^( (S - X)/2 ^ (S-X)/2 ) = X ^ 0 = X. Hence, it is proved that for N == 3 there will always be such sequence and we can just return "Yes".
Case-4: When N == 2 and (S%2 == X%2) and S >= X, assume A + B == S and (A^B) == X then ( A and B) == (S-X)/2 From the equation discussed above. Let C = A.B. On observing carefully it can be noticed that the bits of C are "1" only when A and B bits are "1" for that position and off otherwise. And X that is xor of A, B has on bit only when there are different bits that is at ith position A has '0' and B has '1' or the just opposite: So looking at this sequence, assign every bits into variable A and B, C = ( S - X)/2. Assign A and B from C -> A = C, B = C
Now add the X into A or B to assign all the ones into A and all zero to B so when we XOR both numbers then the added '1' bits into A will just be opposite to what we added into B that is '0'. The fun part is when set bits of C coincides with some set bits of X then it will not give the desired xor of X, Now, A = C + X, B = C. Now A+B = ( C + X) + C = S and when XOR A.B equals X then it can be sure that there exist such pair when A + B == S and (A^B) == X;

Follow the steps below to solve the problem:
- If S is greater than equal to X, and S%2 is equal to X%2 then perform the following steps, else return No.
- If n is greater than equal to 3, then return Yes.
- If n equals 1, and if S equals X, then return Yes else return No.
- If n equals to 2, initialize the variable C as (S-X)/2 and set variables A and B as C and add the value X to the variable A and if A^B equals X, then print Yes else print No.
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find if any sequence is
// possible or not.
string findIfPossible(int N, int S, int X)
{
if (S >= X and S % 2 == X % 2) {
// Since, S is greater than equal to
// X, and either both are odd or even
// There always exists a sequence
if (N >= 3) {
return "Yes";
}
if (N == 1) {
// Only one case possible is
// S == X or NOT;
if (S == X) {
return "Yes";
}
else {
return "No";
}
}
// Considering the above conditions true,
// check if XOR of S^(S-X) is X or not
if (N == 2) {
int C = (S - X) / 2;
int A = C;
int B = C;
A = A + X;
if (((A ^ B) == X)) {
return "Yes";
}
else {
return "No";
}
}
}
else {
return "No";
}
}
// Driver Code
int main()
{
int N = 3, S = 10, X = 4;
cout << findIfPossible(N, S, X);
return 0;
}
C
// C program for the above approach
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to find if any sequence is
// possible or not.
char* findIfPossible(int N, int S, int X)
{
if (S >= X && S % 2 == X % 2) {
// Since, S is greater than equal to
// X, and either both are odd or even
// There always exists a sequence
if (N >= 3) {
return "Yes";
}
if (N == 1) {
// Only one case possible is
// S == X or NOT;
if (S == X) {
return "Yes";
}
else {
return "No";
}
}
// Considering the above conditions true,
// check if XOR of S^(S-X) is X or not
if (N == 2) {
int C = (S - X) / 2;
int A = C;
int B = C;
A = A + X;
if (((A ^ B) == X)) {
return "Yes";
}
else {
return "No";
}
}
}
else {
return "No";
}
}
// Driver Code
int main()
{
int N = 3, S = 10, X = 4;
printf("%s\n", findIfPossible(N, S, X));
return 0;
}
// This code is contributed by phalasi.
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find if any sequence is
// possible or not.
static void findIfPossible(int N, int S, int X)
{
if ((S >= X) && (S % 2 == X % 2)) {
// Since, S is greater than equal to
// X, and either both are odd or even
// There always exists a sequence
if (N >= 3) {
System.out.println("Yes");
}
if (N == 1) {
// Only one case possible is
// S == X or NOT;
if (S == X) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
// Considering the above conditions true,
// check if XOR of S^(S-X) is X or not
if (N == 2) {
int C = (S - X) / 2;
int A = C;
int B = C;
A = A + X;
if (((A ^ B) == X)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
else {
System.out.println("No");
}
}
// Driver code
public static void main(String args[])
{
int N = 3, S = 10, X = 4;
findIfPossible(N, S, X);
}
}
// This code is contributed by code_hunt.
Python3
# Python program for the above approach
# Function to find if any sequence is
# possible or not.
def findIfPossible(N, S, X):
if (S >= X and S % 2 == X % 2):
# Since, S is greater than equal to
# X, and either both are odd or even
# There always exists a sequence
if (N >= 3):
return "Yes"
if (N == 1):
# Only one case possible is
# S == X or NOT
if (S == X):
return "Yes"
else:
return "No"
# Considering the above conditions true,
# check if XOR of S^(S-X) is X or not
if (N == 2):
C = (S - X) // 2
A = C
B = C
A = A + X
if (((A ^ B) == X)):
return "Yes"
else:
return "No"
else:
return "No"
# Driver Code
N = 3
S = 10
X = 4
print(findIfPossible(N, S, X))
# This code is contributed by shivanisinghss2110
C#
// C# program for the above approach
using System;
public class GFG {
// Function to find if any sequence is
// possible or not.
static void findIfPossible(int N, int S, int X)
{
if ((S >= X) && (S % 2 == X % 2)) {
// Since, S is greater than equal to
// X, and either both are odd or even
// There always exists a sequence
if (N >= 3) {
Console.WriteLine("Yes");
}
if (N == 1) {
// Only one case possible is
// S == X or NOT;
if (S == X) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
// Considering the above conditions true,
// check if XOR of S^(S-X) is X or not
if (N == 2) {
int C = (S - X) / 2;
int A = C;
int B = C;
A = A + X;
if (((A ^ B) == X)) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
}
else {
Console.WriteLine("No");
}
}
// Driver code
public static void Main(String[] args)
{
int N = 3, S = 10, X = 4;
findIfPossible(N, S, X);
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Function to find if any sequence is
// possible or not.
function findIfPossible(N, S, X) {
if (S >= X && S % 2 == X % 2) {
// Since, S is greater than equal to
// X, and either both are odd or even
// There always exists a sequence
if (N >= 3) {
return "Yes";
}
if (N == 1) {
// Only one case possible is
// S == X or NOT;
if (S == X) {
return "Yes";
}
else {
return "No";
}
}
// Considering the above conditions true,
// check if XOR of S^(S-X) is X or not
if (N == 2) {
let C = (S - X) / 2;
let A = C;
let B = C;
A = A + X;
if (((A ^ B) == X)) {
return "Yes";
}
else {
return "No";
}
}
}
else {
return "No";
}
}
// Driver Code
let N = 3, S = 10, X = 4;
document.write(findIfPossible(N, S, X));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem