Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Two Sum - Pair sum in sorted array
Next article icon

Two Sum - Pair sum in sorted array

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

Examples:

Input: arr[] = {2, 7, 11, 15}, target = 9
Output: 1 2
Explanation: Since the array is 1-indexed, arr[1] + arr[2] = 2 + 7 = 9

Input: {1, 3, 4, 6, 8, 11} target = 10
Output: 3 4
Explanation: Since the array is 1-indexed, arr[3] + arr[5] = 4 + 6 = 10

Approach: To solve the problem, follow the below idea:

The problem can be solved using two pointers technique. We can maintain two pointers, left = 0 and right = n - 1, and calculate their sum S = arr[left] + arr[right].

  • If S = target, then return left and right.
  • If S < target, then we need to increase sum S, so we will increment left = left + 1.
  • If S > target, then we need to decrease sum S, so we will decrement right = right - 1.

If at any point left >= right, then no pair with sum = target is found.

Step-by-step algorithm:

  • We need to initialize two pointers as left and right with position at the beginning and at the end of the array respectively.
  • Need to calculate the sum of the elements in the array at these two positions of the pointers.
  • If the sum equals to target value, return the 1-indexed positions of the two elements.
  • If the sum comes out to be less than the target, move the left pointer to the right to the increase the sum.
  • If the sum is greater than the target, move the right pointer to the left to decrease the sum.
  • Repeat the following steps till both the pointers meet.

Below is the implementation of the algorithm:

C++
#include <vector> using namespace std;  vector<int> twoSum(vector<int>& numbers, int target) {     int left = 0, right = numbers.size() - 1;      while (left < right) {         int current_sum = numbers[left] + numbers[right];         // If current sum = target, return left and right         if (current_sum == target) {             return { left + 1, right + 1 };         }         // If current sum < target, then increase the         // current sum by moving the left pointer by 1         else if (current_sum < target) {             left++;         }         else {             // If current sum > target, then decrease the             // current sum by moving the right pointer by 1             right--;         }     }      return {}; }  // Example usage #include <iostream> int main() {     vector<int> numbers = { 2, 7, 11, 15 };     int target = 9;     vector<int> result = twoSum(numbers, target);     for (int num : result) {         cout << num << " ";     }     cout << endl;     return 0; }  // This code is contributed by Shivam Gupta 
Java
import java.util.*;  public class TwoSum {     public static List<Integer> twoSum(List<Integer> numbers, int target) {         int left = 0, right = numbers.size() - 1;          while (left < right) {             int current_sum = numbers.get(left) + numbers.get(right);             // If current sum = target, return left and right             if (current_sum == target) {                 return Arrays.asList(left + 1, right + 1);             }             // If current sum < target, then increase the             // current sum by moving the left pointer by 1             else if (current_sum < target) {                 left++;             } else {                 // If current sum > target, then decrease the                 // current sum by moving the right pointer by 1                 right--;             }         }          return Collections.emptyList();     }      public static void main(String[] args) {         List<Integer> numbers = Arrays.asList(2, 7, 11, 15);         int target = 9;         List<Integer> result = twoSum(numbers, target);         for (int num : result) {             System.out.print(num + " ");         }         System.out.println();     } } // This code is contributed by Ayush Mishra 
Python
def twoSum(numbers, target):     left, right = 0, len(numbers) - 1      while left < right:         current_sum = numbers[left] + numbers[right]         # If current sum = target, return left and right         if current_sum == target:             return [left + 1, right + 1]         # If current sum < target, then increase the current sum by moving the left          # pointer by 1         elif current_sum < target:             left += 1         else:             # If current sum > target, then decrease the current sum by              # moving the right pointer by 1             right -= 1      return []   # Example usage numbers = [2, 7, 11, 15] target = 9 print(twoSum(numbers, target)) 
JavaScript
// Function to find two numbers such that they add up to a specific target function twoSum(numbers, target) {     let left = 0;     let right = numbers.length - 1;      // Continue searching while the left index is less than the right index     while (left < right) {         let currentSum = numbers[left] + numbers[right];                  // If the current sum equals the target, return the indices (1-indexed)         if (currentSum === target) {             return [left + 1, right + 1];         }         // If the current sum is less than the target, move the left index to the right         else if (currentSum < target) {             left++;         }         // If the current sum is greater than the target, move the right index to the left         else {             right--;         }     }      // Return an empty array if no two numbers sum up to the target     return []; }  const numbers = [2, 7, 11, 15]; const target = 9; const result = twoSum(numbers, target);  // Output the result result.forEach(num => {     console.log(num); }); 

Output
[1, 2] 

Time Complexity: O(n), where n is declared to be as length of array because elements of array is traced only once.
Auxiliary Space: O(1)


Next Article
Two Sum - Pair sum in sorted array

S

sameerkhan6359
Improve
Article Tags :
  • DSA
  • Arrays
  • two-pointer-algorithm
  • Apple
Practice Tags :
  • Apple
  • Arrays
  • two-pointer-algorithm

Similar Reads

    2 Sum - Count Pairs with given Sum in Sorted Array
    Given a sorted array arr[] and an integer target, the task is to find the number of pairs in the array whose sum is equal to target.Examples: Input: arr[] = [-1, 1, 5, 5, 7], target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7). Input: arr[] = [1, 1, 1, 1], target = 2Outpu
    9 min read
    Maximum Sum Path in Two Arrays
    Given two sorted arrays having some elements in common. Find the sum of the maximum sum path to reach from the beginning of any array to the end of any of the two arrays. We can switch from one array to another array only at common elements. Note: The common elements do not have to be at the same in
    14 min read
    Find the closest pair from two sorted arrays
    Given two arrays arr1[0...m-1] and arr2[0..n-1], and a number x, the task is to find the pair arr1[i] + arr2[j] such that absolute value of (arr1[i] + arr2[j] - x) is minimum. Example: Input: arr1[] = {1, 4, 5, 7}; arr2[] = {10, 20, 30, 40}; x = 32Output: 1 and 30Input: arr1[] = {1, 4, 5, 7}; arr2[]
    15+ min read
    Find k pairs with smallest sums in two arrays
    Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[] Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3Output : [1, 2], [1, 4], [1, 6]Ex
    15+ min read
    Find k pairs with smallest sums in two arrays | Set 2
    Given two arrays arr1[] and arr2[] sorted in ascending order and an integer K. The task is to find k pairs with the smallest sums such that one element of a pair belongs to arr1[] and another element belongs to arr2[]. The sizes of arrays may be different. Assume all the elements to be distinct in e
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences