Skip to content

Commit 2abe0cc

Browse files
leetcode 88
1 parent 5959267 commit 2abe0cc

1 file changed

Lines changed: 94 additions & 0 deletions

File tree

Leetcode/Leetcode_88.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"""
2+
LeetCode Problem: 88. Merge Sorted Array
3+
4+
Problem Statement:
5+
You are given two sorted integer arrays nums1 and nums2, and two integers m and n.
6+
7+
- nums1 has a size of m + n, where:
8+
- first m elements are valid
9+
- last n elements are 0 (empty space)
10+
11+
- nums2 has n elements
12+
13+
Merge nums2 into nums1 as one sorted array (in-place).
14+
15+
--------------------------------------------------
16+
17+
Example:
18+
Input:
19+
nums1 = [1,2,3,0,0,0], m = 3
20+
nums2 = [2,5,6], n = 3
21+
22+
Output:
23+
[1,2,2,3,5,6]
24+
25+
--------------------------------------------------
26+
27+
Approach (Your Method - Fill + Sort):
28+
29+
1. Fill nums2 elements into nums1 starting from index m
30+
2. Sort nums1 to get the final merged sorted array
31+
32+
--------------------------------------------------
33+
34+
Dry Run:
35+
36+
nums1 = [1,2,3,0,0,0]
37+
nums2 = [2,5,6]
38+
39+
Step 1: Fill nums2 into nums1
40+
→ nums1 = [1,2,3,2,5,6]
41+
42+
Step 2: Sort nums1
43+
→ nums1 = [1,2,2,3,5,6]
44+
45+
--------------------------------------------------
46+
47+
Time Complexity:
48+
O((m+n) log(m+n)) → due to sorting
49+
50+
Space Complexity:
51+
O(1) → in-place modification
52+
53+
--------------------------------------------------
54+
55+
Key Learnings:
56+
- Understand difference between actual values and placeholder zeros
57+
- In-place modification is important
58+
- This approach is simple but not optimal
59+
- Optimal solution uses 3 pointers (O(m+n))
60+
61+
--------------------------------------------------
62+
"""
63+
64+
from typing import List
65+
66+
67+
class Solution:
68+
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
69+
# k → pointer for nums2
70+
k = 0
71+
72+
# Fill nums2 elements into nums1 after index m
73+
for l in range(len(nums1)):
74+
if l >= m:
75+
nums1[l] = nums2[k]
76+
k += 1
77+
78+
# Sort the merged array
79+
nums1.sort()
80+
81+
82+
# ------------------------------
83+
# Example Run (for testing)
84+
# ------------------------------
85+
if __name__ == "__main__":
86+
nums1 = [1, 2, 3, 0, 0, 0]
87+
m = 3
88+
nums2 = [2, 5, 6]
89+
n = 3
90+
91+
sol = Solution()
92+
sol.merge(nums1, m, nums2, n)
93+
94+
print("Merged Array:", nums1)

0 commit comments

Comments
 (0)