Looking at the energy level of the Schrödinger equation solution for the hydrogen atom, you would guess that for multi-electron atoms that only the principal quantum number would matter, azimuthal quantum number getting filled randomly.
However, orbitals energies for large atoms don't increase in energy like those of hydrogen due to electron-electron interactions.
In particular, the following would not be naively expected:
  • 2s fills up before 2p. From the hydrogen solution, you might guess that they would randomly go into either one as they'd have the same energy
  • in potassium fills up before 3d, even though it has a higher principal quantum number!
This rule is only an approximation, there exist exceptions to the Madelung energy ordering rule.
The most notable exception is the borrowing of 3d-orbital electrons to 4s as in chromium, leading to a 3d5 4s1 configuration instead of the 3d4 4s2 we would have with the rule. TODO how is that observed observed experimentally?