2177. Find Three Consecutive Integers That Sum to a Given Number
Problem Description
You are given an integer num
. Your task is to find three consecutive integers that add up to num
.
The three integers must be consecutive, meaning they follow one after another with no gaps (like 5, 6, 7 or -2, -1, 0).
Return these three consecutive integers as a sorted array. If it's impossible to express num
as the sum of three consecutive integers, return an empty array.
For example:
- If
num = 33
, you can return[10, 11, 12]
because 10 + 11 + 12 = 33 - If
num = 4
, you would return an empty array[]
because 4 cannot be expressed as the sum of three consecutive integers
The solution uses a mathematical approach: if three consecutive integers are x-1
, x
, and x+1
, their sum equals (x-1) + x + (x+1) = 3x
. This means num
must be divisible by 3 for a valid solution to exist. If num
is divisible by 3, then x = num/3
, and the three consecutive integers are [x-1, x, x+1]
.
Intuition
When looking for three consecutive integers, let's think about their structure. If we have three consecutive numbers, we can represent them as some middle number and its neighbors. For instance, if the middle number is x
, then the three consecutive integers would be x-1
, x
, and x+1
.
Now, what happens when we add these three numbers together?
- Sum =
(x-1) + x + (x+1)
- Sum =
x - 1 + x + x + 1
- Sum =
3x
This reveals a key insight: the sum of any three consecutive integers is always exactly 3 times the middle number!
This means two important things:
- The given
num
must be divisible by 3 for a solution to exist (sincenum = 3x
meansx = num/3
must be a whole number) - If
num
is divisible by 3, we can immediately find the middle number by dividingnum
by 3
Once we have the middle number x
, constructing the answer is straightforward - just return [x-1, x, x+1]
. If num
is not divisible by 3, no three consecutive integers can sum to it, so we return an empty array.
This mathematical relationship transforms what could be a search problem into a simple arithmetic check and calculation.
Learn more about Math patterns.
Solution Approach
The implementation follows directly from our mathematical insight that three consecutive integers x-1
, x
, and x+1
sum to 3x
.
Here's how the solution works step by step:
-
Check divisibility by 3: We use Python's
divmod()
function to simultaneously get both the quotient and remainder when dividingnum
by 3:x, mod = divmod(num, 3)
x
stores the quotient (num // 3
), which would be our middle number if validmod
stores the remainder (num % 3
)
-
Determine if a solution exists: We check if
mod
is 0:- If
mod != 0
, thennum
is not divisible by 3, meaning no three consecutive integers can sum to it. We return an empty list[]
- If
mod == 0
, thennum
is divisible by 3, and we can construct our answer
- If
-
Construct the result: When a valid solution exists (i.e.,
mod == 0
), we return the three consecutive integers:[x - 1, x, x + 1]
where
x
is the middle number we calculated asnum // 3
The entire solution is elegantly expressed in a single line using a conditional expression:
return [] if mod else [x - 1, x, x + 1]
This returns an empty list if mod
is non-zero (truthy), otherwise returns the three consecutive integers centered around x
.
The time complexity is O(1)
since we only perform constant-time arithmetic operations, and the space complexity is O(1)
as we only use a fixed amount of extra space.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with num = 33
:
-
Apply the mathematical formula: We know that three consecutive integers
(x-1)
,x
, and(x+1)
sum to3x
. So ifnum = 33
, we need to check if 33 can be expressed as3x
. -
Check divisibility and find the middle number:
x, mod = divmod(33, 3) # x = 11 (quotient) # mod = 0 (remainder)
Since 33 ÷ 3 = 11 with remainder 0, we know:
- A solution exists (remainder is 0)
- The middle number is 11
-
Construct the three consecutive integers:
- First number:
x - 1 = 11 - 1 = 10
- Middle number:
x = 11
- Third number:
x + 1 = 11 + 1 = 12
- First number:
-
Verify: 10 + 11 + 12 = 33 ✓
-
Return result:
[10, 11, 12]
Now let's see a case where no solution exists with num = 4
:
-
Check divisibility:
x, mod = divmod(4, 3) # x = 1 (quotient) # mod = 1 (remainder)
-
Determine if solution exists: Since
mod = 1
(not 0), we know that 4 cannot be evenly divided by 3. This means 4 cannot be expressed as the sum of three consecutive integers. -
Return result:
[]
(empty array)
The key insight is that any sum of three consecutive integers must be divisible by 3, making this check both necessary and sufficient for determining whether a solution exists.
Solution Implementation
1class Solution:
2 def sumOfThree(self, num: int) -> List[int]:
3 """
4 Find three consecutive integers that sum to num.
5
6 For three consecutive integers (x-1, x, x+1), their sum equals 3x.
7 Therefore, num must be divisible by 3 for a valid solution to exist.
8
9 Args:
10 num: The target sum to achieve with three consecutive integers
11
12 Returns:
13 A list of three consecutive integers if they exist, otherwise empty list
14 """
15 # Divide num by 3 to find the middle number and check divisibility
16 middle_number, remainder = divmod(num, 3)
17
18 # If num is not divisible by 3, no three consecutive integers can sum to it
19 if remainder != 0:
20 return []
21
22 # Return the three consecutive integers: middle-1, middle, middle+1
23 return [middle_number - 1, middle_number, middle_number + 1]
24
1class Solution {
2 /**
3 * Finds three consecutive integers that sum to the given number.
4 *
5 * The three consecutive integers can be represented as: (x-1), x, (x+1)
6 * Their sum equals: (x-1) + x + (x+1) = 3x
7 * Therefore: 3x = num, which means x = num/3
8 *
9 * For three consecutive integers to exist, num must be divisible by 3.
10 *
11 * @param num the target sum to decompose into three consecutive integers
12 * @return an array of three consecutive integers if possible, empty array otherwise
13 */
14 public long[] sumOfThree(long num) {
15 // Check if num is divisible by 3
16 // If not, it's impossible to represent as sum of three consecutive integers
17 if (num % 3 != 0) {
18 return new long[] {};
19 }
20
21 // Calculate the middle number of the three consecutive integers
22 long middleNumber = num / 3;
23
24 // Return the three consecutive integers: middle-1, middle, middle+1
25 return new long[] {middleNumber - 1, middleNumber, middleNumber + 1};
26 }
27}
28
1class Solution {
2public:
3 // Returns three consecutive integers that sum to num, or empty vector if impossible
4 vector<long long> sumOfThree(long long num) {
5 // Three consecutive integers: (x-1) + x + (x+1) = 3x
6 // So num must be divisible by 3 for a valid solution to exist
7 if (num % 3 != 0) {
8 return {}; // Return empty vector if num is not divisible by 3
9 }
10
11 // Calculate the middle number of the three consecutive integers
12 long long middleNumber = num / 3;
13
14 // Return the three consecutive integers: [middle-1, middle, middle+1]
15 return {middleNumber - 1, middleNumber, middleNumber + 1};
16 }
17};
18
1/**
2 * Finds three consecutive integers that sum to the given number.
3 * @param num - The target sum to achieve with three consecutive integers
4 * @returns An array of three consecutive integers if possible, empty array otherwise
5 */
6function sumOfThree(num: number): number[] {
7 // Check if num is divisible by 3
8 // If not, it's impossible to find three consecutive integers that sum to num
9 if (num % 3 !== 0) {
10 return [];
11 }
12
13 // Calculate the middle number of the three consecutive integers
14 // When three consecutive integers (x-1, x, x+1) sum to num:
15 // (x-1) + x + (x+1) = 3x = num, therefore x = num/3
16 const middleNumber: number = Math.floor(num / 3);
17
18 // Return the three consecutive integers: [middle-1, middle, middle+1]
19 return [middleNumber - 1, middleNumber, middleNumber + 1];
20}
21
Time and Space Complexity
The time complexity is O(1)
because the algorithm performs a fixed number of operations regardless of the input size. The divmod()
function computes both the quotient and remainder in constant time, and creating a list with three elements (or an empty list) also takes constant time.
The space complexity is O(1)
because the algorithm uses a constant amount of extra space. It only creates two variables (x
and mod
) and returns either an empty list or a list with exactly three elements, both of which require constant space that doesn't scale with the input.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Integer Overflow in Other Languages
While Python handles arbitrarily large integers gracefully, implementing this solution in languages like Java or C++ could lead to integer overflow issues when calculating x - 1
or x + 1
for extremely large values of num
.
Example scenario: If num
is close to Integer.MAX_VALUE
in Java, calculating x + 1
might overflow.
Solution:
- In languages with fixed integer sizes, check for potential overflow before performing arithmetic operations
- Use long/int64 data types when dealing with large inputs
- Add boundary checks: verify that
x - 1
andx + 1
are within valid integer ranges
2. Misunderstanding the Problem Requirements
A common mistake is trying to find ANY three numbers that sum to num
, rather than three CONSECUTIVE integers. Some might incorrectly attempt solutions like finding three equal numbers (num/3, num/3, num/3
) or arbitrary combinations.
Solution:
- Always remember the consecutive constraint: the numbers must be
n, n+1, n+2
for some integern
- The mathematical relationship
3x = num
only works because we're looking for consecutive integers
3. Incorrect Handling of Negative Numbers
Developers might assume the solution only works for positive numbers, but the algorithm correctly handles negative values as well. For example, num = -6
yields [-3, -2, -1]
.
Solution:
- The algorithm naturally handles negative numbers through integer division
- No special cases needed for negative inputs - the math works universally
4. Forgetting to Return Sorted Order
While the current solution naturally returns integers in ascending order [x-1, x, x+1]
, modifying the approach might accidentally return unsorted results.
Solution:
- Always construct the result as
[x-1, x, x+1]
to maintain sorted order - If using a different approach, explicitly sort the result before returning
How does quick sort divide the problem into subproblems?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!