String Character Logic

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/180 Known filtered set
Difficulty
Read Full Guide Question: 1 of 180

Java Logic Development · Chapter 15 Companion Article

String Character Logic

Fifteen character-level String problems — frequency counting, first/last repeated and non-repeated characters, duplicate and unique detection, most/least frequent characters, removing or replacing characters, sorting characters, separating alphabets from digits, and character occurrence positions — solved with loops, arrays, HashMap, LinkedHashMap, and HashSet. Followed by the recurring problem-solving patterns and edge cases every character-logic solution should be tested against.

Overview

String character problems test how well you can traverse a string, track character occurrences, preserve order, and build a new result. Most problems can be solved using loops, arrays, sets, maps, or StringBuilder.

Key Terms

  • Frequency: Number of times a character occurs.
  • Duplicate character: A character occurring more than once.
  • Unique character: A character occurring exactly once.
  • First repeated character: The first character encountered again while scanning from left to right.
  • Non-repeated character: A character whose total frequency is exactly one.
  • Character position: Index where a character appears. Java string indexes start from 0.
  • LinkedHashMap: Stores key-value pairs while preserving insertion order.
  • HashSet: Stores unique values and is useful for detecting duplicates.

Important Difference

These two operations are not the same:

  • Remove duplicate characters: Keep one copy of each character.
    • programming → progamin
  • Remove repeated characters: Remove every character that occurs more than once.
    • programming → poain

Unless stated otherwise, the examples treat each Java char as one character. A Java char represents a UTF-16 code unit, so supplementary Unicode characters such as some emoji require code-point-based processing.

1. Character Frequency

Problem

Count how many times each character occurs in a string.

Example

Input:

Output
banana

Output:

Output
b -> 1
a -> 3
n -> 2

Hint

Store each character as a key and its occurrence count as the value.

Logic

  1. Create a LinkedHashMap<Character, Integer>.
  2. Traverse the string character by character.
  3. Check whether the character already exists in the map.
  4. Increase its frequency by 1.
  5. Print the map entries after traversal.

LinkedHashMap is useful here because it keeps characters in their first-appearance order.

Dry Run

For:

Output
banana

Processing:

CharacterFrequency after processing
bb=1
ab=1, a=1
nb=1, a=1, n=1
ab=1, a=2, n=1
nb=1, a=2, n=2
ab=1, a=3, n=2

Java Program

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "banana";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

Program Output

Output
b -> 1
a -> 3
n -> 2

Why This Logic Works

Every character is processed exactly once. The map keeps one entry per distinct character and updates its counter whenever that character appears again.

Complexity

  • Time: O(n)
  • Space: O(k)

Here, n is the string length and k is the number of distinct characters.

Common Mistakes

  • Resetting the frequency to 1 every time a character occurs.
  • Using a plain HashMap when output order matters.
  • Counting spaces unintentionally when the requirement says to ignore them.

Interview Tip

Be ready to solve the same problem using:

  • HashMap
  • Frequency array
  • Nested loops

A map is usually cleaner when the possible character set is not restricted.

2. First Non-Repeated Character

Problem

Find the first character whose frequency is exactly one.

Example

Input:

Output
swiss

Output:

Output
w

Hint

First calculate all frequencies. Then scan the original string again.

Logic

A single traversal cannot always tell whether the current character will appear again later.

Use two passes:

  1. Count the frequency of every character.
  2. Traverse the string from left to right.
  3. Return the first character having frequency 1.

Dry Run

For:

Output
swiss

Frequencies:

  • s = 3
  • w = 1
  • i = 1

Original order:

  • s → repeated
  • w → frequency is 1

Answer:

Output
w

Java Program

Java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "swiss";
        Map<Character, Integer> frequency = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        Character result = null;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (frequency.get(ch) == 1) {
                result = ch;
                break;
            }
        }

        System.out.println(result == null ? "None" : result);
    }
}

Program Output

Output
w

Why This Logic Works

The frequency map tells whether a character occurs once or multiple times. Traversing the original string preserves the correct left-to-right order.

Complexity

  • Time: O(n)
  • Space: O(k)

Edge Case

For:

Output
aabbcc

No character occurs exactly once, so the result is:

