Forem

ARUL SELVI ML
ARUL SELVI ML

Posted on

Two Sum & Sorted Two Sum

Problem Statement

You are given an array of integers and a target value. Find two numbers such that they add up to the target and return their indices.


Example

Input
nums = [2, 7, 11, 15]
target = 9

Output
[0, 1]


Method 1 Using Nested Loop

```python id="a1"
def twoSum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]




This method checks all possible pairs to find the correct answer.

---

## Method 2 Using Dictionary



```python id="a2"
def twoSum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        diff = target - num
        if diff in seen:
            return [seen[diff], i]
        seen[num] = i
Enter fullscreen mode Exit fullscreen mode

This method stores values while looping and finds the pair quickly.


Problem 2 Sorted Two Sum

Problem Statement

You are given a sorted array. Find two numbers such that their sum equals the target and return their indices.


Example

Input
numbers = [1, 2, 3, 4, 6]
target = 6

Output
[1, 3]


Method Using Two Pointers

```python id="a3"
def twoSumSorted(numbers, target):
left = 0
right = len(numbers) - 1

while left < right:
    current_sum = numbers[left] + numbers[right]

    if current_sum == target:
        return [left, right]
    elif current_sum < target:
        left += 1
    else:
        right -= 1
Enter fullscreen mode Exit fullscreen mode



This method uses one pointer at the start and another at the end, adjusting them based on the sum.

---


Enter fullscreen mode Exit fullscreen mode

Top comments (0)