Back to articles
Two Sum and Sorted Two Sum

Two Sum and Sorted Two Sum

via Dev.to PythonDharani

Introduction The Two Sum problem is one of the most popular questions in programming interviews. It helps in understanding arrays, hashing, and two-pointer techniques. Problem Statement Two Sum Given an array of integers and a target value, return the indices of the two numbers such that they add up to the target. Two Sum II (Sorted Array) Given a sorted array, find two numbers such that they add up to a target. Return their indices. πŸ’‘ Approach 1: Two Sum (Using Hash Map) Create a dictionary to store numbers and their indices For each element: Find complement = target - element Check if complement exists in dictionary If yes β†’ return indices Python Code (Two Sum) python def two_sum(nums, target): hashmap = {} for i, num in enumerate(nums): complement = target - num if complement in hashmap: return [hashmap[complement], i] hashmap[num] = i Approach 2: Two Sum II (Sorted Array - Two Pointer) Use two pointers: left = 0 right = n - 1 Calculate sum: If sum == target β†’ return indices If sum

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles