Define an array of integers and write a function to determine if any two elements sum to a target value of 20.
💡 Model Answer
A common way to solve the "two sum" problem is to use a hash set to keep track of the numbers we have seen so far. Iterate through the array once. For each element x, compute the complement target - x. If the complement is already in the set, we have found a pair that sums to the target and can return true (or the indices). If not, add x to the set and continue. This approach runs in O(n) time and uses O(n) additional space. In Python:
def has_pair_with_sum(arr, target):
seen = set()
for num in arr:
if target - num in seen:
return True
seen.add(num)
return FalseIf you need the indices, you can store a dictionary mapping numbers to their indices. This solution is efficient for large arrays and is a typical interview question for junior to mid-level developers.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500