The question is grammatically correct. The auxiliary verb 'Did' is used correctly in the interrogative sentence about a past action, followed by the base form of the verb 'write'.
Answer: Did you write a letter to Sam?