Count items common to both the lists but with different prices

Given two lists list1 and list2 containing m and n items respectively. Each item is associated with two fields: name and price. The problem is to count items which are in both the lists but with different prices.

Examples:

Input : list1[] = {{"apple", 60}, {"bread", 20}, 
                   {"wheat", 50}, {"oil", 30}}
    list2[] = {{"milk", 20}, {"bread", 15}, 
                   {"wheat", 40}, {"apple", 60}}
Output : 2
bread and wheat are the two items common to both the
lists but with different prices.

Source: Cognizant Interview Experience | Set 5.

Method 1 (Naive Approach): Using two nested loops compare each item of list1 with all the items of list2. If match is found with a different price then increment the count.

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to count items common to both 
// the lists but with different prices
#include <bits/stdc++.h>
  
using namespace std;
  
// details of an item
struct item
{
    string name;
    int price;
};
  
// function to count items common to both 
// the lists but with different prices
int countItems(item list1[], int m,
               item list2[], int n)
{
    int count = 0;
      
    // for each item of 'list1' check if it is in 'list2'
    // but with a different price
    for (int i = 0; i < m; i++)    
        for (int j = 0; j < n; j++) 
  
            if ((list1[i].name.compare(list2[j].name) == 0) &&
                 (list1[i].price != list2[j].price))
                count++;        
      
    // required count of items
    return count;
}
  
// Driver program to test above
int main()
{
    item list1[] = {{"apple", 60}, {"bread", 20},
                    {"wheat", 50}, {"oil", 30}};
    item list2[] = {{"milk", 20}, {"bread", 15},
                   {"wheat", 40}, {"apple", 60}};
      
    int m = sizeof(list1) / sizeof(list1[0]);
    int n = sizeof(list2) / sizeof(list2[0]);    
      
    cout << "Count = "    
         << countItems(list1, m, list2, n);
           
    return 0;     

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation to
# count items common to both 
# the lists but with different
# prices
  
# function to count items
# common to both 
# the lists but with different prices
def countItems(list1, list2):
    count = 0
      
    # for each item of 'list1'
    # check if it is in 'list2'
    # but with a different price
    for i in list1:
        for j in list2:
  
            if i[0] == j[0] and i[1] != j[1]:
                count += 1
      
    # required count of items
    return count
  
# Driver program to test above
list1 = [("apple", 60), ("bread", 20),
            ("wheat", 50), ("oil", 30)]
list2 = [("milk", 20), ("bread", 15),
            ("wheat", 40), ("apple", 60)]
      
print("Count = ", countItems(list1, list2))
      
# This code is contributed by Ansu Kumari.

chevron_right



Output:

Count = 2

Time Complexity: O(m*n).
Auxiliary Space: O(1).

Method 2 (Binary Search): Sort the list2 in alphabetical order of its items name. Now, for each item of list1 check whether it in present in list2 using binary search technique and get its price from list2. If prices are different the increment the count.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to count items common to both 
// the lists but with different prices
#include <bits/stdc++.h>
  
using namespace std;
  
// details of an item
struct item
{
    string name;
    int price;
};
  
// comparator function used for sorting
bool compare(struct item a, struct item b) 
{
    return (a.name.compare(b.name) <= 0);        
}
  
// function to search 'str' in 'list2[]'. If it exists then
// price associated with 'str' in 'list2[]' is being
// returned else -1 is returned. Here binary serach 
// trechnique is being applied for searching
int binary_search(item list2[], int low, int high, string str)
{
    while (low <= high)
    {
        int mid = (low + high) / 2;
          
        // if true the item 'str' is in 'list2'         
        if (list2[mid].name.compare(str) == 0)
            return list2[mid].price;
          
        else if (list2[mid].name.compare(str) < 0)    
            low = mid + 1;
          
        else
            high = mid - 1;    
    }
      
    // item 'str' is not in 'list2'         
    return -1;
}
  
// function to count items common to both 
// the lists but with different prices
int countItems(item list1[], int m,
               item list2[], int n)
{
    // sort 'list2' in alphabetcal order of
    // items name
    sort(list2, list2 + n, compare);
      
    // initial count
    int count = 0;
      
    for (int i = 0; i < m; i++) {
  
        // get the price of item 'list1[i]' from 'list2'
        // if item in not present in second list then
        // -1 is being obtained
        int r = binary_search(list2, 0, n-1, list1[i].name);
          
        // if item is present in list2 with a 
        // different price
        if ((r != -1) && (r != list1[i].price))
            count++;
    }
      
    // required count of items
    return count;
}
  
// Driver program to test above
int main()
{
    item list1[] = {{"apple", 60}, {"bread", 20}, 
                     {"wheat", 50}, {"oil", 30}};
    item list2[] = {{"milk", 20}, {"bread", 15},
                   {"wheat", 40}, {"apple", 60}};
      
    int m = sizeof(list1) / sizeof(list1[0]);
    int n = sizeof(list2) / sizeof(list2[0]);    
      
    cout << "Count = "    
         << countItems(list1, m, list2, n);
           
    return 0;     
}

chevron_right


Output:

Count = 2

Time Complexity: (m*log2n).
Auxiliary Space: O(1).
For efficiency, the list with maximum number of elements should sorted and used for binary search.

Method 3 (Efficient Approach): Create a hash table with (key, value) tuple as (item name, price). Insert the elements of list1 in the hash table. Now, for each element of list2 check if it is the hash table or not. If it is present, then check if its price is different then the value from the hash table. If so then increment the count.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to count items common to both 
// the lists but with different prices
#include <bits/stdc++.h>
  
using namespace std;
  
// details of an item
struct item
{
    string name;
    int price;
};
  
// function to count items common to both 
// the lists but with different prices
int countItems(item list1[], int m,
               item list2[], int n)
{
    // 'um' implemented as hash table that contains
    // item name as the key and price as the value
    // associated with the key
    unordered_map<string, int> um;
    int count = 0;
      
    // insert elements of 'list1' in 'um'
    for (int i = 0; i < m; i++)
        um[list1[i].name] = list1[i].price;
      
    // for each element of 'list2' check if it is 
    // present in 'um' with a different price
    // value
    for (int i = 0; i < n; i++)    
        if ((um.find(list2[i].name) != um.end()) &&
            (um[list2[i].name] != list2[i].price))
            count++;
      
    // required count of items        
    return count;        
}
  
// Driver program to test above
int main()
{
    item list1[] = {{"apple", 60}, {"bread", 20}, 
                    {"wheat", 50}, {"oil", 30}};
    item list2[] = {{"milk", 20}, {"bread", 15}, 
                    {"wheat", 40}, {"apple", 60}};
      
    int m = sizeof(list1) / sizeof(list1[0]);
    int n = sizeof(list2) / sizeof(list2[0]);    
      
    cout << "Count = "    
         << countItems(list1, m, list2, n);
           
    return 0;     
}

chevron_right


Output:

Count = 2

Time Complexity: O(m + n).
Auxiliary Space: O(m).
For efficiency, the list having minimum number of elements should be inserted in the hash table.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.