DEV Community

Debesh P.
Debesh P.

Posted on

242. Valid Anagram | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/valid-anagram/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/valid-anagram/solutions/7490378/most-optimal-beats-200-in-interview-step-3cmn


leetcode 242


Solution

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

        if (s.length() != t.length()) return false;

        Map<Character, Integer> map = new HashMap<>();

        for (char c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        for (char c : t.toCharArray()) {
            if (!map.containsKey(c) || map.get(c) == 0) {
                return false;
            }
            map.put(c, map.get(c) - 1);
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)