LinkedIn | Phone Screen | Union Of Two Sorted Arrays With Duplicates | O(1) Space Code

4767
Apr 28, 2024
Dec 14, 2024

😊 ~ 𝙒𝙞𝙩𝙝 ❤️ 𝙗𝙮 𝙃𝙞𝙧𝙚𝙣

Given two sorted arrays of size n and m respectively, find their union. The Union of two arrays can be defined as the common and distinct elements in the two arrays. Return the elements in sorted order. Example:-
n = 5, nums1[ ] = {2, 2, 3, 4, 5}
m = 5, nums2[ ] = {1, 1, 2, 3, 4}
Output: 1 2 3 4 5
Explanation: Distinct elements including both the arrays are: 1 2 3 4 5.

Note: Hey There! Just Take A Look At The Code And Comments Within It. You'll Get It.
Note: Time Complexity And Auxiliary Space Is Mentioned With The Code.
Note: If You Have Any Kind Of Doubt, Just Comment And I'll Be There For You.

Approach : Using Two Pointers Technique

class TwoPointers {
public:
    // O(N+M) & O(1)
    vector<int> findUnion(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size(), m = nums2.size();
        int i = 0, j = 0;
        
        vector<int> result;
        
        while(i < n && j < m) {
            if(!result.empty() && nums1[i] == result.back()) // Avoid duplicates from nums1
                i++; 
            else if(!result.empty() && nums2[j] == result.back()) // Avoid duplicates from nums2
                j++; 
            else if(nums1[i] < nums2[j])
                result.push_back(nums1[i]);
            else
                result.push_back(nums2[j]);
        }
        
        // Store the remaining elements of nums1 
        while(i < n) {
            if(nums1[i] != result.back())
                result.push_back(nums1[i]);
            i++;
        }
        // Store the remaining elements of nums2 
        while(j < m) {
            if(nums2[j] != result.back())
                result.push_back(nums2[j]);
            j++;
        }
        
        return result;
    }
};

𝗨𝗣𝗩𝗢𝗧𝗘 𝗜𝗙 𝗬𝗢𝗨 𝗟𝗜𝗞𝗘 𝗧𝗛𝗘 𝗦𝗢𝗟𝗨𝗧𝗜𝗢𝗡 👍

Note: This solutions are created by myself after reading this post :-
Link: https://leetcode.com/discuss/interview-question/349701/LinkedIn-or-Phone-Screen-or-Union-of-two-sorted-arrays

Comments (10)