Output
None

Common Mistake

Iterating through an ordinary HashMap to find the "first" character. HashMap does not guarantee original string order.

Interview Tip

The important point is not only counting frequency. You must also preserve the original character order when finding the first valid character.

3. First Repeated Character

Problem

Find the first character encountered for the second time while scanning from left to right.

Example

Input:

Output
programming

Output:

Output
r

Hint

Store characters that have already been seen.

Logic

  1. Create a HashSet.
  2. Traverse the string.
  3. Try to add each character to the set.
  4. HashSet.add() returns false if the character is already present.
  5. The first failed insertion gives the first repeated character.

This avoids calculating every character frequency.

Dry Run

For:

Output
programming

Traversal:

  • p → new
  • r → new
  • o → new
  • g → new
  • r → already present

First repeated character:

Output
r

Java Program

Java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Set<Character> seen = new HashSet<>();
        Character repeated = null;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!seen.add(ch)) {
                repeated = ch;
                break;
            }
        }

        System.out.println(repeated == null ? "None" : repeated);
    }
}

Program Output

Output
r

Why This Logic Works

A set contains only characters already visited. Therefore, finding a character already inside the set proves that it has occurred previously.

Complexity

  • Time: O(n) average
  • Space: O(k)

Edge Case

For:

Output
java

The second a is the first repeated occurrence, so the result is:

Output
a

For:

Output
code

The result is:

Output
None

Interview Tip

Clarify the definition of "first repeated."

It can mean:

  • first character encountered twice during traversal, or
  • first character in original order whose total frequency is greater than one.

Some inputs produce different answers under these definitions.

4. Last Non-Repeated Character

Problem

Find the last character that occurs exactly once.

Example

Input:

Output
swiss

Output:

Output
i

Hint

Count frequencies first, then search from the end.

Logic

  1. Calculate character frequencies.
  2. Start traversal at the last index.
  3. Move toward index 0.
  4. Stop when frequency equals 1.

Searching backward directly finds the last valid character.

Dry Run

Frequencies of swiss:

  • s = 3
  • w = 1
  • i = 1

Reverse traversal:

  • s → repeated
  • s → repeated
  • i → unique

Answer:

Output
i

Java Program

Java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "swiss";
        Map<Character, Integer> frequency = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        Character result = null;

        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);
            if (frequency.get(ch) == 1) {
                result = ch;
                break;
            }
        }

        System.out.println(result == null ? "None" : result);
    }
}

Program Output

Output
i

Why This Logic Works

Frequency identifies valid non-repeated characters, while reverse traversal changes the selection rule from first unique to last unique.

Complexity

  • Time: O(n)
  • Space: O(k)

Common Mistake

Finding every unique character correctly but returning the first one instead of the last.

Interview Tip

If you already have a first-non-repeated solution, this problem mainly tests whether you can modify traversal direction without unnecessarily redesigning the algorithm.

5. Duplicate Characters

Problem

Print characters that occur more than once. Each duplicate character should be printed only once.

Example

Input:

Output
programming

Output:

Output
r g m

Hint

Count all characters and select those whose frequency is greater than 1.

Logic

  1. Store frequencies in a LinkedHashMap.
  2. Traverse the map.
  3. Print characters having count greater than 1.

LinkedHashMap ensures duplicate characters are shown according to their first appearance.

Dry Run

For programming:

CharacterFrequency
p1
r2
o1
g2
a1
m2
i1
n1

Duplicates:

Output
r g m

Java Program

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        StringBuilder result = new StringBuilder();

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            if (entry.getValue() > 1) {
                if (result.length() > 0) {
                    result.append(" ");
                }
                result.append(entry.getKey());
            }
        }

        System.out.println(result);
    }
}

Program Output

Output
r g m

Why This Logic Works

Frequency greater than one is the exact condition for a duplicate. Since the map contains only one entry per distinct character, each duplicate is printed once.

Complexity

  • Time: O(n)
  • Space: O(k)

Common Mistake

Printing a duplicate whenever it is encountered again. For a character occurring four times, that approach may print the same character three times.

Interview Tip

State whether the expected output needs:

  • duplicate characters only,
  • duplicate characters with counts, or
  • every repeated occurrence.

