One possible explanation is that the Holy Spirit told them what happened as they were writing their histories. Believing the Gospels to be inspired, we can easily accept that explanation.
Another explanation is simply that Jesus later told His disciples what they had missed. No disciple was present with Jesus during the wilderness temptation in Matthew 4, but, later, Jesus spent over three years with the disciples. Isn’t it likely that He related to them what had happened sometime during those three years? Similarly, Jesus was alone as He spoke to the woman at the well in John 4, yet their conversation is quoted at length. A common-sense explanation is that Jesus later filled His disciples in. Or perhaps John got the story from the woman, given the fact that the disciples stayed in her city for two days following her conversion (John 4:40).
After His resurrection, Jesus appeared to the disciples over a period of forty days “speaking to them about the kingdom of God” (Acts 1:3). In those forty days, Jesus would have had ample opportunity to inform the disciples of all the things that happened to Him when they were not around. In any case, the events of Jesus’ life that God wanted us to know—including events that occurred in solitude—were documented. The key is God wanted us to know. Either the events were disclosed directly to the disciples at a later time, by Jesus or by someone else, or the apostles learned the details straight from the Holy Spirit as they wrote God’s Word.