TOKYO — Ahmed Hafnaoui was surprised that he was even in Sunday’s men’s 400-meter freestyle final after he swam the slowest time to qualify in the semifinal heats the day before. The 18-year-old from Tunisia lined up in Lane 8 knowing he wasn’t expected to contend for a medal.

So when he touched the wall after his race, he looked up at the scoreboard and was stunned by what he saw — the teenager had won the gold medal by just 0.16 seconds over Australia’s Jack McLoughlin to become the biggest Cinderella story early on in these Olympics.

“I was surprised myself. It’s unbelievable. I just can’t believe it,” said Hafnaoui, who won with a time of 3 minutes 43.36 seconds.

Hafnaoui did not wear a customary track uniform to the medal podium afterward — perhaps because one wasn’t prepared for him — and he put the gold medal on in a T-shirt and shorts. His eyes swelled with tears as Tunisia’s flag was raised and its anthem played. He won the country’s fifth gold medal and became the second Tunisian swimmer to win a gold, joining Oussama Mellouli, who won the 1,500-meter freestyle at the 2008 Games in Beijing.

“He’s a legend. I wish to be like him someday,” Hafnaoui said of Mellouli. “I was in tears. When I see the flag of my country and I hear the anthem in the background, it was great. I’m so proud of it.”

Hafnaoui said he started in the sport at age 6 when his father, who is reportedly a former member of the Tunisia men’s basketball team, signed him up for a swimming club. His win Sunday was made all the more remarkable considering he finished eighth in the same event at the 2018 Youth Olympic Games. He plans to swim collegiately in the United States next year, although he said Sunday that he doesn’t yet know which school he will attend.

“I just want to get better,” he said.

Hafnaoui should get plenty of attention from college programs after Sunday, when he took control of the race early and held off McLoughlin (3:43.52) over the final 50 meters. American Kieran Smith took the bronze with a time of 3:43.94.

“I saw the Australian guy from Lane 6. It was a great fight in the end,” Hafnaoui said. “I believed when I touched the wall and I saw. I was so surprised. I didn’t expect that.”