CONCORD, N.H. — New Hampshire Gov. Maggie Hassan, a Democrat, has unseated Senator Kelly Ayotte, a Republican, in one of the most competitive and closely watched races of this election cycle. The race was called Wednesday afternoon.

The race cost about $120 million, an extraordinary sum for such a small state.

The main challenge for both was to keep their bases happy while appealing to the state’s large number of independents. This forced both candidates to emphasize bipartisanship and to try to keep politics out of major issues, like the state’s crushing opioid epidemic.

Ms. Ayotte, 48, a former prosecutor, has been a rising star in Washington, where she allied herself with conservative causes, like defunding Planned Parenthood and opposing a confirmation vote on a Supreme Court nominee.