Interview Question


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 4 vote

Please can you explain the concept behind your code?

- chadi4all July 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Void DiffPiar( int array , int array_size){
map<int , int> store //cretae a map to store resulte
int temp;
for ( i=array_size -1 ; i>= 0 ; i-- ){
for( j=0; j<i ; j++{
temp=Difference ( array[0] , array [ j+ 1 ] )
array[j]=temp;
ii=search the map to see whether this temp element is already present inside the map or not , if present return the map index.
if it's present then just increment it's no of occur enc , ie second field in my code.
else
insert this temp element inside the map and keep second element 1.
}
}

after completing this search the map-second elements which are divisible by 2 , and prints those data ..

Example:
array : 1 2 3 6
pass1: 1 2 5
pass 2: 1 4
pass 3: 3

map contains
1->;2
2->;1
3->;1
4->;1
5->;1

- email.suman.roy July 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Void DiffPiar( int array , int array_size){
map<int , int> store //cretae a map to store resulte
int temp;
for ( i=array_size -1 ; i>= 0 ; i-- ){
for( j=0; j<i ; j++{
temp=Difference ( array[0] , array [ j+ 1 ] )
array[j]=temp;
ii=search the map to see whether this temp element is already present inside the map or not , if present return the map index.
if it's present then just increment it's no of occur enc , ie second field in my code.
else
insert this temp element inside the map and keep second element 1.
}
}

after completing this search the map-second elements which are divisible by 2 , and prints those data ..

Example:
array : 1 2 3 6
pass1: 1 2 5
pass 2: 1 4
pass 3: 3

map contains
1->;2
2->;1
3->;1
4->;1
5->;1

- email.suman.roy July 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

c++ solution of this problem
 /*
 Given a sorted array. Find the number of couples with the same difference. For example we can have an array with 2 couples whose difference is 3 and 4 couples whose difference is 5. The Output should be 2 & 4.
 developed by : Suman Roy
Email        : email.suman.roy@gmail.com
 */
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<map>
using namespace std;
int Diff( int &num1 , int &num2 ){
	if ( num1 > num2 ) return num1-num2;
	else return num2-num1;
}
typedef std::map< int , int > storage;
void Print ( storage store ){
	std::cout<<"pair output-->\n";
	for( storage::iterator ii=store.begin() ; ii!=store.end() ; ii++ ){
	        int temp=ii->second;
		 if ( temp % 2 == 0 )
		       std::cout<<ii->first<<" == "<<ii->second <<std::endl;
	}
}

void DiffPair(int *i_array , int &i_num ){
	storage store;
	storage::iterator ii;
	int temp;
	for ( int i=i_num-1 ; i>=0 ; i-- ){
		for( int j=0 ;j<i ; j++ ){
			temp=Diff ( * i_array , * ( i_array + j + 1 ) );
			* ( i_array + j ) = temp;
			ii=store.find ( temp );

			if ( ii== store.end() )
				store[ temp ] =1;
				
			else
				ii->second++;
			
		}
	}
	Print ( store ) ;
}

int main(){
	int i_size;
	std::cin>>i_size;
	int *i_array=new int [ i_size ];
	int i_value;
	for ( int i=0 ; i<i_size ; i++ )
		std::cin>> * ( i_array + i );
	std::cout<<"Print sorted array\n";
	for( int i=0 ; i<i_size ; i++ )
		std::cout<<* ( i_array + i )<<" ";
	std::cout<<std::endl;
	DiffPair( i_array , i_size );

}

- email.suman.roy July 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

temp=Diff ( * i_array , * ( i_array + j + 1 ) );
is above line correct?

- shsf July 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think he means smth like temp = abs(i_array[0] - i_array[j + 1]); This what his code means

- chadi4all July 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

its seems correct implementation...logic for the code:
-calculate numbers relative to min of first two number
iterate above till there is no number left

- shsf July 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If I apply this code to 1 3 6 then I'll get difference 2 repeated twice, and difference 4 repeated 1 time but all the couples in the array are (1, 3) with difference 2 & (1, 6) with difference 5 & (3, 6) with difference 3. Doesn't this mean that you're code is wrong? Did I miss anything?

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Void DiffPiar( int array , int array_size){
map<int , int> store //cretae a map to store resulte
int temp;
for ( i=array_size -1 ; i>= 0 ; i-- ){
for( j=0; j<i ; j++{
temp=Difference ( array[0] , array [ j+ 1 ] )
array[j]=temp;
ii=search the map to see whether this temp element is already present inside the map or not , if present return the map index.
if it's present then just increment it's no of occur enc , ie second field in my code.
else
insert this temp element inside the map and keep second element 1.
}
}

after completing this search the map-second elements which are divisible by 2 , and prints those data ..

Example:
array : 1 2 3 6
pass1: 1 2 5
pass 2: 1 4
pass 3: 3

map contains
1->2
2->1
3->1
4->1
5->1

- email.suman.roy July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Is duplicated counted? For eg: If array has four elements say 2,2,3,3 then I have 2 couples with difference 1 or only one couple?

- Sai July 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Also for above example array 2,2,3,3 - we can get 4 couples (2,2),(3,3),(2,3),(2,3) basically couples whose difference is 0 and difference is 1??

- Sai July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

An approach of binary search is considered although it takes O(nlogn) time in the end because of sorting.First store all possible set of differences in the array and then sort it and check for pairs Here is the code you can test it and ask for any queries:

#include <stdio.h>
#include <conio.h>

int compare(const void *a,const void *b)
{
    return ((*(int *)a)-(*(int *)b));
}
void findCouple(int arr[],int arr1[],int *i,int low,int high)
{
    if(low==high)
    {
        return;
    }
    else if(low+1==high)
    {
        arr1[*i]=arr[high]-arr[low];
        *i=*i+1;
        return;
    }
    else
    {
        int mid=low+(high-low)/2;
        if(low+2==high)
        {
        arr1[*i]=arr[mid]-arr[mid-1];*i=*i+1;
        arr1[*i]=arr[mid+1]-arr[mid];*i=*i+1;
        arr1[*i]=arr[mid+1]-arr[mid-1];*i=*i+1;
        return;
       }
       else if(low+3==high)
      {
          arr1[*i]=arr[mid]-arr[mid-1];*i=*i+1;
         arr1[*i]=arr[mid+1]-arr[mid];*i=*i+1;
         arr1[*i]=arr[mid+1]-arr[mid-1];*i=*i+1;
         arr1[*i]=arr[high]-arr[mid-1];*i=*i+1;
         arr1[*i]=arr[high]-arr[mid];*i=*i+1;
         return;
       }
       else
       { 
            arr1[*i]=arr[mid]-arr[mid-1];*i=*i+1;
         arr1[*i]=arr[mid+1]-arr[mid];*i=*i+1;
         arr1[*i]=arr[mid+1]-arr[mid-1];*i=*i+1;
         arr1[*i]=arr[high]-arr[mid-1];*i=*i+1;
         arr1[*i]=arr[high]-arr[mid];*i=*i+1;
         arr1[*i]=arr[mid]-arr[low];*i=*i+1;
       }
        findCouple(arr,arr1,i,low,mid-1);
        findCouple(arr,arr1,i,mid+1,high);
        return;
    }
}
int main()
{
    int arr[]={1,5,8,11,14,17,20,23,27};
    int arr1[30];
    int i=0;
    int n=sizeof(arr)/sizeof(arr[0]);
    findCouple(arr,arr1,&i,0,n-1);
    int j,count1=0,count2=0,diff1=0,diff2=0;
    qsort(arr1,n+2,sizeof(int),compare);
    for(j=0;j<i;)
    {
        if(arr1[j]==arr1[j+1])
        {
            count1++;
            if(count1==2)
            {
                diff1=arr1[j];
            }
            count2++;
            if(count2==4)
            {

                diff2=arr1[j];
            }
            j=j+2;
        }
        else
        {
            j=j+1;
        }
    }
    if(diff1==diff2)
        printf(" The 4 couples occur with difference of %d ",diff1);
    else if(diff1!=diff2&&(diff1!=0&&diff2!=0))
    {
        printf(" The two couples are there with difference of %d and 4 couples with %d",diff1,diff2);
    }
    else if(diff1!=0&&diff2==0)
    {
        printf(" The 2 couples with difference is %d ",diff1);
    }
    else if(diff2!=0&&diff1==0)
    {
        printf(" The 4 couples with difference is %d ",diff1);
    }
}

- vgeek July 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

My example was just an example vqeek ... If the n is the number of elements in the array then total number of couples is n*(n - 1) / 2. Among these couples there are couples with equal difference. For each couple I need this difference n the number of times it's repeated. so if a difference appears only once no need to print it.

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I know that the total number of couples are n*(n-1)/2. But you have to calculate the difference and also given the sorted array you have to make some optimizations to check for the required difference:
Like:
{10,20,30,40,50,60,70,80,90}. Further
Now {10,90 is a couple} but no need to calculate this difference because the difference of 80 cannot be made by any other couple. Further optimizations like this are made to check for the couples. I am just using the advantage of the sorted array. And i am having all the "POSSIBLE" differences in the array after which i am checking further. I know some one has downvoted it without even considering the approach and I respect his/her reviews but he/she altleast should give the reason for "DOWNVOTNG".

- vgeek July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I just realized that someone down voted ur answer. You're right, he should show us why did he vote this way?

By the way can u explain you're concept?

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just keep on checking for the difference by
a. First dividing the array into two halves
b. Check for left half
c. Check for right half.
d. But also check for the crossing sum that is one that passes through the middle element
e. At last when any two elements are left calculate the difference
f. At every point keep on storing the difference in the array they are the steps mentioned in the code of whom to calculate the differences
g. At last sort the array to check for pairs. Note this is the difference array and if at any consecutive positions four elements with same number are obtained then we have obtained the couple.

- vgeek July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry geek but I think you're algo will count some differences more than once.

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No have a close look

- vgeek July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I have 2 questions ...

1) is it possible that the function is not calculating all the possible differences?

2) Can we use map instead of an array and count number of time a diff occur?

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes it is calculating all possible set of differences.
Consider:
{1,2,3}
it is handled by first case low+2==high and returned no need to further call the function
{1,2,3,4}
it is handled by second case low+3==high and then returned so that no further function calls are made:
But if there are 5 elements and more then the last case handles it and further the function calls do the difference of arr[high]-arr[high-1] similarly for arr[low] with arr[low+1].
It is done like this

- vgeek July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I tried the following example:

arr = {6, 7, 14, 17, 24, 25, 33, 38, 45}

after applying you're code I get one couple with diff 10 while actually there are 2 couples with difference 10 which are (7, 17) & (14, 24).

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It is a one couple with two sets having difference of 10 as in my code i am taking a couple of two sets which should also be the case in real life

- vgeek July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Also if you have any doubt you can print the sorted array and check

- vgeek July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It's not clear to me how you can achieve O(n lg n) performance for arr = {1, 2, 4, 8, 16, 32, 64}. Doesn't every element have to be compared against another in order to calculate a difference? I do think we can do better than O(n(n-1)/2) in the average case by leveraging the fact that the array is sorted. For instance, if arr[arr.length] - arr[0] = 0, then the result is automatically arr.length * (array.length - 1) / 2. Of course, I'm only talking about arrays of length greater than 2.

- Anthony Mays July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anthony Mays
No every element is not to be considered. Now read the below explanation:
arr={1,2,3,4,5,6,7,8,9}. Here I am taking the simplest array with difference of just 1.
Now 9-1=8 this difference cannot be found in the subarray{2,3,4,5,6,7,8} . Further
8-2=6 This difference cannot be found in the subarray {3,4,5,6,7} And further:
7-3=4 this difference cannot be found in subarray {4,5,6}. And also:
9-2=7 Note this difference only needs to be compared with high-1 which is 8 and low+1 which is 1 that is 7. and also 9-3=6 is only to be compared with high-1 and low+1 or high-2 and low. Thus for 9-2 only need to compare 8-1 and for 9-3 need to compare 8-1 or 8-2 or 7-1 . No element can further exist for this difference. Thus here the optimizations are made and the complexity is reduced. For array having 2 or 3 or 4 elements I have handled them seperately else for 5 or more elements further the array is divided into 2 or 3 or 4 elements to handle all the cases.

- vgeek July 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@vgeek
Thanks for your reply! I thought I posted a comment in response so I apologize if it appears twice. The short of it is that I'm having trouble following your logic. Your solution assumes that the input will be unique that that you only need evaluate unique couples. My understanding of the problem assumes that the input can contain all of the same elements such that the number of couples I should report is n(n-1)/2 with a difference of 0.

Sticking to your example where arr = {1,2,3,4,5,6,7,8,9}, there are two couples with difference 7, three couples with difference 6, so forth and so on. A correct algorithm should produce the values 2,3,4,5,6,7, and 8.

I pasted your code into codepad.org (paste bTSskmXA) and changed the input to match your example . The output was not what I was expecting. Please let me know if I'm not using your code correctly.

I think you're on to something, but the implementation needs a little work. Thanks!

- Anthony Mays July 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anthony
Thanks for your comment but this algorithm works for this question where you have to find 2 or 4 pairs of numbers with the same difference. That's why i said earlier that 9-1=8 there can be only one such pair with 8 as difference not any other pair. Similarly other optimizations work like this. So this algo works for finding out 2 or 4 pairs of numbers with the same difference. But if you want to see all such couples which are greater than 2 or 2 as you say that 2,3,4,5,6,7,8. Well for it works but here as it would wont calculate the difference of those whose not more than one pair eixsts so it only calculates the difference of those which have more pairs than 2. So here it will only print the difference till 4. I hope it is clear.Thanks

- vgeek July 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And also here by a couple I mean that (2,9) and (8,1) form one couple not two as these are two different sets and they together form a single couple

- vgeek July 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

sites.google.com/site/spaceofjameschen/annnocements/findthenumberofcoupleswiththesamedifference

void PrintPairCount(int* arr, int len)
{
    hash_map<int, int> hm;

    for(int i = 1; i < len; ++i){
        for(int j = 0; j < i; ++j){
            int d = arr[i] - arr[j];
            auto it = hm.find(d);

            if(it == hm.end()){
                hm.insert(pair<int, int>(d, 1));
            }
            else{
                it->second ++;
            }
        }
    }
    cout << "The output is " << endl;
    int count(0);
    for(auto it = hm.begin(); it != hm.end(); ++it){
        if(it->second != 1){
            cout << "Find " << it->second << " pairs with difference of ";
            cout << it->first << endl;
            count ++;
        }
    }

    if(count == 0){
        cout << "No pair shares the same difference" << endl;
    }
}

- Anonymous July 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thx anonymous, This solution came to my mind but for big arrays it won't work. Is there exist an order of n log n solution??

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi chadi4all, Could you provide a case that it does not work? As to this problem, it requires C(n, 2) to calculate the difference of any 2. I don't think there is a n log n solution.

- Anonymous July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

ii=store.find ( temp );

if ( ii== store.end() )
store[ temp ] =1;

else
ii->second++;


can anybody tell me ..what does this code mean?

- Anonymous July 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

if temp is not in the map add it to the map n initialize it to 1 otherwise increment it.

- chadi4all July 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

/**
 * More more solutions visit blog.abhinavmathur.net
 * 
 *
 */
public class FindSameDifferenceCouple {

    public static void main(String[] args) {

        int[] arr = new int[4];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
             
        // this is the max difference which can exists between two elements as
        // array is sorted
        int maxDiff = arr[arr.length - 1] - arr[0];
        
        // to make more efficient , we could have used a hashmap instead of array
        int[] numCop = new int[maxDiff];
        
        
        // loop over all possible differences betweene elements,
        // we just leave 0 difference couples.
        for(int j=0;j<maxDiff;j++) {
            numCop[j] =0;
            for(int i=0;i<arr.length;i++) {
               int findElem = arr[i]+j;
               if(find(findElem,arr,i)) {
                   numCop[j] = numCop[j]+1;
               }
           }
        }
        
        for(int j=0;j<numCop.length;j++) {
            System.out.println(j+"\t"+numCop[j]);
        }
    }

    // we can make this more efficient by doing a binary search
    private static boolean find(int findElem, int[] arr, int i) {
        for(int j=i+1;j<arr.length;j++)
        {
            if(arr[j] == findElem)
                return true;
        }
        return false;
    }
}

- abhinav@abhinavmathur.net July 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I dont understand why this is voted down. Is there some problem with approach.

My soultion can do this is O(K*n*logn) time with space O(K) where K = a[n]-a[0]

- abhinav@abhinavmathur.net July 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

what happens if is k>n ?

- karthik February 04, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

import java.util.HashMap;
import java.util.Map;

public class TestArrayDifference {
int arr[];
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int diff=0;
public static void main(String[] args) {

TestArrayDifference testArrayDifference=new TestArrayDifference();
testArrayDifference.setArray(5);
testArrayDifference.findDifference();
System.out.println(testArrayDifference.arr);
}
private void setArray(int x) {
arr=new int[x];
for(int i=0;i<x;i++){
arr[i]=i+i*2+(i/2*i); //any dummy number in sorted order
System.out.println(arr[i]);
}
}
private void findDifference(){
for(int i=0;i<arr.length;i++){
for(int j=1;j<arr.length-i;j++){
diff=arr[j]-arr[j-1];
int x=0;
if(map.get(diff)!=null){
map.put(diff, map.get(diff)+1);
}else{
map.put(diff,1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("diffrence = " + entry.getKey() + ", No of couples = " + entry.getValue());
}
}
}
}

- Brijesh Pant July 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

Here's a C# solution. Worst case time complexity of this algorithm is O(n!/2(n-2)!) or O(n choose 2), if I'm not mistaken. Every element in the input is compared with every other element in unique combinations.

public int[] NumCouplesSameDifference(int[] values) {
	Dictionary<int, int> differences = new Dictionary<int, int>();
	if(values == null || values.Length < 2) return new int[0];
	for (int i = 0; i < values.Length - 1; ++ i) {
		for (int j = i + 1; j < values.Length; ++j) {
			int difference = values[j] - values[i];
			if (!differences.ContainsKey(difference)) {
				differences.Add(difference, 0);
			}
			differences[difference]++;
		}
	}
	
	List<int> results = new List<int>();
	foreach (int key in differences.Keys) {
		if(differences[key] > 1) {
			results.Add(differences[key]);
		}
	}
	
	return results.ToArray();
}

- Anthony July 13, 2013 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More