Taro Logo

Find Three Consecutive Integers That Sum to a Given Number

#1 Most AskedMedium
0 views
Topics:
Arrays

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input integer `num` be negative, zero, or extremely large (e.g., exceeding standard 32-bit integer limits)?
  2. Since the problem states 'three consecutive integers', are we strictly limited to integers, or could the result involve floating-point numbers if `num` is not divisible by 3?
  3. If no such three consecutive integers exist that sum to `num`, should I return an empty array, `null`, or throw an exception?
  4. Is it possible for multiple sets of three consecutive integers to sum up to `num`, and if so, does it matter which set is returned?
  5. Should the returned array of three integers be strictly sorted in ascending order?

Brute Force Solution

Approach

To solve this problem using the brute force approach, you systematically test every possible group of three numbers that follow each other in order, checking whether their combined total matches your target number. Since you want three numbers where each is one greater than the previous one, you can just start trying different groups of three until you find the exact group that adds up correctly.

Here's how the algorithm would work step-by-step:

  1. Pick a starting number and look at the next two numbers that immediately follow it to form a group of three consecutive numbers.
  2. Add these three numbers together to see if their total matches the target number you are given.
  3. If the total is too small, throw that group away and try the next starting number, which is one higher than the previous one.
  4. If the total is too large, throw that group away as well.
  5. If the total matches your target number perfectly, you have found your answer and you can stop searching and present those three numbers.
  6. If you try every reasonable starting number and still have not found a matching group, conclude that it is impossible to make that sum using three consecutive numbers.

Code Implementation

def sum_of_three_consecutive(target_number):
    # We set an upper bound because any number past target must sum to more than target
    for starting_number in range(target_number):

        current_total = starting_number + (starting_number + 1) + (starting_number + 2)

        if current_total == target_number:
            # Return the sequence immediately once the exact matching sum is found
            return [starting_number, starting_number + 1, starting_number + 2]

        elif current_total > target_number:
            # Stop early since any further numbers will only exceed the target value
            break

    # Return an empty list if no three consecutive numbers can form the target sum
    return []

Big(O) Analysis

Time Complexity
O(n) – To find the three consecutive integers, the brute force approach systematically tests starting numbers sequentially, checking groups until a match is found or the search space is exhausted. The number of operations is directly driven by the magnitude of the target sum n, which bounds the search range for the starting number. In the worst-case scenario, we evaluate a linear number of starting candidates proportional to n. Thus, the total operations scale linearly with n, simplifying the runtime complexity to O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables to track the current starting number and compute sums during the sequential search. No additional data structures, temporary lists, or recursive stack frames are created regardless of the target number magnitude. Since the extra memory consumed remains constant and does not scale with the input value, the auxiliary space complexity is strictly O(1).

Optimal Solution

Approach

Instead of guessing combinations, we can use a simple mathematical shortcut based on the relationship between three numbers in a row. By dividing the target number into three equal parts, we can instantly find the middle number and the two numbers directly next to it.

Here's how the algorithm would work step-by-step:

  1. Take the target number and divide it by three to find the middle number.
  2. Check if the target number can actually be divided evenly by three. If it cannot, then it is impossible to find three consecutive numbers that add up to it, so stop here.
  3. If the division works out evenly, the resulting middle number is your center value.
  4. Subtract one from the middle number to find the first number in the sequence.
  5. Add one to the middle number to find the final number in the sequence.
  6. Combine the first number, the middle number, and the final number to get your answer.

Code Implementation

def sum_three_integers(target_number):
    # Division checks if the target can be evenly split into three consecutive integers.
    if target_number % 3 != 0:
        return []

    middle_number = target_number // 3

    first_number = middle_number - 1

    final_number = middle_number + 1

    # Combining the sequence values reconstructs the unique consecutive triplet.
    return [first_number, middle_number, final_number]

Big(O) Analysis

Time Complexity
O(1) – The input size is represented by the target number, and the cost is driven by a few basic arithmetic operations. We perform a single division and a modulo check to see if the target can be evenly divided by three. After that, we calculate the adjacent numbers using basic subtraction and addition. Because these few constant steps are executed regardless of how large the target number is, the total operations remain constant and simplify to O(1).
Space Complexity
O(1) – The algorithm allocates a fixed number of primitive variables and a constant-size result structure to hold three integers, regardless of the input value N. Because no dynamic data structures, recursive call stacks, or collections dependent on the size of N are created, the auxiliary memory usage remains entirely constant. Therefore, the space complexity simplifies to Big O of 1.

Edge Cases

Input num is not divisible by 3
How to Handle:
Return an empty array since consecutive integers summing to num cannot exist if num is not a multiple of 3.
Negative numbers for num
How to Handle:
The mathematical formula handles negative sums seamlessly by returning the correct negative consecutive sequence.
Zero as the input num
How to Handle:
Returns the valid sequence minus one, zero, and one whose sum equals zero.
Extremely large integer values near the 64-bit limit
How to Handle:
Use 64-bit integers to prevent arithmetic overflow during division and subtraction operations.
Small integer inputs like 1 or 2
How to Handle:
Division yields a non-integer or incorrect sequence, which is caught by checking if num is divisible by 3.
Cases where no valid three consecutive integers exist
How to Handle:
Return an empty array as explicitly required by the problem statement.
0/2 completed