2177. Find Three Consecutive Integers That Sum to a Given Number
Problem 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.
Examples​
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 <= 10^15
Solution for 2177. Find Three Consecutive Integers That Sum to a Given Number​
-
Function Definition:
- Define a function
sumOfThree
that takes a numbernum
as input. - Initialize an empty list
v
to store the result.
- Define a function
-
Check Divisibility:
- Check if
num
is divisible by 3. - If not, return the empty list
v
.
- Check if
-
Calculate Consecutive Integers:
- If
num
is divisible by 3, calculate the three consecutive integers:- The first integer is
(num / 3) - 1
. - The second integer is
num / 3
. - The third integer is
(num / 3) + 1
.
- The first integer is
- Add these integers to the list
v
.
- If
-
Return the Result:
- Return the list
v
containing the three consecutive integers if they exist, otherwise return the empty list.
- Return the list
- Solution
Implementation​
Live Editor
function sumOfThree(num) { let v = []; if (num % 3 === 0) { v.push((num / 3) - 1); v.push(num / 3); v.push((num / 3) + 1); } return v; } const input = 33 const output = sumOfThree(input) return ( <div> <p> <b>Input: </b> {JSON.stringify(input)} </p> <p> <b>Output:</b> {output.toString()} </p> </div> ); }
Result
Loading...
Complexity Analysis​
- Time Complexity:
- Space Complexity:
Code in Different Languages​
- JavaScript
- TypeScript
- Python
- Java
- C++
class Solution {
sumOfThree(num) {
let v = [];
if (num % 3 === 0) {
v.push((num / 3) - 1);
v.push(num / 3);
v.push((num / 3) + 1);
}
return v;
}
}
class Solution {
sumOfThree(num: number): number[] {
let v: number[] = [];
if (num % 3 === 0) {
v.push((num / 3) - 1);
v.push(num / 3);
v.push((num / 3) + 1);
}
return v;
}
}
class Solution:
def sumOfThree(self, num: int):
v = []
if num % 3 == 0:
v.append((num // 3) - 1)
v.append(num // 3)
v.append((num // 3) + 1)
return v
import java.util.*;
class Solution {
public List<Long> sumOfThree(long num) {
List<Long> v = new ArrayList<>();
if (num % 3 == 0) {
v.add((num / 3) - 1);
v.add(num / 3);
v.add((num / 3) + 1);
}
return v;
}
}
class Solution {
public:
vector<long long> sumOfThree(long long num) {
vector<long long>v;
if(num%3==0)
{
v.push_back((num/3)-1);
v.push_back((num/3));
v.push_back((num/3)+1);
}
else
{
return v;
}
return v;
}
};
References​
-
LeetCode Problem: 2177. Find Three Consecutive Integers That Sum to a Given Number
-
Solution Link: LeetCode Solution