Bird
Raised Fist0
DSA Javaprogramming~20 mins

Anagram Check Techniques in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Anagram Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Sorting-Based Anagram Check
What is the output of the following Java code that checks if two strings are anagrams by sorting their characters?
DSA Java
import java.util.Arrays;
public class Anagram {
    public static boolean isAnagram(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        char[] a1 = s1.toCharArray();
        char[] a2 = s2.toCharArray();
        Arrays.sort(a1);
        Arrays.sort(a2);
        return Arrays.equals(a1, a2);
    }
    public static void main(String[] args) {
        System.out.println(isAnagram("listen", "silent"));
        System.out.println(isAnagram("triangle", "integral"));
        System.out.println(isAnagram("apple", "pale"));
    }
}
A
true
false
false
B
false
true
false
C
true
true
false
D
false
false
true
Attempts:
2 left
💡 Hint
Think about what sorting characters does to the strings before comparing.
❓ Predict Output
intermediate
2:00remaining
Output of Frequency Count Anagram Check
What is the output of this Java code that checks if two strings are anagrams by counting character frequencies?
DSA Java
public class AnagramFreq {
    public static boolean isAnagram(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        int[] count = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            count[s1.charAt(i) - 'a']++;
            count[s2.charAt(i) - 'a']--;
        }
        for (int c : count) {
            if (c != 0) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.println(isAnagram("dusty", "study"));
        System.out.println(isAnagram("night", "thing"));
        System.out.println(isAnagram("hello", "bello"));
    }
}
A
true
true
false
B
false
true
false
C
true
false
false
D
false
false
true
Attempts:
2 left
💡 Hint
Check how the frequency array is updated for both strings simultaneously.
🔧 Debug
advanced
2:00remaining
Identify the Error in Anagram Check Using HashMap
What error will this Java code produce when checking if two strings are anagrams using a HashMap?
DSA Java
import java.util.HashMap;
public class AnagramMap {
    public static boolean isAnagram(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : s1.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (char c : s2.toCharArray()) {
            map.put(c, map.get(c) - 1);
        }
        for (int val : map.values()) {
            if (val != 0) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.println(isAnagram("abc", "cab"));
        System.out.println(isAnagram("abc", "cad"));
    }
}
ANullPointerException at map.get(c) when c not in map
BReturns false for all inputs
CReturns true for all inputs
DCompilation error due to missing imports
Attempts:
2 left
💡 Hint
Consider what happens when s2 contains a character not in s1.
🧠 Conceptual
advanced
2:00remaining
Time Complexity of Different Anagram Checks
Which option correctly ranks the time complexity of these anagram check methods from fastest to slowest for large strings of length n?
AHashMap counting (O(n)) > Frequency count (O(n)) > Sorting (O(n log n))
BSorting (O(n log n)) > Frequency count (O(n)) > HashMap counting (O(n))
CFrequency count (O(n)) > Sorting (O(n log n)) > HashMap counting (O(n))
DFrequency count (O(n)) > HashMap counting (O(n)) > Sorting (O(n log n))
Attempts:
2 left
💡 Hint
Consider that frequency count uses fixed-size arrays, HashMap uses hashing, and sorting is more expensive.
🚀 Application
expert
3:00remaining
Result of Anagram Grouping Using HashMap
Given the following Java code that groups a list of strings into anagrams, what is the printed output?
DSA Java
import java.util.*;
public class AnagramGroup {
    public static void main(String[] args) {
        String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
        Map<String, List<String>> map = new HashMap<>();
        for (String word : words) {
            char[] chars = word.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            map.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
        }
        System.out.println(map.values());
    }
}
A[[eat, tea], [tan, nat, ate], [bat]]
B[[eat, tea, ate], [tan, nat], [bat]]
C[[eat, tea, ate, bat], [tan, nat]]
D[[eat, tea, ate], [tan, nat], [bat, tan]]
Attempts:
2 left
💡 Hint
Anagrams share the same sorted character key in the map.

Practice

(1/5)
1. What does it mean if two strings are anagrams of each other?
easy
A. They end with the same character
B. They have the same length but different characters
C. They start with the same character
D. They contain the same characters in any order

Solution

  1. Step 1: Understand the definition of anagrams

    Anagrams are words or phrases made by rearranging the letters of another, using all original letters exactly once.
  2. Step 2: Compare character sets

