Open In App

Delete consecutive same words in a sequence

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sequence of n strings, the task is to check if any two similar words come together and then destroy each other then print the number of words left in the sequence after this pairwise destruction.

Examples: 

Input : ab aa aa bcd ab
Output : 3
As aa, aa destroys each other so, 
ab bcd ab is the new sequence.

Input :  tom jerry jerry tom
Output : 0

As first both jerry will destroy each other.
Then sequence will be tom, tom they will also destroy
each other. So, the final sequence doesn’t contain any
word.

Method 1: 

1- Start traversing the sequence by storing it in vector.
  a) Check if the current string is equal to next string
     if yes, erase both from the vector.
  b) And check the same till last.
2- Return vector size.

Implementation:

C++




// C++ program to remove consecutive same words
#include<bits/stdc++.h>
using namespace std;
  
// Function to find the size of manipulated sequence
int removeConsecutiveSame(vector <string > v)
{
    int n = v.size();
  
    // Start traversing the sequence
    for (int i=0; i<n-1; )
    {
        // Compare the current string with next one
        // Erase both if equal
        if (v[i].compare(v[i+1]) == 0)
        {
            // Erase function delete the element and
            // also shifts other element that's why
            // i is not updated
            v.erase(v.begin()+i);
            v.erase(v.begin()+i);
  
            // Update i, as to check from previous
            // element again
            if (i > 0)
                i--;
  
            // Reduce sequence size
            n = n-2;
        }
  
        // Increment i, if not equal
        else
            i++;
    }
  
    // Return modified size
    return v.size();
}
  
// Driver code
int main()
{
    vector<string> v = { "tom", "jerry", "jerry", "tom"};
    cout << removeConsecutiveSame(v);
    return 0;
}


Java




// Java program to remove consecutive same words
  
import java.util.Vector;
  
class Test
{
    // Method to find the size of manipulated sequence
    static int removeConsecutiveSame(Vector <String > v)
    {
        int n = v.size();
       
        // Start traversing the sequence
        for (int i=0; i<n-1; )
        {
            // Compare the current string with next one
            // Erase both if equal
            if (v.get(i).equals(v.get(i+1)))
            {
                // Erase function delete the element and
                // also shifts other element that's why
                // i is not updated
                v.remove(i);
                v.remove(i);
       
                // Update i, as to check from previous
                // element again
                if (i > 0)
                    i--;
       
                // Reduce sequence size
                n = n-2;
            }
       
            // Increment i, if not equal
            else
                i++;
        }
       
        // Return modified size
        return v.size();
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        Vector<String> v = new Vector<>();
  
        v.addElement("tom"); v.addElement("jerry");
        v.addElement("jerry");v.addElement("tom");
  
        System.out.println(removeConsecutiveSame(v));
    }
}


Python3




# Python3 program to remove consecutive 
# same words 
  
# Function to find the size of 
# manipulated sequence 
def removeConsecutiveSame(v):
  
    n = len(v)
  
    # Start traversing the sequence
    i = 0
    while(i < n - 1):
          
        # Compare the current string with 
        # next one Erase both if equal 
        if ((i + 1) < len(v)) and (v[i] == v[i + 1]): 
          
            # Erase function delete the element and 
            # also shifts other element that's why 
            # i is not updated 
            v = v[:i] 
            v = v[:i] 
  
            # Update i, as to check from previous 
            # element again 
            if (i > 0):
                i -= 1
  
            # Reduce sequence size 
            n = n - 2
          
        # Increment i, if not equal 
        else:
            i += 1
      
    # Return modified size 
    return len(v[:i - 1])
      
# Driver Code
if __name__ == '__main__':
    v = ["tom", "jerry", "jerry", "tom"]
    print(removeConsecutiveSame(v))
      
# This code is contributed by SHUBHAMSINGH10


C#




// C# program to remove consecutive same words 
using System;
using System.Collections.Generic;
  
class GFG
{
// Method to find the size of 
// manipulated sequence 
public static int removeConsecutiveSame(List<string> v)
{
    int n = v.Count;
  
    // Start traversing the sequence 
    for (int i = 0; i < n - 1;)
    {
        // Compare the current string with 
        // next one Erase both if equal 
        if (v[i].Equals(v[i + 1]))
        {
            // Erase function delete the element and 
            // also shifts other element that's why 
            // i is not updated 
            v.RemoveAt(i);
            v.RemoveAt(i);
  
            // Update i, as to check from 
            // previous element again 
            if (i > 0)
            {
                i--;
            }
  
            // Reduce sequence size 
            n = n - 2;
        }
  
        // Increment i, if not equal 
        else
        {
            i++;
        }
    }
  
    // Return modified size 
    return v.Count;
}
  
// Driver Code 
public static void Main(string[] args)
{
    List<string> v = new List<string>();
  
    v.Add("tom");
    v.Add("jerry");
    v.Add("jerry");
    v.Add("tom");
  
    Console.WriteLine(removeConsecutiveSame(v));
}
}
  
