VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-consecutive-words-sequence/

⇱ Delete consecutive same words in a sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete consecutive same words in a sequence

Last Updated : 16 May, 2026

Given an array of n strings arr[]. The task is to determine the number of words remaining after pairwise destruction.
If two consecutive words in the array are identical, they cancel each other out. This process continues until no more eliminations are possible.

Examples:

Input: arr[] = ["gfg", "for", "geeks", "geeks", "for"]
Output: 1
Explanation: After the first iteration, we'll have: [gfg, for, for]. Then after the second iteration, we'll have: [gfg]. No more eliminations are possible. Hence, the result is 1.

Input: arr[] = ["ab", "aa", "aa", "bcd", "ab"]
Output: 3
Explanation: After the first iteration, we'll have: [ab, bcd, ab]. We can't further destroy more strings and hence we stop and the result is 3.

Input: arr[] = ["tom", "jerry", "jerry", "tom"]
Output: 0
Explanation: After the first iteration, we'll have: [tom, tom]. After the second iteration: 'empty-array' . Hence, the result is 0.

Using Inbuilt Remove Function - O(n^2) Time

The idea is to iteratively remove consecutive same words from the array until no adjacent duplicates remain. The thought process follows a linear scan, checking adjacent elements, and if found equal, they are removed. After removal, the pointer moves back one step to recheck the new adjacency, ensuring all duplicates are handled efficiently.


Output
1

Using Stack - O(n) Time and O(n) Space

The idea is to use a stack to efficiently remove consecutive duplicate words while maintaining order. As we iterate through the array, we check if the top element of the stack matches the current word. If they are the same, we pop the stack, otherwise, we push the word.


Output
1
Comment
Article Tags:
Article Tags: