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

Given an integer num, your task is to find three consecutive integers that sum to exactly num. Return these three integers as a sorted array.

If it's impossible to express num as the sum of three consecutive integers, return an empty array.

What are consecutive integers? They are integers that follow each other in sequence with a difference of 1. For example: 4, 5, 6 or -2, -1, 0.

Key insight: If three consecutive integers start at x, they are: x, x+1, x+2, and their sum is 3x + 3 = 3(x+1).

Input & Output

example_1.py โ€” Basic Case
$ Input: num = 9
โ€บ Output: [2, 3, 4]
๐Ÿ’ก Note: 2 + 3 + 4 = 9, and these are three consecutive integers
example_2.py โ€” Negative Numbers
$ Input: num = 0
โ€บ Output: [-1, 0, 1]
๐Ÿ’ก Note: -1 + 0 + 1 = 0, consecutive integers can include negative numbers
example_3.py โ€” Impossible Case
$ Input: num = 1
โ€บ Output: []
๐Ÿ’ก Note: No three consecutive integers can sum to 1. The equation (1-3)/3 = -2/3 is not an integer

Constraints

  • -109 โ‰ค num โ‰ค 109
  • The three integers must be consecutive
  • Return empty array if no solution exists

Visualization

Tap to expand
Three Consecutive Integers VisualizationExample: Find three consecutive integers that sum to 9xx+1x+2+1+1Mathematical Solutionx + (x+1) + (x+2) = 9 โ†’ 3x + 3 = 9 โ†’ x = 2Answer: [2, 3, 4]
Understanding the Visualization
1
Identify the pattern
Three consecutive integers: x, x+1, x+2
2
Set up equation
Sum = x + (x+1) + (x+2) = 3x + 3
3
Solve directly
If 3x + 3 = num, then x = (num-3)/3
4
Verify solution
Check if x is an integer (divisibility test)
Key Takeaway
๐ŸŽฏ Key Insight: The sum of three consecutive integers starting at x is always 3x+3, allowing us to solve directly with algebra instead of searching
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 5
28.6K Views
Medium Frequency
~8 min Avg. Time
890 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