Back to Arrays
Q82Question 82 of 109

Single Number (Find the One Element That Appears Once)

Key Concepts
  • Array traversal, search, and manipulation
  • Common patterns: two-pointer, prefix sum, sliding window
  • Find max/min, reverse, rotate, remove duplicates
  • Time complexity: O(n) traversal, O(1) access by index
  • XOR has three properties we rely on: a number XOR itself is zero, a number XOR zero is itself, and XOR is commutative and associative so order does not matter.
  • We start a running result at zero and XOR every element into it: `int result = 0; for (int n : nums) result ^= n;`.
  • Because each paired value appears an even number of times, those values XOR to zero, and only the odd-one-out remains in `result`.

Definition

XOR all numbers together; pairs cancel to zero and the single unpaired number survives.

Single Number is the foundational Bitwise XOR problem. Because XOR of a number with itself is zero and XOR with zero leaves the number unchanged, XOR-ing every element together cancels each pair and leaves only the unpaired number. This runs in O(n) time and O(1) space, beating a hash-set approach on memory.

At the National Bank of India, every reconciliation entry should appear twice, once as a debit leg and once as a matching credit leg, except for one orphan entry that was posted only once. If we XOR all the entry codes together, every matched pair cancels out and the lone orphan code remains.

Understanding the Concepts

What is the problem?

Single Number (Find the One Element That Appears Once). In an array where every number appears exactly twice except for one number that appears once, find that single number using constant extra space. Explain why XOR of all elements gives the answer.

How does the approach work?

XOR has three properties we rely on: a number XOR itself is zero, a number XOR zero is itself, and XOR is commutative and associative so order does not matter. We start a running result at zero and XOR every element into it: int result = 0; for (int n : nums) result ^= n;. Because each paired value appears an even number of times, those values XOR to zero, and only the odd-one-out remains in result.

This is strictly better than the obvious approaches. Sorting then scanning is O(n log n); a hash set counting occurrences is O(n) time but O(n) space. The XOR method is O(n) time and O(1) space, which is the senior-level answer the interviewer is looking for.

A senior nuance is that XOR works here precisely because every other element is perfectly paired; if elements could appear three times or some other odd count, this simple XOR would not isolate the single number and we would need bit-counting across positions instead. Complexity is O(n) time and O(1) space.

What is the banking use case?

Problem 1 — The National Bank of India posts reconciliation entries in matched debit and credit pairs, but a glitch left exactly one entry unmatched, and operations must find that orphan code without allocating a big lookup structure on a memory-constrained batch node. This is exactly how Single Number works.
Problem 2 — Building a hash set of all codes would work but wastes memory on huge batches. This is why we XOR all codes together so matched pairs cancel and the orphan survives, using only one integer of extra space.

The code defines a ReconService exposing findOrphan(codes) returning the unmatched code. A Demo runs it over a batch with one orphan and logs the orphan code.

How do you implement this in Java?

JAVA
// ─── File: src/main/java/com/bank/recon/service/ReconService.java ───
package com.bank.recon.service;

import java.util.logging.Logger;

// Finds the single unmatched reconciliation code via XOR.
public class ReconService {
    private static final Logger log = Logger.getLogger(ReconService.class.getName());

    public int findOrphan(int[] codes) {
        int result = 0;
        for (int code : codes) result ^= code; // pairs cancel to zero
        final int orphan = result;
        log.info(() -> "Unmatched reconciliation code = " + orphan);
        return result;
    }
}
JAVA
// ─── File: src/main/java/com/bank/recon/ReconOrphanApplication.java ───
package com.bank.recon;

import com.bank.recon.service.ReconService;
import java.util.logging.Logger;

public class ReconOrphanApplication {
    private static final Logger log = Logger.getLogger(ReconOrphanApplication.class.getName());

    public static void main(String[] args) {
        ReconService service = new ReconService();
        int[] codes = {7012, 7045, 7012, 7099, 7045}; // 7099 is the orphan
        log.info("Orphan code: " + service.findOrphan(codes));
    }
}

What is the project structure?

DIAGRAM
recon-orphan-service/
├── pom.xml
├── src/
│   ├── main/
│   │   ├── java/com/bank/recon/
│   │   │   ├── ReconOrphanApplication.java       (main class)
│   │   │   └── service/
│   │   │       └── ReconService.java
│   │   └── resources/
│   │       └── application.yml
│   └── test/
│       └── java/com/bank/recon/
│           └── ReconServiceTest.java

How do you build and run?

BASH
# Build
mvn clean package -DskipTests

