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

Number: 2278

Difficulty: Medium

Paid? No

Companies: FPT


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.


Code Solutions

# Python solution to find three consecutive integers that sum to num

def sum_of_three(num: int) -> list:
    # Check if num is divisible by 3
    if num % 3 != 0:
        return []  # Return empty list if no valid triple exists
    
    # Calculate the first integer in the sequence
    first_int = (num // 3) - 1
    # Return the three consecutive integers as a list
    return [first_int, first_int + 1, first_int + 2]

# Test cases
print(sum_of_three(33))  # Expected output: [10, 11, 12]
print(sum_of_three(4))   # Expected output: []
← Back to All Questions