logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›leetcode›easy

88. Merge Sorted Array (In-Place)

# Question

You are given two integer arrays nums1nums1nums1 and nums2nums2nums2, sorted in non-decreasing order. You are also given integers mmm and nnn, which represent the number of initialized elements in nums1nums1nums1 and nums2nums2nums2 respectively.

Merge nums1nums1nums1 and nums2nums2nums2 into a single array sorted in non-decreasing order. The final sorted array must be stored in-place inside the array nums1nums1nums1. To accommodate this, nums1nums1nums1 has a total length of m+nm + nm+n.

# Solution

# Pattern

Backward Three-Pointer Manipulation Instead of processing elements from the beginning (which forces an expensive array shift operation), compare and write elements starting from the back of the pre-allocated buffer space.

# How to Identify

  • Two input data structures are provided already sorted.
  • The destination container contains trailing empty padding explicitly designed to fit the incoming dataset.
  • Constraints demand an in-place modification with O(1)O(1)O(1) auxiliary space.

# Description

Step-by-step explanation:

  • Step 1: Pointer Initialization. Create three tracking pointers:
    • p1 positioned at the end of valid data in nums1nums1nums1 (m−1m - 1m−1).
    • p2 positioned at the end of nums2nums2nums2 (n−1n - 1n−1).
    • w (write pointer) positioned at the absolute end of the nums1nums1nums1 storage buffer (m+n−1m + n - 1m+n−1).
  • Step 2: Core Processing Loop. Execute a loop that runs continuously as long as there are valid uncopied elements remaining in nums2nums2nums2 (p2≥0p2 \ge 0p2≥0).
  • Step 3: Evaluation & Assignment. - If p1 >= 0 and nums1[p1]>nums2[p2]nums1[p1] > nums2[p2]nums1[p1]>nums2[p2], copy the value at nums1[p1]nums1[p1]nums1[p1] to nums1[w]nums1[w]nums1[w], then decrement p1.
    • Otherwise, copy the value at nums2[p2]nums2[p2]nums2[p2] to nums1[w]nums1[w]nums1[w], then decrement p2.
  • Step 4: Shift Write Position. Decrement the write pointer w after every assignment step.
  • Step 5: Implicit Completion. Once p2 drops below 0, terminate. Any remaining elements belonging to nums1nums1nums1 are already left in their correctly sorted configurations.

# The Intuition

Think of this as loading a delivery truck from back to front.

If you try to load new packages into the front of the truck (nums1nums1nums1), you would have to manually push all the existing items (mmm elements) backward every single time to clear out space, resulting in highly inefficient work.

By starting at the very back of the truck where empty space is guaranteed (m+n−1m + n - 1m+n−1), you can compare the largest items from both sets and place them securely in position. You never have to shift any items, and you will never accidentally crush (overwrite) a package that hasn't been scanned yet.

# Complexity

LabelWorstAverage
Time ComplexityO(m+n)O(m + n)O(m+n)O(m+n)O(m + n)O(m+n)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

O(m+n)O(m + n)O(m+n). In the worst-case scenario, every item from both inputs must be individually evaluated and written into the composite layout. Each element is moved at most once.

# Space Complexity

O(1)O(1)O(1). The solution edits elements completely in-place inside the pre-allocated tail space of nums1nums1nums1. No dynamic tracking collections or recursive stack contexts are used.

# Code

class Solution {
    /**
     * Merges nums2 into nums1 backwards to guarantee O(1) auxiliary space.
     */
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        // Isolate pointers to avoid destroying the input method parameters
        int p1 = m - 1;        // High index of valid data in nums1
        int p2 = n - 1;        // High index of data in nums2
        int w = m + n - 1;     // Global write pointer at the back of the buffer
 
        // The process is complete the exact moment nums2 elements are exhausted.
        // If nums1 empties out early, the conditional block naturally flushes nums2 items forward.
        while (p2 >= 0) {
            if (p1 >= 0 && nums1[p1] > nums2[p2]) {
                nums1[w] = nums1[p1];
                p1--;
            } else {
                nums1[w] = nums2[p2];
                p2--;
            }
            w--; // Pull the global write tracking position backward
        }
    }
}

# Caveats

  • Short-Circuit Order Check: The index out-of-bounds guard p1 >= 0 must be written prior to evaluating nums1[p1] in the conditional check expression. Reversing this order will cause a runtime exception if nums1nums1nums1 runs out of elements first.
  • The Early Termination Trap: Do not write the loop boundary condition as while (p1 >= 0 && p2 >= 0). If you do, the loop will exit early if nums1nums1nums1 elements are exhausted first, leaving the remaining smaller items of nums2nums2nums2 completely missing from the front of the array.

# Concepts to Think About

  • Stable Sort Consistency: Utilizing a strict inequality check (> instead of >=) ensures that the relative placement order of identical matching keys coming from different source streams remains stable.
  • Hardware Cache Layouts: Iterating through sequential memory arrays from back to front reads contiguous cash blocks, which plays favorably with modern hardware architecture pre-fetching rules.
  • System Buffer Architecture: This strategy mirrors lower-level operating system network ring-buffer mechanics, where structural padding spaces are pre-allocated to bypass secondary allocation bottlenecks.

# Logical Follow-up

Question: How would you resolve this problem if nums1nums1nums1 did not possess any trailing buffer padding?

Solution: To maintain O(1)O(1)O(1) space without padding, you would be forced to insert from the front and shift elements downstream on insertions, degrading runtime performance to O(m⋅n)O(m \cdot n)O(m⋅n). To maintain linear O(m+n)O(m + n)O(m+n) time, you would have to allocate an auxiliary data array copy of size mmm, moving your auxiliary space footprint up to O(m)O(m)O(m).

Question: How does the strategy shift if the input datasets are presented as two Singly Linked Lists instead of sequential memory arrays?

Solution: Linked lists allow structural modification via pointer manipulation without memory shifting overhead. A forward merge pattern is preferred here: you maintain a dummy head node and stitch the pointers together from smallest to largest. The time complexity stays O(m+n)O(m + n)O(m+n), and the space complexity stays O(1)O(1)O(1).

Previous70. Climbing StairsNext104. Maximum Depth of Binary Tree
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up