Find first and last position
In a sorted array every copy of the target sits in one block. Its first position is the first value >= target; its last is just before the first value >= target + 1. One binary search, run twice, finds both ends.
In the numbered examples nums has one more slot, index n, where a search for a value bigger than everything ends.