2177. Find Three Consecutive Integers That Sum to a Given Number LeetCode Solution
In this guide, you will get 2177. Find Three Consecutive Integers That Sum to a Given Number LeetCode Solution with the best time and space complexity. The solution to Find Three Consecutive Integers That Sum to a Given Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Find Three Consecutive Integers That Sum to a Given Number solution in C++
- Find Three Consecutive Integers That Sum to a Given Number solution in Java
- Find Three Consecutive Integers That Sum to a Given Number solution in Python
- Additional Resources
Problem Statement of Find Three Consecutive Integers That Sum to a Given Number
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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2177. Find Three Consecutive Integers That Sum to a Given Number LeetCode Solution in C++
class Solution {
public:
vector<long long> sumOfThree(long long num) {
if (num % 3)
return {};
const long x = num / 3;
return {x - 1, x, x + 1};
}
};
/* code provided by PROGIEZ */
2177. Find Three Consecutive Integers That Sum to a Given Number LeetCode Solution in Java
class Solution {
public long[] sumOfThree(long num) {
if (num % 3 != 0)
return new long[] {};
final long x = num / 3;
return new long[] {x - 1, x, x + 1};
}
}
// code provided by PROGIEZ
2177. Find Three Consecutive Integers That Sum to a Given Number LeetCode Solution in Python
class Solution:
def sumOfThree(self, num: int) -> list[int]:
if num % 3:
return []
x = num // 3
return [x - 1, x, x + 1]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.