Similar Problems

Similar Problems not available

Find The Difference Of Two Arrays - Leetcode Solution

Companies:

LeetCode:  Find The Difference Of Two Arrays Leetcode Solution

Difficulty: Easy

Topics: hash-table array  

Problem Statement:

You are given two arrays, nums1 and nums2, where nums1 is a subset of nums2. Each element in nums1 appears only once in nums2 and both arrays are sorted in non-decreasing order. Find the difference between the largest number in nums1 and the smallest number in nums2.

Example:

Input: nums1 = [1,3], nums2 = [2,5,7,8,9]

Output: 1

Explanation: The largest number in nums1 is 3 and the smallest number in nums2 is 2, so the difference is 1.

Solution:

The approach to solve this problem involves finding the maximum element of the nums1 array and the minimum element of the nums2 array, and then finding the difference between them.

We can use two pointers to traverse the arrays. The pointer i starts from the beginning of nums1 and the pointer j starts from the beginning of nums2. We keep incrementing j until we find an element that is greater than or equal to nums1[i].

We can then calculate the difference between nums2[j] and nums1[i] and update the answer accordingly. After this, we increment both i and j and repeat the process until we have reached the end of either array.

If we reached the end of nums1, then we will calculate the difference between the last element of nums1 and the last element of nums2.

If we reached the end of nums2 without finding an element greater than or equal to nums1[i], then we return -1 as it means that nums2 does not contain all the elements of nums1.

The time complexity of this approach is O(n), where n is the length of the longer array.

Code:

int findTheDifference(vector<int>& nums1, vector<int>& nums2) { int i = 0, j = 0, ans = -1; while(i < nums1.size() && j < nums2.size()){ if(nums1[i] <= nums2[j]) j++; else{ if(ans == -1) ans = nums2[j] - nums1[i]; else ans = min(ans, nums2[j] - nums1[i]); i++, j++; } } if(i == nums1.size()) ans = min(ans, nums2[j] - nums1[i-1]); if(ans == -1) return ans; return ans; }

Note: This solution has been implemented in C++ and the time complexity of this solution is O(n).

Find The Difference Of Two Arrays Solution Code

1