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 <= 1015
The problem asks to find three consecutive integers that sum up to a given number num
. The core idea is to leverage mathematical properties to efficiently solve this.
Mathematical Approach:
Let's represent the three consecutive integers as x - 1
, x
, and x + 1
. Their sum is:
(x - 1) + x + (x + 1) = 3x
This means that the given number num
must be divisible by 3. If num
is not divisible by 3, there's no solution, and we return an empty array.
If num
is divisible by 3, then x = num / 3
. The three consecutive integers are simply x - 1
, x
, and x + 1
.
Time and Space Complexity:
Time Complexity: O(1) - The solution involves a single division and a few arithmetic operations, all of which take constant time. The time complexity is independent of the input size.
Space Complexity: O(1) - The solution uses a constant amount of extra space to store the result (the array of three integers). The space used doesn't grow with the input.
The code implementations below directly reflect the mathematical solution. They first check for divisibility by 3. If divisible, they calculate x
and return the three consecutive integers; otherwise, they return an empty array.
Python:
class Solution:
def sumOfThree(self, num: int) -> List[int]:
if num % 3 != 0:
return []
x = num // 3
return [x - 1, x, x + 1]
Java:
class Solution {
public long[] sumOfThree(long num) {
if (num % 3 != 0) {
return new long[0]; // Return an empty array
}
long x = num / 3;
return new long[] {x - 1, x, x + 1};
}
}
C++:
class Solution {
public:
vector<long long> sumOfThree(long long num) {
if (num % 3 != 0) {
return {}; // Return an empty vector
}
long long x = num / 3;
return {x - 1, x, x + 1};
}
};
Go:
func sumOfThree(num int64) []int64 {
if num%3 != 0 {
return []int64{}
}
x := num / 3
return []int64{x - 1, x, x + 1}
}
TypeScript:
function sumOfThree(num: number): number[] {
if (num % 3 !== 0) {
return [];
}
const x = Math.floor(num / 3);
return [x - 1, x, x + 1];
}
Rust:
impl Solution {
pub fn sum_of_three(num: i64) -> Vec<i64> {
if num % 3 != 0 {
return Vec::new();
}
let x = num / 3;
vec![x - 1, x, x + 1]
}
}
JavaScript:
var sumOfThree = function(num) {
if (num % 3 !== 0) {
return [];
}
let x = Math.floor(num / 3);
return [x - 1, x, x + 1];
};
All these code snippets follow the same logic: check divisibility by 3, calculate x
, and return the result or an empty array accordingly. They all achieve O(1) time and space complexity.