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 <= 1015This approach utilizes the property of consecutive integers. If we let the three consecutive integers be x, x+1, x+2, their sum is 3x + 3. To find these integers, we set up the equation: 3x + 3 = num. Solve this equation for x to see if it results in an integer value, as the integers are required to be consecutive.
The code solves the sum of three consecutive integers using algebra. After checking the divisibility condition, it calculates the smallest integer x and constructs the consecutive numbers.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
This approach also involves understanding the sum of consecutive integers: (x) + (x + 1) + (x + 2) = num, simplifying to 3x + 3 = num. Modify the equation slightly to 3x = num - 3. Check if num-3 is divisible by 3 and apply integer division to find x.
This C code checks if num can be divided evenly by 3 and computes the middle integer as the average of the sum.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Algebraic Approach | Time Complexity: O(1) |
| Modulo Check and Integer Division | Time Complexity: O(1) |
How To Find Three Consecutive Integers With A Given Sum • mrmaisonet • 114,058 views views
Watch 9 more video solutions →Practice Find Three Consecutive Integers That Sum to a Given Number with our built-in code editor and test cases.
Practice on FleetCode