# Run
java -jar target/recon-orphan-service-1.0.0.jar

# Verbose
java -Djava.util.logging.ConsoleHandler.level=FINE \
  -jar target/recon-orphan-service-1.0.0.jar

What is the step-by-step walkthrough?

Input: codes 7012, 7045, 7012, 7099, 7045.

Step 1: result starts at 0. XOR 7012 gives 7012.
Step 2: XOR 7045 gives 7012 XOR 7045.
Step 3: XOR 7012 cancels the earlier 7012, leaving 7045.
Step 4: XOR 7099 gives 7045 XOR 7099.
Step 5: XOR 7045 cancels the earlier 7045, leaving 7099, the orphan.
CODE
Oct 27, 2026 10:52:41 PM com.bank.recon.service.ReconService findOrphan
INFO: Unmatched reconciliation code = 7099
INFO: Orphan code: 7099

What is the high-level design?

DIAGRAM
  ═══ HLD — Reconciliation Orphan Finder (Banking) ═══

  ┌────────────┐ HTTPS ┌──────────────┐ REST ┌─────────────────────┐
  │ Recon Batch│──────→│ API Gateway  │─────→│ Recon Svc ×2        │
  └────────────┘       │ (JWT, rate)  │      │ (Spring Boot)       │
                       └──────────────┘      └─────────┬───────────┘
                                                      │ stream codes
                                                      ▼
                                           ┌─────────────────────┐
                                           │ Ledger entries store │
                                           └─────────────────────┘

What is the low-level design?

DIAGRAM
  ═══ LLD — Single Number ═══

  ┌─ Design Patterns Used ──────────────────────────────────┐
  │  XOR fold (self-inverse cancels pairs)                   │
  │     WHY: O(1) space, no lookup structure                 │
  └──────────────────────────────────────────────────────────┘

  ┌─ SOLID Principles Applied ──────────────────────────────┐
  │  S: service only isolates the orphan                     │
  │  O: any paired-with-one-odd input works                  │
  │  D: depends only on primitive int array                  │
  └──────────────────────────────────────────────────────────┘

  ── Class Diagram ──────────────────────────────────────────
  ┌──────────────────────────────────────┐
  │ ReconService                          │
  │ ───────────────────────────────────── │
  │ + findOrphan(codes): int              │
  └──────────────────────────────────────┘

  ── State: single running XOR accumulator ─────────────────
  result ^= each code; pairs vanish

  Contract for findOrphan(codes):
    Pre:  every code paired except exactly one
    Post: the single unpaired code

What is the time and space complexity?

Analyze the solution based on the algorithm used. Consider both the time to process input and the space required for any data structures.

What are common mistakes?

Common mistakes include off-by-one errors, not handling edge cases like empty input, and not considering the constraints of the problem.

What are the edge cases?

Edge cases include empty input, single element input, all identical elements, and boundary values.

What should a senior engineer know?

A senior engineer should understand the time-space tradeoffs, be able to explain the algorithm clearly, and know when this technique applies versus alternatives.

Visual Overview

DIAGRAM
  codes:[7012,7045,7012,7099,7045]
    │  fold with XOR (identity 0)
    ▼
  0 ^7012 ^7045 ^7012 ^7099 ^7045
    │ paired 7012 cancel, paired 7045 cancel
    ▼
  result = 7099  (the single unmatched code)

Key Takeaway

Single Number is the foundational Bitwise XOR problem. Every element appears twice except one, and I exploit three properties of XOR: a number XOR-ed with itself is zero, a number XOR-ed with zero is unchanged, and XOR is order-independent. So if I fold every element into a running accumulator with XOR, each perfectly paired value cancels itself to zero, and the only value left standing is the one that appeared once.

This beats the alternatives on the metric interviewers care about. Sorting and scanning is n log n, and a hash set is linear time but linear space. The XOR fold is linear time and constant space, which is the senior answer. I would be clear that this trick depends on every other element being exactly paired; if elements repeated an odd number of times I would instead count set bits across each bit position.

At the National Bank of India I used this when reconciliation entries, which should always come in matched debit and credit pairs, left exactly one orphan after a glitch, and the batch node was memory-constrained. I XOR-ed all the entry codes together so every matched pair cancelled and the orphan code remained, using just a single integer of extra space. Explaining the self-inverse property of XOR and why it gives constant space is what shows an interviewer I understand the bit-level reasoning rather than just the trick.

Remember one sentence: understand the core algorithm and apply it to banking domain problems.

---

Share
Use ← → arrow keys to navigate