They are different problems.

6. Unique Characters

Problem

Find all characters that occur exactly once.

Example

Input:

Output
programming

Output:

Output
p o a i n

Hint

A unique character has frequency exactly 1.

Logic

  1. Count each character.
  2. Preserve insertion order.
  3. Select entries having frequency equal to 1.

Dry Run

For programming:

Repeated characters:

  • r
  • g
  • m

Characters occurring once:

  • p
  • o
  • a
  • i
  • n

Java Program

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        StringBuilder result = new StringBuilder();

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            if (entry.getValue() == 1) {
                if (result.length() > 0) {
                    result.append(" ");
                }
                result.append(entry.getKey());
            }
        }

        System.out.println(result);
    }
}

Program Output

Output
p o a i n

Why This Logic Works

A character is unique only when its total number of occurrences is one. Checking frequency after processing the complete string avoids incorrectly classifying a character before later occurrences are known.

Complexity

  • Time: O(n)
  • Space: O(k)

Common Mistake

Confusing "unique characters" with "distinct characters."

For:

Output
banana

Distinct characters are:

Output
b a n

Unique characters are only:

Output
b

Interview Tip

Always clarify the terminology. In interview questions, "unique" normally means frequency 1, while "distinct" normally means no duplicate values in the output.

7. Most Frequent Character

Problem

Find the character having the highest frequency.

Example

Input:

Output
banana

Output:

Output
a -> 3

Hint

Count frequencies and maintain the largest count seen.

Logic

  1. Build a LinkedHashMap containing character frequencies.
  2. Initialize maxFrequency to 0.
  3. Traverse the map.
  4. Whenever a frequency is greater than maxFrequency, update the result.

Using greater-than instead of greater-than-or-equal keeps the first character when multiple characters have the same maximum frequency.

Dry Run

Frequency table:

  • b = 1
  • a = 3
  • n = 2

Comparisons:

  • b → max = 1
  • a → max = 3
  • n → 2 is smaller than 3

Result:

Output
a -> 3

Java Program

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "banana";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        Character mostFrequent = null;
        int maxFrequency = 0;

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            if (entry.getValue() > maxFrequency) {
                maxFrequency = entry.getValue();
                mostFrequent = entry.getKey();
            }
        }

        if (mostFrequent == null) {
            System.out.println("None");
        } else {
            System.out.println(mostFrequent + " -> " + maxFrequency);
        }
    }
}

Program Output

Output
a -> 3

Why This Logic Works

Every distinct character has one final frequency. Comparing those values is sufficient to identify the maximum.

Complexity

  • Time: O(n)
  • Space: O(k)

Tie Handling

For:

Output
aabb

Both a and b occur twice.

This implementation returns:

Output
a -> 2

because a appears first.

Common Mistake

Using greater-than-or-equal when the requirement says to return the first character in case of a tie.

Interview Tip

Ask how ties should be handled:

  • first occurring character,
  • last occurring character,
  • lexicographically smallest character,
  • or all tied characters.

8. Least Frequent Character

Problem

Find the character having the smallest occurrence count.

Example

Input:

Output
banana

Output:

Output
b -> 1

Hint

Start with a very large minimum value and reduce it whenever a smaller frequency is found.

Logic

  1. Count all character occurrences.
  2. Initialize minFrequency to Integer.MAX_VALUE.
  3. Traverse each distinct character.
  4. Update the answer when its frequency is smaller than the current minimum.

Dry Run

Frequency:

  • b = 1
  • a = 3
  • n = 2

Processing:

  • b → min becomes 1
  • a → 3 is not smaller
  • n → 2 is not smaller

Result:

Output
b -> 1

Java Program

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "banana";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        Character leastFrequent = null;
        int minFrequency = Integer.MAX_VALUE;

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            if (entry.getValue() < minFrequency) {
                minFrequency = entry.getValue();
                leastFrequent = entry.getKey();
            }
        }

        if (leastFrequent == null) {
            System.out.println("None");
        } else {
            System.out.println(leastFrequent + " -> " + minFrequency);
        }
    }
}

Program Output

Output
b -> 1

Why This Logic Works

The algorithm compares the final frequency of every distinct character and keeps the smallest value found.

