#How to fix this algo

5 messages · Page 1 of 1 (latest)

viral hazel
#
public String missingNumber(int[] array) {
        for (int i = 0; i < array.length - 1; i ++) { //will stop at 2nd last element
            
            for (int j = i + 1; j < array.length; j++) { //will stop at last element 
                System.out.println(array[i] + 1);
                System.out.println(array[j]);
                if (array[i] + 1 != array[j]) { //since all nums in order will be -1 of next element
                    return  "Missing number is " + (array[i] + 1);
                }
            }
        }
        
        return "There were no missing numbers";
    }```
clear dirgeBOT
#

This post has been reserved for your question.

Hey @viral hazel! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

limber sentinel
# viral hazel ```java public String missingNumber(int[] array) { for (int i = 0; i < a...

That second for loop results in the unexpected behaviour. You are only meant to check if the next number follows the sequence not all consecutive numbers. If there is any missing number in your data set, regardless of position, the value of the first element + 1 will be printed. As how to fix this: Remove the inner for loop but keep your logic then it should work.

still garnet