algoadvance

Clarifying Questions

To ensure we’re both on the same page, I’ll need to clarify a few points:

  1. What are the input constraints?
  2. What kind of data structures will the inputs be in?
  3. Should we return -1 if there is no common value?

Assuming the common interpretation:

Strategy

Here’s a step-by-step strategy to solve the problem:

  1. Convert Lists to Sets: Converting lists to sets allows us to efficiently find common elements.
  2. Find Intersection: Use the set intersection operation to find common elements.
  3. Return Minimum: If the intersection is non-empty, return the smallest element from the intersection. Otherwise, return -1.

Time Complexity

  1. Converting Lists to Sets: This operation is O(n + m) where n and m are the lengths of the two lists.
  2. Intersection of Sets: Finding the intersection of two sets is O(min(n, m)).
  3. Finding the Minimum: This is O(k), where k is the number of common elements. In the worst case, k could be min(n, m).

Overall, the time complexity is O(n + m), which is efficient given that we need to examine all elements at least once.

Code

Here’s the Python code to implement the above strategy:

def min_common_value(list1, list2):
    set1 = set(list1)
    set2 = set(list2)
    
    common_elements = set1.intersection(set2)
    
    if not common_elements:
        return -1
    
    return min(common_elements)

# Example usage
list1 = [10, 20, 30, 40, 50]
list2 = [15, 25, 35, 40, 45]

print(min_common_value(list1, list2))  # Output: 40

Explanation of Code

  1. Conversion to Sets: set1 = set(list1) and set2 = set(list2) convert the input lists to sets.
  2. Intersection: common_elements = set1.intersection(set2) calculates the common elements.
  3. Check for Common Elements: If common_elements is empty, return -1.
  4. Minimum of Common Elements: If there are common elements, return the minimum using min(common_elements).

This solution is straightforward, efficient, and leverages Python’s built-in set operations to ensure optimal performance.

Try our interview co-pilot at AlgoAdvance.com