#2177

Find Three Consecutive Integers That Sum to a Given Number

Medium
MathSimulationMathematical propertiesArray manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal approach recognizes that if three consecutive integers can sum to a number, they can be represented as x-1, x, and x+1. This leads us to derive a formula for x directly from num.

⚙️

Algorithm

4 steps
  1. 1Step 1: Check if num is divisible by 3.
  2. 2Step 2: If not divisible, return an empty array since three consecutive integers cannot sum to num.
  3. 3Step 3: Calculate x as num / 3.
  4. 4Step 4: Return the array [x-1, x, x+1].
solution.py7 lines
1# Full working Python code
2
3def find_consecutive_integers(num):
4    if num % 3 != 0:
5        return []
6    x = num // 3
7    return [x - 1, x, x + 1]

Complexity note: The time complexity is O(1) because we are performing a constant number of operations regardless of the input size.

  • 1Three consecutive integers can be expressed in terms of their average.
  • 2If the sum is not divisible by 3, it's impossible to find three consecutive integers that sum to it.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.