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);
}


Refactor Tests



Last updated