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.
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