Junior — Middle
How can two sorted arrays be merged into one while maintaining the order of elements?
sobes.tech AI
Answer from AI
To merge two sorted arrays into one sorted array, you can use a merging algorithm similar to the one used in merge sort. The idea is to traverse both arrays simultaneously, compare the current elements, and add the smaller one to the result array.
Example in Go:
func mergeSortedArrays(a, b []int) []int {
result := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
result = append(result, a[i])
i++
} else {
result = append(result, b[j])
j++
}
}
// Append remaining elements
result = append(result, a[i:]...)
result = append(result, b[j:]...)
return result
}
This method works in O(n + m) time, where n and m are the sizes of the input arrays.