After polls closed, the Liberals were projected to win more of Parliament's 343 seats than the Conservative Party. However, it wasn't immediately clear if they would win an outright majority that would allow them to pass legislation without needing help.
The Liberals looked headed for a crushing defeat until the American president started attacking Canada's economy and threatening its sovereignty, suggesting it should become the 51st state.
Trump's actions infuriated Canadians and stoked a surge in nationalism that helped the Liberals flip the election narrative and win a fourth straight term in power.
"We were dead and buried in December. Now we are going to form a government," David Lametti, a former Liberal justice minister, told CTV.
"We have turned this around thanks to Mark."
With AAP.