NBA standout Leandrinho Barbosa scored 23 points to lead a second-half rally that lifted Brazil over Spain 88-82 on Monday and into a second seed spot in the Olympic men's basketball medal playoffs.
Brazil finished level with Russia in Group B at 4-1 but lost the top seed by having lost their head-to-head matchup. Spain finished 3-2, level with Australia but taking the tie-breaker thanks to a head-to-head win.
Exact quarter-final matchups will not be known until after the US NBA Dream Team plays Argentina later in the final preliminary game in Group A.
Brazil-Spain had overtones of a badminton scandal that saw eight women banished for not trying to win in order to avoid an early knockout-round match against a favoured duo that had been upset in preliminaries.
In this case, the teams were in a position where the Spain-Brazil winner would likely be set for a potential semi-final meeting with the US NBA Dream Team while the loser would not play the Americans until a possible title game.
Before the game, players on both teams dismissed the notion they would give anything less than their best.
But Brazil's Nene Hilario, a centre for the NBA Washington Wizards who was among the Olympic rebound and blocked shot leaders, did not play against Spain, which had struggled with inconsistent play throughout the tournament.
The Spaniards led 44-38 at half-time and NBA big man Marc Gasol scored seven points in a 14-9 run midway into the third period to give Spain a 62-51 edge on the way to a 66-57 advantage entering the fourth quarter.
Back-to-back 3-pointers by Marquinhos Veira Sousa pulled Brazil within 67-63 just 58 seconds into the final period.
Pau Gasol hit a free throw to put Spain ahead 73-67 but Barbosa hit two free throws and back-to-back 3-pointers to give Brazil the lead for the first time at 75-73 with 4:17 remaining.
Pau Gasol answered with a dunk but Barbosa sank two free throws to put Brazil back on top and Larry Taylor banked in a layup for a 79-75 Brazil edge with 3:22 to play.
Barbosa made a fast break layup and Anderson Varejao added a layup for an 84-76 lead with 96 seconds to play, ending a 12-3 Brazil run.
Marc Gasol hit three late free throws to pull Spain closer but Taylor flipped in a reverse layup and a Tiago Splitter slam dunk with five seconds remaining sealed Spain's fate.
Pau Gasol had 25 points and Marc Gasol 20 to lead Spain.