Brocade Interview Question
Software TraineesCountry: United States
This is how I'd solve that, considering arrays a and b to merge to c
check one element from a and b and add the min to c until one of the arrays runs out of elements
add remaining elements from a or b to c
fun main() {
val a = arrayOf(1, 3, 5, 7, 8, 9)
val b = arrayOf(2, 4, 6)
print("A = ${a.asList()}")
print("B = ${b.asList()}")
val c = Array(a.size + b.size) { 0 }
var i = 0
var j = 0
var k = 0
// find the min of a[j],b[j] and add it at c[k]
// until one of the arrays(a or b) is empty
while (i < a.size && j < b.size) {
if (a[i] < b[j]) {
c[k] = a[i]
i++
k++
} else {
c[k] = b[j]
j++
k++
}
}
// add remaining elements to c
while (i < a.size) {
c[k] = a[i]
i++
k++
}
while (j < b.size) {
c[k] = b[j]
j++
k++
}
print("C = ${c.asList()}")
}
note: i contains position of current element in A similarly j for B and k for C
The idea is to use Merge function of Merge sort.
- Nits January 30, 2020Create an array arr3[] of size n1 + n2.
Simultaneously traverse arr1[] and arr2[].
Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked.
If there are remaining elements in arr1[] or arr2[], copy them also in arr3[].