242. Valid Anagram

RMAG news

Problem Statement

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = “anagram”, t = “nagaram”
Output: true

Example 2:

Input: s = “rat”, t = “car”
Output: false

Constraints

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters

Approach 1: Using Hashmap

This code utilizes a HashMap to track the occurrences of characters in one string and adjusts these counts based on the characters in the second string. By ensuring that all character counts become zero, it confirms if the strings are basic anagrams of each other.

class Solution {
public boolean isAnagram(String s, String t) {

Map<Character, Integer> mp = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
mp.put(ch, mp.getOrDefault(ch, 0) + 1);
}

for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
if (!mp.containsKey(ch) || mp.get(ch) == 0) {
return false;
}
mp.put(ch, mp.get(ch) – 1);
}

for (int count : mp.values()) {
if (count != 0) {
return false;
}
}

return true;

}
}

Runtime: 16ms

Approach 2: Using Arrays

import java.util.Arrays;

class Solution {
public boolean isAnagram(String s, String t) {
// Check if lengths are equal, if not, they can’t be anagrams
if (s.length() != t.length())
return false;

// Convert strings to character arrays
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();

// Sort character arrays
Arrays.sort(sChars);
Arrays.sort(tChars);

// Compare sorted character arrays
return Arrays.equals(sChars, tChars);
}
}

Runtime: 4ms

Approach 3: Hash Table (Using Array)

class Solution {
public boolean isAnagram(String s, String t) {
// Create an array to store the count of occurrences of each character (26 lowercase letters)
int[] count = new int[26];

// Iterate through the characters of string s
for (char x : s.toCharArray()) {
// Increment the count for the character ‘x’ (subtracting ‘a’ gives the index corresponding to ‘x’)
count[x – ‘a’]++;
}

// Iterate through the characters of string t
for (char x : t.toCharArray()) {
// Decrement the count for the character ‘x’ (subtracting ‘a’ gives the index corresponding to ‘x’)
count[x – ‘a’]–;
}

// Check if all counts in the array are zero
for (int val : count) {
if (val != 0) {
// If any count is not zero, return false indicating strings are not anagrams
return false;
}
}

// If all counts are zero, return true indicating strings are anagrams
return true;
}
}

Runtime: 2ms

Leave a Reply

Your email address will not be published. Required fields are marked *