    If two strings have the same characters with the same frequency, they are anagrams regardless of order.
  3. Final Answer:

    They contain the same characters in any order -> Option D
  4. Quick Check:

    Anagrams = same characters any order [OK]
Hint: Check if sorted strings match to confirm anagrams [OK]
Common Mistakes:
  • Thinking same length means anagrams
  • Only comparing first or last characters
  • Ignoring character frequency
2. Which Java code snippet correctly checks if two strings s1 and s2 are anagrams using sorting?
easy
A. char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); return Arrays.equals(a1, a2);
B. Arrays.sort(s1.toCharArray()); Arrays.sort(s2.toCharArray()); return s1.equals(s2);
C. return s1.equalsIgnoreCase(s2);
D. return s1.length() == s2.length();

Solution

  1. Step 1: Convert strings to char arrays and sort

    We must convert strings to char arrays because Arrays.sort works on arrays, not strings.
  2. Step 2: Compare sorted arrays for equality

    After sorting, if arrays are equal, strings are anagrams. Use Arrays.equals to compare arrays.
  3. Final Answer:

    char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); return Arrays.equals(a1, a2); -> Option A
  4. Quick Check:

    Sort char arrays and compare arrays [OK]
Hint: Sort char arrays, then compare with Arrays.equals [OK]
Common Mistakes:
  • Sorting strings directly without converting to char arrays
  • Using equals() on unsorted strings
  • Comparing only lengths
3. What will be the output of the following Java code?
String s1 = "listen";
String s2 = "silent";
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
System.out.println(Arrays.equals(a1, a2));
medium
A. Runtime exception
B. false
C. true
D. Compilation error

Solution

  1. Step 1: Convert and sort both strings

    Both strings "listen" and "silent" are converted to char arrays and sorted. Sorted arrays become ['e','i','l','n','s','t'] for both.
  2. Step 2: Compare sorted arrays

    Since sorted arrays are identical, Arrays.equals(a1, a2) returns true.
  3. Final Answer:

    true -> Option C
  4. Quick Check:

    Sorted arrays match = true [OK]
Hint: Sort and compare arrays to check anagrams [OK]
Common Mistakes:
  • Assuming order matters without sorting
  • Confusing equals() on strings with arrays
  • Forgetting to sort arrays
4. Identify the error in this Java method that checks if two strings are anagrams:
public boolean isAnagram(String s1, String s2) {
  if (s1.length() != s2.length()) return false;
  char[] a1 = s1.toCharArray();
  char[] a2 = s2.toCharArray();
  Arrays.sort(a1);
  Arrays.sort(a2);
  return a1.equals(a2);
}
medium
A. Using a1.equals(a2) compares references, not content
B. Missing length check before sorting
C. Sorting arrays is incorrect for anagram check
D. Method should return void, not boolean

Solution

  1. Step 1: Understand array equality in Java

    Using a1.equals(a2) compares if both arrays are the same object, not their contents.
  2. Step 2: Use correct method to compare arrays

    To compare contents, use Arrays.equals(a1, a2) instead of a1.equals(a2).
  3. Final Answer:

    Using a1.equals(a2) compares references, not content -> Option A
  4. Quick Check:

    Use Arrays.equals() for array content comparison [OK]
Hint: Use Arrays.equals() to compare array contents [OK]
Common Mistakes:
  • Using equals() on arrays instead of Arrays.equals()
  • Ignoring length check
  • Returning wrong data type
5. You want to check if two strings are anagrams but ignoring case and spaces. Which approach is best?
hard
A. Compare strings directly with equalsIgnoreCase()
B. Remove spaces, convert to lowercase, then sort and compare char arrays
C. Count characters without removing spaces or changing case
D. Check if lengths are equal and first characters match

Solution

  1. Step 1: Normalize strings by removing spaces and converting to lowercase

    Removing spaces and converting to lowercase ensures uniform comparison ignoring case and spaces.
  2. Step 2: Sort char arrays and compare

    After normalization, convert to char arrays, sort them, and compare to check anagram status.
  3. Final Answer:

    Remove spaces, convert to lowercase, then sort and compare char arrays -> Option B
  4. Quick Check:

    Normalize then sort and compare [OK]
Hint: Normalize strings before sorting to ignore case and spaces [OK]
Common Mistakes:
  • Not removing spaces before comparison
  • Ignoring case differences
  • Only comparing lengths or first characters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard