Skip to main content

Command Palette

Search for a command to run...

Strings - Valid Anagram

Published
1 min read
Strings - Valid Anagram
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Valid Anagram

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

My approach:

  1. I used the concept of hashing.

  2. You can use hashmap or in this case just a simple array of size 26.

  3. Iterate through 's' string and update hash array by increasing the value of alphabets.

  4. Iterate through 't' string and update hash array by decreasing the value of alphabets.

  5. Iterate through hash array and,

    • if (arr[i]!=0) -> return false

    • else -> return true

Code:

// TIME COMPLEXITY : O(N)+O(N)
// SPACE COMPLEXITY : O(1)

class Solution {
public:
    bool isAnagram(string s, string t) {

        vector<int> arr(26,0);

        for(int i=0;i<s.size();i++){
            arr[s[i]-97]++;
        }

        for(int i=0;i<t.size();i++){
            arr[t[i]-97]--;
            if(arr[t[i]-97]<0){
                return false;
            }
        }

        for(int i=0;i<26;i++){
            if(arr[i]!=0){
                return false;
            }
        }

        return true;
    }
};

DSA prep

Part 15 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Strings - Rotate String

Rotate String Problem Link: https://leetcode.com/problems/rotate-string/description/ Hint: Use 'substr' method to change the string without actually modifying the string. Code: class Solution { public: bool rotateString(string s, string goal) { ...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.