Given a string str. The task is to count the words having the same length as str and each letter at the i-th position is either (i-1)-th, i-th, or (i+1)-th position letter of str.
Note: For the first letter consider i-th and (i+1)-th position letter of W. And for last letter consider (i-1)-th and i-th position letter of str.
Input : str = "ab" Output : 4 Words that can be formed: aa, ab, ba, bb. Input : str = "x" Output : 1
For any letter at index i, except first and last letter, there are three possible letter i.e (i-1)th, ith or (i+1)th letter of given words. So, if three of them are distinct, we have 3 possibilities. If two of them are same, we have 2 possibilities. And if all are same we have only 1 possibility.
So, traverse the given words and find the possibility of each letter and multiply them.
Similarly, for first letter check the distinct letter at first and second position. And for last position check the distinct letter at last and second last position.
Below is the implementation of this approach:
Time complexity : O(length of string).
This article is contributed by Anuj Chauhan. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Get the first letter of each word in a string using regex in Java
- String containing first letter of every word in a given string with spaces
- Move all occurence of letter 'x' from the string s to the end using Recursion
- First uppercase letter in a string (Iterative and Recursive)
- Find letter's position in Alphabet using Bit operation
- Get K-th letter of the decoded string formed by repeating substrings
- Check if the string contains consecutive letters and each letter occurs exactly once
- Program to accept String starting with Capital letter
- Number of positions where a letter can be inserted such that a string becomes palindrome
- Minimum letters to be removed to make all occurrences of a given letter continuous
- Count words that appear exactly two times in an array of words
- Count occurrences of a word in string
- Count words in a given string
- Count words present in a string
- Count palindrome words in a sentence