How to handle duplicate target pairs

I have this code its working for most cases , kindly help in finding the bug
void solve() {
int N ; // size of array
cin >> N ;
vector arr(N);
for (int i = 0 ; i < N ; i++) {
cin >> arr[i];
}

int target = 0 ;
cin >> target ;

sort(arr.begin(), arr.end());

int left = 0 ;
int right = N - 1 ;



while (left < right) {

	int leftEle = arr[left];
	int rightEle = arr[right];

	if ( leftEle + rightEle   == target) {
		int leftCount = 0 ;
		int rightCount = 0 ;
		while (left < right and arr[left] == leftEle) {
			left++;
			leftCount++;
		}

		while (left <= right and arr[right] == rightEle) {
			right--;
			rightCount ++;
		}

		for (int i = 0 ; i < leftCount * rightCount ; i++) {
			cout << leftEle << " and " << rightEle << endl;
		}
	}
	else if (leftEle + rightEle > target) {
		right--;
	}
	else
	{
		left--;
	}
}

}

this should be left++;
and no need of

modified Code

void solve() {
    int N ; // size of array
    cin >> N ;
    vector<int>arr(N);
    for (int i = 0 ; i < N ; i++) {
        cin >> arr[i];
    }

    int target = 0 ;
    cin >> target ;

    sort(arr.begin(), arr.end());
        int left = 0 ;
    int right = N - 1 ;



    while (left < right) {

        int leftEle = arr[left];
        int rightEle = arr[right];

        if ( leftEle + rightEle   == target) {
            cout << leftEle << " and " << rightEle << endl;
            left++;
            right--;
        }
        else if (leftEle + rightEle > target) {
            right--;
        }
        else
        {
            left++;
        }
    }
}

and it is passing all testcases

i hope this help
if you have more doubts regarding this feel free to ask
if your doubt is resolved mark it as resolved from your doubt section inside your course

1 Like