How to use Two-Pointers Approach In Javascript

The function find_Median_fun finds the median of two sorted arrays by iterating through them simultaneously with two pointers, selecting elements in ascending order until reaching the middle point of the combined arrays. It determines the median based on whether the total length is even or odd and returns the result accordingly.

Example: The example below shows how to find Median of two sorted arrays of different sizes using JavaScript Using Two-Pointers.

JavaScript
function find_Median_fun(nums1, nums2) {
    const totalLength = nums1.length + nums2.length;
    const ifEven = totalLength % 2 === 0;
    const halfLength = Math.floor(totalLength / 2);

    // 2 pointers
    let i = 0, j = 0;
    let count = 0;
    let median = 0, prevMedian = 0;

    while (count <= halfLength) {
        prevMedian = median;
        if (i < nums1.length && 
            (j >= nums2.length || nums1[i] < nums2[j])) {
            median = nums1[i];
            i++;
        } else {
            median = nums2[j];
            j++;
        }
        count++;
    }

    // If length is even 
    if (ifEven) {
        return (prevMedian + median) / 2;
    } else {
        return median;
    }
}

const nums1 = [1, 3];
const nums2 = [2];
console.log("Median:", 
             find_Median_fun(nums1, nums2));

Output
Median: 2

Time Complexity: O(m + n), where m and n are the lengths of the two input arrays.

Space Complexity: O(1)



Median of Two Sorted Arrays of Different Sizes using JavaScript

Given two arrays, our goal is to find the median of two sorted arrays of different sizes by merging both of them. The median is the middle value of the array after dividing it into two halves.

Example:

Input:  Arr1: [1,4,5], Arr2: [2,8,7,3]
Output: Median = 4
Explanation: The merged and sorted array is: ar3[] = [1,2,3,4,5,7,8]
The median is 4

Table of Content

  • Using Binary Search
  • Using Two-Pointers Approach

Similar Reads

Using Binary Search

In this approach, we will be performing binary search on the shorter array so that we can partition it in such a way that the newly combined left half of both the arrays will have elements less than the combined right half. Adjust the partition point until the condition for median gets satisfied. If the combined length of the new array is odd, return the maximum element of the left partition. If it’s even, return the average of the maximum element of the left partition and the minimum element of the right partition....

Using Two-Pointers Approach

The function find_Median_fun finds the median of two sorted arrays by iterating through them simultaneously with two pointers, selecting elements in ascending order until reaching the middle point of the combined arrays. It determines the median based on whether the total length is even or odd and returns the result accordingly....

Contact Us