Complexity

  • Time: O(n)
  • Space: O(k)

Edge Case

If every character occurs once, every character has the same minimum frequency. This implementation returns the first character.

Common Mistake

Initializing minimum frequency to 0. Character frequencies are positive, so no valid count will normally be smaller than 0.

Interview Tip

Integer.MAX_VALUE is a common and safe initialization when searching for a minimum value.

9. Remove Duplicate Characters

Problem

Remove additional occurrences of characters while keeping the first occurrence.

Example

Input:

Output
programming

Output:

Output
progamin

Hint

Append a character only when it has not appeared before.

Logic

  1. Create a HashSet for visited characters.
  2. Traverse the string.
  3. Add each character to the set.
  4. HashSet.add() returns true only for a new value.
  5. Append only newly added characters.

Dry Run

For programming:

CharacterAlready Seen?Result
pNop
rNopr
oNopro
gNoprog
rYesprog
aNoproga
mNoprogam
mYesprogam
iNoprogami
nNoprogamin
gYesprogamin

Java Program

Java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Set<Character> seen = new HashSet<>();
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (seen.add(ch)) {
                result.append(ch);
            }
        }

        System.out.println(result);
    }
}

Program Output

Output
progamin

Why This Logic Works

A set accepts each character only once. The string is scanned in original order, so the first occurrence is preserved and later copies are skipped.

Complexity

  • Time: O(n) average
  • Space: O(k)

Edge Cases

Input:

Output
aaaa

Output:

Output
a

Input:

Output
java

Output:

Output
jav

Common Mistake

Sorting the string before removing duplicates. Sorting changes the original character order.

Interview Tip

This problem can be solved without a frequency map because you only need to know whether a character has already appeared.

10. Remove Repeated Characters

Problem

Remove every character that occurs more than once. Keep only characters whose total frequency is exactly one.

Example

Input:

Output
programming

Output:

Output
poain

Hint

A set alone is not enough because you must know the final frequency before deciding whether to keep a character.

Logic

  1. Count the total frequency of every character.
  2. Traverse the original string again.
  3. Append only characters whose frequency equals 1.

Repeated characters are completely removed, including their first occurrence.

Dry Run

For programming:

Frequencies:

  • p = 1
  • r = 2
  • o = 1
  • g = 2
  • a = 1
  • m = 2
  • i = 1
  • n = 1

Keep:

  • p
  • o
  • a
  • i
  • n

Result:

Output
poain

Java Program

Java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> frequency = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (frequency.get(ch) == 1) {
                result.append(ch);
            }
        }

        System.out.println(result);
    }
}

Program Output

Output
poain

Why This Logic Works

A character should remain only when its total count is one. Calculating frequencies before constructing the result provides that information.

Complexity

  • Time: O(n)
  • Space: O(k)

Important Difference

For:

Output
banana

Remove duplicate characters:

Output
ban

Remove repeated characters:

Output
b

The first operation keeps one copy. The second removes every character that appeared multiple times.

Common Mistake

Using only a HashSet and assuming it can determine total character frequency.

Interview Tip

The wording "remove duplicates" and "remove repeated characters" is sometimes used inconsistently. Confirm the expected output before coding.

11. Replace Character

Problem

Replace every occurrence of one character with another character.

Example

String:

Output
banana

Replace:

Output
a with o

Output:

Output
bonono

Hint

Traverse every position and decide whether to append the replacement or original character.

Logic

For each character:

  • If it equals the target character, append the replacement.
  • Otherwise, append the original character.

String objects are immutable in Java, so StringBuilder is suitable for constructing the modified string.

Dry Run

Input:

Output
banana

Target:

Output
a

Replacement:

Output
o

Processing:

  • b → b
  • a → o
  • n → n
  • a → o
  • n → n
  • a → o

Result:

Output
bonono

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String str = "banana";
        char target = 'a';
        char replacement = 'o';
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == target) {
                result.append(replacement);
            } else {
                result.append(ch);
            }
        }

        System.out.println(result);
    }
}

Program Output

Output
bonono

Why This Logic Works

Every character is copied into a new result. Only positions containing the target character receive a different value.

Complexity

  • Time: O(n)
  • Space: O(n)