// This code is contributed by Shrikant13


Javascript




<script>
// Javascript program to remove consecutive same words
  
// Method to find the size of
// manipulated sequence
function removeConsecutiveSame(v)
{
    let n = v.length;
  
    // Start traversing the sequence
    for (let i = 0; i < n - 1;) 
    {
      
        // Compare the current string with
        // next one Erase both if equal
        if (v[i] == (v[i + 1]))
        {
          
            // Erase function delete the element and
            // also shifts other element that's why
            // i is not updated
            v.splice(i, 1);
            v.splice(i, 1);
  
            // Update i, as to check from
            // previous element again
            if (i > 0) {
                i--;
            }
  
            // Reduce sequence size
            n = n - 2;
        }
  
        // Increment i, if not equal
        else {
            i++;
        }
    }
  
    // Return modified size
    return v.length;
}
  
// Driver Code
  
let v = [];
  
v.push("tom");
v.push("jerry");
v.push("jerry");
v.push("tom");
  
document.write(removeConsecutiveSame(v));
  
// This code is contributed by gfgking
</script>


Output

0

Time Complexity: O(n)
Auxiliary Space : O(1)

Method 2:(Using Stack) 

1- Start traversing the strings and push into stack.
    a) Check if the current string is same as the string
       at the top of the stack
        i) If yes, pop the string from top.
        ii) Else push the current string.
2- Return stack size if the whole sequence is traversed.

Implementation:

C++




//  C++ implementation of above method
#include<bits/stdc++.h>
using namespace std;
  
// Function to find the size of manipulated sequence
int removeConsecutiveSame(vector <string> v)
{
    stack<string> st;
  
    // Start traversing the sequence
    for (int i=0; i<v.size(); i++)
    {
        // Push the current string if the stack
        // is empty
        if (st.empty())
            st.push(v[i]);
        else
        {
            string str = st.top();
  
            // compare the current string with stack top
            // if equal, pop the top
            if (str.compare(v[i]) == 0)
                st.pop();
  
            // Otherwise push the current string
            else
                st.push(v[i]);
        }
    }
  
    // Return stack size
    return st.size();
}
  
// Driver code
int main()
{
    vector<string> V = { "ab", "aa", "aa", "bcd", "ab"};
    cout << removeConsecutiveSame(V);
    return 0;
}


Java




//  Java implementation of above method
  
import java.util.Stack;
import java.util.Vector;
  
class Test
{
    // Method to find the size of manipulated sequence
    static int removeConsecutiveSame(Vector <String> v)
    {
        Stack<String> st = new Stack<>();
       
        // Start traversing the sequence
        for (int i=0; i<v.size(); i++)
        {
            // Push the current string if the stack
            // is empty
            if (st.empty())
                st.push(v.get(i));
            else
            {
                String str = st.peek();
       
                // compare the current string with stack top
                // if equal, pop the top
                if (str.equals(v.get(i)))    
                    st.pop();
       
                // Otherwise push the current string
                else
                    st.push(v.get(i));
            }
        }
       
        // Return stack size
        return st.size();
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        Vector<String> v = new Vector<>();
          
        v.addElement("ab"); v.addElement("aa");
        v.addElement("aa");v.addElement("bcd");
        v.addElement("ab");
          
        System.out.println(removeConsecutiveSame(v));
    }
}


Python3




# Python implementation of above method 
  
