-2

Pretty much what the title said. I thought of using Sets and comparing sizes with the normal array but then if I had 2 elements with duplicates the Set size would be the same as having one element with 2 duplicates.

Any help on how to approach this would be much appreciated!

Tarik
  • 4,961
  • 3
  • 36
  • 67
user3484582
  • 557
  • 1
  • 6
  • 22

4 Answers4

0

I think the fastest approach is the brute force one, i.e. traversing the array and count what you want to count. Each other implementation which you can call by a one liner must traverse the array as well, using a HashMap adds the overhead to fill and maintain the map, and you cannot stop iterating if you have found what you searched for.

With following private method you can use it also by a one liner call from your main code:

    main()
    {
        String[] myArray = new String[] {
                                          "Hello",
                                          "Hello",
                                          "Hello",
                                          null,
                                          null,
                                           };
        boolean gotIt = hasAtLeastThreeOccurences( myArray, "Hello");
        myLog.debug( "gotIt: " + gotIt );
    }

private <T> boolean hasAtLeastThreeOccurences( T[] aArray, T aValue)
{
    int count = 0;
    boolean isNull = (aValue == null);

    for ( T t : aArray )
    {
        if ( isNull )
        {
            if ( t == null )
            {
                count++;
            }
        }
        else
        {
            if ( aValue.equals( t ) )
            {
                count++;
            }
        }

        if ( count >= 3 )
        {
            return true;
        }
    }

    return false;
}
Heri
  • 4,368
  • 1
  • 31
  • 51
0

Assuming your array is a String Array (just as an example), you can call this method, if it return null then there is no 3 elements or more with the same value, else it will return the first element found 3 times or more

public String getRedundantItem(String... myArray) {

    // Convert the array to List
    ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));

    // Look for the element which frequency is three or more
    for (String item : myList) {
        if (Collections.frequency(myList, item) > 2) {
            return item;
        }
    }

    // No element more than 2 times
    return null;
}

Test Example:

public void test(){     

    String[] someData = {"stack","over", "flow", "stack", "stack"};
    String[] otherData = {"stack","over", "flow", "stack", "flow"};

    System.out.println(getRedundantItem(someData)); // prints stack
    System.out.println(getRedundantItem(otherData)); // prints null

}
Tarik
  • 4,961
  • 3
  • 36
  • 67
0

If an array have three elements with same value

we keep : element => number of occurence. difficult to do less or faster

List<String> array=Arrays.asList(new String[] {"aa","bb","cc","aa","bb","dd"});  // Complete with other tests

Iterator<String> it=array.iterator();

// Keep element => occurences
Map<String,Integer> occurences=new HashMap<String,Integer>();

while (it.hasNext())
    {
    String one_string=it.next();

    if (occurences.containsKey(one_string))
        {
        int how_many=occurences.get(one_string);
        if (how_many==2) return true;

        // IF NOT
        occurences.put(one_string, how_many+1);
        }
    else // NEW
        occurences.put(one_string, 1);
    }
// finally
return false;
-1

This is an example using int variables, but the basic idea is that the value to be compared to the other values of the array is set to the first variable. Then as we find elements equal to the key, we increment a temporary count variable. If the temporary count variable is greater than the real count variable, then the real count variable is replaced by the temporary count variable. Once an unequal element is found, a new key value is set to the current element being iterated on and the temporary count variable is reset. This could be tinkered with, however, for example you can break out of the loop once the the temporary count reaches three. I'm not sure if this was what you were looking for, but enjoy.

int key = arr[0];
int tempCount = 0;
int realCount = 0;
for(int i = 1; i < arr.length; i++){
    if(arr[i] == key){
        tempCount++;
    }
    else{
        key = arr[i];
        tempCount = 0;
    }
    if(tempCount > realCount){
        realCount = tempCount;
    }
}
if(realCount >= 3){
    boolean hasThreeOfTheSame = true;
    //do stuff you want to do
}

EDIT: I now realize that the OP wanted a way to find if there were 3 of the same elements in an array despite the order. I misread this so my solution finds whether an array has 3 or more consecutive elements in a row (ex: [1, 1, 1, 2, 3] or [1, 2, 2, 2, 3]). I'm only going to keep this up because it may help someone out there.

Chris Gong
  • 8,031
  • 4
  • 30
  • 51