Remove adjacent duplicates in a string

Sdílet
Vložit
  • čas přidán 13. 10. 2019
  • This video explains how to remove adjacent duplicates from a string. The lecture explains the intuition with help of code which is dry run in the video itself. This is a frequent coding round as well as interview round programming question. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)

Komentáře • 109

  • @divyagupta6854
    @divyagupta6854 Před rokem +2

    Thanks, this video really helped me to grasp the concept behind the problem. Just a thing want to add, when input is given as an array of integers, this exact code will not work, and we need to check another condition at first line of outer loop, to prevent array index out of bounds exception.

  • @subhamsekharpradhan297
    @subhamsekharpradhan297 Před 3 lety +1

    Sir this code is showing index error in the inner while loop, what needs to be changed?

  • @DeepakSingh-bd6mk
    @DeepakSingh-bd6mk Před 3 lety +11

    for this case: abccbccba
    it is giving abbba but it should be null

    • @factzzseeker1233
      @factzzseeker1233 Před 2 lety +2

      bcz it is wrong ,apply your brain only

    • @Liv_Life
      @Liv_Life Před 2 lety

      @@factzzseeker1233 nyc

    • @shikujha4141
      @shikujha4141 Před 2 lety +3

      Just add on more line of code
      If(res==s) return res and break;
      Else continue;

  • @notondrugs5860
    @notondrugs5860 Před 4 lety +7

    how can we do it recursively?

  • @khakr01
    @khakr01 Před 4 lety +19

    In leetcode example, for a given input - "abbaca" the output was - "ca" instead of "aaca" .. basically it is again reducing the aaca to "ca". Could you elaborate for one such example

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Can you please read the answer given to Ritwik Jain. I have explained there.

    • @tilakrajrao2753
      @tilakrajrao2753 Před 3 lety +11

      @@techdose4u there is no comment from Ritwik jain is showing here sir. could you please tell once again??

    • @sayantaniguha8519
      @sayantaniguha8519 Před 2 lety +2

      Question link?

    • @imshivendra
      @imshivendra Před 2 lety

      Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
      Input:
      S = aabb
      Output: ab
      Explanation: 'a' at 2nd position is
      appearing 2nd time consecutively.
      Similiar explanation for b at
      4th position.

    • @the.arty.heart_
      @the.arty.heart_ Před 2 lety

      @@imshivendra No, it would be same if at end of sir's code you again call the same function

  • @025_basharatnawaz4
    @025_basharatnawaz4 Před 3 lety +14

    according to me.
    there is one more condition need to be check.
    before putting a character into the result
    check if(character != res.back())
    then res.push_back(character);
    else
    simply skip the character.

    • @ShivamKumar-oh9bw
      @ShivamKumar-oh9bw Před 2 lety

      not just skip , we have to do res.pop_back() also

    • @imshivendra
      @imshivendra Před 2 lety

      Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
      Input:
      S = aabb
      Output: ab
      Explanation: 'a' at 2nd position is
      appearing 2nd time consecutively.
      Similiar explanation for b at
      4th position.

  • @AlmogYosef520
    @AlmogYosef520 Před 4 lety +1

    Do you use a dynamic array here In order to save the new string ? if so, can you explain without the help of dynamic array to store a string ? I want to know how can i update the current string without the help of another string. Thanks !

    • @techdose4u
      @techdose4u  Před 4 lety

      I am not using any type of array. The only thing being used is the string res (you may think res to be a char type array). I will store the result of one operation of the string in res and then i will again repeat the entire algo. Keep repeating untill you traverse the entire string without having to delete any character (this is the breaking condition). Please read the pinned comment to understand the method of solving. If you still face any problem then do let me know.

    • @imshivendra
      @imshivendra Před 2 lety

      Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
      Input:
      S = aabb
      Output: ab
      Explanation: 'a' at 2nd position is
      appearing 2nd time consecutively.
      Similiar explanation for b at
      4th position.

  • @imshivendra
    @imshivendra Před 2 lety

    Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
    Input:
    S = aabb
    Output: ab
    Explanation: 'a' at 2nd position is
    appearing 2nd time consecutively.
    Similiar explanation for b at
    4th position.

  • @crazyboy-gw7rk
    @crazyboy-gw7rk Před 3 lety

    Can you give recursive approach
    I/p -> "axeexc" o/p->"ac"

  • @Kushagra_21
    @Kushagra_21 Před 4 lety +1

    #code
    T=int(input())
    for _ in range(T):
    s=input()
    res=""
    if (len(s) == 0 or len(s) == 1):
    print(s)
    else:
    for i in range(len(s)):
    while(s[i]):
    if(s[i]!=s[i+1]):
    res+=(s[i])
    i+=1
    if(s[i+1] and s[i]==s[i+1]):
    while(s[i+1] and s[i]==s[i+1]):
    i+=1
    i+=1
    print(res)
    this is the code i wrote but its giving string index out of range .....can you plzz help out in this

  • @vijayatest5373
    @vijayatest5373 Před 4 lety +2

    Very good explanation. Thank you !!

    • @techdose4u
      @techdose4u  Před 4 lety

      Thanks :)

    • @imshivendra
      @imshivendra Před 2 lety

      Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
      Input:
      S = aabb
      Output: ab
      Explanation: 'a' at 2nd position is
      appearing 2nd time consecutively.
      Similiar explanation for b at
      4th position.

  • @tejeshwarshivanandan4966
    @tejeshwarshivanandan4966 Před 4 lety +2

    Assume i is the last char will it not raise an error while comparing i!=i+1 as i+1 is out of range?

  • @kunnudev7250
    @kunnudev7250 Před rokem

    Sir greetings great job please continue awesome videos salute to you brother awesome videos plz make more videos like these thanks a lot

  • @ut100mishra
    @ut100mishra Před 3 lety

    Please tell the recursive approach too

  • @ash_engineering
    @ash_engineering Před 4 lety +3

    Using a stack gives a more elegant solution . In O(n) time and O(n) space complexity and guarantees to work for all input cases .

    • @techdose4u
      @techdose4u  Před 4 lety

      Yea correct.

    • @ericcartman4799
      @ericcartman4799 Před 3 lety +2

      @Arun: Can you share the code using stack. I have implemented using stack but it fails for the case "MISSISSIPIE "

    • @imshivendra
      @imshivendra Před 2 lety

      Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
      Input:
      S = aabb
      Output: ab
      Explanation: 'a' at 2nd position is
      appearing 2nd time consecutively.
      Similiar explanation for b at
      4th position.

    • @pranas2493
      @pranas2493 Před rokem

      What about set

  • @utkarshgupta2909
    @utkarshgupta2909 Před 3 lety

    for each elem compare just left and right .. anyone of them shouldnot be equal to current one. if not print it. For i==0 compare with a[1] and for last compare a[n-1] with just a[n-2] (corner case). Also tell if I my approach is wrong

  • @spetsnaz_2
    @spetsnaz_2 Před 4 lety

    impressive explanation.!

  • @michaelscott4830
    @michaelscott4830 Před 2 lety

    Very helpful 🙏

  • @HomemadeTechARC08
    @HomemadeTechARC08 Před 4 lety +1

    Is there any approach less than o(n)

    • @techdose4u
      @techdose4u  Před 4 lety +6

      I don't think there can be an approach of lower time than O(N) because you atleast need to read all the characters in order to either eliminate or store in result.

  • @rakshith3547
    @rakshith3547 Před 3 lety +1

    This is not the exact sol for 1047. Remove All Adjacent Duplicates In String problem. It is not handling a case when input is "abbaca"

  • @learn_fun_miss
    @learn_fun_miss Před 3 lety +4

    Recursively call this method gives correct result.

    • @praveenreddychalamalla
      @praveenreddychalamalla Před 2 lety

      But it goes to O(n^2) if you call the method recursively. Worst Case input leading to O(n^2) could be an even length palindrome!!

  • @HimanshuSharma-tm2ms
    @HimanshuSharma-tm2ms Před 4 lety

    a simple solution is (O(n))
    #not including the edge cases like index 0 or n-1
    if( a[i] != a[i+1] && a[i]!=a[i-1]) #if arr[i] not equal to element ahead of it and behind it then add it to result
    res+=a[i];
    Now I am assuming that we don't have to go over the res also to make it non repeating type

  • @nettemsusrinivas2046
    @nettemsusrinivas2046 Před 3 lety +1

    Good explanation

  • @fb_a
    @fb_a Před 4 lety +5

    it takes *O(n^2)* time for palindrome type strings like *abcdeedcba* , this algorithm has to be repeated for each result until we don't find any adjacent duplicates in particualr result.
    as we have to consider worst case for time complexity so we have to do it (n+n-2+n-4+n-6.....) times, it takes O(n^2)

    • @techdose4u
      @techdose4u  Před 4 lety

      You can take a stack and easily do it in O(N) time. Just keep pushing and whenever you find like elements, just pop the top and don't push the present. Move to next element. This is the optimized soln in O(N). I hope you got it.

    • @fb_a
      @fb_a Před 4 lety +2

      Stack solution fails for
      *baaab* and
      *IssIssI* kind of cases

    • @techdose4u
      @techdose4u  Před 4 lety

      For these type of cases you need to remember the last character which got removed so as to handle the odd number of characters. This is a boundary case and easy to handle. Its simple to implement. Isn't it.

    • @dashrathyadav1476
      @dashrathyadav1476 Před 4 lety +1

      @@techdose4u "Mississippi"...what about this..

    • @praveenreddychalamalla
      @praveenreddychalamalla Před 2 lety

      @@techdose4u Even if we remember the last character which got removed, it fails. Eg: abccbccba . The answer will be "" empty string but we end up getting answer as "aba" which is wrong one

  • @justineandru
    @justineandru Před 4 lety +1

    Why there is string index out of bound exception

  • @divyatejaswinivengada6368

    Good one man! (y)

  • @SiddharthRay1
    @SiddharthRay1 Před 4 lety +1

    best explanation of an algorithm ❤️

  • @saarthjhaveri8716
    @saarthjhaveri8716 Před 3 lety

    abccbccba what is the ans for this?

  • @SatyaPrakash-il2ed
    @SatyaPrakash-il2ed Před rokem +1

    Dude why you stopped uploading? You ok ?

  • @avinashg.k8166
    @avinashg.k8166 Před 3 lety

    in python the code will be like bellow one
    a = input()
    array = []
    i = 0
    try:
    while True:
    if a[i] != a[i+1] or len(a)-1 == i:
    array.append(a[i])
    i += 1
    if a[i] == a[i+1]:
    while a[i] == a[i+1]:
    i += 1
    i += 1
    except:
    pass
    if a[-1] != a[-2]:
    array.append(a[-1])
    for i in array:
    print(i, end="")

  • @shivanshrawat2688
    @shivanshrawat2688 Před 4 lety +1

    Can i prepare from amazon interview from your site in two months?

  • @rithikraj1813
    @rithikraj1813 Před 3 lety

    Eg alg diya h aur accept alg chiz ke basis mei krra h gfg idk why abccbccba iska null nii anaa chaiye eg se aba aana chahiye but null lera h 😓😓

  • @shreyaboinpally5255
    @shreyaboinpally5255 Před 3 lety +4

    it doesnt work for acaaabbbcdddd

  • @nehasharma6171
    @nehasharma6171 Před rokem +1

    thank you

  • @aravindhkumar3640
    @aravindhkumar3640 Před 4 lety +1

    Try to make continues video

    • @techdose4u
      @techdose4u  Před 4 lety

      Whenever I get time from office I do make videos :)

  • @AnkitYadav-tz3ph
    @AnkitYadav-tz3ph Před 4 lety +1

    Above program may not work for 'caaabbbaacdddd'

    • @1988respect
      @1988respect Před 3 lety

      this will:
      const removeAdjecentDuplicate = function(input) {
      const result = [];
      let isInserted = false;
      for(let i = 0; i < input.length; i++) {
      if(input[i] && input[i] !== input[i+1]) {
      result.push(input[i]);
      } else {
      while(input[i] && input[i] === input[i+1]) {
      isInserted = true;
      i++;
      }
      }
      }
      console.log(result.join(''), 'isInserted', isInserted);
      if(!isInserted) {
      return result.join('');
      } else {
      return removeAdjecentDuplicate(result.join(''));
      }
      }

  • @iit_da_munda
    @iit_da_munda Před 2 lety

    Shouldn't the answer be a?

  • @poonamagrawal8596
    @poonamagrawal8596 Před 3 lety

    mississipie
    output coming as miiipie
    output should be mpie

  • @nimishgupta5289
    @nimishgupta5289 Před 4 lety

    On what you write?

    • @techdose4u
      @techdose4u  Před 4 lety

      Did not get your question! Please elaborate.

    • @nimishgupta5289
      @nimishgupta5289 Před 4 lety

      @@techdose4u on what do you write.... means it is not pen paper not a black board, then what is it...

  • @mayurkapadnis4265
    @mayurkapadnis4265 Před 3 lety +1

    Recursive way is more efficient

  • @mrudul5018
    @mrudul5018 Před rokem

    I think this solution is wrong for gfg test cases

  • @QVL75
    @QVL75 Před 4 lety +1

    No way you can solve this with O(n) time and no extra space.

    • @techdose4u
      @techdose4u  Před 4 lety +2

      With extra space O(N) and Time O(N)---> Use stack.

    • @saigopalraopeechara6912
      @saigopalraopeechara6912 Před 3 lety

      @@techdose4u cant we use erase function and delete adjacent duplicates in the string itself so that no extra space will be taken?
      int main(){
      string s;
      cin>>s;
      int i=0, j=0;
      while(s[i]){
      if(s[i]!=s[i+1])
      i++;
      else{
      j=i;
      while(s[i+1]&&s[i]==s[i+1])
      i++;
      s.erase(j,i-j+1);
      i=j;
      }
      }
      cout

  • @ericksibrian6981
    @ericksibrian6981 Před 3 lety +2

    He could have used a whole keyboard but decided to draw chicken scratch instead. awesome!!!

  • @pushpendrahpx
    @pushpendrahpx Před 2 lety

    its incomplete bro

  • @ayushgarg5929
    @ayushgarg5929 Před 4 lety +1

    Question's name should rather be Recursively remove adjacent duplicates in a string

    • @techdose4u
      @techdose4u  Před 4 lety

      I missed the most optimized approach using stack.

    • @ayushgarg5929
      @ayushgarg5929 Před 4 lety +2

      @@techdose4u sir i have also seen that stack approach ...that's also does not work in all cases.

  • @ranselynigrel8714
    @ranselynigrel8714 Před rokem

    For below code I am facing issue
    class Solution
    {
    public String removeDuplicates(String s)
    {
    String result ="";
    int i;
    //int len = s.length();
    //char s[]= p.toCharArray();
    for(i=0;i

  • @mohitmotwani9256
    @mohitmotwani9256 Před 3 lety

    CODE FOR THE ABOVE EXPLANATION
    string removeUtul(string& s)
    {
    int n = s.size();
    int i = 0;
    string res;
    while( i < n)
    {
    if(i < n-1 && s[i] == s[i+1])
    {
    while(i < n-1 && s[i] == s[i+1])
    {
    i++;
    }
    }
    else
    res.push_back(s[i]);
    i++;
    }
    return res;
    }
    string remove(string s){
    string res = s;
    string temp;
    while(temp.size() != res.size())
    {
    temp = res;
    res = removeUtul(res);
    }
    return res;
    }

  • @nikhilrauniyar9084
    @nikhilrauniyar9084 Před rokem

    Simplest thing to do in c++;
    if that letters in s string match the ans string you remove the letters from ans string otherwise you push in the letters that do not match into the ans string. Might be the easiest explanation available
    class Solution {
    public:
    string removeDuplicates(string s) {
    string ans;
    for(int i = 0; i

  • @lucratividadedocanal981

    for (int i = 0; i < input.Length; i++)
    {
    if (i == 0){
    result += input[i];
    }
    else if (input[i] != result[result.Length - 1])
    {
    result += input[i];
    }
    }

    • @lucratividadedocanal981
      @lucratividadedocanal981 Před 2 lety

      another way
      var regex = new Regex("(.)\\1+");
      result = input;
      return regex.Replace(result, "$1");

  • @goutamhalder9871
    @goutamhalder9871 Před 3 lety

    int i=0;
    while(i

  • @rahulbajetha4057
    @rahulbajetha4057 Před 3 lety +2

    Those who wants recursively remove adjacent duplicates :
    For Ex. I/P : accabbax O/P : x
    string remove(string s){
    int f=0,i=0;
    string res;
    while(i

    • @imshivendra
      @imshivendra Před 2 lety

      Is this problem is similar to remove adjacent duplicates in a string at geeksfoegeeks.Please tell me.
      Input:
      S = aabb
      Output: ab
      Explanation: 'a' at 2nd position is
      appearing 2nd time consecutively.
      Similiar explanation for b at
      4th position.

    • @vedanshsharma1156
      @vedanshsharma1156 Před 9 měsíci

      nicce