Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 242 · Hashing / Anagram

Valid Anagram

LeetCode 242 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

One frequency table: +1 for s, −1 for t, all zeros at the end.

ಸುಲಭHash TableStringSorting
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Valid Anagram (LeetCode 242) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Hashing / Anagram ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Two strings are anagrams when every letter appears the same number of times in both. Count letters of s up and letters of t down in one 26-slot table; if every slot ends at zero, the counts match.

Approach

  1. 1

    Different lengths can't be anagrams.

  2. 2

    Map each letter to an index 0–25 with ord(c) − ord('a').

  3. 3

    Increment for s[i], decrement for t[i] in the same loop.

  4. 4

    Return True if every count is zero.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Frequency tablePythonO(n) time · O(1) space
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s)!=len(t):
            return False
        n = len(s)
        freq_table = [0]*26
        for i in range(n):
            char1 = s[i]
            char2 = t[i]
            """
            ord(a) = 97
            ord(b) = 98
            ord('a') - ord('a') =0
            ord('b') - ord('a') = 1
            ord('c') - ord('a') = 2
            """
            freq_table[ord(char1)-ord('a')]+=1
            freq_table[ord(char2)-ord('a')]-=1
        return all(x==0 for x in freq_table)
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Valid Anagram — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Valid Anagram ಹಿಂದಿನ intuition ಏನು?

Two strings are anagrams when every letter appears the same number of times in both. Count letters of s up and letters of t down in one 26-slot table; if every slot ends at zero, the counts match.

Valid Anagram (LeetCode 242) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Different lengths can't be anagrams. 2. Map each letter to an index 0–25 with ord(c) − ord('a'). 3. Increment for s[i], decrement for t[i] in the same loop. 4. Return True if every count is zero.

Valid Anagram ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(1) — 26 counters. (Accepted approach: Frequency table.)

Valid Anagram ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Unicode input would need a dict instead of a fixed 26-slot array.