I think the episode you are referring to is the TNG episode "Cause and Effect".
https://en.wikipedia.org/wiki/Cause_and_Effect_(Star_Trek:_The_Next_Generation)
From the Wikipedia article on the episode:
The Enterprise is severely damaged. The ship explodes, killing the entire crew. Data,<PERSON> and some others then play cards.
The Enterprise-D is shown to be stuck in a time loop, with events culminating in the destruction of the ship as a result of a collision with another Starfleet vessel that emerges from a space-time distortion. As each loop proceeds, the crew members, though unaware they are in the loop, have increasing feelings of déjà vu; Dr. <PERSON> begins to hear numerous conversations before going to bed, and during one cycle, manages to record the voices on a tricorder. Analysis reveals that the voices are Enterprise crewmembers during the hours before the destruction of the ship, with <PERSON> yelling "all hands abandon ship !" before the recording stops abruptly. The crew discovers the time loop is caused by dekyon distortions near the space-time anomaly, and program Data to send a short message to his counterpart in the next iteration to take action on. 837
Data sends the signal moments before the ship is destroyed again.
On the next iteration, the crew still experiences déjà vu, but actions performed by Data often reveal the number three, going against their vague memories. They make the same conclusions from the previous iteration, and Data realizes the number three must have some as-yet-unknown significance to break the loop. The Enterprise again arrives at the anomaly, and as the other ship emerges, both <PERSON> and <PERSON> suggest alternate plans to avoid being hit. Though Captain <PERSON> opts for <PERSON>'s plan, <PERSON> realizes that the "three" message was in reference to the number of insignia pips worn by <PERSON>, and initiates <PERSON>'s plan instead. The Enterprise is able to avoid being hit and thus, the time loop is broken. The crew discovers they have been stuck in the loop for 17 days, while the ship they narrowly avoided, the USS Bozeman, has been missing for more than 80 years. The Enterprise welcomes the Bozeman to the 24th century at the end of the episode. 715