Remove Duplicate from Sorted Integer Array Without Using Set

Arrays by default keep duplicate values.

package org.wesome.dsalgo;

import java.util.ArrayList;

public class SortedIntegerArrayDuplicateRemove {
    static ArrayList<Integer> duplicateRemove(int[] arr) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        int slow = 0, fast;
        arrayList.add(0, arr[0]);
        for (fast = 0; fast < arr.length - 1; ) {
            if (arrayList.get(slow) == arr[fast]) {
                fast++;
            } else {
                slow++;
                arrayList.add(slow, arr[fast]);
                fast++;
            }
        }
        return arrayList;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.stream.IntStream;

import static org.wesome.dsalgo.SortedIntegerArrayDuplicateRemove.duplicateRemove;

public class SortedIntegerArrayDuplicateRemoveTest {
    @Test
    void IntegerArrayDuplicateRemoveTest1() {
        int[] arr = new int[]{1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
        ArrayList<Integer> arrayList = new ArrayList<>();
        IntStream.rangeClosed(1, 5).forEach(arrayList::add);
        Assertions.assertTrue(arrayList.equals(duplicateRemove(arr)));
    }

    @Test
    void IntegerArrayDuplicateRemoveTest2() {
        int[] arr = new int[]{1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
        ArrayList<Integer> arrayList = new ArrayList<>();
        IntStream.rangeClosed(1, 5).forEach(arrayList::add);
        Assertions.assertTrue(arrayList.equals(duplicateRemove(arr)));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on