Lecture
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]
Previous lessonCoding Quiz - Finding Indices for a Target SumNext lessonCoding Quiz - Maximize Stock Trading Profit
Lessons in this chapter · Python Coding Quiz Practice
- 1. Coding Quiz - Palindrome Check
- 2. Checking for Palindrome Strings - Problem Solving
- 3. Coding Quiz - Find Unique Words
- 4. Finding Unique Words - Problem Solving
- 5. Coding Quiz - Caesar Cipher
- 6. Caesar Cipher - Problem Solving
- 7. Coding Quiz - Find Prime Numbers
- 8. Finding Primes - Problem Solving
- 9. Coding Quiz - Finding Indices for a Target Sum
- 10. Creating Target Value with Two-Sum - Problem Solution
- 11. Coding Quiz - Maximize Stock Trading Profit
- 12. Finding Maximum Profit - Solution Explanation
- 13. Coding Quiz - Detecting Anagrams
- 14. Anagram Checker - Problem Solution
- 15. Coding Quiz - Remove the Smallest Number
- 16. Removing the Smallest Number - Problem Solution
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help