But the deal still won't provide enough votes in parliament for both parties to take office without the support of other groups.
Incumbent Prime Minister Pedro Sánchez's left-of-center Socialists captured 120 seats in Sunday's ballot but fell far short of a majority in the 350-seat chamber. United We Can got 35 seats.
In a joint appearance, Sánchez and United We Can leader Pablo Iglesias say under the deal Sánchez would be prime minister and Iglesias his deputy in a future government. They will begin talks with other parties to get more support.
On Tuesday, they were all smiles as they signed the agreement in front of television cameras and hugged each other at the end.
United We Can has traditionally taken a more radical approach than the center-left Socialists. The party grew out of protests against austerity measures during Europe's debt crisis.
"Spain needs a stable government, not an interim one, a solid one not a trial one and it needs it now," Sánchez said. He said the accord was aimed at lasting the statutory four-year term.
Pony-tailed Iglesias wore jeans and an open-necked shirt to the signing ceremony, contrasting with Sanchez's dark blue suit and tie.
Spain is undergoing its worst political crisis in decades with the secession conflict in the northeastern region of Catalonia, which in turn has fueled a resurgence of extreme Spanish nationalism in the form of the far-right Vox party that won 52 seats in the election to become Spain's third parliamentary force.
Both politicians said they will announce detailed policies at a later date.
The two will have to strike deals chiefly with regional parties and smaller leftist groups.
The deal was immediately dismissed by the Vox party as well as the main opposition conservative Popular Party, which won 88 seats.
Newly elected parliamentarians will select a house speaker in December and then talks between King Felipe VI and party leaders will begin so that one of them, most likely Sánchez, will be called on to try to form a government.
Hatton contributed from Lisbon, Portugal.