Kylian Mbappe, Federico Valverde and Jude Bellingham scored in Sunday's match to close the gap on Barcelona, who had conceded two late goals in a 2-2 draw at Celta Vigo on Saturday.
Madrid have played one game less than Barcelona after their match at Valencia was postponed because of the deadly floods in October.
Madrid will make the trip to England to face Premier League leader Liverpool on Wednesday in the Champions League, and are hoping to recover from a demoralising 3-1 home loss against AC Milan in the previous round of matches.
Madrid's attack worked well against Leganes with Vinícius Júnior playing inside and Mbappé more on the flank. The France striker scored after going four straight games without finding the net for the Spanish powerhouse.
"We switched their positions and the team was able to stay in control during the whole match," Madrid coach Carlo Ancelotti said.
Mbappé said he is fine playing wherever Ancelotti puts him.
"I've said it on the first day that I can play in several different positions," Mbappé said. "All I want is to keep playing well and scoring goals."
Oihan Sancet scored a 26th-minute winner as Athletic Bilbao defeated Real Sociedad 1-0 in the Basque Country derby.
It was Athletic's fourth straight home win against Sociedad in the derby.
The victory moved Athletic to fifth place and left Sociedad in 10th position.
Fourth-place Villarreal scored an equaliser in stoppage time to salvage a 2-2 draw at sixth-place Osasuna.
Ante Budimir scored twice in the first 20 minutes for Osasuna.
Villarreal, which were coming off three straight victories in all competitions, scored through Álex Baena in the 67th and a penalty kick converted by Gerard Moreno three minutes into injury time.
Osasuna, sitting three points behind Villarreal, were coming off a 4-0 loss at Madrid.
Also on Sunday, Sevilla ended a two-game losing streak in the league with a 1-0 win against Rayo Vallecano, who played the entire second half with 10 men after Unai López was sent off for a hard foul.
Djibril Sow scored Sevilla's goal in the 27th.