The output itself may contain n characters.

Built-in Alternative

Java also provides String.replace() when manual logic is not required.

Conceptually:

Output
str.replace('a', 'o')

For logic-development exercises, manual traversal better demonstrates the underlying operation.

Common Mistake

Expecting the original String object to change. Java strings are immutable.

Interview Tip

Be clear whether the requirement is to replace:

  • every occurrence,
  • only the first occurrence,
  • the character at a particular index,
  • or a complete substring.

12. Remove Character

Problem

Remove every occurrence of a specified character from a string.

Example

String:

Output
banana

Remove:

Output
a

Output:

Output
bnn

Hint

Build a result containing every character except the target.

Logic

  1. Traverse the string.
  2. Compare each character with the character to remove.
  3. Skip matching characters.
  4. Append all other characters.

Dry Run

Input:

Output
banana

Remove:

Output
a

Processing:

  • b → keep → b
  • a → skip
  • n → keep → bn
  • a → skip
  • n → keep → bnn
  • a → skip

Result:

Output
bnn

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String str = "banana";
        char remove = 'a';
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch != remove) {
                result.append(ch);
            }
        }

        System.out.println(result);
    }
}

Program Output

Output
bnn

Why This Logic Works

Removing a character from an immutable String is effectively the same as constructing another string without the unwanted positions.

Complexity

  • Time: O(n)
  • Space: O(n)

Edge Cases

If the character does not exist, the original text remains unchanged.

If every character matches the target, the result is an empty string.

Common Mistake

Removing characters while increasing indexes in a mutable sequence without considering that indexes shift after deletion.

Building a new result avoids that issue.

Interview Tip

For a single-pass filter operation, StringBuilder is usually simpler than repeatedly creating new String objects.

13. Sort Characters

Problem

Arrange string characters in ascending order.

Example

Input:

Output
logic

Output:

Output
cgilo

Hint

Convert the String to a char array so individual positions can be swapped.

Logic

This example manually sorts characters to demonstrate the sorting logic.

  1. Convert the string to char[].
  2. Compare each character with characters after it.
  3. Swap them whenever the left character is greater.
  4. Convert the sorted array back to a String.

Character comparison is based on Java's numeric char values.

Dry Run

Input:

Output
logic

Initial:

Output
l o g i c

After comparisons and swaps, the ordered characters become:

Output
c g i l o

Result:

Output
cgilo

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String str = "logic";
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length - 1; i++) {
            for (int j = i + 1; j < chars.length; j++) {
                if (chars[i] > chars[j]) {
                    char temp = chars[i];
                    chars[i] = chars[j];
                    chars[j] = temp;
                }
            }
        }

        System.out.println(new String(chars));
    }
}

Program Output

Output
cgilo

Why This Logic Works

After each outer-loop iteration, the smallest remaining character is placed at the current position. Eventually every position contains the correct ascending character.

Complexity

For this manual sorting algorithm:

  • Time: O(n²)
  • Space: O(n) because the String is converted to a char array

Production Alternative

When implementing application code rather than practicing sorting logic, Java's standard library is preferable.

Typical approach:

Output
char[] chars = str.toCharArray();
Arrays.sort(chars);

Character Ordering

Uppercase and lowercase letters do not naturally sort as though case were ignored.

For example, character values place uppercase Latin letters before lowercase Latin letters.

Therefore, define the required ordering when case-insensitive sorting is expected.

Common Mistake

Assuming alphabetical order and raw char-value order are always identical for every language and Unicode character.

Interview Tip

If built-in sorting is prohibited, explain which sorting algorithm you are using and its time complexity.

14. Separate Alphabets and Digits

Problem

Separate letters and numeric digits from a mixed string.

Example

Input:

Output
Java17SE21

Output:

Output
Alphabets: JavaSE
Digits: 1721

Hint

Character.isLetter() and Character.isDigit() clearly express the required classification.

Logic

  1. Create one StringBuilder for letters.
  2. Create another for digits.
  3. Traverse the string.
  4. Use Character.isLetter(ch) to identify letters.
  5. Use Character.isDigit(ch) to identify digits.
  6. Ignore other characters unless the problem specifically requires them.

Dry Run

For:

