Creating Target Value with Two-Sum - Problem Solution
In this coding challenge, you are required to write a function to find the indices of two numbers
in a given integer array
that add up to a specific target value
.
The function takes an integer array and a target value as inputs from the user,
and returns a list with the indices of the two numbers whose sum matches the target value.
The resulting list of indices should be sorted in ascending order
.
Using a Nested For Loop
Method 1
def solution(numbers, target):
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
return [i, j]
return []
-
The first for loop selects the first number.
-
The second for loop selects the second number.
-
If the sum of the two numbers equals the target value, the function returns a list with the two indices.
Example Usage
Input/Output Example
result = solution([2, 7, 11, 15], 9)
print(result) # Output: [0, 1]
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.