Prepin
Log in

Merge two sorted arrays in place.

Approach / Explanation

This question pertains to data manipulation and optimization within programming. You are presented with two sorted arrays, which are data structures that hold elements of the same type in a contiguous memory block. Your objective is to merge these two sorted arrays "in place," meaning you should not utilize any additional space (such as creating a new array) for storing intermediate results. The resulting merged array should also remain sorted. To effectively address this type of question, you should organize your response to include the following aspects: Clarify your comprehension of the problem. Outline the steps you will take to execute your solution. Evaluate its efficiency regarding time and space complexity.

Suggested Answer

I interpret this issue as combining two sorted arrays without generating a new one, essentially performing it "in place." Here’s my proposed method: Initially, I will check the last elements of both arrays. If the last element of the first array is larger than that of the second array, I will swap the two elements. After that, I will re-sort the first array while keeping the last element in place, as it is already correctly positioned. I will repeat this process until the first array is fully sorted. The time complexity of this method would be O(M*N log M), where M and N represent the sizes of the two arrays, since each operation involves re-sorting the first array.

Alternative Answer

Another method to tackle this issue involves the use of pointers. If the last element of the first array is greater than that of the second array, I will exchange them. Next, I will decrement the pointer in the first array by one and make a comparison again, continuing this process until every element in the first array is smaller than those in the second. Finally, I will sort both arrays. The time complexity for this method is comparable to the previous solution, at O(M*N log M), since sorting is necessary after each swap. However, this method may yield better performance in practice if the two initial arrays are nearly sorted, as it may require fewer swaps.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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