We establish through numerical simulation conditions for optimal undulatory propulsion for a single fish, and for a pair of hydrodynamically interacting fish, accounting for linear and angular recoil. We first employ systematic two-dimensional (2-D) simulations to identify conditions for minimal propulsive power of a self-propelled fish, and continue with targeted 3-D simulations for a danio-like fish; all at Reynolds number 5000. We find that the Strouhal number, phase angle between heave and pitch at the trailing edge, and angle of attack are principal parameters. For 2-D simulations, imposing a deformation based on measured displacement for carangiform swimming provides, at best, efficiency of 35 %, which increases to 50 % for an optimized motion; for a 3-D fish, the efficiency increases from 22 % to 34 %. Indeed, angular recoil has significant impact on efficiency, and optimized body bending requires maximum bending amplitude upstream of the trailing edge. Next, we turn to 2-D simulation of two hydrodynamically interacting fish. We find that the upstream fish benefits energetically only for small distances. In contrast, the downstream fish can benefit at any position that allows interaction with the upstream wake, provided its body motion is timed appropriately with respect to the oncoming vortices. For an in-line configuration, one body length apart, the efficiency of the downstream fish can increase from 50 % to 60 %; for an offset arrangement it can reach 80 %. This proves that in groups of fish, energy savings can be achieved for downstream fish through interaction with oncoming vortices, even when the downstream fish lies directly inside the jet-like flow of an upstream fish.