DSA Array | Valid Anagram

Problem Statement

Write a function that takes two strings, s and t, as input and determines whether they are anagrams of each other. Return true if the two strings are anagrams and false otherwise.

An anagram is defined as a string formed by rearranging the characters of another string, using all the original characters exactly once.

Example 1:

Input:
s = "listen", t = "silent"
Output:
true
Explanation: Both strings contain the same characters ('l', 'i', 's', 't', 'e', 'n') in different orders.

Example 2:

Input:
s = "hello", t = "world"
Output:
false
Explanation: The characters in s and t do not match exactly.

Code:
  
  	
class Solution {
    public boolean isAnagram(String s, String t) {
        Map <Character, Integer>
        map = new HashMap <>
        ();

        int n1 = s.length();
        int n2 = t.length();

        for (int i = 0; i < n1 ;i++){
            Character c = s.charAt(i);
            Integer count = map.getOrDefault(c, 0);
            count++;
            map.put(c, count);
        }

        for (int i = 0; i < n2; i++){
            Character c = t.charAt(i);
            Integer count = map.get(c);
            if (count == null) {
                return false;
            }

            count--;
            map.put(c, count);
        }

        return !map.values().stream().filter(i - > i != 0).findAny().isPresent();
    }
} 
  	
  
Time complexity: O(m+n)
Space complexity: O(1), because we can at most 26 characters

Comments

Popular posts from this blog

Spring-Boot externalize logback configuration file (logback-spring.xml)

Create Height Balanced BST from Sorted Linkedlist

Reverse LinkedList in K nodes group - Data Structure Linked List

Spring Cloud - Configuration Server with Git Integration

Finding Height Of A Binary Tree