Lädt...


🔧 🚀 Solving the Two Sum Problem: Multiple Approaches Using Java/Python


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

The "Two Sum" problem is a popular coding challenge that tests your ability to find pairs in an array that sum up to a specific target. Let’s dive into various methods to solve this problem efficiently.

Problem Statement 🎯

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

Input: nums = [2, 7, 11, 15], target = 9

Output: [0, 1] (because nums[0] + nums[1] == 9)

1. Brute Force Approach ⚔️

Python:

def two_sum_bruteforce(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []

Java:

public int[] twoSumBruteforce(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[] { i, j };
            }
        }
    }
    return new int[] {}; // If no solution is found
}

Explanation:

  • Iterate over each pair of indices and check if their sum equals the target.

2. Hash Map Approach 📚

Python:

def two_sum_hash_map(nums, target):
    num_to_index = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in num_to_index:
            return [num_to_index[complement], i]
        num_to_index[num] = i
    return []

Java:

import java.util.HashMap;

public int[] twoSumHashMap(int[] nums, int target) {
    HashMap<Integer, Integer> numToIndex = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (numToIndex.containsKey(complement)) {
            return new int[] { numToIndex.get(complement), i };
        }
        numToIndex.put(nums[i], i);
    }
    return new int[] {}; // If no solution is found
}

Explanation:

  • Use a hash map to store the index of each number.
  • For each element, check if its complement (target - current number) exists in the hash map.

3. Two-Pointer Approach 🏃‍♂️

Python:

def two_sum_two_pointer(nums, target):
    nums_with_index = list(enumerate(nums))
    nums_with_index.sort(key=lambda x: x[1])

    left, right = 0, len(nums) - 1
    while left < right:
        current_sum = nums_with_index[left][1] + nums_with_index[right][1]
        if current_sum == target:
            return [nums_with_index[left][0], nums_with_index[right][0]]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return []

Java:

import java.util.Arrays;
import java.util.Comparator;

public int[] twoSumTwoPointer(int[] nums, int target) {
    int[][] numsWithIndex = new int[nums.length][2];
    for (int i = 0; i < nums.length; i++) {
        numsWithIndex[i][0] = i;
        numsWithIndex[i][1] = nums[i];
    }
    Arrays.sort(numsWithIndex, Comparator.comparingInt(a -> a[1]));

    int left = 0, right = nums.length - 1;
    while (left < right) {
        int currentSum = numsWithIndex[left][1] + numsWithIndex[right][1];
        if (currentSum == target) {
            return new int[] { numsWithIndex[left][0], numsWithIndex[right][0] };
        } else if (currentSum < target) {
            left++;
        } else {
            right--;
        }
    }
    return new int[] {}; // If no solution is found
}

Explanation:

  • First, sort the array while keeping track of the original indices.
  • Use two pointers to find the pair that sums up to the target.

4. Optimized Space Approach 🔍

Python:

def two_sum_optimized(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        diff = target - num
        if diff in seen:
            return [seen[diff], i]
        seen[num] = i
    return []

Java:

import java.util.HashMap;

public int[] twoSumOptimized(int[] nums, int target) {
    HashMap<Integer, Integer> seen = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int diff = target - nums[i];
        if (seen.containsKey(diff)) {
            return new int[] { seen.get(diff), i };
        }
        seen.put(nums[i], i);
    }
    return new int[] {}; // If no solution is found
}

Explanation:

  • Iterate through the array while maintaining a hash map of the numbers seen so far.
  • Check if the complement of the current number exists in the hash map.

Conclusion 🌟

These methods offer various ways to solve the Two Sum problem, each with its advantages and trade-offs. Whether you prefer the straightforward brute force method or the efficient hash map approach, understanding these techniques will enhance your problem-solving skills.

Feel free to share your thoughts or additional methods in the comments!

Connect with me:

Happy coding! 🚀

...

🔧 🚀 Solving the Two Sum Problem: Multiple Approaches Using Java/Python


📈 83.69 Punkte
🔧 Programmierung

🔧 Min sum of set of positive integers so that sum of no two elements is K


📈 40.89 Punkte
🔧 Programmierung

🔧 Tìm Hiểu Về RAG: Công Nghệ Đột Phá Đang "Làm Mưa Làm Gió" Trong Thế Giới Chatbot


📈 39.51 Punkte
🔧 Programmierung

🔧 A More Straightforward Guide to Solving Two Sum.


📈 37.44 Punkte
🔧 Programmierung

🔧 C#: functional approaches explained solving one specific problem


📈 36.83 Punkte
🔧 Programmierung

🔧 You're Not Solving the Problem You Think You're Solving | AI Show


📈 34.13 Punkte
🔧 Programmierung

🎥 You're Not Solving the Problem You Think You're Solving


📈 34.13 Punkte
🎥 Video | Youtube

🔧 Count numbers in range whose sum of digits is divisible by XOR sum of digits


📈 33.92 Punkte
🔧 Programmierung

🔧 Two sum problem solution in easy way [Day-03]


📈 31.06 Punkte
🔧 Programmierung

🔧 How to Build a Visualization for Leetcode's Two Sum Problem – HTML, CSS, & JavaScript Project


📈 31.06 Punkte
🔧 Programmierung

🔧 LeetCode1425: Solving Constrained Subsequence Sum with DP and Heap Approach


📈 30.46 Punkte
🔧 Programmierung

🔧 Java logical interview question | Sum a list but ignore any duplicates codewars java solution


📈 29.55 Punkte
🔧 Programmierung

🔧 Solving A Graph Problem: Part Two


📈 27.6 Punkte
🔧 Programmierung

🔧 A Study on Java Static Analysis Tool Reports Triage Using Machine Learning Approaches


📈 27.16 Punkte
🔧 Programmierung

🕵️ Solving a VM-based CTF challenge without solving it properly - gynvael.coldwind//vx.log


📈 27.01 Punkte
🕵️ Reverse Engineering

🔧 Functional Programming in Python: A New Way to Think About Problem-Solving


📈 26.57 Punkte
🔧 Programmierung

🔧 Solving the Valid Anagram Problem in Python 🐍


📈 26.57 Punkte
🔧 Programmierung

📰 Implementing, solving and visualizing the Traveling Salesman Problem with Python


📈 26.57 Punkte
🔧 AI Nachrichten

📰 Solving The Travelling Salesman Problem Using A Genetic Algorithm


📈 25.28 Punkte
🔧 AI Nachrichten

📰 Solving The Travelling Salesman Problem Using A Genetic Algorithm


📈 25.28 Punkte
🔧 AI Nachrichten

🔧 Solving the Eight Queens Problem Using Backtracking


📈 25.28 Punkte
🔧 Programmierung

🔧 Problem Solving Using Recursion


📈 25.28 Punkte
🔧 Programmierung

📰 Solving a Tennis Refactoring Challenge in Python using SOLID


📈 24.11 Punkte
🔧 AI Nachrichten

🔧 Minimum Subset sum difference problem with Subset partitioning


📈 24.08 Punkte
🔧 Programmierung

🔧 A More Idiomatic Two-Sum Solution in JavaScript


📈 23.93 Punkte
🔧 Programmierung

🔧 LeetCode #1. Two Sum


📈 23.93 Punkte
🔧 Programmierung

🔧 Two Sum


📈 23.93 Punkte
🔧 Programmierung

🔧 1. Two Sum-Arrays & Hashing


📈 23.93 Punkte
🔧 Programmierung

🔧 167. Two Sum II - Input Array Is Sorted


📈 23.93 Punkte
🔧 Programmierung

matomo