user3768997 user3768997 - 1 year ago 120
Java Question

Compare two Arrays and remove duplicates from Original Array java(no lists)

So I am trying to compare two char arrays, and all letters that are present in keyW, should be removed from the array invAlphabet. I have been able to find the duplicates inside the invAlphabet array, however, I don't know how to remove the duplicate elements without using Lists or Collections which I should not use...
Any idea?

public static void main(String[] args)
final int SIZE = 26;
char[] keyW = {'A', 'L','O'};

char[] invAlphabet = new char [SIZE];

for (int i = 0; i < SIZE; i++)
invAlphabet[i] = (char)('Z' - i);


for (int i = 0; i<keyW.length; i++)
for (int j = 0; j < invAlphabet.length; j++)
if(keyW[i] == invAlphabet[j])
//need to delete the invAlphabet[j] elements that are duplicates




Answer Source

If you want to solve it in O(n), then you can mark all the character That are present in keyW[] array, and then check and don't add them to your new noDuplicateArray[].

char[] keyW = {'A', 'L', 'O', 'P'};
char[] invAlphabet = {'X', 'A', 'P', 'B', 'C'};

//create boolean array
boolean[] mark = new boolean[128];
Arrays.fill(mark, false);

//mark which characters are present in keyW array
for (char ch : keyW) {
    mark[ch] = true;

// find number of duplicate character in invAlphabet array
int duplicateCount = 0;
for (char ch : invAlphabet) {
    if (mark[ch]) {

// create new array
// size of new array = invAlphabet array length - duplicate number of character in invAlphabet array
char[] noDuplicateArray = new char[invAlphabet.length - duplicateCount];

//add character in new array
int idx = 0;
for (char ch : invAlphabet) {
    if (!mark[ch]) {
        noDuplicateArray[idx++] = ch;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download