Both Egypt and Algeria were equal on seven points and they were also tied on a plus six goal difference and on goals scored, leaving fair play to determine the group leaders.
In a bizarre yet exciting fair-play duel, Egypt and Algeria were neck and neck in yellow cards. But striker Hilal Soudani was booked in stoppage time and youngster Yacine Titraoui was then dismissed following a VAR review after a studs-up challenge on Mohanad Lashin.
Egypt will now take on Jordan in the quarters, with Algeria facing a stern test against North African rivals Morocco.
A fluke goal from Mohamed Amine Tougai put Algeria ahead in the first half. But Egypt came on with all guns blazing in the second half, even though they lost defender Ahmed Hegazi and midfielder Ayman Ashraf to injury before the break.
A period of sustained pressure in a high-octane half saw Egypt awarded a penalty after Tougai kicked the foot of Ahly midfielder Amr El-Sulaya as he attempted to clear the ball. The referee pointed to the spot after checking a video replay, with El-Sulaya tucking it away although keeper Rais M’Bolhi got a hand to it.