Posts Count of Pairs with k Sum in Sorted Array
Post
Cancel

Count of Pairs with k Sum in Sorted Array

Problem Description

Given a sorted array of distinct integers A and an integer B, find and return how many pair of integers ( A[i], A[j] ) such that i != j have sum equal to B.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {

    public int solve(int[] A, int B) {

        int count=0;
        int i=0;
        int j=A.length-1;

        while(i<j){

            int sum = A[i] + A[j];

            if(sum == B){ //If we got the required sum, move both the pointers since there are distinct elements.
                count++;
                i++;
                j--;
            }else{          
                if(sum<B){//If currentSum is lesser, move index i to get a larger value
                    i++;
                }else{
                    j--;
                }
            }
        }
        return count;
    }
}
This post is licensed under CC BY 4.0 by the author.