Strings - Minimum Length of String After Deleting Similar Ends

Strings - Minimum Length of String After Deleting Similar Ends

Minimum Length of String After Deleting Similar Ends

https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/description/?envType=daily-question&envId=2024-03-05

My approach:

  1. Take two pointers 'si=0' and 'ei=n-1'

  2. Create one count = 0 variable to store number of deletion.

  3. Run a while loop and remember they cannot intersect (si < ei)

  4. if str[si] == str[ei]

    • Count all the characters from 'si' equal to str[si] and update:

      • si++, count++
    • Count all the characters from 'ei' equal to str[si] and update :

      • e--, count++
  5. if at any point str[si] != str[ei], break out from the loop.

  6. Return n-count

Code:

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

class Solution {
public:
    int minimumLength(string s) {

        int ind = 0;

        int n = s.size();

        int si = 0;
        int ei = n-1;

        while(si<ei){
            if(s[si]==s[ei]){
                char ch = s[si];
                while(si<=ei){
                    if(s[si]==ch){
                        si++;
                        ind++;
                    }
                    else{
                        break;
                    }
                }

                while(ei>si){
                    if(s[ei]==ch){
                        ei--;
                        ind++;
                    }
                    else{
                        break;
                    }
                }
            }
            else{
                break;
            }
        }

        return n-ind;
    }
};