Find Missing and Repeating
Problem Statement
You are given an array arr of size n. It should contain each number from 1 to n exactly once. Instead, one number A appears twice and one number B is missing.
Write findTwoElement(arr) that returns {A, B} — the repeating number first, then the missing number.
The array can be very large (up to 10^6 elements), so the solution should be O(N) time with O(1) extra space.
An integer array arr of size n, with values in 1..n.
A vector of two numbers: {A, B}, where A repeats and B is missing.
2 appears twice, so 1 is missing.
3 appears twice and 2 is missing.
1 appears twice and 5 is missing.
- • 2 ≤ n ≤ 10^6
- • 1 ≤ arr[i] ≤ n
- • Expected: O(N) time, O(1) auxiliary space.
- • Sums of the values (and of their squares) do not fit in `int` — use `long long` if you add them up.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each k in 1..n, scan the array and count k
Count every value once in an array of size n + 1
Swap each value v into index v − 1; the one wrong slot gives {A, B}
For k = 1, 2, …, n, count how often k appears by scanning the whole array. Count 2 is A; count 0 is B.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Cyclic Sort translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.