The loss of Istanbul, which has been in his party’s hands since Mr. Erdogan was mayor in the 1990s, caught the party by surprise, one of its lawmakers from the city acknowledged. Istanbul is Mr. Erdogan’s home base and a huge source of wealth and prestige for the A.K.P.

The legislator, who spoke on condition of anonymity in keeping with party guidelines, said Istanbul had been presumed to be in the bag. But the last election proved that assumption flawed, at best.

Ihsan Aktas of the Genar polling firm, which had correctly predicted a close race in Istanbul, said the A.K.P. “forgot how to win by winning so often.” The opposition, he said, was far more motivated and united because of its opposition to Mr. Erdogan.

Opinion polls show the opposition candidate, Mr. Imamoglu, 49, just ahead of Mr. Yildirim, 63. Mr. Imamoglu, mayor of an outlying district of Istanbul, won support with an all-embracing grass-roots campaign that played well with residents of the city.

Many have grown weary of more than 20 years of the A.K.P.’s running Istanbul and are feeling the bite of an economic downturn as the currency, the lira, has shed much of its value.

Some analysts have predicted that a sympathy vote for Mr. Imamoglu — who was declared winner and took up office the first time around, only to have his mandate subsequently withdrawn — could increase his chances in the rerun.