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
Start with a small and naive failing test, say for just 2 elements
Code just enough to pass it
Refactor if you can
Move ahead with a less naive failing test, this time with 3 elements
Code just enough to pass it
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);
}