Output
Java17SE21

Processing:

CharacterTypeDestination
JLetterAlphabets
aLetterAlphabets
vLetterAlphabets
aLetterAlphabets
1DigitDigits
7DigitDigits
SLetterAlphabets
ELetterAlphabets
2DigitDigits
1DigitDigits

Results:

Output
JavaSE
1721

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String str = "Java17SE21";
        StringBuilder alphabets = new StringBuilder();
        StringBuilder digits = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (Character.isLetter(ch)) {
                alphabets.append(ch);
            } else if (Character.isDigit(ch)) {
                digits.append(ch);
            }
        }

        System.out.println("Alphabets: " + alphabets);
        System.out.println("Digits: " + digits);
    }
}

Program Output

Output
Alphabets: JavaSE
Digits: 1721

Why This Logic Works

Each character is independently classified. Letters and digits are appended to different result builders while their original relative order remains unchanged.

Complexity

  • Time: O(n)
  • Space: O(n)

Handling Special Characters

For:

Output
Java@17#SE

The current program ignores @ and #.

If special characters must also be collected, use a third StringBuilder inside an else block.

Alternative for ASCII-Only Input

For English letters and ASCII digits, conditions can also be written manually:

Output
ch >= 'A' && ch <= 'Z'
ch >= 'a' && ch <= 'z'
ch >= '0' && ch <= '9'

Character.isLetter() and Character.isDigit() are clearer and support more Unicode characters.

Common Mistake

Using only lowercase ranges and accidentally ignoring uppercase letters.

Interview Tip

Mention whether the problem expects only English A-Z/a-z characters or broader Unicode letter classification.

15. Character Occurrence Positions

Problem

Find every index at which a specified character occurs.

Example

String:

Output
banana

Character:

Output
a

Output:

Output
[1, 3, 5]

Hint

Compare the target character with every position and store matching indexes.

Logic

  1. Create a list for indexes.
  2. Traverse the string from index 0.
  3. Compare str.charAt(i) with the target character.
  4. Add i whenever they match.
  5. Print the collected positions.

Dry Run

Input:

Output
banana

Target:

Output
a

Traversal:

IndexCharacterMatch?
0bNo
1aYes
2nNo
3aYes
4nNo
5aYes

Positions:

Output
1, 3, 5

Java Program

Java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String str = "banana";
        char target = 'a';
        List<Integer> positions = new ArrayList<>();

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == target) {
                positions.add(i);
            }
        }

        System.out.println(positions);
    }
}

Program Output

Output
[1, 3, 5]

Why This Logic Works

The loop checks every valid string index, so no occurrence can be missed. Matching indexes are stored rather than the characters themselves.

Complexity

  • Time: O(n)
  • Space: O(m)

Here, m is the number of matching occurrences.

Edge Case

If the target character does not occur, the list remains empty:

Output
[]

Zero-Based vs One-Based Position

Java uses zero-based indexes.

For:

Output
banana

The character a occurs at Java indexes:

Output
1, 3, 5

If a problem asks for human-readable positions starting from 1, store:

Output
i + 1

instead.

Common Mistake

Printing i + 1 when the question specifically asks for Java indexes.

Interview Tip

Clarify whether the interviewer wants:

  • all occurrence indexes,
  • first occurrence,
  • last occurrence,
  • occurrence count,
  • or nth occurrence.

Core Logic Comparison

ProblemBest Basic TechniqueMain Condition
Character FrequencyMapIncrement count
First Non-RepeatedFrequency + forward scancount == 1
First RepeatedSetCharacter already seen
Last Non-RepeatedFrequency + reverse scancount == 1
Duplicate CharactersFrequency mapcount > 1
Unique CharactersFrequency mapcount == 1
Most Frequent CharacterFrequency + maximumcount > max
Least Frequent CharacterFrequency + minimumcount < min
Remove Duplicate CharactersSetKeep first occurrence
Remove Repeated CharactersFrequency mapKeep count == 1
Replace CharacterStringBuilderch == target
Remove CharacterStringBuilderch != target
Sort Characterschar[] + sortingCompare characters
Separate Alphabets and DigitsCharacter methodsisLetter / isDigit
Character Occurrence PositionsIndex traversalch == target

