A former prime minister who holds dual Somali-US citizenship has been declared Somalia's new president.
Abdullahi Mohamed Farmajo was named the new leader after two rounds of voting on Wednesday and quickly took the oath of office.
Incumbent President Hassan Sheikh Mohamud conceded defeat.
"History was made. We have taken this path to democracy, and now I want to congratulate Mohamed Abdullahi Farmajo," Mohamud said.
The country is trying to put together its first fully functioning central government in a quarter-century.
The protracted vote began on Wednesday after 14,000 elders and prominent regional figures chose 275 members of parliament and 54 senators, who in turn chose whether to back Mohamud for a second term or one of 21 rivals.
Fears of attacks by al-Shabab, an armed group, limited the election to the country's legislators, who voted at a heavily guarded former air force base in the capital, Mogadishu.
|Fears of attacks by al-Shabab limited the election to the country's legislators [Feisal Omar/Reuters]
Al Jazeera's Mohammed Adow, reporting from the capital Mogadishu, said sources within the parliament had confirmed that huge sums of money were paid by some of the candidates and rival presidential candidates have accused each other of buying the loyalty of MPs, drawing furious denials.
"One member of the parliament told me that he received thousands from one of the presidential candidates," he said.
"There is lot at stake here. This election is supposed to bring leadership that heals the country but if corruption plays an important role, many doubt whether Somalia is going to be on the right road."
In 2012, just 135 elders picked the MPs, who chose the president.
"It tells us that we are in the midst of a long transition and in theory, based on the provisional constitution we should be having a one-person-one-vote election this year, but that hasn't been possible because of security constraints but also because the government did not focus on preparing the ground," Matt Bryden, chairman of Sahan Research and Development Organisation, a political think-tank covering the Horn of Africa, told Al Jazeera.
"This is an ad hoc political compromise agreed by Somalia political leaders, which is simply a way of continuing a transition and giving us four more years in which to consolidate architecture of the new Somalia state."
READ MORE: Somalia beefs up security ahead of presidential vote
The airport, where the vote was taking place, was guarded by the African Union peacekeeping force AMISOM and is surrounded by high concrete barriers to protect it from attack.
UN agencies and foreign embassies were also located in the compound.
Al-Shabab, which ruled Somalia for several years, has been slowly driven out of its major strongholds in a campaign by AMISOM and Somali troops.
But its fighters continue to launch regular gun and bomb attacks in their effort to topple the government.
Source: Al Jazeera and news agencies