SEOUL, South Korea — South Korea elected Moon Jae-in, a human rights lawyer who favors dialogue with North Korea, as president on Tuesday, returning the nation’s liberals to power after nearly a decade in the political wilderness and setting up a potential rift with the United States over the North’s nuclear weapons program.

His victory caps a remarkable national drama in which a corruption scandal, mass protests and impeachment forced a South Korean president from office for the first time in almost 60 years, leaving the conservative establishment in disarray and its former leader in jail.

Mr. Moon, 64, a son of North Korean refugees, faces the challenge of enacting changes to limit the power of big business and address the abuses uncovered in his predecessor’s downfall. He must also make good on his promise of a new approach to North Korea while balancing relations with the United States and China.

His election immediately scrambles the geopolitics over North Korea’s nuclear arsenal. Even as the Trump administration urges the world to step up pressure on Pyongyang, it now faces the prospect of a critical ally — one with the most at stake in any conflict with the North — breaking ranks and adopting a more conciliatory approach.