Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
The Merge Sorted Array (In-place from End) pattern applies when you need the Merge Sorted Array (In-place from End) technique within the Array/Matrix Manipulation Patterns pattern. Its time complexity is O(m + n) and space complexity O(1). It is used in 1 problem on Thita, including Merge Sorted Array. Common variations are Product Except Self (Prefix/Suffix Products) and Spiral Traversal.
Learn the merge sorted array technique starting from the end. Essential for space-efficient array merging in coding interviews.
Merge Sorted Array (In-place from End) is one of the 10 subpatterns of the Array/Matrix Manipulation Patterns pattern, which covers in-place operations, hashing, prefix sums, spiral traversal, and cyclic sort. The whole pattern is about 4 hours of study. This subpattern is a core technique: expect it to come up directly in interviews.
Master array and matrix manipulation techniques including in-place rotation, spiral traversal, prefix/suffix products, and cyclic sort. Essential patterns for coding interviews at FAANG companies. Problems in this subpattern are usually searched for as merge sorted array, in-place merge, array merging, two pointer merge, leetcode 88.
Read the theory for Merge Sorted Array (In-place from End), then work the problems attached to it in the browser editor. Your solution runs against the problem's test cases, and the AI coach offers a hint about the technique you are missing rather than a finished solution. Progress is tracked per subpattern, so the Array/Matrix Manipulation Patterns tracker shows this one as covered once you have solved its problems.
Merge Sorted Array (In-place from End) is one lesson in a 16-pattern DSA course. If you are preparing end to end, work the interview-critical patterns first and use the pattern sheet as the checklist; if you are here for one technique, the Array/Matrix Manipulation Patterns guide is the shortest path back to the rest of it.
1 problem, easiest first.
Imagine you have two stacks of sorted papers—one for invoices and one for receipts—and you want to combine them into a single, neatly sorted pile. But here's the twist: you only have space on your desk for the final pile, not for spreading everything out. So, you need to carefully insert each paper into its correct place without making a mess.
This is the essence of the Merge Sorted Array (In-place from End) pattern. It’s all about combining two sorted arrays into one, but with a constraint: you must do it inside the space of the first array, starting from the end. This pattern shines in scenarios where memory is limited, like merging two sorted lists of transactions in a banking app or combining search results from two sources in a mobile device.
Everyday analogy:
Think of packing a suitcase that already has some clothes (nums1), and you want to add more clothes (nums2) in sorted order by size. Since you can't take everything out, you start filling from the back of the suitcase, placing the largest items first, so you don’t overwrite anything important.
When is this pattern useful?
Let’s break down the key ideas behind this pattern:
i at the last valid element of nums1 (i.e., m - 1)j at the last element of nums2 (i.e., n - 1)k at the very end of nums1 (i.e., m + n - 1)nums1[i] and nums2[j].nums1[k].nums2 still has elements left, copy them into nums1.nums1 has elements left, they’re already in place.Let's build a mental model for tackling these problems:
Merging [1,2,3] and [2,5,6] from the back: k writes the larger of nums1[i] and nums2[j] into nums1, and the pointers walk left until nums2 is used up.
nums1) is your only workspace.Set Up Your Pointers:
i = m - 1 (last valid element in nums1)j = n - 1 (last element in nums2)k = m + n - 1 (last position in nums1)While both arrays have elements:
nums1[i] and nums2[j].nums1[k].k.If nums2 still has elements:
nums1.nums1 has elements left, they’re already in place (since we’re merging into nums1).nums1 is already sorted.nums2 into nums1.nums2 are smaller/larger than those in nums1:Example:
If nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3,
the merge process fills nums1 from the end:
[1,2,3,0,0,6] → [1,2,3,0,5,6] → [1,2,3,3,5,6] → ... until fully merged.
Let's walk through a well-commented C++ solution for the Merge Sorted Array problem.
1#include <vector>
2#include <iostream>
3using namespace std;
4
5// Merges nums2 into nums1 in-place, assuming nums1 has enough space
6void mergeSortedArray(vector<int>& nums1, int m, vector<int>& nums2, int n) {
7 // i: last valid element in nums1
8 int i = m - 1;
9 // j: last element in nums2
10 int j = n - 1;
11 // k: last position in nums1 (total length)
12 int k = m + n - 1;
13
14 // Merge from the end to avoid overwriting unprocessed elements
15 while (i >= 0 && j >= 0) {
16 // Compare the largest elements from both arrays
17 if (nums1[i] > nums2[j]) {
18 nums1[k] = nums1[i]; // Place nums1[i] at the end
19 i--; // Move pointer in nums1
20 } else {
21 nums1[k] = nums2[j]; // Place nums2[j] at the end
22 j--; // Move pointer in nums2
23 }
24 k--; // Move to next position from the end
25 }
26
27 // If nums2 still has elements, copy them into nums1
28 // (If nums1 has elements left, they're already in place)
29 while (j >= 0) {
30 nums1[k] = nums2[j];
31 j--;
32 k--;
33 }
34}
35
36// Example usage
37int main() {
38 vector<int> nums1 = {1, 2, 3, 0, 0, 0};
39 int m = 3;
40 vector<int> nums2 = {2, 5, 6};
41 int n = 3;
42
43 mergeSortedArray(nums1, m, nums2, n);
44
45 // Output the merged array
46 for (int num : nums1) {
47 cout << num << " ";
48 }
49 // Output: 1 2 2 3 5 6
50 return 0;
51}Key Points in the Code:
nums1 that haven’t been merged yet.nums2 has leftover elements do we copy them; leftover elements in nums1 are already in place.Let’s analyze the Merge Sorted Array problem step by step, as if explaining to a friend:
Problem Recap:
You’re given two sorted arrays, nums1 and nums2. nums1 has enough space at the end to hold all elements from both arrays. Your task is to merge nums2 into nums1 in sorted order, in-place.
Step-by-Step Intuition:
Why start from the end?
If you started from the front, you’d risk overwriting elements in nums1 that you haven’t compared yet. By starting from the back, you always have empty space to fill.
How do we know which number to place next?
Since both arrays are sorted, the largest unplaced number is always at the end of either nums1 or nums2. Compare them, and put the larger one at the end of nums1.
What if one array runs out?
nums2 runs out first, nums1 is already in place.nums1 runs out first, copy the rest of nums2 into the front of nums1.Example Walkthrough:
Suppose nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3.
[1,2,3,0,0,6][1,2,3,0,5,6][1,2,3,3,5,6][1,2,2,3,5,6]Connection to Pattern:
This solution is a textbook application of the "merge from end" pattern, using two pointers and in-place manipulation to achieve efficient merging without extra space.
Signals to Recognize This Pattern:
Aha! Moments:
Debugging Tips:
i, j, k).Memory Tricks:
With practice, recognizing and applying this pattern will become second nature, especially when you spot the "merge two sorted arrays in-place" scenario!