BAEL-7357 Code for the Find Equilibrium Indexes of an Array

This commit is contained in:
Thibault Faure 2024-01-27 16:20:31 +01:00
parent 002384b668
commit 6e83e84cd6
2 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,24 @@
package com.baeldung.equilibriumindex;
import java.util.ArrayList;
import java.util.List;
class EquilibriumIndexFinder {
List<Integer> findEquilibriumIndexes(int[] array) {
int[] partialSums = new int[array.length + 1];
partialSums[0] = 0;
for (int i=0; i<array.length; i++) {
partialSums[i+1] = partialSums[i] + array[i];
}
List<Integer> equilibriumIndexes = new ArrayList<Integer>();
for (int i=0; i<array.length; i++) {
if (partialSums[i] == (partialSums[array.length] - (partialSums[i+1]))) {
equilibriumIndexes.add(i);
}
}
return equilibriumIndexes;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.equilibriumindex;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class EquilibriumIndexFinderUnitTest {
@Test
void givenArrayHasEquilibriumIndexes_whenFindEquilibriumIndexes_thenListAllEquilibriumIndexes() {
int[] array = {1, -3, 0, 4, -5, 4, 0, 1, -2, -1};
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(1, 4, 9);
}
@Test
void givenArrayWithoutEquilibriumIndexes_whenFindEquilibriumIndexes_thenEmptyList() {
int[] array = {1, 2, 3};
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).isEmpty();
}
@Test
void givenArrayWithOneElement_whenFindEquilibriumIndexes_thenListFirstIndex() {
int[] array = {5};
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(0);
}
}