string/Array : gfg and other selected Ques Level Wise

                           Basics and Easy Level


cout<<'B'-'A';    => 1
cout<<'C'-'A';    =>2

Given a string check if it is Pangram or not:  A pangram is a sentence containing every letter(at least once) in the English Alphabet.
The best-known English pangram is “The quick brown fox jumps over the lazy dog.”

// Returns true if the string is pangram else false
bool checkPangram(string& str)
{
    // Create a hash table to mark the characters
    // present in the string
    vector<bool> mark(26false);
 
    // For indexing in mark[]
    int index;
 
    // Traverse all characters
    for (int i = 0; i < str.length(); i++) {
 
        // If uppercase character, subtract 'A'
        // to find index.
        if ('A' <= str[i] && str[i] <= 'Z')
            index = str[i] - 'A';
 
        // If lowercase character, subtract 'a'
        // to find index.
        else if ('a' <= str[i] && str[i] <= 'z')
            index = str[i] - 'a';
 
        // If this character is other than english
        // lowercase and uppercase characters.
        else
            continue;
 
        mark[index] = true;
    }
 
    // Return false if any character is unmarked
    for (int i = 0; i <= 25; i++)
        if (mark[i] == false)
            return (false);
 
    // If all characters were present
    return (true);
}

(char)(2+'a') => 'c'

c++ inBuilt to check alphabet and digit: 

isalpha(str[i])

isdigit(str[i])
punctuations:    !"#$%&'()*+,-./:;?@[\]^_`{|}~ 


        // check whether parsing character is punctuation or not

ispunct(str[i]) => but it returns int mostly 16


Delete char in string at given index:

s.erase(i,1);


Quick way to check if all the characters of a string are same:


Quick Way (Not time complexity wise, but in terms of number of lines of code)
bool allCharactersSame(string s)
{
    return (s.find_first_not_of(s[0]) == string::npos);
}

remember:

toupper(s[i]) => returns ASCII value After Converting to upperCase

tolower(s[i]) => returns ASCII value After Converting to lowerCase

ASCII value to char : (char) ASCII_value or char(ASCII_value)

मतलब uppercase me बदलने ke liye:


char(toupper('a'));

char to ASCII value: (int) 'A' or int('A')


Attention: '0' and '5' is char

 int('0') =>48, (ASCII value)

                              int('5') =>> 53, (ASCII value)

but num char to int ke liye: e.g. '5'-'0' =>5

Ascii Values

  • For capital alphabets 65 – 90
  • For small alphabets 97 – 122
  • For digits 48 – 57

number to string:

string s= to_string(num);

string to num:

  int num=stoi(s);

note: char* ke case me atoi() use krna

intersection of two vector:


vector<int> v3;

sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());

set_intersection(v1.begin(),v1.end(),
                 v2.begin(),v2.end(),
                 back_inserter(v3));


lexicographically sort string:


sort(s.begin(),s.end());


Find one extra character in a string:

Given two strings which are of lengths n and n+1.
Input : string strA = "abcd";
        string strB = "cbdae";
Output : e
string B contain all the element 
there is a one extra character which is e

char findExtraCharcter(string strA, string strB)
{
    // store string values in map
    unordered_map<charint> m1;
 
    // store second string in map with frequency
    for (int i = 0; i < strB.length(); i++)
        m1[strB[i]]++;
 
    // store first string in map with frequency
    for (int i = 0; i < strA.length(); i++)
        m1[strA[i]]--;
 
    for (auto h1 = m1.begin(); h1 != m1.end(); h1++) {
 
        // if the frequency is 1 then this
        // character is which is added extra
        if (h1->second == 1)
            return h1->first;
    }
}




find in C++:

 ele search in vector:

int ser = 30;
      
    // std::find function call
    it = std::find (vec.begin(), vec.end(), ser);
    if (it != vec.end())
    {
        std::cout << "Element " << ser <<" found at position : " ;
        std::cout << it - vec.begin() << " (counting from zero) \n" ;
    }
    else
        std::cout << "Element not found.\n\n";

