Similar Problems
Similar Problems not available
Find Three Consecutive Integers That Sum To A Given Number - Leetcode Solution
Companies:
LeetCode: Find Three Consecutive Integers That Sum To A Given Number Leetcode Solution
Difficulty: Medium
Topics: math simulation
Problem Statement: Given an integer n, find three consecutive integers that sum up to n. Return the three integers as a list. If no such integers exist, return an empty list.
Example: Input: n = 9 Output: [2, 3, 4] Explanation: 2 + 3 + 4 = 9
Input: n = 15 Output: [4, 5, 6] Explanation: 4 + 5 + 6 = 15
Algorithm:
- Initialize an empty list.
- Loop through the range of integers from 1 to n-2 (because we need 3 consecutive integers).
- For each integer i, find the sum of i, i+1 and i+2.
- If the sum is equal to n, append i, i+1 and i+2 to the list and return it.
- If the loop completes and no such integers are found, return an empty list.
Solution:
def find_consecutive_integers(n): result = [] for i in range(1, n-1): temp_sum = i + (i+1) + (i+2) if temp_sum == n: result.append(i) result.append(i+1) result.append(i+2) return result return result
#example print(find_consecutive_integers(9)) # [2, 3, 4] print(find_consecutive_integers(15)) # [4, 5, 6] print(find_consecutive_integers(5)) # [] print(find_consecutive_integers(20)) # [6, 7, 8]
Find Three Consecutive Integers That Sum To A Given Number Solution Code
1