Implement zip pairing two int slices up to the shorter length
Implement zip(s1, s2) returning a slice of pairs, one per index, stopping at the shorter input. Each pair is a two-element []int. Example: zip([]int{1,2,3}, []int{4,5,6,7,8}) → [[1 4] [2 5] [3 6]].
func zip(s1, s2 []int) [][]int {
// your code here
return nil
}
Write the implementation.
Compute minLen as the smaller of the two lengths, preallocate the result with make([][]int, 0, minLen), then loop i from 0 to minLen appending []int{s1[i], s2[i]}. Stopping at the shorter length avoids an out-of-range panic, and preallocating capacity avoids repeated regrowth. It is O(minLen) time.
- ✗Looping to the longer length and indexing out of range
- ✗Thinking an out-of-range slice index returns zero instead of panicking
- ✗Flattening into one slice instead of producing pairs
- →How would you make a variadic
zip(s ...[]int)for any number of slices? - →How would generics let
zipwork on slices of any element type?
Solution
Iterate to the shorter length to avoid out-of-range; the capacity is known up front.
func zip(s1, s2 []int) [][]int {
minLen := len(s1)
if len(s2) < minLen {
minLen = len(s2)
}
res := make([][]int, 0, minLen)
for i := 0; i < minLen; i++ {
res = append(res, []int{s1[i], s2[i]})
}
return res
}
// zip([]int{1,2,3}, []int{4,5,6,7,8}) -> [[1 4] [2 5] [3 6]]
Indexing s1[i] or s2[i] past its length would panic, so the loop runs exactly to minLen. Preallocating with make(..., 0, minLen) avoids repeated regrowth on append.
⚠️ An out-of-range slice index in Go panics rather than returning zero — so looping to the longer length is not safe.