Prepin
Log in

L

Combine two sorted arrays.

Approach / Explanation

This is a fundamental question related to array or list manipulation. The interviewer aims to assess your understanding of basic operations on sorted arrays and your ability to efficiently merge them into a single sorted array. Important points to consider when answering the question: Recognize that both arrays are already sorted. This is crucial as it simplifies the problem significantly. The objective is to combine these two sorted arrays into one sorted array without the need for additional sorting. Think about employing the two-pointer technique, as it allows you to minimize unnecessary comparisons. The time complexity should be maintained at linear time complexity, that is, O(n), where n represents the total number of elements in both arrays.

Suggested Answer

To combine two sorted arrays, we can employ the two-pointer technique. We initiate by setting two pointers at the first element of each array. By comparing the values at these pointers, we place the smaller value into the output array and advance the pointer for that value to the next element. This process is repeated until we reach the end of one of the arrays. Subsequently, we add the remaining elements from the other array to the output array. Here’s an example in Python: def merge_sorted_arrays ( nums1 , nums2 ) : i , j = 0 , 0 result = [ ] while i < len ( nums1 ) and j < len ( nums2 ) : if nums1 [ i ] < nums2 [ j ] : result . append ( nums1 [ i ] ) i += 1 else : result . append ( nums2 [ j ] ) j += 1 while i < len ( nums1 ) : result . append ( nums1 [ i ] ) i += 1 while j < len ( nums2 ) : result . append ( nums2 [ j ] ) j += 1 return result This function combines two sorted arrays, nums1 and nums2, and returns the resulting array.

Alternative Answer

Another method to address this issue is by utilizing the built-in functions of the programming language. You can directly combine the two sorted arrays and then sort the resulting array. This method appears to be more straightforward than the previous one; however, it is not the most efficient solution in terms of time complexity. Sorting a merged array requires O(n log n) time, where n is the total size of the new array. Python Example: def merge_sorted_arrays ( nums1 , nums2 ) : nums1 . extend ( nums2 ) nums1 . sort ( ) return nums1 This function combines two sorted arrays, nums1 and nums2, sorts the resulting array, and returns it.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)
LinkedIn

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.