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.
Key Insights
- Represent three consecutive integers as x, x+1, and x+2.
- Their sum is calculated as 3x + 3.
- The equation 3x + 3 = num can be rearranged to x = (num / 3) - 1.
- The value of num must be divisible by 3 for a valid solution to exist.
- If num % 3 is not 0, no such consecutive sequence exists.
Space and Time Complexity
Time Complexity: O(1) - Only constant arithmetic operations are involved. Space Complexity: O(1) - No additional space is used beyond a few variables.
Solution
The solution utilizes arithmetic properties of consecutive integers. We express the three numbers as x, x+1, x+2 and set their sum equal to num. By solving the arithmetic equation 3x + 3 = num, we deduce that x = (num / 3) - 1. Crucially, num must be divisible by 3 for x to be an integer; otherwise, the function returns an empty array. This approach directly computes the answer using simple conditional checks and mathematical equations.