A vast majority of the time, both of you had the same solution and were writing it at the same time, it's just one was slightly faster.
More often the phrasing of the answer is slightly different so it can be beneficial to have answers that explain concepts in different ways. If answers are almost word-for-word duplicates, then it is customary for the author of the 2nd post to delete their answer (which is probably what happened here), but no one is under any obligation to do so.
Beyond the parallel writing efforts (so a duplicate answer was posted hours or days after the initial), there are other cases some innocent, some not.
- Different explanation (same case as I mentioned above - someone felt they had a better way to explain a concept)
- They didn't see a duplicate answer, just saw a post that they could answer
- Rep sniping - someone is trying to post answers to get upvotes regardless of existing answers.
I am ignoring plagiarism because that is basically the same idea as rep sniping, But if you encounter someone copying your post word-for-word, then you can flag it and let the mods deal with it.