We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Three Consecutive Integers That Sum to a Given Number

Difficulty: Medium


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

  • The sum of three consecutive integers can be represented as x + (x + 1) + (x + 2) = 3x + 3.
  • Therefore, for a given num, it can be written as num = 3x + 3, leading to the equation x = (num / 3) - 1.
  • If num is not divisible by 3, it cannot be expressed as the sum of three consecutive integers.
  • The three consecutive integers can be found easily if the above condition is satisfied.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To solve the problem, we need to check if the given number can be expressed as the sum of three consecutive integers. We can derive the first integer of the three consecutive numbers using the formula x = (num / 3) - 1. If num is not divisible by 3, we return an empty array. Otherwise, we return the three integers starting from x.


Code Solutions

def findThreeConsecutiveIntegers(num):
    if num % 3 != 0:
        return []
    x = num // 3 - 1
    return [x, x + 1, x + 2]
← Back to All Questions