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 <= 1015In #2177 Find Three Consecutive Integers That Sum to a Given Number, the goal is to determine whether a number can be expressed as the sum of three consecutive integers. A helpful observation is that three consecutive integers can be written in the form x-1, x, and x+1. Their sum simplifies to 3x, meaning the middle number represents the average of the three values.
This mathematical insight allows us to check whether the given number can be evenly divided into such a pattern. If the number satisfies this property, the three integers can be derived directly from the middle value. Otherwise, no valid triplet exists.
Because this approach relies on a constant-time arithmetic check rather than iteration or simulation, it is extremely efficient. The optimized method runs in O(1) time with O(1) space, making it ideal for interview scenarios where recognizing patterns in mathematical expressions is key.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Mathematical Observation (using middle integer) | O(1) | O(1) |
| Brute Force / Simulation Check | O(1) | O(1) |
mrmaisonet
Use these hints if you're stuck. Try solving on your own first.
Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number?
Notice the sum of the numbers will be 3x. Can you solve for x?
Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
The sum of three consecutive integers simplifies to three times the middle integer. Therefore, the target number must be divisible by 3 for such a sequence to exist. If it is not divisible by 3, no three consecutive integers can produce that sum.
Yes, problems like this are commonly used in interviews to test mathematical reasoning and pattern recognition. Interviewers expect candidates to simplify the expression and derive an O(1) solution instead of using brute force.
The optimal approach uses a mathematical observation. Three consecutive integers can be represented as x-1, x, and x+1, whose sum equals 3x. If the given number is divisible by 3, you can compute the middle integer and derive the other two values directly.
No special data structure is required for this problem. Since the solution relies on simple arithmetic properties, only basic variables and an output array are needed.