it to find occurrence of a character in striing:
    string str = "geeksforgeeks a computer science";
    char c = 'g';
  
    // Find first occurrence of 'g'
    size_t found = str.find(c);
    if (found != string::npos)
        cout << "First occurrence is " << found << endl;
  
    // Find next occurrence of 'g'
    found = str.find(c, found+1);
    if (found != string::npos)
        cout << "Next occurrence is " << found << endl;
Output:
First occurrence is 0
Next occurrence is 8
it to find occurrence of a string in sentence:
string str = "geeksforgeeks a computer science";
    string str1 = "geeks";
  
    // Find first occurrence of "geeks"
    size_t found = str.find(str1);
    if (found != string::npos)
        cout << "First occurrence is " << found << endl;
  
    // Find next occurrence of "geeks". Note here we pass
    // "geeks" as C style string.
    char arr[] = "geeks";
    found = str.find(arr, found+1);
    if (found != string::npos)
        cout << "Next occurrence is " << found << endl;

Output:
0

  string removeOuterParentheses(string s) {
        
        stack<char> st;
  
        string ans="";
        
        for(int i=0;i<s.length();i++){
            
            if(s[i]==')') st.pop();
            if(!st.empty()) ans.push_back(s[i]);
                        
            if(s[i]=='(')    st.push(s[i]);
            
            
            
        }
        return ans;
        
    }

remove All adjacent duplicates from string:

Input: azxxzy 
Output: ay 
First “azxxzy” is reduced to “azzy”. 
The string “azzy” contains duplicates, 
so it is further reduced to “ay”.

Input: geeksforgeeg 
Output: gksfor 
First “geeksforgeeg” is reduced to 
“gksforgg”. The string “gksforgg” 
contains duplicates, so it is further 
reduced to “gksfor”.

Input: caaabbbaacdddd 
Output: Empty String

Input: acaaabbbacdddd 
Output: acac 


following code are in exception:


int main(){
    string s;
    cin>>s;
  
    stack<char> st;
    string ans="";
    for(int i=0;i<s.length();i++){
      
      if(st.empty()){
            st.push(s[i]); continue;
      }
      if(st.top()==s[i])  st.pop();
      else st.push(s[i]);
    }

      while(!st.empty()){
         ans=st.top()+ans;
         st.pop();
      }
      cout<<ans;
 
  return 0;
}

