Thursday, January 15, 2026

Find Pairs - Unordered pairs with Bitwise-XOR condition (Easy)

Index of "Algorithms: Design and Analysis"

Solve on HackerEarth    Test Cases
Problem
Given an array 
 of 
 integers. Find the number of unordered pairs 
, 
 such that 
    `
 is odd where 
 represents bitwise XOR operation.
Input format

The first line contains three space-separated integers 
.
The next line contains 
 space-separated integers denoting the array 
Output format

Print the number of unordered pairs 
 which satisfy the above conditions in a new line.

Constraints

1 ≤ N ≤ 10^5
 

Sample Input
4 2 10
1 2 3 4
Sample Output
4
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
Following unordered pairs satisfy the above conditions:

Key Learnings on Paper

My Code


N, L, R = tuple(map(int, input().split()))
A = list(map(int, input().split()))

odd_num = []
even_num = []

for i in A:
    if i % 2 == 0:
        even_num.append(i)
    else:
        odd_num.append(i)


from bisect import bisect_left, bisect_right


even_num.sort()
ans = 0
for o in odd_num:
    left = bisect_left(even_num, L-o)
    right = bisect_right(even_num, R-o)
    ans += (right - left)

print(ans)

Help I Took From ChatGPT

Explain the second required condition in this coding puzzle

Let’s focus only on the second condition, explain it in plain language, and build intuition step by step.


ЁЯФ╣ The second condition (from the problem)

A[i] ⊕ A[j] is odd, where ⊕ means bitwise XOR


ЁЯФ╣ What does “XOR” mean? (very simply)

XOR compares two numbers bit by bit:

  • 0 ⊕ 0 = 0

  • 1 ⊕ 1 = 0

  • 0 ⊕ 1 = 1

  • 1 ⊕ 0 = 1

So:

  • Bits that are different → 1

  • Bits that are same → 0


ЁЯФ╣ What makes a number odd?

A number is odd if its last bit (LSB) is 1.

Example:

  • 5 = 101 → odd

  • 6 = 110 → even

So for:

css
A[i]A[j] to be odd

ЁЯСЙ the last bit of the XOR must be 1


ЁЯФС Crucial Insight (this is the whole trick)

The last bit of A[i] ⊕ A[j] depends only on the last bits of A[i] and A[j].

Let’s check all possibilities:

A[i]A[j]Last bit of A[i]Last bit of A[j]XOR last bitOdd?
eveneven000
oddodd110
evenodd011
oddeven101

✅ Conclusion (VERY IMPORTANT)

A[i] ⊕ A[j] is odd if and only if one number is even and the other is odd.

That’s it.

No need to compute XOR explicitly.


ЁЯФ╣ What the condition really means (in plain English)

The problem is secretly saying:

“Only count pairs where one element is odd and the other is even.”


ЁЯзк Example from the sample

Array

ini
A = [1, 2, 3, 4]
PairValuesOdd/EvenXOROdd?
(1,2)1,2odd, even3
(1,3)1,3odd, odd2
(1,4)1,4odd, even5
(2,3)2,3even, odd1
(2,4)2,4even, even6
(3,4)3,4odd, even7

Exactly the pairs listed in the explanation.


ЁЯза Why problem setters love this condition

Because:

  • It sounds complicated

  • But reduces to a simple parity check

  • It tests whether you understand bitwise logic


ЁЯФС One-line takeaway

The XOR of two numbers is odd if and only if they have opposite parity (one odd, one even).


If you want next, I can:

  • Show how this simplifies the full solution

  • Combine this with the sum condition efficiently

  • Write the optimized algorithm

  • Explain why brute force fails

Just tell me ЁЯШК


yes, write the complete code and explain in layman terms

Great ЁЯСН
Let’s do this step by step, in very simple language, and then I’ll give you the complete working code.


ЁЯФН Problem recap (in plain English)

You are given:

  • An array A of N numbers

  • Two numbers L and R

You must count how many unordered pairs (i, j) (with i < j) satisfy both conditions:

✅ Condition 1: Sum condition

css
L ≤ A[i] + A[j]R

✅ Condition 2: XOR condition

css
A[i]A[j] is odd

ЁЯза Key observations (the tricks)

ЁЯФС Trick 1: Understanding the XOR condition

As we discussed earlier:

A[i] ⊕ A[j] is odd
if and only if one number is odd and the other is even

So:

  • Ignore XOR completely

  • Just ensure one odd + one even


ЁЯФС Trick 2: Split the array

Separate the array into:

  • odds → all odd numbers

  • evens → all even numbers

Now:

  • We only form pairs between odds and evens

  • Never odd–odd or even–even


ЁЯФС Trick 3: Efficiently count valid sums

For each odd number:

  • Count how many even numbers form a valid sum in [L, R]

To do this fast:

  1. Sort the evens list

  2. For each odd, find:

    • how many even values satisfy:

      css
      L - odd ≤ even ≤ R - odd
  3. Use binary search to count that range


⚙️ Why this is fast

  • Sorting: O(N log N)

  • Each search: O(log N)

  • Total: O(N log N) → works for N ≤ 10⁵


✅ Complete Python Code

python
def solve(): import sys input = sys.stdin.readline from bisect import bisect_left, bisect_right # Read inputs N, L, R = map(int, input().split()) A = list(map(int, input().split())) # Separate odds and evens odds = [] evens = [] for x in A: if x % 2 == 0: evens.append(x) else: odds.append(x) # Sort evens for binary search evens.sort() ans = 0 # For each odd, count valid evens for odd in odds: low = L - odd high = R - odd left_idx = bisect_left(evens, low) right_idx = bisect_right(evens, high) ans += (right_idx - left_idx) print(ans)

ЁЯзк Example walk-through

Input

4 2 10 1 2 3 4

Step 1: Split

ini
odds = [1, 3] evens = [2, 4]

Step 2: Check pairs

OddEvenSumValid?
123
145
325
347

Answer = 4


ЁЯза One-line intuition

“Count how many odd–even pairs have sums in the required range.”


ЁЯОУ What this problem teaches you

  1. XOR parity trick (odd ↔ different parity)

  2. Breaking a hard condition into a simple rule

  3. Using binary search to avoid brute force

  4. Thinking in terms of pair counting

  5. Writing scalable solutions for large input


If you want next, I can:

  • Optimize further

  • Add comments line-by-line

  • Show a brute-force version for comparison

  • Convert this to C++ / Java

Just tell me ЁЯШК


is bisect a core python package or I would need to do some setup

Good question — this is an important practical detail ЁЯСН

✅ Short answer

bisect is a core Python module.
You do NOT need to install anything.

It comes bundled with Python by default.


ЁЯУж What is bisect?

bisect is part of Python’s standard library.

You can safely use:

python
from bisect import bisect_left, bisect_right

in:

  • Competitive programming

  • Interviews

  • Online judges (Codeforces, LeetCode, HackerEarth, etc.)

  • Local Python installations


ЁЯза What bisect does (quick reminder)

It performs binary search on a sorted list.

Example:

python
from bisect import bisect_left, bisect_right arr = [2, 4, 6, 8] bisect_left(arr, 4) # 1 bisect_right(arr, 4) # 2

So the count of 4 is:

2 - 1 = 1

❌ When would you need setup?

Only if:

  • You’re using a very restricted runtime (rare)

  • Or a non-standard Python implementation (also rare)

In 99.9% of cases → no setup needed


ЁЯзк If you want to avoid bisect (optional)

You could implement binary search manually — but that’s not necessary and worse for readability.


✅ Final verdict

✔️ bisect is safe
✔️ No installation required
✔️ Standard, accepted, efficient

You’re good to go ЁЯЪА


what if the sought out number is not in input array then what does bisect do?

Excellent question — this gets to the heart of what bisect actually does ЁЯСН
And the answer is exactly why bisect is perfect for this problem.


ЁЯФ╣ Short answer

bisect does NOT search for the element.
It finds the position where the element should be inserted to keep the list sorted.

So it works even if the number is not present.


ЁЯФ╣ What does bisect_left do?

python
bisect_left(arr, x)

ЁЯСЙ Returns the index where x should be inserted so that:

  • the list remains sorted

  • x would go before any equal elements


ЁЯФ╣ What does bisect_right do?

python
bisect_right(arr, x)

ЁЯСЙ Returns the index where x should be inserted:

  • after any equal elements


ЁЯзк Example 1: Number NOT in array

python
arr = [2, 4, 6, 8] bisect_left(arr, 5) # 2 bisect_right(arr, 5) # 2

Why?

csharp
[2, 4, |5|, 6, 8] ↑ index 2

So the range [2, 2) contains 0 elements → correct.


ЁЯзк Example 2: Count numbers in a range (THIS is the trick)

python
arr = [2, 4, 6, 8, 10] low = 5 high = 9 left = bisect_left(arr, low) # 2 right = bisect_right(arr, high) # 4 count = right - left # 2

Numbers in [5, 9] are:

6, 8

✔️ Correct


ЁЯФ╣ Why this is perfect for our problem

We want:

nginx
low ≤ even ≤ high

We compute:

python
left = bisect_left(evens, low) right = bisect_right(evens, high)

And count:

python
right - left

Even if:

  • low or high do NOT exist in the array

  • OR the array has no valid values

ЁЯСЙ bisect still gives the correct count


ЁЯза Mental model (easy to remember)

bisect answers: “Where would this number go?”

Not:

“Is this number present?”


ЁЯФ╣ One-line takeaway

bisect works on positions, not on presence — which is exactly why it’s used for range counting.


If you want, I can:

  • Draw a visual diagram

  • Compare with linear scan

  • Show how wrong code behaves without bisect

  • Explain bisect edge cases

Just tell me ЁЯШК


No comments:

Post a Comment