When police officers heard gunfire at the Gilroy Garlic Festival Sunday night, they rushed toward the shooting and drew their handguns.

The man they confronted was a teenager armed with what officials later described as an AK-style semiautomatic assault rifle. Officers managed to take down the gunman quickly, averting far worse bloodshed.

But officials later said the teenager should never have had the weapon in the first place.

In Nevada, the purchase by the 19-year-old was legal. But just across the line in California, where the minimum age for purchasing a rifle is now 21, the weapon is banned and should never have been brought into the state, according to the state’s attorney general, Xavier Becerra.

California has some of the toughest gun laws in the country. But the tragedy that played out on Sunday, in which three people were killed and 12 wounded, illustrated a familiar problem for states that have ratcheted up their own gun laws in recent years, only to see them neutralized by neighboring states with more lax rules.