Median of Two Sorted Arrays Algorithm

Day - 28 Median of Two Sorted Arrays The problem - Find the Median of two sorted arrays. Example : nums1 = [1,3], nums2 = [2] -> 2.0 nums = [1,2], nums2 = [3,4] -> 2.5 Brute force - Merge both arrays and find the Median. Approach Used - Two Pointers •) Initialize n=nums1.length, m=nums2.length, i=0,j=0. •) Track two variables, m1(current middle element), m2(previous middle element). •) Loop until we reach the median position, count from 0 to (n+m)/2. •) In each iteration, save current m1 as m2.Compare elements at i and j. 1 - If both arrays have elements remaining, pick smaller one and move that pointer. 2 - If only nums1 has elements, take from nums1(i++). 3 - If only nums2 has elements, take from nums2(j++). •) After loop ends, if total length is odd, median = m1, if total length is even, median = (m1+m2)/2. •) Return the median. Complexity - Time - O(m+n), we iterate until median position. Space - O(1), we use pointers. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories