Merge Two Sorted Arrays
Question
Merge two given sorted integer array A and B into a new sorted integer array.
Example
Analysis
Two ways to think about this. Two pointers (one for each) for two input arrays until you reach the end for both of them. Or one pointer for the result array, and keep filling it until it's full. (more do the same distance first then fill in the rest).
Do both methods then compare them.
Easy To Get Bug
Keep filling then handle the case where n > m or n < m will be easier to write bug free code.
Hard to Get Bug
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
nums1 has m elements and nums2 has n elements. Assume nums1 can hold m+n elements.
Example
Analysis
So this problem is engineered so we can do it "in-place". The brute force solution will be O(n^2) compare it then shift if necessary. Where to merge? Can we do it in one pass? Maybe we can hold a temp variable? Well check out the solution after no clue for 2 min.
ᶘ ᵒᴥᵒᶅ By default our mind is always telling us to start from left -> right or small -> large. What if we start filling from large -> small? ohhhh
Code
Recap
I can feel a significant improvement by writing analysis and going through thought process. I am no longer the no-clue-run-code-bug Zed, but the new pseudo-code-test-pass Zed. Congrats on understanding (read carefully and do examples) and figuring out (what paradigm / property to use) a problem. That's only the initial step. You also have to write a easy to follow pseudo code and write clear code then review and test a complex case.
Last updated