Find Three Consecutive Integers That Sum to a Given Number - Problem

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.

Note: Consecutive integers are integers that follow each other in order without gaps. For example: 1, 2, 3 or -2, -1, 0.

Input & Output

Example 1 — Basic Case
$ Input: num = 33
Output: [10,11,12]
💡 Note: Three consecutive integers 10, 11, 12 sum to 33: 10 + 11 + 12 = 33
Example 2 — Small Number
$ Input: num = 4
Output: []
💡 Note: No three consecutive integers can sum to 4. The minimum sum is 0+1+2=3, next is 1+2+3=6
Example 3 — Negative Numbers
$ Input: num = 0
Output: [-1,0,1]
💡 Note: Three consecutive integers -1, 0, 1 sum to 0: -1 + 0 + 1 = 0

Constraints

  • -1015 ≤ num ≤ 1015

Visualization

Tap to expand
Find Three Consecutive Integers That Sum to a Given Number INPUT num = 33 Find three consecutive integers: x, x+1, x+2 x x+1 x+2 x + (x+1) + (x+2) = 33 3x + 3 = 33 3x = 30 x = 10 ALGORITHM STEPS 1 Check Divisibility If num % 3 != 0 Return empty array 2 Calculate Middle mid = num / 3 mid = 33/3 = 11 3 Find Three Numbers first = mid - 1 = 10 second = mid = 11 third = mid + 1 = 12 4 Return Result Return [10, 11, 12] Verification: 10 + 11 + 12 = 33 OK - Sum matches! FINAL RESULT Three Consecutive Integers: 10 11 12 +1 +1 Output Array: [10, 11, 12] Solution Found! 33 can be expressed as sum of three consecutive integers Key Insight: Three consecutive integers (x-1, x, x+1) always sum to 3x. Therefore, num must be divisible by 3. The middle number is simply num/3, and the other two are one less and one more than the middle. Time Complexity: O(1) | Space Complexity: O(1) TutorialsPoint - Find Three Consecutive Integers That Sum to a Given Number | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen