Molecular freeze-out as a tracer of the thermal and dynamical evolution of pre- and protostellar cores