Skip to main content

2177. Find Three Consecutive Integers That Sum to a Given Number

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.

Examples​

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 <= 10^15

Solution for 2177. Find Three Consecutive Integers That Sum to a Given Number​

  1. Function Definition:

    • Define a function sumOfThree that takes a number num as input.
    • Initialize an empty list v to store the result.
  2. Check Divisibility:

    • Check if num is divisible by 3.
    • If not, return the empty list v.
  3. Calculate Consecutive Integers:

    • If num is divisible by 3, calculate the three consecutive integers:
      • The first integer is (num / 3) - 1.
      • The second integer is num / 3.
      • The third integer is (num / 3) + 1.
    • Add these integers to the list v.
  4. Return the Result:

    • Return the list v containing the three consecutive integers if they exist, otherwise return the empty list.

Implementation​

Live Editor
  function  sumOfThree(num) {
    let v = [];
    if (num % 3 === 0) {
        v.push((num / 3) - 1);
        v.push(num / 3);
        v.push((num / 3) + 1);
    }
    return v;
}
  const input  = 33
  const output = sumOfThree(input)
  return (
    <div>
      <p>
        <b>Input: </b>
        {JSON.stringify(input)}
      </p>
      <p>
        <b>Output:</b> {output.toString()}
      </p>
    </div>
  );
}
Result
Loading...

Complexity Analysis​

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

Code in Different Languages​

Written by @hiteshgahanolia
class Solution {
sumOfThree(num) {
let v = [];
if (num % 3 === 0) {
v.push((num / 3) - 1);
v.push(num / 3);
v.push((num / 3) + 1);
}
return v;
}
}

References​