DEV Community

Cover image for Two Sum in C# – From Brute Force to Optimal Hash Map & Beyond
Mostafa Said
Mostafa Said

Posted on

Two Sum in C# – From Brute Force to Optimal Hash Map & Beyond

🔍 Problem Description

Given an integer array nums and an integer target, return the indices of the two numbers whose sum equals target. You may assume exactly one solution exists and you can't use the same element twice.

Image description

public int[] TwoSum(int[] nums, int target)
Enter fullscreen mode Exit fullscreen mode

Examples:

nums = [2,7,11,15], target = 9  // → [0,1]
nums = [3,2,4],    target = 6   // → [1,2]
nums = [3,3],      target = 6   // → [0,1]

#### 🔁 1. Brute‑Force (Nested Loops)

Enter fullscreen mode Exit fullscreen mode
public int[] TwoSumBrute(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 Array.Empty<int>();
}
Enter fullscreen mode Exit fullscreen mode
  • 🕒 Time: O(n²) – checks every possible pair
  • 💾 Space: O(1) – constant space usage
  • ✅ Best for tiny arrays or as a conceptual starting point

🗂️ 2. Two‑Pass Hash Map

public int[] TwoSumTwoPass(int[] nums, int target) {
    var map = new Dictionary<int, int>(nums.Length);
    for (int i = 0; i < nums.Length; i++)
        map[nums[i]] = i;

    for (int i = 0; i < nums.Length; i++) {
        int comp = target - nums[i];
        if (map.TryGetValue(comp, out int j) && j != i)
            return new int[]{ i, j };
    }
    return Array.Empty<int>();
}
Enter fullscreen mode Exit fullscreen mode
  • 🕒 Time: O(n) – two passes
  • 💾 Space: O(n) – storing elements in map

🔥 3. One‑Pass Hash Map (Optimal)

public int[] TwoSumOnePass(int[] nums, int target) {
    var map = new Dictionary<int, int>(nums.Length);
    for (int i = 0; i < nums.Length; i++) {
        int comp = target - nums[i];
        if (map.TryGetValue(comp, out int j))
            return new int[]{ j, i };
        map[nums[i]] = i;
    }
    return Array.Empty<int>();
}

Enter fullscreen mode Exit fullscreen mode
  • 🕒 Time: O(n) – single traversal
  • 💾 Space: O(n) – map tracks seen values

🧪 4. Benchmark Insights

  • “The brute force solution outperforms the Dictionary solution … for small or skewed inputs”
  • “Arrays will be faster no matter the size. … dense buffers pretty often perform best”
  • Reddit benchmarking shows brute force beating hash-map for small inputs, but hash-map scales much better on larger, randomized datasets
  • stackoverflow.com

📊 Quick Comparison Table

Method Time Space Ideal Use Case
Brute Force O(n²) O(1) Tiny arrays, simple logic
Two‑Pass Hash Map O(n) O(n) Good clarity, two-stage logic
One‑Pass Hash Map O(n) O(n) Interview-friendly, single-scan optimal

🚀 5. Visual Explanation

 link Youtube
Enter fullscreen mode Exit fullscreen mode




🧠 6. Challenges & Extensions

  • ✅ Return all unique pairs — avoid duplicates using sets
  • 🎯 Adapt to streaming input — handle data in chunks
  • 📉 Space-optimized variant: sort + two-pointer, then map back indices
  • ⚡ Benchmark with BenchmarkDotNet — validate real-world performance

✅ Conclusion

  • 🟢 Brute Force: easiest but becomes impractical as n grows
  • 🟢 One-Pass Hash Map: balanced, efficient, ideal for interviews
  • 🎯 Always consider data size, distribution, and cache behavior when choosing your approach

📝 Call to Action

  1. Implement all three methods in C# code.
  2. Benchmark them using BenchmarkDotNet across diverse datasets.
  3. Share surprising results—especially browser-based micro-benchmark behaviors 👇
  4. Need help setting up benchmarks, visual diagrams, or tackling streaming data? Just ask!

🔗 References

  1. Reddit: brute-force vs dictionary benchmark insights medium.com
  2. DesignGurus: step-by-step from brute force to optimized solution junian.net
  3. Junian Network – hash map solution in C# meheedihasaan.medium.com

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.