Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit bb3d1d3

Browse files
author
Ram swaroop
committed
two repeating elements : comments added
1 parent 02807a9 commit bb3d1d3

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/me/ramswaroop/arrays/TwoRepeatingElements.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,38 @@
1111
*/
1212
public class TwoRepeatingElements {
1313

14+
/**
15+
* Finds the 2 repeating elements in an array {@param a} of 1 to n elements and n+2 length. This is
16+
* similar to {@link me.ramswaroop.bits.TwoNonRepeatingElements}.
17+
* <p/>
18+
* EXPLANATION:
19+
* Let the repeating numbers be X and Y, if we xor all the elements in the array and all integers from 1 to n,
20+
* then the result is X xor Y.
21+
* The 1’s in binary representation of X xor Y is corresponding to the different bits between X and Y.
22+
* Suppose that the kth bit of X xor Y is 1, we can xor all the elements in the array and all integers
23+
* from 1 to n, whose kth bits are 1. The result will be one of X and Y.
24+
*
25+
* @param a
26+
* @return
27+
*/
1428
public static int[] getTwoRepeatingElements(int[] a) {
1529
int xor = a[0];
1630
int rightMostSetBit;
1731
int x = 0, y = 0;
18-
32+
1933
for (int i = 1; i < a.length; i++) {
2034
xor ^= a[i];
2135
}
36+
2237
for (int i = 1; i <= a.length - 2; i++) {
2338
xor ^= i;
2439
}
40+
41+
// now xor is X xor Y, therefore find any of its set bit
2542
rightMostSetBit = xor & ~(xor - 1);
2643

2744
for (int i = 0; i < a.length; i++) {
45+
// one number will have a set bit at that position and other wouldn't
2846
if ((a[i] & rightMostSetBit) == 0) {
2947
x ^= a[i];
3048
} else {
@@ -33,6 +51,7 @@ public static int[] getTwoRepeatingElements(int[] a) {
3351
}
3452

3553
for (int i = 1; i <= a.length - 2; i++) {
54+
// one number will have a set bit at that position and other wouldn't
3655
if ((i & rightMostSetBit) == 0) {
3756
x ^= i;
3857
} else {
@@ -45,5 +64,7 @@ public static int[] getTwoRepeatingElements(int[] a) {
4564

4665
public static void main(String a[]) {
4766
System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{4, 2, 4, 5, 2, 3, 1})));
67+
System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{2, 4, 5, 2, 3, 1, 6, 7, 7})));
68+
System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{1, 2, 1, 2})));
4869
}
4970
}

0 commit comments

Comments
 (0)