Repeat & Missing Number
BRUTE FORCEunknown
java
a year ago
1.4 kB
9
Indexable
public class RepeatAndMissingNumber {
public static int[] findRepeatAndMissing(int[] arr) {
int n = arr.length;
int[] result = new int[2]; // result[0] = repeating, result[1] = missing
boolean foundRepeating = false;
boolean foundMissing = false;
// Outer loop: Iterate through numbers 1 to n (variable 'i')
for (int i = 1; i <= n; i++) {
int count = 0;
// Inner loop: Iterate through elements of the array (variable 'j')
for (int j = 0; j < arr.length; j++) {
if (arr[j] == i) {
count++;
}
}
// Determine if i is repeating or missing
if (count == 2) {
result[0] = i; // Repeating number
foundRepeating = true;
} else if (count == 0) {
result[1] = i; // Missing number
foundMissing = true;
}
// Stop if both numbers are found
if (foundRepeating && foundMissing) {
break;
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {3, 1, 2, 5, 3}; // Example: 3 is repeating, 4 is missing
int[] ans = findRepeatAndMissing(arr);
System.out.println("Repeating: " + ans[0] + ", Missing: " + ans[1]);
}
}
Editor is loading...
Leave a Comment