Skip to content

2177. Find Three Consecutive Integers That Sum to a Given Number

Description

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

Solutions

Solution 1: Mathematics

Assume the three consecutive integers are \(x-1\), \(x\), and \(x+1\). Their sum is \(3x\), so \(\textit{num}\) must be a multiple of \(3\). If \(\textit{num}\) is not a multiple of \(3\), it cannot be represented as the sum of three consecutive integers, and we return an empty array. Otherwise, let \(x = \frac{\textit{num}}{3}\), then \(x-1\), \(x\), and \(x+1\) are the three consecutive integers whose sum is \(\textit{num}\).

The time complexity is \(O(1)\), and the space complexity is \(O(1)\).

1
2
3
4
class Solution:
    def sumOfThree(self, num: int) -> List[int]:
        x, mod = divmod(num, 3)
        return [] if mod else [x - 1, x, x + 1]
1
2
3
4
5
6
7
8
9
class Solution {
    public long[] sumOfThree(long num) {
        if (num % 3 != 0) {
            return new long[] {};
        }
        long x = num / 3;
        return new long[] {x - 1, x, x + 1};
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    vector<long long> sumOfThree(long long num) {
        if (num % 3) {
            return {};
        }
        long long x = num / 3;
        return {x - 1, x, x + 1};
    }
};
1
2
3
4
5
6
7
func sumOfThree(num int64) []int64 {
    if num%3 != 0 {
        return []int64{}
    }
    x := num / 3
    return []int64{x - 1, x, x + 1}
}
1
2
3
4
5
6
7
function sumOfThree(num: number): number[] {
    if (num % 3) {
        return [];
    }
    const x = Math.floor(num / 3);
    return [x - 1, x, x + 1];
}
1
2
3
4
5
6
7
8
9
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]
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * @param {number} num
 * @return {number[]}
 */
var sumOfThree = function (num) {
    if (num % 3) {
        return [];
    }
    const x = Math.floor(num / 3);
    return [x - 1, x, x + 1];
};

Comments

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy