Homework #3 SolutionsCS 344: Design and Analysis of Computer Algorithms (Spring 2022)Problem 1Say there areqarraysA1, A2, ..., Aq. Each arrayAiis sorted from smallest to largest. Youcan assume all numbers are distinct: so if a numberxappears in someAi, thenxappearsinAiexactly once and alsoxdoes not appear in any of the otherAj. Defineni=len(Ai)and defineN=∑qi=1ni. That is,Nis the total number of elements among all the arrays.Write pseudocode that outputs asortedarrayB[0....N−1]of lengthNsuch thatBcontains all the elements from all theAi. That is, ifxis someAjthenxshould appear inB. Note thatBshould be sorted from smallest to largest.Your algorithm should run in timeO(Nlog(q)).You will want to use the heap datastructure. You must make it clear why the run-time isO(Nlog(q))by analyzing how oftenyou call each heap operation.At a high level, our algorithm maintainsqpointers, one for each arrayAi. In eachstep, the algorithm adds to the output the smallest element pointed to, and thenincrements the corresponding pointer or ceases to maintain the corresponding pointerif increasing it brings it out of bounds. Once all pointers are no longer maintained(that is,Nelements have been accumulated), the algorithms returns.To obtain an efficient implementation, we maintain the elements pointed to in apriority queue.In this way, extracting the minimum element in the priority queuegives us the next smallest value to add to the output. We then need to increment thecorresponding pointer and update the priority queue. To do this, we also associatewith each item in the priority queue the details of a pointer.Merge(A1[0..n1−1], . . . , Aq[0..nq−1]):N←∑niH←BuildMinHeap()fori←1toqH.add(Ai[0],(i,0))initializeB[0..N−1]forj←0toN−1B[j],(i, k)←H.find-min()H.delete-min()ifk+ 1< niH.add(Ai[k+ 1],(i, k+ 1))returnBCorrectness.Correctness can be established by observing the following loop in-variant is maintained by the second loop: in the beginning of iterationj,Hcontainsthe smallest element ofA1∪ · · · ∪Aqthat is not already present inB. Indeed, if thisinvariant holds, then clearlyBwill contain the elements in sorted order after the loop.This can be formally proven by induction.