logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

88. Merge Sorted Array

1 min read
On this pageIntuition
IntuitionApproachComplexityCode

Given two sorted array the goal is to merge them

Input
nums1 = [1,2,3,0,0,0], m = 3, 
nums2 = [2,5,6], n = 3
 
Output
[1,2,2,3,5,6]

the first array has capacity to hold to the merged sorted array.


# Intuition

  • Uses two pointers two track the current position in respective arrays
  • Since nums1 is of size m+nm+nm+n use this extra space to store the merged array.

# Approach

  • Iterate through the arrays from the end and place the larger element in the end of nums1.

# Complexity

  • Time complexity : O(m+n)\text{O}(m+n)O(m+n)
    • Since we iterate over the m+nm+nm+n array elements only once.
  • Space complexity : O(1)\text{O}(1)O(1)
    • Not using any extra space, apart from the one provided

# Code

int i  = m-1 , j = n-1; 
 
// Start filling the merged array from end
for(int k = n+m-1; k >= 0; k--) {
	// We compare if there are elements left in one of the array 
	// if all elements are finished simply put all the remaining 
	// elements
	if(i >= 0 && j >= 0) {
		nums1[k]= nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
	} else if (i >=0) {
		nums1[k] = nums1[i--];
	} else {
		nums1[k] = nums2[j--];
	}
}
←Previous80. Remove Duplicates from Sorted Array IINext→121. Best Time to Buy and Sell Stock

On this page

IntuitionApproachComplexityCode