Merging Sorted Arrays with Three Pointers in Java

Problem :- Merge Sorted Array (LeetCode 88) Problem Statement :- You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n representing the number of elements in nums1 and nums2 respectively. Merge nums2 into nums1 as one sorted array. The final sorted array should not be returned, but instead be stored inside nums1. Approach :- Three Pointer Technique i - Use three pointers: i → last element of nums1 (m-1) j → last element of nums2 (n-1) k → last position of nums1 (m+n-1) ii - Compare nums1[i] and nums2[j], place larger at nums1[k] iii - Move pointers accordingly iv - If elements left in nums2, copy them v - Time Complexity : O(m + n) vi - Space Complexity : O(1) class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m -1; int p2 = n -1; int p = m + n -1; while(p1 >=0 && p2 >= 0){ if(nums1[p1] > nums2[p2]){ nums1[p] = nums1[p1]; p1--; }else { nums1[p] = nums2[p2]; p2--; } p--; } while (p2 >= 0){ nums1[p] = nums2[p2]; p2--; p--; } } } Key Takeaway :- Instead of merging from the front (which causes shifting), start from the end and place elements in correct position using three pointers. How would you optimize this further? Is there any way to handle merging without using extra space in other variations? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers

  • text

To view or add a comment, sign in

Explore content categories