Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Optimized Solutions for the Two Sum Problem in C#

Tech May 8 4

Problem Overview

The task requires identifying the indices of two specific numbers within an integer array that sum up to a defined target value. It is guaranteed that each input set contains exactly one valid solution, and the same element cannot be used twice to form the sum.

Brute Force Implementation

The most straightforward method involves iterating through the collection with nested loops. The outer loop selects a reference number, while the inner loop compares it against every subsequent number to check if they satisfy the target sum.

public int[] FindIndicesBruteForce(int[] numbers, int goal)
{
    if (numbers == null || numbers.Length < 2) return Array.Empty<int>();

    for (int i = 0; i < numbers.Length; i++)
    {
        for (int j = i + 1; j < numbers.Length; j++)
        {
            if (numbers[i] + numbers[j] == goal)
            {
                return new int[] { i, j };
            }
        }
    }
    return Array.Empty<int>();
}

This approach ensures correctness with a space complexity of O(1), as no additional data structures are allocated. However, the nested iteration results in a time complexity of O(n²), which is inefficient for large datasets.

Hash Map Optimization

To achieve linear time complexity, we can utilize a dictionary (hash map) to store numbers and their indices as we traverse the array. This allows us to check if the complementary value (target minus current number) exists in constant time.

public int[] FindIndicesOptimized(int[] numbers, int goal)
{
    if (numbers == null || numbers.Length < 2) return Array.Empty<int>();

    var valueToIndexMap = new Dictionary<int, int>();

    for (int i = 0; i < numbers.Length; i++)
    {
        int current = numbers[i];
        int complement = goal - current;

        // Check if the required partner exists in the map
        if (valueToIndexMap.TryGetValue(complement, out int foundIndex))
        {
            return new int[] { foundIndex, i };
        }

        // Store the current number and index if not already present
        if (!valueToIndexMap.ContainsKey(current))
        {
            valueToIndexMap[current] = i;
        }
    }
    return Array.Empty<int>();
}

By trading space for time, this algorithm reduces the time complexity to O(n). The space complexity increases to O(n) to accommodate the storage requirements of the dictionary.

Tags: C#

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.