Implement the medianTwoSortedArraysFloor method that returns the floor of the median of two sorted arrays.

The input contains two sorted integer arrays: a with length sizeA, and b with length sizeB. Your task is to return the floor value of the median after combining both arrays.

The median is the middle value after all numbers are placed in sorted order. If the total number of values is even, take the average of the two middle values and return its floor value.

For example, combining [1,2] and [3,4] gives [1,2,3,4]. The median is 2.5, so the floor value is 2.

Example 1

Input
a (int[]) = [1,3]
sizeA (int) = 2
b (int[]) = [2]
sizeB (int) = 1
Returns (int) 2

Example 2

Input
a (int[]) = [1,2]
sizeA (int) = 2
b (int[]) = [3,4]
sizeB (int) = 2
Returns (int) 2

Example 3

Input
a (int[]) = [0,0]
sizeA (int) = 2
b (int[]) = [0,0]
sizeB (int) = 2
Returns (int) 0

Because both arrays are already sorted, use the merge process from merge sort.

Move through both arrays with two pointers and count how many values have been consumed. You only need to track the values around the middle position, so a full merged array is not required.

For an odd total length, return the middle value. For an even total length, return the floor of the average of the two middle values.

Pseudocode:

function medianTwoSortedArraysFloor(a, sizeA, b, sizeB):
    total = sizeA + sizeB
    mid1 = (total - 1) / 2
    mid2 = total / 2
    previous = 0
    current = 0
    i = 0
    j = 0
    for count from 0 to mid2:
        previous = current
        if j >= sizeB or (i < sizeA and a[i] <= b[j]):
            current = a[i]
            i++
        else:
            current = b[j]
            j++
    if total is odd:
        return current
    return floor((previous + current) / 2)
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.