|
| 1 | +package interview.amazon; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import junit.framework.TestCase; |
| 6 | + |
| 7 | +/** |
| 8 | + * Given an array of coins of same weight, find the single heavier coin. |
| 9 | + * |
| 10 | + * @author shivam.maharshi |
| 11 | + */ |
| 12 | +public class FindHeavyCoin extends TestCase { |
| 13 | + |
| 14 | + @Test |
| 15 | + public static void test() { |
| 16 | + assertEquals(1, find(new int[] { 5, 8 })); |
| 17 | + assertEquals(0, find(new int[] { 8, 5 })); |
| 18 | + assertEquals(0, find(new int[] { 8, 5, 5 })); |
| 19 | + assertEquals(1, find(new int[] { 5, 8, 5 })); |
| 20 | + assertEquals(2, find(new int[] { 5, 5, 8 })); |
| 21 | + assertEquals(3, find(new int[] { 5, 5, 5, 8 })); |
| 22 | + assertEquals(2, find(new int[] { 5, 5, 8, 5 })); |
| 23 | + assertEquals(1, find(new int[] { 5, 8, 5, 5 })); |
| 24 | + assertEquals(0, find(new int[] { 8, 5, 5, 5 })); |
| 25 | + assertEquals(2, find(new int[] { 5, 5, 8, 5, 5, 5, 5, 5, 5, 5, 5 })); |
| 26 | + assertEquals(0, find(new int[] { 8, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); |
| 27 | + assertEquals(10, find(new int[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8 })); |
| 28 | + assertEquals(2, find(new int[] { 5, 5, 8, 5, 5, 5, 5, 5, 5, 5 })); |
| 29 | + assertEquals(0, find(new int[] { 8, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); |
| 30 | + assertEquals(9, find(new int[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 8 })); |
| 31 | + } |
| 32 | + |
| 33 | + public static int find(int[] a) { |
| 34 | + if (a == null || a.length == 0 || a.length == 1) |
| 35 | + return -1; |
| 36 | + int l = 0, h = a.length - 1; |
| 37 | + while (h > l) { |
| 38 | + if (h - l == 1) |
| 39 | + return a[l] > a[h] ? l : h; |
| 40 | + int m = ((h - l) / 2) + l, ls = 0, hs = 0; |
| 41 | + ls = (h - l + 1) % 2 == 1 ? getSum(a, l, m - 1) : getSum(a, l, m); |
| 42 | + hs = getSum(a, m + 1, h); |
| 43 | + if (ls == hs) |
| 44 | + return m; |
| 45 | + if (ls < hs) |
| 46 | + l = m + 1; |
| 47 | + else |
| 48 | + h = (h - l + 1) % 2 == 1 ? m - 1 : m; |
| 49 | + } |
| 50 | + return l; |
| 51 | + } |
| 52 | + |
| 53 | + public static int getSum(int[] a, int l, int h) { |
| 54 | + int r = 0; |
| 55 | + for (int i = l; i <= h; i++) |
| 56 | + r += a[i]; |
| 57 | + return r; |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments