You can create a Python class to find a pair of elements in an array whose sum equals a specific target number using a dictionary to keep track of the elements you've seen so far. Here's a sample implementation:
In this code, we define a TwoSumFinder
class with an __init__
method to initialize array (self.numbers
), target number(self.target
) and an empty dictionary (self.indices
). The find_indices
method iterates through the elements of numbers
list. For each element, it calculates the complement needed to reach the target sum and checks if that complement exists in the dictionary. If it does, it returns the indices of the two elements that add up to the target sum. If no such pair is found, it returns None
.
The example usage at the end demonstrates how to create an instance of the TwoSumFinder
class and use it to find the indices of the pair of elements that add up to the target sum. In this case, it would print "Output: 3, 4" as specified in your example input and output.
Additionaly, there are also some alternative functions which provides same functionality.