Count the Number of Duplicates in Java


The challenge

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

“abcde” -> 0 # no characters repeats more than once
“aabbcde” -> 2 # 'a' and 'b'
“aabBcde” -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
“indivisibility” -> 1 # 'i' occurs six times
“Indivisibilities” -> 2 # 'i' occurs seven times and 's' occurs twice
“aA11” -> 2 # 'a' and '1'
“ABBA” -> 2 # 'A' and 'B' each occur twice

The solution in Java code

Option 1 (using a HashMap):

import java.util.*;

public class CountingDuplicates {
  public static int duplicateCount(String text) {
    Map<String, Integer> map = new HashMap<>();
    int ans = 0;
    
    for (int i=0; i<text.length(); i++)
      map.merge(text.toLowerCase().charAt(i)+"", 1, Integer::sum);
    
    for (Integer value : map.values())
      if (value>1) ans++;
    
    return ans;
  }
}

Option 2 (using a substring):

public class CountingDuplicates {
  public static int duplicateCount(String text) {
    int ans = 0;
    text = text.toLowerCase();
    while (text.length() > 0) {
      String firstLetter = text.substring(0,1);
      text = text.substring(1);
      if (text.contains(firstLetter)) ans ++;
      text = text.replace(firstLetter, "");
    }
    return ans;
  }
}

Option 3 (using Streams):

import java.util.Map;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

class CountingDuplicates {
    private static Map<Character, Long> charFrequenciesMap(final String text) {
        return text.codePoints()
            .map(Character::toLowerCase)
            .mapToObj(c -> (char) c)
            .collect(groupingBy(identity(), counting()));
    }
    
    static int duplicateCount(final String text) {
        return (int) charFrequenciesMap(text).values().stream()
            .filter(i -> i > 1)
            .count();
    }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void abcdeReturnsZero() {
        assertEquals(0, CountingDuplicates.duplicateCount("abcde"));
    }
    
    @Test
    public void abcdeaReturnsOne() {
        assertEquals(1, CountingDuplicates.duplicateCount("abcdea"));
    }
    
    @Test
    public void indivisibilityReturnsOne() {
        assertEquals(1, CountingDuplicates.duplicateCount("indivisibility"));
    }
    
    @Test 
    public void reallyLongStringContainingDuplicatesReturnsThree() {
        String testThousandA = new String(new char[1000]).replace('\0', 'a');
        String testHundredB = new String(new char[100]).replace('\0', 'b');
        String testTenC = new String(new char[10]).replace('\0', 'c');
        String test1CapitalA = new String(new char[1]).replace('\0', 'A'); 
        String test1d = new String(new char[1]).replace('\0', 'd'); 
        String test = test1d + test1CapitalA + testTenC + 
            testHundredB + testThousandA;
        

        assertEquals(3, CountingDuplicates.duplicateCount(test));
    }
    
}