Python Interview coding 4 With Funny Example

➕ Two Sum Problem: Find Pairs That Sum to a Target Value (Python Solution)

Given an array of numbers, our goal is to find two numbers that add up to a given target. 🚀

For example, in the array [2, 7, 11, 15] with a target of 9, the numbers 2 and 7 form the pair. Let’s explore different ways to solve this in Python!

🛠️ Method 1: Brute Force Approach

This method checks every pair in the array to find the target sum.


def two_sum_brute_force(nums, target):
    n = len(nums)
    for i in range(n):
        for j in range(i + 1, n):
            if nums[i] + nums[j] == target:
                return [i, j]  # Return indices of the two numbers
    return []  # No pair found

# Example Usage
nums = [2, 7, 11, 15]
target = 9
print(f"Indices: {two_sum_brute_force(nums, target)}")  # Output: [0, 1]

    

🔍 Explanation (Line-by-Line)

  • for i in range(n): → Loop through each number.
  • for j in range(i + 1, n): → Check every other number after i.
  • if nums[i] + nums[j] == target: → If their sum matches the target, return the indices.
  • return [] → If no pair is found, return an empty list.

📊 Time and Space Complexity

  • Time Complexity: O(n²) → Two nested loops.
  • Space Complexity: O(1) → No extra space used.

✅ Method 2: Using a HashMap (Optimized)

This method uses a dictionary (hash map) to store numbers and their indices, reducing time complexity.


def two_sum_hashmap(nums, target):
    num_map = {}  # Dictionary to store numbers and their indices
    for i, num in enumerate(nums):
        complement = target - num  # Find the needed number
        if complement in num_map:
            return [num_map[complement], i]  # Return the indices
        num_map[num] = i  # Store index of current number
    return []

# Example Usage
nums = [2, 7, 11, 15]
target = 9
print(f"Indices: {two_sum_hashmap(nums, target)}")  # Output: [0, 1]

    

🔍 Explanation (Line-by-Line)

  • num_map = {} → Create an empty dictionary to store seen numbers.
  • for i, num in enumerate(nums): → Iterate through the array with indices.
  • complement = target - num → Find the number we need to complete the sum.
  • if complement in num_map: → If it’s already in the dictionary, return the pair.
  • num_map[num] = i → Store the number with its index.

📊 Time and Space Complexity

  • Time Complexity: O(n) → We traverse the list once.
  • Space Complexity: O(n) → We store numbers in a dictionary.

🏆 Conclusion: Which Method is Best?

Method Pros Cons Time Complexity Space Complexity
Brute Force Simple and easy Slow for large arrays O(n²) O(1)
HashMap Fast and efficient Uses extra memory O(n) O(n)

The HashMap method is much faster and works well for large inputs. If efficiency is important, use this approach! 🚀

Can you think of a real-life scenario where this problem might be useful? Drop a comment below! 😆

python-interview-coding-5-with-funny-example

Comments