DEV Community

Quipoin
Quipoin

Posted on

Anagram & Palindrome Problems Explained Simply in Java


String interview questions often look tricky…

But many of them are built on:

  • character counting
  • frequency matching
  • two-pointer logic

Anagram and palindrome problems are perfect examples.

1. Check if Two Strings are Anagrams

Two strings are anagrams if:

  • both contain the same characters
  • with the same frequency.

Example:

  • listen
  • silent

Efficient Approach

Use a frequency array.

public static boolean areAnagrams(String s1, String s2) {

if (s1.length() != s2.length())
    return false;

int[] freq = new int[26];

for (int i = 0; i < s1.length(); i++) {

    freq[s1.charAt(i) - 'a']++;
    freq[s2.charAt(i) - 'a']--;
}

for (int count : freq) {

    if (count != 0)
        return false;
}

return true;
Enter fullscreen mode Exit fullscreen mode

}

Why This Works

If both strings contain the same letters:

  • all frequencies cancel out to zero.

2. Group Anagrams

Given:

["eat", "tea", "tan", "ate"]

Output:

[["eat","tea","ate"], ["tan"]]

Smart Trick

Sort characters of each string.

Example:

  • eat → aet
  • tea → aet

Same sorted form:

  • same group.

public static List> groupAnagrams(String[] strs) {

Map<String, List<String>> map = new HashMap<>();

for (String s : strs) {

    char[] arr = s.toCharArray();

    Arrays.sort(arr);

    String key = new String(arr);

    map.computeIfAbsent(key,
        k -> new ArrayList<>()).add(s);
}

return new ArrayList<>(map.values());
Enter fullscreen mode Exit fullscreen mode

}

3. Palindrome Check

Palindrome:

  • reads same forwards & backwards.

Example:

  • madam
  • racecar

Two Pointer Technique

Compare:

  • left character
  • right character

Move inward until middle.

Most string interview problems are about:

  • counting characters
  • comparing efficiently
  • reducing repeated work
  • Anagrams → frequency matching
  • Grouping → hashing + sorting
  • Palindrome → two pointers

These problems may look basic…

But the same logic appears in advanced interview questions too

Explore More: https://www.quipoin.com/tutorial/data-structure-with-java/anagram-palindrome-problems

Top comments (0)