# Function to find the size of manipulated sequence 
def removeConsecutiveSame(v):
    st = []
  
    # Start traversing the sequence
    for i in range(len(v)):
          
        # Push the current string if the stack 
        # is empty 
        if (len(st) == 0): 
            st.append(v[i]) 
        else:
            Str = st[-1
  
            # compare the current string with stack top 
            # if equal, pop the top 
            if (Str == v[i]): 
                st.pop() 
  
            # Otherwise push the current string 
            else:
                st.append(v[i])
  
    # Return stack size 
    return len(st)
  
# Driver code 
if __name__ == '__main__':
    V = [ "ab", "aa", "aa", "bcd", "ab"
    print(removeConsecutiveSame(V))
  
# This code is contributed by PranchalK.


C#




// C# implementation of above method 
using System;
using System.Collections.Generic;
  
class GFG
{
// Method to find the size of 
// manipulated sequence 
public static int removeConsecutiveSame(List<string> v)
{
    Stack<string> st = new Stack<string>();
  
    // Start traversing the sequence 
    for (int i = 0; i < v.Count; i++)
    {
        // Push the current string if 
        // the stack is empty 
        if (st.Count == 0)
        {
            st.Push(v[i]);
        }
        else
        {
            string str = st.Peek();
  
            // compare the current string with  
            // stack top if equal, pop the top 
            if (str.Equals(v[i]))
            {
                st.Pop();
            }
  
            // Otherwise push the current 
            // string 
            else
            {
                st.Push(v[i]);
            }
        }
    }
  
    // Return stack size 
    return st.Count;
}
  
// Driver Code 
public static void Main(string[] args)
{
    List<string> v = new List<string>();
  
    v.Add("ab");
    v.Add("aa");
    v.Add("aa");
    v.Add("bcd");
    v.Add("ab");
  
    Console.WriteLine(removeConsecutiveSame(v));
}
}
  
// This code is contributed by Shrikant13


Javascript




<script>
    // Javascript implementation of above method
      
    // Method to find the size of
    // manipulated sequence
    function removeConsecutiveSame(v)
    {
        let st = [];
  
        // Start traversing the sequence
        for (let i = 0; i < v.length; i++)
        {
            // Push the current string if
            // the stack is empty
            if (st.length == 0)
            {
                st.push(v[i]);
            }
            else
            {
                let str = st[st.length - 1];
  
                // compare the current string with 
                // stack top if equal, pop the top
                if (str == v[i])
                {
                    st.pop();
                }
  
                // Otherwise push the current
                // string
                else
                {
                    st.push(v[i]);
                }
            }
        }
  
        // Return stack size
        return st.length;
    }
      
    let v = [];
   
    v.push("ab");
    v.push("aa");
    v.push("aa");
    v.push("bcd");
    v.push("ab");
   
    document.write(removeConsecutiveSame(v));
  
// This code is contributed by decode2207.
</script>


Output

3

Time Complexity: O(N), where N is the size of the given sequence.
Auxiliary Space: O(N), since we are using a stack to store the elements of the sequence.

 



Previous Article
Next Article

Similar Reads

Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
15+ min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Number of words in a camelcase sequence
CamelCase is the sequence of one or more than one words having the following properties: It is a concatenation of one or more words consisting of English letters.All letters in the first word are lowercase.For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase. Given a CamelCase sequence represented as
3 min read
Given a sequence of words, print all anagrams together | Set 2
Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”. Recommended PracticePrint Anagrams TogetherTry It! We have discussed two different methods in the previous post. In this post, a more efficient solution is discussed.Trie data struct
13 min read
Given a sequence of words, print all anagrams together | Set 1
Given an array of words, print all anagrams together. For example, if the given array is {"cat", "dog", "tac", "god", "act"}, then output may be "cat tac act dog god". Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. A simple method is to create a Hash Table. Calculate the hash value of each word in such a way th
15+ min read
Given a sequence of words, print all anagrams together using STL
Given an array of words, print all anagrams together. For example, Input: array = {“cat”, “dog”, “tac”, “god”, “act”}output: cat tac act, dog godExplanation: cat tac and act are anagrams and dog and god are anagrams as they have the same set of characters.Input: array = {“abc”, “def”, “ghi”}output: abc, def, ghiExplanation: There are no anagrams in
10 min read
Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
Given a sequence of integers of even length 'n', the task is to find the minimum number of operations required to convert the sequence to follow the rule a[i]=a[i+2] where 'i' is the index. The operation here is to replace any element of the sequence with any element. Examples: Input : n=4 ; Array : 3, 1, 3, 2 Output : 1 If we change the last eleme
11 min read
Convert an unbalanced bracket sequence to a balanced sequence
Given an unbalanced bracket sequence of '(' and ')', convert it into a balanced sequence by adding the minimum number of '(' at the beginning of the string and ')' at the end of the string. Examples: Input: str = ")))()" Output: "((()))()" Input: str = "())())(())())" Output: "(((())())(())())" Method 1: Approach: Initialize an empty stack.Iterate
13 min read
Find original sequence from Array containing the sequence merged many times in order
Given a number N and an array arr[] that consist of merging N length sequence of distinct integers any number of times maintaining the relative order of elements in the initial sequence. The task is to find the initial sequence of length N maintaining the right order. Examples: Input: N = 4, arr[] = {1, 13, 1, 24, 13, 24, 2, 2}Output: 1 13 24 2 Exp
10 min read
Article Tags :
Practice Tags :