Skip to main content

Command Palette

Search for a command to run...

Strings - Minimum Length of String After Deleting Similar Ends

Published
1 min read
Strings - Minimum Length of String After Deleting Similar Ends
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 .

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;
    }
};

DSA prep

Part 17 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 - Isomorphic Strings

Isomorphic Strings Problem Link: https://leetcode.com/problems/isomorphic-strings/description/ My approach: We have to do bi-directional mapping so I used two hashmaps. Code: // TIME COMPLEXITY : O(N) // SPACE COMPLEXITY : O(1) , Hashmaps will never ...

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.