Merge Two Sorted Arrays
GoogleTechnicalDifficulty: Easy
Share on
Ready to answer it out loud?
Run a mock interview on this exact question and get instant AI feedback.
Question Explain
Given two sorted arrays nums1 and nums2, merge them into a single sorted array.
Example: Input: nums1 = [1,3,5], nums2 = [2,4,6] Output: [1,2,3,4,5,6]
Follow-up: Can you do it in O(n) time complexity?
Answer Example
Solution for Merging Two Sorted Arrays:
-
Approach:
- Use two pointers technique
- Compare elements from both arrays
- Build result array in sorted order
-
Code Implementation:
def merge_sorted_arrays(nums1, nums2):
result = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
result.append(nums1[i])
i += 1
else:
result.append(nums2[j])
j += 1
# Add remaining elements
result.extend(nums1[i:])
result.extend(nums2[j:])
return result
-
Time & Space Complexity:
- Time: O(n + m) where n, m are lengths of input arrays
- Space: O(n + m) for result array
-
Edge Cases:
- Empty arrays
- Arrays of different lengths
- Duplicate elements
- Negative numbers
-
Optimizations:
- In-place merge if one array has extra space
- Early termination if one array is exhausted
- Handling special cases for small arrays
-
Testing:
# Test cases
print(merge_sorted_arrays([1,3,5], [2,4,6])) # [1,2,3,4,5,6]
print(merge_sorted_arrays([], [1,2,3])) # [1,2,3]
print(merge_sorted_arrays([1], [])) # [1]
Company Context (Google):
- Focus on clean, efficient code
- Handle edge cases gracefully
- Consider scalability for large arrays
- Discuss potential optimizations
Related Interview Questions
Knowledge of storage architectures and types
AmazonMedium
Basic String ManipulationAdobe
Investment Portfolio OptimizationGoldman SachsMedium
Can you share an example of using innovative problem-solving skills to overcome a major work challenge?GoogleHard
How would you implement a custom authentication mechanism for a new AEM feature while adhering to AEM's security best practices?PwCHard
What strategies help you solve complex technical problems under pressure?eBayHard
Cybersecurity SolutionsMetaHard
Can you describe a situation where you used your problem-solving skills to overcome a technical challenge?TwitterMedium