TechByteByByte

Count Duplicate Characters in a String - Java

A difficult QA/automation coding interview question: count Duplicate Characters in a String, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Strings#HashMap#Frequency Counting#Difficult#Java

@Note: This is categorized as “Difficult” because it presents a high risk of misinterpretation during interviews due to the two conflicting conventions for “duplicate count”.


Category: Difficult | Concepts used: Frequency map, counting characters that repeat


Problem Statement

Given a string, count how many distinct characters repeat (appear more than once) — NOT the total count of duplicate occurrences.

Input : "programming"      Output: 3   (r, g, m each repeat — 3 DISTINCT repeating characters)

Note: Two possible interpretations exist — always clarify: (1) count of distinct characters that repeat (e.g., 3 for the example above), or (2) total count of “extra” occurrences (e.g., r appears twice = 1 extra, g appears twice = 1 extra, m appears twice = 1 extra → also happens to be 3 here, but would differ for characters appearing 3+ times).

Examples (with edge scenarios)

#InputDistinct repeating chars“Extra” occurrences countWhy
1"programming"3 (r, g, m)3 (1 extra each)Both interpretations agree here
2"aabbbcc"3 (a, b, c)4 (a:+1, b:+2, c:+1)Interpretations diverge when a character appears 3+ times
3"" (empty)00No characters at all
4"abcdef" (no repeats)00Every character appears exactly once
5"aaaa"1 (just ‘a’)3 (appears 4 times = 3 “extra”)Single character repeating many times

Common Fresher Mistake

MistakeWhat happensFix
Not clarifying which interpretation is wanted before codingMight solve the “wrong version” and get marked incorrect despite correct logicAlways ask: “distinct repeating characters, or total extra occurrences?”
Case-sensitivity assumptions'A' and 'a' treated as same or different without confirmingClarify whether the check should be case-sensitive

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.

Analogy: Spotting Duplicate Subscriptions

Imagine you are managing a newsletter subscriber list:

  • Some users accidentally subscribed multiple times (like a subscribed 2 times, b subscribed 3 times).
  • Interpretation 1 (Counting Distinct Spam Senders): You want to find out how many unique people sent duplicate requests. You look at your tally: “A sent duplicates, B sent duplicates.” That’s 2 distinct people who spammed you.
  • Interpretation 2 (Counting Total Excess Paper): You want to find out how many extra sheets of paper were wasted.
    • For A, they sent 2 papers (so 2 - 1 = 1 extra paper wasted).
    • For B, they sent 3 papers (so 3 - 1 = 2 extra papers wasted).
    • The total wasted paper count is 1 + 2 = 3 sheets!

Solution 1 — Count Distinct Characters That Repeat (Interpretation 1)

Intuition

Build a frequency map (as usual), then simply count how many keys (distinct characters) in that map have a value greater than 1 — we’re counting the number of characters that qualify, not how many times they each repeat.

import java.util.HashMap;

public class CountDuplicateCharsDistinct {
    public static int countDuplicates(String str) {
        HashMap<Character, Integer> freq = new HashMap<>();
        for (char ch : str.toCharArray()) {
            freq.put(ch, freq.getOrDefault(ch, 0) + 1);
        }

int duplicateCount = 0;
        for (int count : freq.values()) {
            if (count > 1) {
                duplicateCount++; // count the CHARACTER, not the extra occurrences
            }
        }
        return duplicateCount;
    }

public static void main(String[] args) {
        System.out.println(countDuplicates("programming")); // 3
        System.out.println(countDuplicates("aabbbcc"));        // 3
        System.out.println(countDuplicates("aaaa"));            // 1
    }
}

Output:

3
3
1

Dry Run (str = “aabbbcc”)

freq = {a:2, b:3, c:2}

Scanning values:
2 > 1 -> duplicateCount=1
3 > 1 -> duplicateCount=2
2 > 1 -> duplicateCount=3

Final: 3  (three DISTINCT characters repeat: a, b, c — regardless of how many times each repeats)

Interviewer’s take

This is the more commonly expected interpretation — “how many characters repeat” typically means distinct characters, not total extra occurrences. Still, always state your interpretation explicitly when presenting your answer, since this exact ambiguity is a known trap in this question.

Follow-up questions you might get:

  • “What if I wanted the total number of ‘extra’ occurrences instead?” → leads to Solution 2.

Solution 2 — Count Total “Extra” Occurrences (Interpretation 2)

Intuition

Instead of just checking “does this character repeat at all,” sum up how many occurrences beyond the first count as “extra” for each character — a character appearing k times contributes k-1 extra occurrences (since the first occurrence isn’t a “duplicate” of anything, but every occurrence after it is).

import java.util.HashMap;

public class CountDuplicateCharsTotal {
    public static int countDuplicates(String str) {
        HashMap<Character, Integer> freq = new HashMap<>();
        for (char ch : str.toCharArray()) {
            freq.put(ch, freq.getOrDefault(ch, 0) + 1);
        }

int totalExtra = 0;
        for (int count : freq.values()) {
            if (count > 1) {
                totalExtra += (count - 1); // every occurrence beyond the first is "extra"
            }
        }
        return totalExtra;
    }

public static void main(String[] args) {
        System.out.println(countDuplicates("programming")); // 3
        System.out.println(countDuplicates("aabbbcc"));        // 4
        System.out.println(countDuplicates("aaaa"));            // 3
    }
}

Output:

3
4
3

Dry Run (str = “aabbbcc”)

freq = {a:2, b:3, c:2}

a: count=2>1 -> extra += (2-1)=1 -> totalExtra=1
b: count=3>1 -> extra += (3-1)=2 -> totalExtra=3
c: count=2>1 -> extra += (2-1)=1 -> totalExtra=4

Final: 4  (notice this differs from Solution 1's answer of 3 for the same input!)

Interviewer’s take

Equally valid, but answers a different question — this is why clarifying the exact definition matters so much for this problem. The “extra occurrences” interpretation is useful in contexts like “how much redundant data is in this string,” while “distinct repeating characters” answers “how many unique letters show up more than once.”


📊 Visual Flowchart

graph TD
    Start["Input String str"] --> Pass1["Build Frequency Map freqMap"]
    Pass1 --> Decide{"Choose Interpretation"}
    Decide -->|Distinct Repeating Chars| Path1["Initialize duplicateCount = 0"]
    Path1 --> Loop1{"For each count in freqMap.values()"}
    Loop1 --> Check1{"count > 1?"}
    Check1 -->|Yes| Inc1["duplicateCount++"]
    Inc1 --> Loop1
    Check1 -->|No| Loop1
    Loop1 -->|Done| End1["Return duplicateCount"]
    Decide -->|Total Extra Occurrences| Path2["Initialize totalExtra = 0"]
    Path2 --> Loop2{"For each count in freqMap.values()"}
    Loop2 --> Check2{"count > 1?"}
    Check2 -->|Yes| AddExtra["totalExtra += (count - 1)"]
    AddExtra --> Loop2
    Check2 -->|No| Loop2
    Loop2 -->|Done| End2["Return totalExtra"]

Final Verdict — Which Solution Should You Give?

  • The single most important thing here is clarifying the definition before coding — both solutions are simple once the interpretation is settled, and getting this wrong silently (without asking) is the real risk in this problem.

Quick Recap

InterpretationApproachTimeSpace
Distinct repeating charactersCount map values > 1O(n)O(k) — k = distinct chars
Total extra occurrencesSum of (count - 1) for values > 1O(n)O(k)
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed