Find Three Consecutive Integers That Sum to a Given Number Problem
#2177
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2177.
Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.
Example 1:
Input: num = 33
Output: [10,11,12]
Explanation: 33 can be expressed as 10 + 11 + 12 = 33.
10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].
Example 2:
Input: num = 4
Output: []
Explanation: There is no way to express 4 as the sum of 3 consecutive integers.
Constraints:
0 <= num <= 10^15
Solution
Approach: Mathematics
Write the three consecutive integers as x - 1, x and x + 1. Their sum is 3x, so num must be a multiple of 3; otherwise return an empty array. If it is, then x = num / 3 and the answer is [x - 1, x, x + 1].
Complexity: time O(1), space O(1).
class Solution:
def sumOfThree(self, num: int) -> List[int]:
x, mod = divmod(num, 3)
return [] if mod else [x - 1, x, x + 1]