|
| 1 | +package me.ramswaroop.arrays; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by IntelliJ IDEA. |
| 7 | + * |
| 8 | + * @author: ramswaroop |
| 9 | + * @date: 9/7/15 |
| 10 | + * @time: 10:54 AM |
| 11 | + */ |
| 12 | +public class MissingAndRepeatingElements { |
| 13 | + |
| 14 | + /** |
| 15 | + * Finds two numbers in an unsorted array of size n with elements in range from |
| 16 | + * 1 to n where one number from set {1, 2, …n} is missing and one number occurs |
| 17 | + * twice in array. |
| 18 | + * |
| 19 | + * @param a |
| 20 | + * @return an array where 1st element is the repeating element and 2nd is the missing one |
| 21 | + */ |
| 22 | + public static int[] findMissingAndRepeatingElements(int[] a) { |
| 23 | + int[] result = new int[2]; |
| 24 | + for (int i = 0; i < a.length; i++) { |
| 25 | + // we use indices to mark already encountered numbers |
| 26 | + if (a[Math.abs(a[i]) - 1] < 0) { |
| 27 | + result[0] = Math.abs(a[i]); // repeating element |
| 28 | + } else { |
| 29 | + a[Math.abs(a[i]) - 1] = -a[Math.abs(a[i]) - 1]; |
| 30 | + } |
| 31 | + } |
| 32 | + // no. is +ve means its index wasn't encountered |
| 33 | + for (int i = 0; i < a.length; i++) { |
| 34 | + if (a[i] > 0) { |
| 35 | + result[1] = i + 1; // missing element |
| 36 | + } |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | + |
| 41 | + public static void main(String a[]) { |
| 42 | + System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{3, 1, 3}))); |
| 43 | + System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 3, 6, 2, 1, 1}))); |
| 44 | + System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 4, 6, 2, 5, 1}))); |
| 45 | + } |
| 46 | +} |
0 commit comments