🔀 Merge Sorted Array | LeetCode 88 | Swift Solutionsort merged arrays
Автор: DebuggingLife
Загружено: 2025-12-03
Просмотров: 29
Описание:
Problem Overview:
Given two sorted arrays nums1 and nums2, merge them into a single sorted array. The twist? nums1 has extra space at the end to accommodate nums2, and you must merge in-place without using extra space.
Solution Approach
I solve this using the reverse three-pointer technique - starting from the end of both arrays and working backwards:Three Pointers:
x: Tracks last element in nums1's actual values (m - 1)
y: Tracks last element in nums2 (n - 1)
k: Tracks current position to fill (m + n - 1)
Algorithm:
1. Compare nums1[x] with nums2[y]
2. Place the larger element at position k
3. Move the corresponding pointer (x or y) and k backwards
4. Stop when all nums2 elements are placed
Time Complexity: O(m + n) - Single pass
Space Complexity: O(1) - True in-place, no extra space
Examples Covered
Example 1: nums1 = [1,2,3,0,0,0], nums2 = [2,5,6] → Output: [1,2,2,3,5,6]
Example 2: nums1 = [1], nums2 = [] → Output: [1]
Example 3: nums1 = [0], nums2 = [1] → Output: [1]
Resources
LeetCode Problem: https://leetcode.com/u/debugging-life/
My GitHub:https://github.com/debuging-life
Key Insights
1. Early termination: Once y less than 0, all nums2 elements are placed - remaining nums1 elements are already in correct position
2. Boundary check: x greater than equals to 0 prevents array out of bounds when nums1 runs out first
3. No shifting needed: Using the empty space at the end eliminates expensive operations
Common in interviews at: Apple, Google, Meta, Amazon
#Swift #LeetCode #DSA #iOSDevelopment #CodingInterview #Algorithms #SwiftProgramming #TechInterview #FAANG #TwoPointers #ArrayProblems #iOSEngineer
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: