A bench headed by Justice Ranjan Gogoi said the amendment in the legislation was ultra vires to the Constitution since it transgresses the concept of equality under the Constitution.
The bench said the amendment was "arbitrary, discriminatory" and violates the concept of equality.
The apex court said that once such persons demit public office, there is nothing to distinguish them from the common man.
The apex court had on April 19 reserved its verdict on an NGO's plea challenging amendments to the UP legislation allowing ex-chief ministers of the state to continue occupying government bungalows.
The top court had earlier observed that if the provision, which has been challenged by NGO Lok Prahari, was held invalid, then similar legislation in other states might also come under challenge.
The NGO had challenged the amendments made by the erstwhile Akhilesh Yadav government to the 'UP Ministers (Salaries, Allowances and Miscellaneous Provisions) Act, 1981'.
It had also challenged another UP law of 2016 called 'The Allotment of Houses under Control of the Estate Department Bill-2016' to regulate the allotment of government accommodation to trusts, journalists, political parties, speaker and deputy speaker of the legislative assembly, judicial officers and government officials.