Engineering coherent perfect absorption and lasing