Given a sequence of n strings, the task is to check if any two similar words come together then they destroy each other then print the number of words left in the sequence after this pairwise destruction.
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.
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.
# Python3 program to remove consecutive
# same words
# Function to find the size of
# manipulated sequence
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
i += 1
# Return modified size
return len(v[:i – 1])
# Driver Code
if __name__ == ‘__main__’:
v = [“tom”, “jerry”, “jerry”, “tom”]
# This code is contributed by SHUBHAMSINGH10
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.
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of sub-sequence such that it has one consecutive element with difference less than or equal to 1
- Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
- k-th missing element in increasing sequence which is not present in a given sequence
- Reverse individual words
- Print all possible words from phone digits
- Program to convert a given number to words
- Delete all even elements from a stack
- Reorder the position of the words in alphabetical order
- Check if words are sorted according to new order of alphabets
- Sort the words in lexicographical order in Python
- Sorting array of strings (or words) using Trie
- Delete middle element of a stack
- Python | Sort words of sentence in ascending order
- Search, insert and delete in an unsorted array
- Search, insert and delete in a sorted array