Mr. Anwar was released in 2004 and elected to Parliament in 2008 after the five-year restriction on his return to politics expired. That year, he was again accused of sodomy under a British-era law that human rights groups say is archaic. That case was also seen as being manipulated by his political rivals, including Mr. Najib, who became prime minister in 2009.

After years of suspension and legal jeopardy, he was sentenced to five years in prison on a sodomy charge in 2015. Originally scheduled to leave detention in June, he instead walked free on Wednesday morning.

He left Cheras Rehabilitation Hospital in Kuala Lumpur, the capital, where he was recovering from shoulder surgery, at 11:30 a.m. along with his wife, Dr. Wan Azizah Wan Ismail, who is to become deputy prime minister.

Mobbed by well-wishers, the two got into a vehicle together to travel to the royal palace, where they had an audience with Malaysia’s king, Sultan Muhammad V, who made it official: Mr. Anwar had been fully pardoned, lifting a statutory five-year ban on his political activity and allowing him to pursue elected office quickly.

The ouster of Mr. Najib last week marked the first time UMNO had been out of power since Malaysia’s independence from Britain in 1957. Many voters said they were upset about reports of widespread corruption, including accusations of the misappropriation of billions of dollars from 1Malaysia Development Berhad, a state fund he once led.

Mr. Najib and his wife have been barred from leaving the country, and Mr. Mahathir said he would be investigated. Officials accused of covering up the scandal have stepped down or were suspended in some of the first official acts of the new government.