You are not logged in. Please login at to post your questions!


Grouping anagrams of strings together?

Given one array of strings, you have to sort the array such that anagrams should occur together. Below is my solution, can anyone tell me why this approach is not giving the correct answer.

 class Solution {

    public static void main(String[] args) {
        String s[] = new String[]{"abc", "arp", "bac", "cba", "pra", "apr"};
        Arrays.sort(s, new AnagramComparator());

    private static boolean isAnaGram(String s1, String s2) {
        int freq[] = new int[26];
        s1.chars().forEach(x -> freq[x - 'a']++);
        s2.chars().forEach(x -> freq[x - 'a']--);
        return Arrays
                .allMatch(x -> x == 0);

    static class AnagramComparator implements Comparator<String> {
        public int compare(String s1, String s2) {
            if (isAnaGram(s1, s2)) {
                return 0;
            return s1.compareTo(s2);

asked 19 Oct '18, 12:22

arpit728's gravatar image

accept rate: 10%

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 19 Oct '18, 12:22

question was seen: 32 times

last updated: 19 Oct '18, 12:22