Search code examples
c++arrayssortingmergeundefined-behavior

88. Merge Sorted Array


The task is: here

i've successfuly got working code on local machine, also on platform first three casess attempted my solution. But if i run Submit i've get the undefined behavior runtime error on this case: nums1 = [2,0], m = 1, nums2 = [1], n = 1. As i understand in result must be nums1 = [1,2] and i've get it in local machine without any errors. why that happen?

class Solution {
public:
    void merge(std::vector<int>& nums1, int m, std::vector<int>& nums2, int n);
};

void Solution::merge(std::vector<int>& nums1, int m, std::vector<int>& nums2, int n)
{
    int iNums1 = m - 1;
    int iNums2 = n - 1;
    int iResult = m + n - 1;

    for (; iResult >= 0 && iNums2 >= 0; iResult--)
    {
        if (iNums2 < 0)
        {
            break;;
        }
        else if (iNums1 < 0 && iNums2 >= 0)
        {
            std::swap(nums2, nums1);
            break;
        }       
        else if (nums2[iNums2] > nums1[iNums1])
        {
            nums1[iResult] = nums2[iNums2--];
        }
        else if (iResult <= m && nums1[iResult - 1] <= nums2[iNums2] && nums1[iResult] > nums2[iNums2])
        {
            nums1[iResult + 1] = nums1[iResult];
            nums1[iResult] = nums2[iNums2--];
        }
    }
}

used testcase on local machine, no errors occured:

Solution s;
std::vector<int> nums1 = { 2, 0 };
std::vector<int> nums2 = { 1 };
std::vector<int> result = { 1, 2 };
s.merge(nums1, 1, nums2, 1);



Solution

  • Swapping nums1 and nums2 does not make sense as the result is supposed to be entirely stored inside nums1.

    Additionally, the last condition is not needed; if the next element to add to the output is not from the first vector, then it must necessarily be from the second one. What remains to be checked is the bounds: if there are no elements left in the first vector, we can only take elements from the second one and vice versa.

    for (; iResult >= 0 && iNums2 >= 0; iResult--) {      
        if (iNums1 < 0 || iNums2 >= 0 && nums2[iNums2] > nums1[iNums1]){
            nums1[iResult] = nums2[iNums2--];
        } else {
            nums1[iResult] = nums1[iNums1--];
        }
    }