Find the Two Repeating Elements
Problem Statement
You are given an array arr of size n + 2. Every value is between 1 and n. Each value 1..n appears once, except two values that appear twice.
Return those two repeated values in the order of their second occurrence: the value whose second copy comes first (from the left) goes first. This is the order the GFG practice problem "Two Repeated Elements" expects.
The function here is vector<int> twoRepeated(vector<int>& arr), where n = arr.size() − 2. Aim for O(N) time and O(1) extra space.
An integer array arr of size n + 2, with 1 ≤ arr[i] ≤ n.
The two repeated values, ordered by where their second copy appears.
1 repeats at index 2, and 3 repeats at index 5. Index 2 comes first, so 1 is listed first.
1 appears first in the array, but its second copy is at index 3. The second copy of 2 is at index 2, so 2 comes first.
3 appears first, but 1 repeats first (index 3), then 3 (index 4).
- • 2 ≤ n ≤ 10^5
- • arr.length == n + 2
- • 1 ≤ arr[i] ≤ n
- • Exactly two values appear twice; every other value 1..n appears once.
- • Expected: O(N) time, O(1) extra space.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each i, scan indices before i for the same value
Remember each value in a bool array; report on the second sighting
Make arr[x − 1] negative the first time x is seen; already negative means repeat
Walk left to right. For each arr[i], scan arr[0 … i−1]. If an equal value is there, i is that value's second occurrence, so push it. Stop after two.
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.