Important Problem-Solving Patterns

Frequency Pattern

Use when the answer depends on the total number of occurrences.

Typical problems:

  • Character frequency
  • Unique characters
  • Duplicate characters
  • First non-repeated character
  • Most frequent character
  • Least frequent character

Basic pattern:

Output
Map<Character, Integer> frequency = new HashMap<>();

for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}

Seen-Character Pattern

Use when only previous occurrence information is required.

Typical problems:

  • First repeated character
  • Remove duplicate characters

Basic idea:

Output
Set<Character> seen = new HashSet<>();

for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (seen.add(ch)) {
        // First occurrence
    } else {
        // Already appeared
    }
}

Result-Building Pattern

Use StringBuilder when creating a transformed string.

Typical problems:

  • Remove character
  • Replace character
  • Remove duplicates
  • Remove repeated characters
  • Separate alphabets and digits

Repeated String concatenation inside large loops can create unnecessary temporary String objects because String is immutable.

Forward vs Reverse Traversal

Traversal direction can simplify positional requirements.

Use forward traversal for:

  • first occurrence
  • first repeated character
  • first non-repeated character

Use reverse traversal for:

  • last occurrence
  • last non-repeated character

Order Preservation

Choose the collection based on the requirement.

HashMap

Useful when:

  • Only frequency matters.
  • Output order does not matter.

LinkedHashMap

Useful when:

  • Frequency is required.
  • First-appearance order must be retained.

HashSet

Useful when:

  • Only presence or absence matters.
  • You want to detect whether a character was already encountered.

Common Edge Cases

String character programs should be tested with meaningful boundary cases.

Empty String

Output
""

No character is available for frequency-based selection problems.

Single Character

Output
"a"

The character is:

  • unique,
  • non-repeated,
  • both most and least frequent.

All Same Characters

Output
"aaaa"

Frequency:

Output
a = 4

There is no non-repeated character.

All Unique Characters

Output
"javax"

Every character occurs once.

Spaces

For:

Output
"java code"

A space is also a char and will be processed unless explicitly ignored.

To ignore spaces:

Output
if (ch == ' ') {
    continue;
}

Case Sensitivity

Java character comparison is case-sensitive.

Therefore:

Output
'A' != 'a'

For:

Output
JavaJAVA

uppercase and lowercase versions are different characters unless the input is normalized first.

For case-insensitive logic, one possible preprocessing step is:

Output
str = str.toLowerCase();

Only do this when the problem explicitly says case should be ignored.

Interview-Focused Points

  • Understand the difference between character occurrence, frequency, duplicate, distinct, and unique.
  • Do not use nested loops automatically when a HashMap or HashSet can reduce O(n²) logic to average O(n).
  • Use LinkedHashMap when both frequency and insertion order matter.
  • Use StringBuilder when repeatedly constructing a result.
  • State how ties are handled in most-frequency and least-frequency problems.
  • Clarify whether spaces and special characters should participate.
  • Clarify whether character matching is case-sensitive.
  • Clarify whether positions are zero-based or one-based.
  • Do not use a Set when total frequency is required; a Set knows only whether a value exists.
  • Avoid sorting when the required answer depends on original character order.
  • For full Unicode correctness beyond individual Java char values, consider processing Unicode code points rather than UTF-16 code units.

Practice Variations

After understanding the basic problems, useful variations include:

  1. Count frequency without using Map.
  2. Find the second most frequent character.
  3. Find all characters having maximum frequency.
  4. Find all characters having minimum frequency.
  5. Find the nth non-repeated character.
  6. Find the nth repeated character.
  7. Remove duplicates without using Set.
  8. Remove duplicate characters while ignoring case.
  9. Replace only the first occurrence of a character.
  10. Replace only the last occurrence.
  11. Remove a character at a specific index.
  12. Sort uppercase and lowercase characters separately.
  13. Sort characters by frequency.
  14. Find positions of every distinct character.
  15. Count letters, digits, spaces, and special characters separately.
  16. Find consecutive repeated characters.
  17. Find the longest sequence of the same character.
  18. Find characters common to two strings.
  19. Find characters present in one string but not another.
  20. Rearrange characters based on their frequency.

Question Hint