Longest Common Prefix in an Array:


  //helper func 
    string lcp(string arr[],string prefix,int idx,int n){
        // base case
        if(idx==nreturn prefix
        
        string tmp=arr[idx];
        string newPrefix;
        int i=0,j=0,n1=prefix.length(),n2=tmp.length();
        
        while(i<n1 && j<n2){
            if(prefix[i]!=tmp[j]break;
            newPrefix.push_back(tmp[j]);
            i++; j++;
        }
        
        string ans=lcp(arr,newPrefix,idx+1,n);
        return ans.length()?ans:"-1";
    }

    string longestCommonPrefix (string arr[], int n)
    {
          string prefix=arr[0];
         return lcp(arr,prefix,1,n);
    }
gfg Roman Number to Integer
    int romanToDecimal(string &s) {
       
       unordered_map<char,int> mp;
       mp['I']=1; mp['V']=5;mp['X']=10,mp['L']=50;mp['C']=100;mp['D']=500;mp['M']=1000;
       
       int ans=mp[s[0]];
       for(int i=1;i<s.length();i++){
           if(mp[s[i]]>mp[s[i-1]]){
               ans=ans-2*mp[s[i-1]]+mp[s[i]];
           }
           else ans+=mp[s[i]];
       }
       return ans;
       
       

    } 

Find a peak element

Example:

Input: array[]= {5, 10, 20, 15}
Output: 20
The element 20 has neighbours 10 and 15,
both of them are less than 20.

Input: array[] = {10, 20, 15, 2, 23, 90, 67}
Output: 20 or 90
The element 20 has neighbours 10 and 15, 
both of them are less than 20, similarly 90 has neighbours 23 and 67.
condition: Time Complexity: O(Logn)  :Binary Search (divide & conquer)
  int peak(int* a,int l,int r,int n){  // here we return only index 
    // single ele array
    if(n==1return 0;
    int mid=l+(r-l)/2;
    
    //check for  first ele
    if(mid==0){
        if(a[0]>a[1]) return mid;
        else return peak(a,1,r,n);
    }
    //check for  last ele
    else if(mid==n-1){
        if(a[n-1]>a[n-2]) return mid;
        else return peak(a,l,mid+1,n);
    }
    else if(mid>0&&mid<n-1)
    {    if(a[mid-1]<=a[mid] && a[mid]>=a[mid+1]) return mid;
         else if(a[mid-1]>a[mid]) return peak(a,l,mid-1,n);
         else return peak(a,mid+1,r,n);
    }
    return -1;



Find subarray with given sum

(Handles Negative Numbers)


sare subarray nikalne ki jarurat nhi



vector<intsubarraySum(int arr[], int nint sum)
    {
         int start=0;
         int end=-1;
         int curr_sum=0;
         unordered_map<int,int> mp;
         vector<int> v;
         for(int i=0;i<n;i++){
             curr_sum+=arr[i];
             if(curr_sum==sum){
                 end=i;
                 v.push_back(start+1);
                 v.push_back(end+1);
                  return v;
             }
             // if curr_sum-sum key is present 
             if(mp.find(curr_sum-sum)!=mp.end()){
                 start=mp[curr_sum-sum]+1;
                 end=i;
                 v.push_back(start+1);
                 v.push_back(end+1);
                 return v;
             }
             mp[curr_sum]=i;
         }
         v.push_back(end);
         return v;  
         
    }


Find subarray with given sum (Nonnegative Numbers)

    vector<intsubarraySum(int arr[], int nint sum)
    {
         int start=0;
         int end=-1;
         int curr_sum=0;
         vector<int> v;
    /* Add elements one by one to curr_sum and
    if the curr_sum exceeds the sum,
    then remove starting element */
         for(int i=0;i<n;i++){
             curr_sum+=arr[i];
       // If curr_sum exceeds the sum,
        // then remove the starting elements
            while(curr_sum>sum && start<i){
                 curr_sum=curr_sum-arr[start];
                 start++;
             }
             
             if(curr_sum==sum){
                 end=i;
                 v.push_back(start+1);  // add one for pos purpose
                 v.push_back(end+1);
                 return v;
             }
             

             
         }
         v.push_back(end);
         return v;

    }

copy ele one array to another array:

    // Copy contents of temp[] to arr[]
    memcpy(arr, temp, sizeof(temp));

Subarrays with equal 1s and 0s:




    long long int countSubarrWithEqualZeroAndOne(int a[], int n)
    {
        for(int i=0;i<n;i++){
            if(a[i]==0a[i]=-1;
        }
        
        unordered_map<int,int> mp;
        long long int curr_sum=0;
        long long int count=0;
        for(int i=0;i<n;i++){
            curr_sum+=a[i];
            if(curr_sum==0) count++;
            mp[curr_sum]++;
        }
        
        for(auto it:mp){
            int freq=it.second;
            if(freq>1) count+=(freq*(freq-1)/2);
        }
        return count;
    }

gfg Subarray with 0 sum exist or not

    bool subArrayExists(int arr[], int n)
    {
      unordered_map<int,int> mp;
      
      int curr_sum=0;
      
      for(int i=0;i<n;i++){
          curr_sum+=arr[i];
          if(curr_sum==0 || mp.find(curr_sum-0)!=mp.end() ) return true;
//e.g. 4 2 -3 1 6 me 1 tk curr_sum=> 4, lekin map me
// curr_sum-0 phle aa chuka hai (4), iska mtlb beech me khi
//0 hokar yah fir se 4 bn gya
          mp[curr_sum]++;
      }
      return false;

    }

Kadane's Algorithm: Largest sum contiguous Subarray 

1,2,3,-2,5  => ans is 9
-1,-2,-3,-4  => ans is -1
//approach:
// do variable lekar chalna hai 
   // 1. max_sum =INT_MIN;  yhi hamara ans dega
   // 2.temp_sum=0;  isko har bar arr[i] ke saath add krenge , ydi yah max_sum se jyada to max_sum update 
// lekin jahan temp_sum ki value -ve ho gyi, temp_sum ko bhi update as 0;
    int maxSubarraySum(int arr[], int n){
        
       int max_sum=INT_MIN;
       int temp_sum=0;
       for(int i=0;i<n;i++){
        temp_sum+=arr[i];
        if(temp_sum>max_sum) max_sum=temp_sum;
        if(temp_sum<0) temp_sum=0;
       }
       return max_sum;
        
    }

Move all -ve ele to end:

extra space allowed

        vector<int> v1;
        vector<int> v2;
        for(int i=0;i<n;i++){
            if(arr[i]>=0) v1.push_back(arr[i]);
            else v2.push_back(arr[i]);
        }
      
      for(int i=0;i<v1.size();i++) arr[i]=v1[i];
      for(int i=v1.size();i<n;i++) arr[i]=v2[i-v1.size()];

extra space not allowed

void rearrange(int arr[], int n)
{
  int j = 0;
  for (int i = 0; i < n; i++) {
    if (arr[i] > 0) {
      if (i != j)
        swap(arr[i], arr[j]);
      j++;
    }
  }
}

useful in missing no: XOR concept


gfg Count pairs with given sum

    int getPairsCount(int arr[], int nint summ) {
        // code here
        unordered_map<int,int> m;
        int twc=0 ;// twice count
        for(int i=0;i<n;i++) m[arr[i]]++;
        
        for(int i=0;i<n;i++){
            twc+=m[summ-arr[i]];
            if(summ-arr[i]==arr[i]) twc--;
        }
        return twc/2;
    }


effucient method in one loop:
    unordered_map<intint> m;
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (m.find(k - arr[i]) != m.end()) {
            count += m[k - arr[i]];
        }
        m[arr[i]]++;
    }
    return count;

gfg Find duplicates in an array


    vector<intduplicates(int arr[], int n) {
        
        unordered_map<int,int> mp;

        // store all ele count
        for(int i=0;i<n;i++) mp[arr[i]]++;
        
        vector<int> v;
        
        // store whose count>1 , in serial according to arr
        for(int i=0;i<n;i++){
            if(mp[arr[i]]>1){
                v.push_back(arr[i]);
                mp[arr[i]]=0;
            }
        }
        sort(v.begin(),v.end());
        if(!v.size()) v.push_back(-1);
        
        return v;
    }

   Remove duplicate elements in an unsorted array:(extra space)


// Hash map which will store the elements which has appeared previously.
    unordered_map<intbool> mp;

    for (int i = 0; i < n; ++i) {

// Print the element if it is there in the hash map
    if (mp.find(arr[i]) == mp.end()) {
// same as array order
        cout << arr[i] << ” “;// ya to vector me push kr lo
    }

// Insert the element in the hash map
    mp[arr[i]] = true;
    }

 remove duplicate elements in an sorted array:



 reverse an array or string: same concept

  while (start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }

gfg common elements in three sorted arrays


       vector <int> commonElements (int A[], int B[], int C[], int n1int n2int n3)
        {
          int i=0,j=0,k=0;
          
          unordered_map<int,int> mp;
          
          while(i<n1 && j<n2 && k<n3){
              
              
              if(A[i]==B[j] && B[j]==C[k]){
                    mp[A[i]]++;
                  i++; j++; k++;
              }
           
              else if(A[i]<B[j]) i++;
              else if(B[j]<C[k]) j++;
              else k++;
          }
          vector<int> v;
          // store ele as in arr order
          for(int i=0;i<n1;i++){
              if(mp[A[i]]>0){
                  v.push_back(A[i]);
                  mp[A[i]]=0;
              }
          }
          return v;
        }

gfg Alternate positive and negative numbers

    void rearrange(int arr[], int n) {
        
        vector<int> v1;
        vector<int> v2;
        for(int i=0;i<n;i++){
            if(arr[i]>=0) v1.push_back(arr[i]);
            else v2.push_back(arr[i]);
        }
        int n1=v1.size(),n2=v2.size();
        int i=0,j=0;
        int idx=0;
        while(i<n1 && j<n2){
            if(idx&1arr[idx++]=v2[j++]; // odd index 
            else arr[idx++]=v1[i++];
            
        }
        while(i<n1){
            arr[idx++]=v1[i++];
        }
        while(j<n2){
            arr[idx++]=v2[j++];
        }
        
    }

Factorials of large numbers:


class Node{
    public:
     int data;
     Node* prev;
     Node(int val){
         data=val;
         prev=NULL;
     }
         
};
  void multiply(Node** tail_ref,int i){
      Node* tmp=*tail_ref;   //tmp at tail
      Node* prevNode=tmp;
      int carry=0;

    // tmp move backward till it exist
    while(tmp){
      int multiply_ans=tmp->data * i+carry;
      int last_digit= multiply_ans%10;
      carry=multiply_ans / 10;
      tmp->data=last_digit;
      prevNode=tmp;
      tmp=tmp->prev; // tmp move backward
      
    }
    // if carry left 
    while(carry){
      int last_digit= carry%10;
      Node* newNode=new Node(last_digit);
      prevNode->prev=newNode;
      prevNode=prevNode->prev; // move prevNode backward
      carry=carry/10
    }

  }
  
  vector<int> v;
  void push_in_rev(Node* tail){
      if(!tailreturn;
      push_in_rev(tail->prev);
    //   cout<<tail->data<<" ";
      v.push_back(tail->data);
  }

    vector<intfactorial(int N){
         // create first Node as tail
        
         Node* tail=new Node(1);
         for(int i=2;i<=N;i++)  multiply(&tail,i);
         
         // push all data in vector in rev order 
          push_in_rev(tail);
        
        return v;
      
    }


Array rotation by k times:



     int n,k;
      cin>>n>>k;
      k=k%n;
      vector<int> v1,v2;
      for(int i=0;i<n;i++){
          int x; cin>>x;
        if(i>=(n-k)) v2.push_back(x);
        else v1.push_back(x);
      }
      for(auto x:v2) cout<<x<<" "
      for(auto x:v1) cout<<x<<" ";
      cout<<endl;











substrings:

generate all substrings :
abcd ke liye:
a
a
ab
abc
abcd       // start a ke liye max_length=4
b
bc
bcd         //start  b ke liye max_length=3        
c
cd            // start c ke liye max_length=2
d               // start d ke liye max_length=1

 int n=s.size();

  // select starting 
 for(int i=0;i<n;i++){
  
  //select length as 1,2,3,....upto max_length
   int max_length=n-i;
  for(int len=1;len<=max_length;len++){

    cout<<s.substr(i,len)<<endl;
 
  }
 }

in above s.substr(i,len) is nothing but below code
      for(int k=i;k<i+len;k++){
        cout<<s[k];
      }

all substrings of length 3:

 for(int i=0;i<=n-3;i++){
  
    cout<<s.substr(i,3)<<endl;
 }

                                          or

 for(int i=0;i<=n-3;i++){
    
    for(int j=i;j<i+3;j++){
      cout<<s[j];
    }
    cout<<endl;
 }



  int countGoodSubstrings(string s) {
         
        if(s.size()<3return 0;
        
          int count;
        
        for(int i=0;i<s.size()-2;i++){
            unordered_set<char> sett;
            for(int j=i;j<i+3;j++){
               sett.insert(s[j]);
            }
             if(sett.size()==3) count++;
        }
       return count; 
    }

                                                          or 
int countGoodSubstrings(string s) {

    string str;
    int count=0;
    int l=s.length();
    
    if(l<=2)
    {
        return count;
    }
    else
    {
          for(int i=0;i<l-2;i++)
          {
       
            if(s[i]!=s[i+1] && s[i]!=s[i+2] && s[i+1]!=s[i+2])
            {
               count++;
            }
          }
    
         return count;
    }

Sliding Window Concept:

Maximum sum subarray of size k:

k=3 example:

int i=0; // starting point of window
int sum=0;
int mx=INT_MIN;
for(int j=0;j<n;j++){   // j is ending point of window
      sum+=v[j];
      if(j-i+1==k){ //j-i+1 is window size
        mx=max(mx,sum);
        sum=sum-v[i++]; // ab window age move kregi, starting point ki value ghatakar start++
      }
}
cout<<mx;


First negative integer in every window of size k:



      queue<int> q;
         vector<int> ans;
         int i=0;
         
         for(int j=0;j<n;j++){
             if(arr[j]<0) q.push(arr[j]); // push if -ve found
             
             if(j-i+1==k){   //window of size k
                 if(q.empty()) ans.push_back(0);
                 else{
                     
                     ans.push_back(q.front());
                     //delete front if it is equal to statrting
                     // point value of queue
                     if(q.front()==arr[i]) q.pop();
                 }
                i++; 
             }
         }
         return ans;

An anagram is a word or phrase that's formed by rearranging the letters of another word or phrase.
e.g total anagram of  word "for" is 3!


check two string are anagram or not:
bool areAnagram(string s1, string s2)
{
    map<charint> mp;
    for(int i = 0; i < s1.length(); i++)
        mp[s1[i]]++;
         
    for(int i = 0; i < s2.length(); i++)
        mp[s2[i]]--;
         
    for(auto it = mp.begin(); it != mp.end(); it++)
        if(it -> second != 0)
            return false;
             
        return true;
}

Count Occurrences of Anagrams:

Input : forxxorfxdofr
        for
Output : 3
Explanation : Anagrams of the word for - for, orf, 
ofr appear in the text and hence the count is 3.\
 simple approach:
int countAnagrams(string sen, string word)
{
     
    int n=sen.length();
    int k=word.length();
    int count = 0;
    for(int i = 0; i < n- k + 1; i++){
         
        // Check if the word and substring are
        // anagram of each other.
     if (areAnagram(sen.substr(i, k),word)) count++;
          
    }
    return count;
}
  Sliding window approach:
                                             
                                                    -------------

Sliding Window Maximum (Maximum of all subarrays of size k):

Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 
Output: 3 3 4 5 5 5 6
Explanation: 
Maximum of 1, 2, 3 is 3
Maximum of 2, 3, 1 is 3
Maximum of 3, 1, 4 is 4
Maximum of 1, 4, 5 is 5
Maximum of 4, 5, 2 is 5 
Maximum of 5, 2, 3 is 5
Maximum of 2, 3, 6 is 6
brute force approach:
    int mx;
    for (int i = 0; i <= n - k; i++)
    {
        mx = arr[i];
 
        for (int j = i; j < i+k; j++)
        {
            mx=max(mx,arr[j]);
        }
        cout << mx << " ";
    }
Sliding window approach:
-------

Imp questions for interview:




convert arr to set unordered_set<int> s(A, A + n);

unordered_set<int> s(begin(A), end(A));
 // Declaring the vector and set iterator
    vector<int>::iterator it = vec.begin();
    set<int>::iterator it= s.begin();
    // Printing alternate elements
    while (it < vec.end()) {
        std::cout << *it << " ";
        std::advance(it, 2);
    }
input:  0 10 20 30 40 50 60 70 80 90 
output: 0 20 40 60 80
Kth smallest in unsorted array:
    set<int> s(arr, arr + n); // stored as sorted
    set<int>::iterator itr
        = s.begin(); // s.begin() returns a pointer to first
                     // element in the set
// kth smallest
    advance(itr, k - 1); // itr points to kth element in set
 
    cout << *itr << "\n";
-----
 
----------------

(ye already upar hai)
effucient method in one loop:
    unordered_map<intint> m;
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (m.find(k - arr[i]) != m.end()) {
            count += m[k - arr[i]];
        }
        m[arr[i]]++;
    }
    return count;
// Store counts of all elements in map m
    unordered_map<int, int> m;
 
    // Traverse through all elements
    for (int i = 0; i < n; i++) {
 
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
        if (m.find(rem) != m.end()) {
            int count = m[rem];
            for (int j = 0; j < count; j++)
                cout << "(" << rem << ", "
                     << arr[i] << ")" << endl;
        }
        m[arr[i]]++;
    }

another method:

 sort(arr, arr + n);
  int low = 0;
  int high = n - 1;
 
  while (low < high)
  {
    if (arr[low] + arr[high] == sum)
    {
      cout << "The pair is : (" <<
               arr[low] << ", " <<
               arr[high] << ")" << endl;
    }
    if (arr[low] + arr[high] > sum)
    {
      high--;
    }
    else
    {
      low++;
    }

  }

more than one duplicates find: (already upar hai)

----------------------------

Comments

Popular posts from this blog

c++ oops

Takeoff (hackerearth.3, datastructure, array 1-D)

Aptitude tricks