Find All Pairs with Given Sum

Given an integer array arr and an integer Sum, count and return the total number of pairs in the array whose elements add up to the given Sum.

Input:

The first line contains two space-separated integers N and Sum. The second line contains N space-separated integers representing the array elements.

Output:

Print the total number of pairs present in the array that add up to the given Sum.

Example:

Input:
N = 5, Sum = 7
arr = [1, 5, 3, 4, 2]
Output:
2
Explanation:

There are two pairs that add up to 7: (3, 4) and (5, 2).

Constraints:

  • 1 <= N <= 10^5
  • -10^4 <= Sum <= 10^4
  • -10^4 <= arr[i] <= 10^4
  • Time Limit: 1 sec
Note:
Arrays can contain duplicate elements. Pairs (arr[i],arr[j]) and (arr[j],arr[i]) are considered the same.
AnswerBot
4mo

Count and return the total number of pairs in the array whose elements add up to a given sum.

  • Use a hashmap to store the frequency of each element in the array.

  • Iterate through the array and for each el...read more

Help your peers!
Select
Add answer anonymously...

Cadence Design Systems SDE-2 interview questions & answers

A SDE-2 was asked 3mo agoQ. Design a data structure that supports the following two operations: void addNum(...read more
A SDE-2 was asked 3mo agoQ. How would you sort an array based on a user-defined order?
A SDE-2 was asked 3mo agoQ. What is a copy constructor?

Popular interview questions of SDE-2

A SDE-2 was asked 2mo agoQ1. Design a data structure that supports the following two operations: void addNum(...read more
A SDE-2 was asked 2mo agoQ2. How would you sort an array based on a user-defined order?
A SDE-2 was asked 2mo agoQ3. What is a copy constructor?
Cadence Design Systems SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits