The concept used here is the Law of Conservation of Mass. Technically, it's more specifically included in the Law of Definite Proportions. According to Dalton's atomic theory, when substances react together, they form a compound that has the same fixed ratio of the individual elements. That is the main reason why we balance, because stoichiometric coefficients are essential to obey the Law.
For the reaction a + b ⇒ ab, this is a combination reaction. For every 1 mole of a and 1 mole of b, 1 mole of product ab is formed. This is the fixed ratio we have to follow: 1:1:1. Now, the next thing to note is the limiting and excess reactant. If initially, there are 2 moles of A and 3 moles of B, the limiting reactant is A and the excess is B. Since the ratio between reactants is 1:1, 3 moles of B requires 3 moles of A. But since only 2 moles are available, reactant A is limited. In this problem, we assume that B is provided in excess. So, we just focus on the amount of the limiting reactant a.
If there are 5,000 molecules of a, we can determine the molecules of ab using the fixed ratio, 1 part a is to 1 part ab. Then, that means that 5,000 molecules of a would yield also 5,000 molecules of ab.