LeetCode 242. Valid Anagram Solution Explained - Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 14 ม.ค. 2025
  • The Best Place To Learn Anything Coding Related - bit.ly/3MFZLIZ
    Join my free exclusive community built to empower programmers! - www.skool.com/...
    Preparing For Your Coding Interviews? Use These Resources
    --------------------
    (My Course) Data Structures & Algorithms for Coding Interviews - thedailybyte.d...
    AlgoCademy - algocademy.com...
    Daily Coding Interview Questions - bit.ly/3xw1Sqz
    10% Off Of The Best Web Hosting! - hostinger.com/...
    Follow Me on X/Twitter - x.com/nickwhit...
    Follow My Instagram - / nickwwhite
    Other Social Media
    ----------------------------------------------
    Discord - / discord
    Twitch - / nickwhitettv
    TikTok - / nickwhitetiktok
    LinkedIn - / nicholas-w-white
    Show Support
    ------------------------------------------------------------------------------
    Patreon - / nick_white
    PayPal - paypal.me/nick....
    Become A Member - / @nickwhite
    #coding #programming #softwareengineering

ความคิดเห็น • 57

  • @babumon5351
    @babumon5351 5 ปีที่แล้ว +20

    Thanks. You are really good in algorithms..

  • @philbowden
    @philbowden 4 ปีที่แล้ว +96

    Starting your video with "this is one of the easiest problems," tends to be a bit of a turn off. If the problem was easy for your viewers we would not be viewing your tutorial.

    • @oingomoingo7411
      @oingomoingo7411 3 ปีที่แล้ว +12

      haha i also thought that

    • @stepbystepcoding4113
      @stepbystepcoding4113 3 ปีที่แล้ว +4

      @@oingomoingo7411 me too

    • @carguy-xv2cl
      @carguy-xv2cl 3 ปีที่แล้ว +12

      Exactly, sounds so arrogant.

    • @vivekmishra641
      @vivekmishra641 2 ปีที่แล้ว +1

      True

    • @Gazeld
      @Gazeld 2 ปีที่แล้ว +7

      @@carguy-xv2cl It's not, and you know it. It simply means there are far more difficult problems.

  • @sheriffcrandy
    @sheriffcrandy 2 ปีที่แล้ว +11

    I understand that char 'a' is the ACSII symbol whose value is 97, but how does this
    for (int i = 0; i < s.length(); i++) {
    characterCount[s.charAt(i) - 'a']++;
    characterCount[t.charAt(i) - 'a']--;
    }
    check for anagrams? Why can't I use any other ACSII symbol char like 'b' or 'c'?

    • @Gazeld
      @Gazeld 2 ปีที่แล้ว +12

      In the first line, we store in char_count array the number of occurences of each letter encountered in string s : each time we encounter a 'a', the content of char_count[0] is increased.
      In the second line, we do almost the same for string t, but decreasing the same element in the array.
      This way if the number of occurences of a letter in t is the same as in s, the corresponding count in char_count[] must be 0.
      And if this is true for all the letters (all the elements of the array are 0), that means we have an anagram, because neither of s or t has more occurences of a letter.
      "Why can't I use any other ACSII symbol char like 'b' or 'c'?" : 'a' here is taken as the basis, since this is the first letter in the alphabet, so taking the ascii value of any letter and substracting the ascii code of 'a' from it will give us 0-25, the perfect indexes for our array to store our letter count of occurrences.

    • @tamilchad6165
      @tamilchad6165 2 ปีที่แล้ว

      @@Gazeld each time we encounter a 'a', the content of char_count[0] is increased. which means char_count[1] and after another encounter it becomes char_counter[2]??

    • @ruben5233
      @ruben5233 ปีที่แล้ว +10

      I know this is old but here it goes:
      If we look at the ASCII table, the decimal value for 'a' is 97, 'b' 98 and so on until 'z' which is 122.
      If we were to store the characters count with these indexes, we would need an int[] array of size 123 and we would not be using indexes 0 to 96. So by subtracting 97('a') to each character's decimal value, we ensure we only use indexes 0 to 25 (thus an int array of size 26).
      'a' = 97 - 97 = 0
      'b' = 98 - 97 = 1
      .
      .
      'z' = 122 - 97 = 25
      Now, at these positions, we increment by one how many times we see a character for S and decrement its value every time we see the character in T. In the end if they are anagrams we should have 0 at every position. If we have -1, -2, 1, 2, 3 or any other number it means we have more occurrences of a letter in either of the Strings and they are not anagrams.

  • @Kitchen-Raccoon4572
    @Kitchen-Raccoon4572 4 ปีที่แล้ว +7

    Thank you Mr. White always appreciated

  • @ritchievales
    @ritchievales 2 ปีที่แล้ว +9

    I solved it by using two hashmaps and three for loops.... feeling so stupid after seeing this solution 😢

    • @robertcole3260
      @robertcole3260 3 หลายเดือนก่อน

      I did the same exact thing lol.

  • @isaacli8376
    @isaacli8376 2 ปีที่แล้ว +2

    very clear and simple solution, thank you!

  • @saiavinashduddupudi8975
    @saiavinashduddupudi8975 5 ปีที่แล้ว +5

    What is the space complexity here?

    • @danw6922
      @danw6922 4 ปีที่แล้ว +9

      I think the space complexity is O(1), because although it uses an int array, but it's fix sized (26 integer).This int array does not change its size when string grows.

    • @mosbahhoucemeddine1147
      @mosbahhoucemeddine1147 2 ปีที่แล้ว

      @@danw6922 no i think O(n) because no matter is the size ..if the size is 2 it is also n

    • @Gazeld
      @Gazeld 2 ปีที่แล้ว

      @@mosbahhoucemeddine1147 No, it would be O(n) if the size was depending on the size of the strings ; here the size of the array does not depend on anything.

  • @billynader0
    @billynader0 2 ปีที่แล้ว +3

    Hi, when I saw the solution, at first I did not get it until I watched your solution
    I solved it with HasMap run time and memory was too high

  • @maksymr.7191
    @maksymr.7191 2 ปีที่แล้ว

    Thank you, my friend. That's what I need now to survive.

  • @samj9822
    @samj9822 8 หลายเดือนก่อน

    Can we create StringBuilder for t and start removing one (only) character for each character in s. If StringBuilder is left with zero element then return true.

  • @ronyEdits110
    @ronyEdits110 ปีที่แล้ว

    the code showing wrong answer when you check for the input rat and car

  • @kathaigal27
    @kathaigal27 ปีที่แล้ว

    Sort them and check if they are equal or not

  • @syed_4138
    @syed_4138 ปีที่แล้ว

    Well one of the easiest solution i came across thank you.

  • @shiyangnie6738
    @shiyangnie6738 3 ปีที่แล้ว +7

    Still confused about the char_count[s.charAt(i)-'a'] and the char_count[t.charAt(i)-'a'];

    • @akshatpahwa534
      @akshatpahwa534 3 ปีที่แล้ว +1

      Read about ASCII values.

    • @sheriffcrandy
      @sheriffcrandy 2 ปีที่แล้ว

      @@maxlievikoff2162 I still don't get it. how does
      char_count[s.charAt(i)-'a']++;
      and
      char_count[t.charAt(i)-'a']--;
      check for anagrams?

    • @Gazeld
      @Gazeld 2 ปีที่แล้ว

      @@sheriffcrandy In the first line, we store in char_count array the number of occurences of each letter encountered in string s : each time we encounter a 'a', the content of char_count[0] is increased.
      In the second line, we do almost the same for string t, but *decreasing* the same element in the array.
      This way if the number of occurences of a letter in t is the same as in s, the corresponding count in char_count[] must be 0.
      And if this is true for all the letters (all the elements of the array are 0), that means we have an anagram, because neither of s or t has more occurences of a letter.

  • @sachitdalwadi
    @sachitdalwadi ปีที่แล้ว

    Very help full I wish I could support you more than I can

  • @debdijmazumder7182
    @debdijmazumder7182 2 ปีที่แล้ว

    would a hashmap be more or less efficient?

    • @Hrit
      @Hrit 2 ปีที่แล้ว

      I used a HashMap too, it would be same, either way it is going to take O(1) for incrementing and decrementing the count. Apart from that, if you do it in 2 traversals (i.e one traversal for incrementing and decrementing and other one for checking) - time complexity is O(n).

  • @ericsodt
    @ericsodt 2 ปีที่แล้ว

    ("Hello", "hello") leads to indexOutOfBoundsException. The capital 'H' is the issue here.

    • @mohamedsayed8697
      @mohamedsayed8697 2 ปีที่แล้ว

      Check leetcode description it says the input string is lowercase only, so this solution is valid for lowercase cases only.

  • @sanchit537
    @sanchit537 2 ปีที่แล้ว +5

    Good solution bad explanation. Where's my Indian guy explaining iteration at?

  • @stoiandelev12345678
    @stoiandelev12345678 ปีที่แล้ว

    interesting approach :)

  • @chandanvishwakarma9203
    @chandanvishwakarma9203 4 ปีที่แล้ว

    Thanks bro!

  • @jacobodoyo2793
    @jacobodoyo2793 2 ปีที่แล้ว

    just learned the code

  • @zihaoyan4741
    @zihaoyan4741 2 ปีที่แล้ว +2

    I tried using Hashmap but got me 24ms, time complexity I beleive was O(m+n). that is the best I could do if this is a interview question...LoL. Never would have come up with this solution.

  • @Witch_Quiz
    @Witch_Quiz ปีที่แล้ว

    thank

  • @george_998
    @george_998 ปีที่แล้ว

    perfect

  • @patrakarpopatlaltoofanexpr3258
    @patrakarpopatlaltoofanexpr3258 3 ปีที่แล้ว +6

    "MOST EASIEST SOLUTION"
    class Solution {
    public boolean isAnagram(String s, String t) {
    if(s.length()!=t.length()){
    return false;
    }
    char[] st_s=s.toCharArray();
    char[] st_t=t.toCharArray();
    Arrays.sort(st_s);
    Arrays.sort(st_t);
    for(int i=0;i

    • @Donkle365
      @Donkle365 2 ปีที่แล้ว +1

      but it's more complex than the solution of the video

    • @karanaa1093
      @karanaa1093 2 ปีที่แล้ว +1

      @@Donkle365 no not at all. Its just checking if the arrays from each string are equal.

    • @karthikprabhu_career
      @karthikprabhu_career 2 ปีที่แล้ว +2

      Thank you Popatlal !! Your code is pretty easy to understand

    • @patrakarpopatlaltoofanexpr3258
      @patrakarpopatlaltoofanexpr3258 2 ปีที่แล้ว +2

      @@karthikprabhu_career Thanks Karthik,
      Long code ko kaho cancel, cancel, cancel !

    • @mosbahhoucemeddine1147
      @mosbahhoucemeddine1147 2 ปีที่แล้ว

      blh bara nayek

  • @Impromptu21
    @Impromptu21 4 ปีที่แล้ว

    Why dont sort both strings and compare if they both r same ..return true if it is else false

    • @woodendscott
      @woodendscott 4 ปีที่แล้ว +2

      If you sort best case time complexity is O(n log n). The solution provided here is O(n)

    • @vishwaskhurana1217
      @vishwaskhurana1217 3 ปีที่แล้ว

      @@Godsu0417 hahahahah

  • @lokanadhamc3827
    @lokanadhamc3827 3 ปีที่แล้ว +1

    i think you should have submit the code to see all testcase passed or not

  • @amerelsayed
    @amerelsayed 2 ปีที่แล้ว

    java.lang.ArrayIndexOutOfBoundsException: Index 13 out of bounds for length 1
    at line 12, Solution.isAnagram
    at line 54, __DriverSolution__.__helper__
    at line 87, __Driver__.main
    this exception is happen

  • @jamsranjavodgerel803
    @jamsranjavodgerel803 2 ปีที่แล้ว

    Thanks for the video