easyString ProblemsJava

Print the Duplicate Characters in a String

Print each character that appears more than once in a string along with its count.

Quick Answer

Count every character with an order-preserving map, then print only the characters whose count is greater than one, showing each count. A LinkedHashMap keeps the output in first-appearance order. The whole thing runs in O(n) time.

Problem Statement

Given a string, print every character that appears more than once, along with how many times it occurs. For programming, the duplicates are r, g and m, each appearing twice.

List each duplicate once, in the order it first appears in the string.

Input: A single string s.

Output: Each duplicate character with its count, in first-appearance order.

Examples

Example 1
Input:  "programming"
Output: r:2, g:2, m:2

r, g and m each appear twice; single characters are not printed.

Example 2
Input:  "hello"
Output: l:2

Only l repeats, appearing twice.

Constraints

  • 0 <= s.length <= 10^5
  • Report each duplicate character only once

Think Before You Code

Reveal the questions to ask yourself first
  • How do you know how many times each character appears?
  • How do you avoid printing the same duplicate more than once?
  • How do you keep the output in first-appearance order?
  • What should happen when there are no duplicates at all?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
Build a character-to-count map in a first pass over the string.
Hint 2
In a second pass over the map, keep only entries whose count is greater than one.
Hint 3
A LinkedHashMap preserves first-appearance order, so duplicates print in a predictable sequence.

Approach

Reveal the step-by-step approach

Count first, then filter.

  1. Build a LinkedHashMap<Character, Integer> of counts in first-seen order.
  2. Iterate the map's entries.
  3. For each entry whose value is greater than 1, append character:count to the output, separating entries with , .
  4. Print the assembled line (empty if there are no duplicates).

Iterating the map, rather than the string, guarantees each duplicate is reported exactly once instead of once per occurrence.

Dry Run

Walk through the example step by step

Finding duplicates in "programming":

counts (first-seen order): {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}

scan entries, keep count > 1:
entry | count | keep?
------+-------+------
p=1   | 1     | no
r=2   | 2     | yes -> "r:2"
o=1   | 1     | no
g=2   | 2     | yes -> "g:2"
a=1   | 1     | no
m=2   | 2     | yes -> "m:2"
output: r:2, g:2, m:2

Solution

Reveal the full Java solution
import java.util.LinkedHashMap;
import java.util.Map;

public class DuplicateCharacters {
    public static void printDuplicates(String s) {
        Map<Character, Integer> freq = new LinkedHashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
            if (entry.getValue() > 1) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append(entry.getKey()).append(":").append(entry.getValue());
            }
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        printDuplicates("programming"); // r:2, g:2, m:2
        printDuplicates("hello");       // l:2
    }
}

The first pass tallies each character. The second pass walks the map in first-appearance order and emits only entries with a count above one, so a duplicate is printed a single time regardless of how often it occurs. The sb.length() > 0 guard adds the , separator only between entries, keeping the output clean. If nothing repeats, the builder stays empty and prints a blank line.

Time: O(n) where n is the string lengthSpace: O(k) where k is the number of distinct characters

Common Mistakes

  • Printing a duplicate once per occurrence instead of once overall.
  • Iterating the string again for output, which reprints repeated characters.
  • Using a HashMap and losing the first-appearance ordering.

Edge Cases to Test

  • A string with no duplicates prints an empty line.
  • An empty string prints an empty line.
  • A string of all identical characters, like "aaa", prints a:3.

Interview Follow-Ups

  • How would you print only the duplicate characters without their counts?
  • How would you make the duplicate detection case-insensitive?
  • How would you return the duplicates as a list instead of printing them?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us