Michael Poplawski, 21, who is studying finance and accounting at the University of Warsaw, described himself as an ardent supporter of capitalism and said he decided, in the end, to support Mr. Komorowski.

But he knows many of his fellow students rejected the president.

“I think it was mostly a protest vote,” he said. “A rejection of the current president and the ruling party, which made many promises in the last election but failed to keep them.”

The key, Mr. Poplawski said — and many political analysts agree — had been the surprising rise of a third-party challenge by a well-known rock star, Pawel Kukiz.

In the first round of voting, in early May, no candidate got over 50 percent, setting up a second round between Mr. Komorowski and Mr. Duda. But in that first round, Mr. Kukiz assembled a coalition of angry retirees, rowdy anarchists and disaffected youth that drew 20 percent of the vote, stunning the Polish elite.

In the second round, it was Mr. Duda who won most of those Kukiz voters even though the platform of his party, Law and Justice, had virtually no correlation to the grab bag of changes that Mr. Kukiz had proposed.

“Duda presented himself very successfully as the person who represented change,” said Andrzej Rychard, a sociologist at the Polish Academy of Sciences. “Kukiz was the first to recognize that there was something new in the air, this anti-establishment energy, and Duda was able to capitalize on it.”

Mr. Rychard said that what he found most interesting about the coalition that Mr. Duda assembled to win the presidency was that it mixed two large groups of dissatisfied voters: older ones, who struggle to make do with their pensions and think the pace of the market-based overhaul has gone too far, and younger ones, who hunger for more jobs and faster growth, and who believe the changes have not gone nearly far enough.