Suppose we have two arrays A[n] and b[n], the goal is to compare every element in A to elements in B. Then return a list result[n] that records the number of each element in A that is larger than the elements in B.
For example,
A = [38, 24, 43, 3], B = [9, 82, 10, 11]
Since 38 is larger than 9, 10 and 11, so result[0] is 3. Then result is [3, 3, 3, 0].
It will be the best if you can provide some pseudocode.
Thank you.
Both lists need to be sorted ascending for this to work.
Sorting costs O(log n). And big-O arithmetic means doing it twice is still
O(n log n)
. I'm going to assume they are already sorted. The remaining work below doesn't affect the big-O cost.Have an index to the
B
array calledindexB
, value zero (my pseudocode will use zero-based indexing). AndindexA
forA
also starting at zero.After that, all of the remaining items in the
result
fromindexA
onward are bigger than all the items inB
, so set the rest of them toB.Length
.You can perform the above algorithm in O(nlogn) complexity where n is the length of array A and array B as given in the question.
Algorithm
At the end you will have
res
array ready with the answer.Overall time complexity -
O(nlogn)
.Hope this helps!