In medium-voltage medium- and high-power inverters, which are most likely to connect distributed generation systems to grids, it is of great importance to reach high quality waveforms using the least possible number of switching transitions. The power quality is also important to be kept as high as possible. Both inverter output harmonics and grid pre-existing distortions affect the power quality. The well-known selective harmonic elimination pulse width modulation (SHEPWM) method is able to totally eliminate some specific harmonics. But the recently introduced selective harmonic mitigation pulse width modulation (SHMPWM) method can mitigate a higher number of harmonics using the same switching frequency. In this paper, implementation of an optimal selective harmonic mitigation (OSHM) method using the least possible switching frequency to satisfy three grid codes EN 50160, CIGRE JWG C4.07 and IEC 61000-3-6 is presented. In the proposed method, also a technique is employed to minimize the individual harmonics as much as possible. Using the proposed method, there is no need to the bulky and heavy line side filters. Some simulations as well as experimental investigations are carried out to prove the claim and also compare the OSHM method with the conventional SHEPWM method using the same switching pattern to confirm its better performance over SHEPWM.