Nikon D40 has a 6.0MP APS-C (23.7 x 15.5 mm ) sized CCD sensor . On the other hand, Pentax K-S2 has a 20.0MP APS-C (23.5 x 15.6 mm ) sized CMOS sensor and features PRIME MII processor.
Pentax K-S2's sensor provides 14MP more than Nikon D40's sensor, which gives a significant advantage in real life. You can print your images larger or crop more freely.
On the other hand, please keep in mind that Max sensor resolution is not the only determinant of resolving power. Factors such as the optical elements, low pass filter, pixel size and sensor technology also affects the final resolution of the captured image.
One other difference between these two cameras that is worth mentioning is that Pentax K-S2's sensor doesn't have an anti-alias (Low-Pass) filter. Removing anti-alias filter increases the sharpness and level of detail but at the same time, it increases the chance of moire occurring in certain scenes.
Below you can see the D40 and K-S2 sensor size comparison.
Sensor Size and Resolution Comparison image of Nikon D40 and Pentax K-S2 Cameras
Nikon D40 and Pentax K-S2 have almost the same sensor size so none of them has any significant advantage over other in providing control over depth of field when used with same focal length and aperture.