Valid Anagram – LeetCode Problem Solution

Listen to this Post

URL:

https://lnkd.in/e2dX7EYz

Problem Description:

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

Example:

Input: `s = “anagram”`, `t = “nagaram”`

Output: `true`

Approach:

  1. If `s` and `t` have different lengths, return `false` immediately.
  2. Create an array `freq[26]` to store character frequencies.

3. Update Frequencies:

  • Iterate through both strings simultaneously.
  • Increment the count for `s[i]` and decrement for t[i].
  1. If all values in `freq` are zero, the strings are anagrams; otherwise, return false.

Practice Verified Code (Python):

def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
freq = [0] * 26
for i in range(len(s)):
freq[ord(s[i]) - ord('a')] += 1
freq[ord(t[i]) - ord('a')] -= 1
for count in freq:
if count != 0:
return False
return True

Practice Verified Code (Bash – Linux Command for String Comparison):

#!/bin/bash
s="anagram"
t="nagaram"
if [ $(echo $s | grep -o . | sort | tr -d '\n') == $(echo $t | grep -o . | sort | tr -d '\n') ]; then
echo "true"
else
echo "false"
fi

What Undercode Say:

The problem of determining whether two strings are anagrams is a classic example of string manipulation and frequency counting. By leveraging a frequency array, we can efficiently compare the character counts of both strings. This approach ensures optimal performance with a time complexity of O(n), where n is the length of the strings.

In Linux, string manipulation can be achieved using commands like grep, sort, and tr. For instance, the provided Bash script sorts the characters of both strings and compares them to determine if they are anagrams. This method is useful for quick checks in a terminal environment.

For further exploration of string manipulation in Python, refer to the official Python documentation:
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str

In addition, Linux users can explore advanced text processing using `awk` and `sed` for more complex string operations. For example, to count character frequencies in a file, you can use:

awk -F '' '{for(i=1;i<=NF;i++) freq[$i]++} END {for(char in freq) print char, freq[char]}' filename.txt

Understanding these concepts is crucial for solving similar problems in coding interviews and real-world applications. Practice these commands and codes to strengthen your skills in string manipulation and algorithmic thinking.

For more coding challenges and solutions, visit LeetCode:

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

Keep exploring, and happy coding!

References:

initially reported by: https://www.linkedin.com/posts/sana-afrin-830931341_leetcode-string-activity-7301289057832103936-cMqR – Hackers Feeds
Extra Hub:
Undercode AIFeatured Image