Two Sum Problem in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include<stdio.h>

int main() {
    int n, t, a[100];
    scanf("%d%d", &n, &t);
    for(int i=0; i<n; i++) scanf("%d", &a[i]);
    for(int i=0; i<n; i++)
        for(int j=i+1; j<n; j++)
            if(a[i]+a[j]==t) printf("%d %d", i, j);
}




C++ Program

#include<iostream>
#include<unordered_map>
using namespace std;

int main() {
    int n, t, x;
    cin >> n >> t;
    unordered_map<int,int> m;
    for(int i=0; i<n; i++) {
        cin >> x;
        if(m.count(t - x)) cout << m[t - x] << " " << i;
        m[x] = i;
    }
}



JAVA Program

import java.util.*;

class TwoSum {
    public static void main(String[] a) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), t = sc.nextInt();
        Map<Integer, Integer> m = new HashMap<>();
        for(int i=0;i<n;i++) {
            int x = sc.nextInt();
            if(m.containsKey(t-x)) System.out.print(m.get(t-x)+" "+i);
            m.put(x, i);
        }
    }
}




Python Program

a = list(map(int, input().split()))
t = int(input())
d = {}
for i, x in enumerate(a):
    if t - x in d: print(d[t - x], i); break
    d[x] = i




In-Depth Learning – Two Sum Problem

Concept and Logic

You're given an array and a target sum. Find the first pair of indices whose values add up to that sum. The optimal method uses a dictionary (hash map) for O(n) lookup.

Example

Input: a = [2, 7, 11, 15], target = 9
Output: 0 1 → because 2 + 7 = 9

Real-Life Analogy

Like finding two expenses that add up to your budget limit.

Use Case

  • Shopping cart logic

  • Fraud detection

  • Banking transactions

Time Complexity

  • Brute-force: O(n²)

  • Hash map: O(n)


SEO-Friendly Paragraph for Ranking

Want to solve the Two Sum or 3Sum (Triplet Sum Zero) problems using C, C++, Java, or Python? This complete guide provides optimized and minimal code for two of the most famous array-based problems. You’ll learn how to use hashing, two-pointers, and logic to solve problems efficiently. These are must-know questions for coding interviews at top companies and help build a foundation in problem-solving and optimization techniques. Understand edge cases, improve speed, and implement solutions like a pro.