Tutorialspoint
Problem
Solution
Submissions

Valid Anagram

Certification: Basic Level Accuracy: 60% Submissions: 15 Points: 5

Write a Java program to check if two strings are anagrams of each other.

Example 1
  • Input: s = "listen", t = "silent"
  • Output: true
  • Explanation:
    • Same characters with same frequencies
Example 2
  • Input: s = "hello", t = "world"
  • Output: false
  • Explanation:
    • Different character sets and frequencies
Constraints
  • 1 ≤ s.length, t.length ≤ 5 * 10^4
  • s and t consist of lowercase English letters
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsAccentureDeloitte
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider that anagrams must have the same characters with the same frequency
  • You can use an array of size 26 to count the frequency of each character in both strings
  • Remember to check if the lengths of both strings are equal first
  • A frequency table or hash map can be used to count occurrences of each character

Steps to solve by this approach:

 Step 1: Check if the lengths of both strings are equal. If not, they cannot be anagrams.
 Step 2: Create a frequency array of size 26 (for lowercase English letters).
 Step 3: Increment the count for each character in the first string.
 Step 4: Decrement the count for each character in the second string.
 Step 5: If any count becomes negative during step 4, return false.
 Step 6: If we complete the process without returning false, return true.
 Step 7: Time complexity is O(n) where n is the length of the strings.

Submitted Code :