LeetCode 2177: Find Three Consecutive Integers That Sum to a Given Number Solution
Master LeetCode problem 2177 (Find Three Consecutive Integers That Sum to a Given Number), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2177. Find Three Consecutive Integers That Sum to a Given Number
Problem Explanation
Explanation:
To solve this problem, we can iterate through a range of numbers and check if the sum of three consecutive integers equals the given number num. We can start from 1 and keep a window of size 3 to calculate the sum of consecutive integers. If the sum matches num, we return the three consecutive integers. We continue this process until we reach the end of the range. If no such triplet is found, we return an empty array.
- Time complexity: O(n), where n is the value of
num. - Space complexity: O(1).
:
Solution Code
class Solution {
public int[] findConsecutiveNumbers(int num) {
for (int i = 1; i <= num / 3; i++) {
int sum = i + (i + 1) + (i + 2);
if (sum == num) {
return new int[]{i, i + 1, i + 2};
}
}
return new int[]{};
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2177 (Find Three Consecutive Integers That Sum to a Given Number)?
This page provides optimized solutions for LeetCode problem 2177 (Find Three Consecutive Integers That Sum to a Given Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2177 (Find Three Consecutive Integers That Sum to a Given Number)?
The time complexity for LeetCode 2177 (Find Three Consecutive Integers That Sum to a Given Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2177 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2177 in Java, C++, or Python.