We have a 2 arrays e.g. arr1[]={2,3,4,4,5,6,7} , arr2[]={1,2,2,4,6,8,8} . Assuming that both the arrays are sorted , if we want to write a program to find common numbers present in both arrays , how do we do that ? Note that nested for loop has a complexity of n2 , hence avoid nested for loop.

Questions by Ajay Kanse   answers by Ajay Kanse

Showing Answers 1 - 5 of 5 Answers

Meghraj

  • Jun 14th, 2014
 

well check for how many 1s,2s, upto 9s in both the arrays and minimum of a particular digit(from 1 to 9) in an array will be the common numbers of that particular digit. we will check upto 9 in both arrays for total common numbers.

  Was this answer useful?  Yes

Assuming both arrays are sorted in ascending order, this is pretty easy to do in a single loop with two array counters. Start both counters at zero. Compare array elements at their respective counters ( a1[s1] == a2[s2] ). If they match, write the matched value to the result array, then advance both array counters until they both point to a new value (that way you dont match mulutpie occurences). If they dont match, advance the counter in the array with the lower value. Repeat until you reach the end of either array.

Code
  1. #include <stdio.h>

  2. #include <stdlib.h>

  3. #include <string.h>

  4. #include <math.h>

  5. #include <time.h>

  6.  

  7. /**

  8.   * callback function for qsort

  9.   *//**

  10.  * Display array contents to specified file stream

  11.  */"""%s = {""%s%d", sep, arr[i] );

  12.     sep = ",""}\n" );

  13. }

  14.  

  15. /**

  16.  * Generate a sorted array with a random size no less than minsize and

  17.  * and random contents between 1 and 10.  

  18.  *//**

  19.  * Find matching values in the two arrays.

  20.  *//**

  21.  * Test driver.

  22.  */"allocation failure\n"" a1"" a2""allocation failure\n""res"

  Was this answer useful?  Yes

Sagar Ys

  • Aug 13th, 2015
 

Sort both the arrays, remove duplicate in both the arrays.
Combine two arrays sort it and find the duplicate.

  Was this answer useful?  Yes

Nitin Garg

  • Dec 12th, 2015
 

Code
  1. #include<stdio.h>

  2. #include<conio.h>

  3. #include<math.h>

  4. "%d "//if

  5.              

  6. }//for

  7. k++;

  8.  

  9. }//while

  10.  

  11.  

  12. getch();

  13. }

  Was this answer useful?  Yes

Alejandro Visiedo

  • Mar 5th, 2016
 

Code
  1. span style="color: #ff0000;">"%d, "

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions