Finding Duplicate Java

Finding Duplicate: A TDD Exercise

The problem

Given an integer array of any size, we need to find if it contains duplicate elements or not, without using any built-in functions specifically for that and also by not using any data structures other than arrays!

Approach using TDD

  1. Start with a small and naive failing test, say for just 2 elements

  2. Code just enough to pass it

  3. Refactor if you can

  4. Move ahead with a less naive failing test, this time with 3 elements

  5. Code just enough to pass it

  6. Refactor

Repeat the same until most non-trivial cases with more elements are passing. Once we have enough cases, we could also see at improving the code or doing it in more efficient ways!

Tests and solution snippets

@Test
public void two_ones_must_return_true() {
    // arrange
    int[] arr = { 1, 1 };

    // act
    Duplicate cut = new Duplicate();
    var result = cut.hasDuplicate(arr);

    // assert
    assertTrue(result);
}
public boolean hasDuplicate(int[] arr) {
    return false;   
}
public boolean hasDuplicate(int[] arr) {
    return (arr[0] == arr[1]);
}

@Test
public void two_ones_with_two_must_return_true() {
    // arrange
    int[] arr = { 1, 2, 1 };

    // act       
    Duplicate cut = new Duplicate(); 
    var result = cut.hasDuplicate(arr);

    // assert
    assertTrue(result);
}
public boolean hasDuplicate(int[] arr) {
    return (arr[0] == arr[1] || arr[0] == arr[2]);
}

Refactor Tests

public class DuplicateTests {
        
    Duplicate cut;
    
    @Before
    public void Init(){
        cut = new Duplicate();
    }

    @Test
    public void two_ones_must_return_true() {
        // arrange
        int[] arr = { 1, 1 };

        // act        
        var result = cut.hasDuplicate(arr);

        // assert
        assertTrue(result);
    }

    @Test
    public void two_ones_with_two_must_return_true() {
        // arrange
        int[] arr = { 1, 2, 1 };

        // act        
        var result = cut.hasDuplicate(arr);

        // assert
        assertTrue(result);
    }
}

@Test
public void two_ones_some_where_must_return_true() {
    // arrange
    int[] arr = { 1, 2, 3, 1 };

    // act       
    Duplicate cut = new Duplicate(); 
    var result = cut.hasDuplicate(arr);

    // assert
    assertTrue(result);
}
public boolean hasDuplicate(int[] arr) {
    
    for (int i = 0; i < arr.length; i++) {
        for (int j = i+1; j < arr.length; j++) {
            if (arr[i] == arr[j])
                return true;
        }
    }
    
    return false;
}    

public boolean hasDuplicate(int[] arr) {
    var distinctLength = Arrays.stream(arr).distinct().count();
    return distinctLength < arr.length;
}

Last updated