Question

Given two arrays A and B of n integers both of which are sorted in ascending...

Given two arrays A and B of n integers both of which are sorted in ascending order. Write an algorithm to check whether or not A and B have an element in common. Find the worst case number of array element comparisons done by this algorithm as a function of n and its Big-O complexity

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please upvote if you like the answer, as it helps the community a lot.

Also if you have any doubts, feel free to ask in comments, we will reach you ASAP.

SOLUTION:

ALGORITHM:

  1. Simultaneously start traversing arr1[] and arr2[].
    • If the current elements of both arrays is same, we have found at least one common element, return True.
    • If they are not same, pick the array which has smaller of current elements among arr1[] and arr2[], and move ahead in the array which had smaller current element.
    • Repeat these steps unless either a common element gets found or one of the array reaches its ending.
  2. If we reached till the end in atleast one of the arrays it means there was no common element.

WORST CASE:

Number of comprisons = 2*n-1 = 2n-1 when only one element remains at last.

Big-O Complexity = O(2n) = O(n)

CODE SAMPLE:

bool commonInArrays(int arr1[], int arr2[], int n)

{

    int i = 0, j = 0;   

    // Traverse both array

    while (i<n && j <n)

    {

        // Check if current element of first

        // array is smaller than current element

        // of second array. If yes, increment first array

        // index. Otherwise do same with second array

        if (arr1[i] < arr2[j])

i++;

        else if(arr1[i] > arr2[j])

j++;

        else

return true;

    }

// If we reached the end in atleast one array then there is no common element for sure

return false;

}

Add a comment
Know the answer?
Add Answer to:
Given two arrays A and B of n integers both of which are sorted in ascending...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT