#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
DSA Practice Problems

Two Sum Problem

Given an array of integers and a target value, the Two Sum problem asks you to find the indices of two numbers such that they add up to the target.

Brute Force Approach

Check every pair of elements using nested loops and test if they sum to the target. This works but takes O(n²) time.

Optimal Approach — Hash Map

Traverse the array once. For each element, calculate the complement (target - element) and check if it already exists in a hash map of previously seen values. If found, return the pair of indices; otherwise, store the current element and its index.

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

print(two_sum([2, 7, 11, 15], 9))  # Output: [0, 1]

Complexity

ApproachTimeSpace
Brute ForceO(n²)O(1)
Hash MapO(n)O(n)

Variations

  • Two Sum on a sorted array — solved with the two-pointer technique in O(n) time and O(1) space.
  • Three Sum / Four Sum — extensions that build on the same hashing or two-pointer ideas.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course