The script makes it entirely clear how he worked it out. It was the expression on Doctor Stelline's face when she recognised the memory ("Ana stops the imaging. Affected by what she is seeing.").
At the time he thought it was sympathy for the person in his memory, but he now realises that it was the fact that the memory was especially vivid for her because it's one of her own memories that she implanted into Wallace's Replicants
K: No. A girl died. It was a boy you hid.
Freysa shakes her head knowingly.
FREYSA: Just a piece a puzzle.
A wave of nausea rocks K. The crushing realization slowly taking
root... eating away at his new soul... He was wrong about who he is.
ON K. At the moment he sees it. The connection forming.
INSERT CUT: ANA. STARING, CONFUSED, MOVED BY WHAT SHE SEES IN K’S
MEMORY. A MOMENT OF RECOGNITION.
ANA: No one invented that. It was a real moment. Someone lived this.
INSERT CUT: THE DENABASE SCREEN. THE TWO COPIES. THE GHOST AND THE
REAL.
DECKARD (V.O.): I showed them how to scramble the records, cover their
tracks.
INSERT CUT: THE CHILD WITH THE HORSE IN FRONT OF THE FIERY FURNACE.
CHIN SET, DETERMINED.
INSERT CUT: ON ANA. LOOKING AT K.
ANA: There is a bit of every artist in their work...
BACK ON K. RIVEN. THE TRUTH REVEALED. THE CASE SOLVED AT HIS OWN
EXPENSE. IT WAS NEVER HIM AT ALL.
Something inside K breaks. Freysa can see his pain. And understands.
FREYSA: You imagine it was you? Ohhhh... You did, you did. We all wish it was us. That’s why we believe.
ON K -- SHAKING -- SHATTERED -- WE MOVE --