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

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.

Constraints:

  • 0 <= num <= 1015

Solution:

class Solution {
    public long[] sumOfThree(long num) {
        long base = num/3;
        long[] result = new long[3];
        long secNum;
        long thridNum;
        if(num == 0) return new long[] {-1,0,1};
        if(num == 3) return new long[] {0,1,2};
        
        for(long i=base-1;i<=num;i++){
            secNum = i+1;
            thridNum = secNum+1;
            if(i+secNum+thridNum == num) {
                result[0] = i;
                result[1] = secNum;
                result[2] = thridNum;
                return result;
            }
            else if(i+secNum+thridNum>num) break;
        }
        return new long[0];
    }
}

Approach:

Initialize a base variable with one-third of the given number. Use this as the starting point to compute the sum of three consecutive numbers: base, base + 1, and base + 2. Check whether their sum equals the given number.

  • If the sum matches the number, we have found the required sequence.
  • If the sum exceeds the number, break the loop to avoid unnecessary checks.

Also, handle base cases separately for inputs like 0 and 3, since dividing by 3 may result in 0, and they require special treatment. You can use a condition to return early for these cases.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x