Find Three Consecutive Integers That Sum to a Given Number — Medium Problem & Solution

Return three consecutive integers that sum to num, in increasing order. If no such triple exists, return an empty array.

  • Difficulty: Medium
  • Topics: Math, Simulation
  • Asked at: Amazon, Adobe, Infosys
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Return three consecutive integers that sum to num, in increasing order. If no such triple exists, return an empty array.

Example 1

Input: num = 33
Output: [10,11,12]
Explanation: 10 + 11 + 12 = 33.

Example 2

Input: num = 4
Output: []
Explanation: 4 is not divisible by 3.

Example 3

Input: num = 0
Output: [-1,0,1]

Constraints

  • 0 <= num <= 1000000000

How to solve Find Three Consecutive Integers That Sum to a Given Number

Centre the triple on its middle value. Three consecutive integers around m sum to 3m, which makes divisibility by 3 both necessary and sufficient.

Approach

  1. If num % 3 != 0, return an empty array.
  2. Otherwise set m = num / 3 and return [m - 1, m, m + 1].

Why it works

(m-1) + m + (m+1) = 3m collapses the whole search to one division. Since m is determined uniquely, the triple is unique too — there is no choice to make and nothing to search.

Complexity

  • Time — O(1)
  • Space — O(1)

Pitfalls

  • Searching for the triple by iteration is unnecessary and slow at num = 10^9.
  • The middle value is num / 3, not num / 3 - 1 or the first element.
  • num = 0 is legal and yields [-1,0,1].

Reference solution

Python

from typing import List

def sumOfThree(num: int) -> List[int]:
    if num % 3 != 0:
        return []
    m = num // 3
    return [m - 1, m, m + 1]

JavaScript

var sumOfThree = function(num) {
    if (num % 3 !== 0) return [];
    var m = num / 3;
    return [m - 1, m, m + 1];
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 213 math problems · the whole catalogue