Problem

Given an integer num, return _three consecutive integers (as a sorted array)__thatsum to _num. If num cannot be expressed as the sum of three consecutive integers, return anempty array.

Examples

Example 1

1
2
3
4
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

1
2
3
Input: num = 4
Output: []
Explanation: There is no way to express 4 as the sum of 3 consecutive integers.

Constraints

  • 0 <= num <= 1015

Solution

Method 1 – Math (Direct Formula)

Intuition

Let the three consecutive integers be x, x+1, x+2. Their sum is 3x+3. So, num = 3x+3 ⇒ x = (num-3)//3. If num is not divisible by 3, there is no solution.

Approach

  1. Check if num % 3 == 0.
  2. If not, return an empty array.
  3. Otherwise, compute x = num // 3 - 1.
  4. Return [x, x+1, x+2].

Code

1
2
3
4
5
6
7
8
class Solution {
public:
    vector<long long> sumOfThree(long long num) {
        if (num % 3 != 0) return {};
        long long x = num / 3 - 1;
        return {x, x + 1, x + 2};
    }
};
1
2
3
4
5
6
7
func sumOfThree(num int64) []int64 {
    if num%3 != 0 {
        return []int64{}
    }
    x := num/3 - 1
    return []int64{x, x + 1, x + 2}
}
1
2
3
4
5
6
7
class Solution {
    public long[] sumOfThree(long num) {
        if (num % 3 != 0) return new long[0];
        long x = num / 3 - 1;
        return new long[]{x, x + 1, x + 2};
    }
}
1
2
3
4
5
6
7
class Solution {
    fun sumOfThree(num: Long): LongArray {
        if (num % 3L != 0L) return longArrayOf()
        val x = num / 3 - 1
        return longArrayOf(x, x + 1, x + 2)
    }
}
1
2
3
4
5
6
class Solution:
    def sumOfThree(self, num: int) -> list[int]:
        if num % 3 != 0:
            return []
        x = num // 3 - 1
        return [x, x + 1, x + 2]
1
2
3
4
5
6
7
impl Solution {
    pub fn sum_of_three(num: i64) -> Vec<i64> {
        if num % 3 != 0 { return vec![]; }
        let x = num / 3 - 1;
        vec![x, x + 1, x + 2]
    }
}
1
2
3
4
5
6
7
class Solution {
    sumOfThree(num: number): number[] {
        if (num % 3 !== 0) return [];
        const x = Math.floor(num / 3) - 1;
        return [x, x + 1, x + 2];
    }
}

Complexity

  • ⏰ Time complexity: O(1) — Only a few arithmetic operations.
  • 🧺 Space complexity: O(1) — No extra space used.