First string from the given array whose reverse is also present in the same array
Given a string array str[], the task is to find the first string from the given array whose reverse is also present in the same array. If there is no such string then print -1.
Examples:
Input: str[] = {“Beginner”, “for”, “skeeg”}
Output: Beginner
“Beginner” is the first string from the array whose reverse is also present in the array i.e. “skeeg”.
Input: str[] = {“there”, “you”, “are”}
Output: -1
Approach: Traverse the array element by element and for every string, check whether there is any string that appears after the current string in the array and is equal to the reverse of it. If yes then print the current string else print -1 in the end.
Below is the implementation of the above approach:
C++
// CPP implementation of the approach #include<bits/stdc++.h> using namespace std; // Function that returns true if s1 // is equal to reverse of s2 bool isReverseEqual(string s1, string s2) { // If both the strings differ in length if (s1.length() != s2.length()) return false ; int len = s1.length(); for ( int i = 0; i < len; i++) // In case of any character mismatch if (s1[i] != s2[len - i - 1]) return false ; return true ; } // Function to return the first word whose // reverse is also present in the array string getWord(string str[], int n) { // Check every string for ( int i = 0; i < n - 1; i++) // Pair with every other string // appearing after the current string for ( int j = i + 1; j < n; j++) // If first string is equal to the // reverse of the second string if (isReverseEqual(str[i], str[j])) return str[i]; // No such string exists return "-1" ; } // Driver code int main() { string str[] = { "Beginner" , "for" , "skeeg" }; cout<<(getWord(str, 3)); } // This code is contributed by // Surendra_Gangwar |
Java
// Java implementation of the approach class GFG { // Function that returns true if s1 // is equal to reverse of s2 static boolean isReverseEqual(String s1, String s2) { // If both the strings differ in length if (s1.length() != s2.length()) return false ; int len = s1.length(); for ( int i = 0 ; i < len; i++) // In case of any character mismatch if (s1.charAt(i) != s2.charAt(len - i - 1 )) return false ; return true ; } // Function to return the first word whose // reverse is also present in the array static String getWord(String str[], int n) { // Check every string for ( int i = 0 ; i < n - 1 ; i++) // Pair with every other string // appearing after the current string for ( int j = i + 1 ; j < n; j++) // If first string is equal to the // reverse of the second string if (isReverseEqual(str[i], str[j])) return str[i]; // No such string exists return "-1" ; } // Driver code public static void main(String[] args) { String str[] = { "Beginner" , "for" , "skeeg" }; int n = str.length; System.out.print(getWord(str, n)); } } |
Python3
# Python implementation of the approach # Function that returns true if s1 # is equal to reverse of s2 def isReverseEqual(s1, s2): # If both the strings differ in length if len (s1) ! = len (s2): return False l = len (s1) for i in range (l): # In case of any character mismatch if s1[i] ! = s2[l - i - 1 ]: return False return True # Function to return the first word whose # reverse is also present in the array def getWord( str , n): # Check every string for i in range (n - 1 ): # Pair with every other string # appearing after the current string for j in range (i + 1 , n): # If first string is equal to the # reverse of the second string if (isReverseEqual( str [i], str [j])): return str [i] # No such string exists return "-1" # Driver code if __name__ = = "__main__" : str = [ "Beginner" , "for" , "skeeg" ] print (getWord( str , 3 )) # This code is contributed by # sanjeev2552 |
C#
// C# implementation of the approach using System; class GFG { // Function that returns true if s1 // is equal to reverse of s2 static bool isReverseEqual(String s1, String s2) { // If both the strings differ in length if (s1.Length != s2.Length) return false ; int len = s1.Length; for ( int i = 0; i < len; i++) // In case of any character mismatch if (s1[i] != s2[len - i - 1]) return false ; return true ; } // Function to return the first word whose // reverse is also present in the array static String getWord(String []str, int n) { // Check every string for ( int i = 0; i < n - 1; i++) // Pair with every other string // appearing after the current string for ( int j = i + 1; j < n; j++) // If first string is equal to the // reverse of the second string if (isReverseEqual(str[i], str[j])) return str[i]; // No such string exists return "-1" ; } // Driver code public static void Main(String[] args) { String []str = { "Beginner" , "for" , "skeeg" }; int n = str.Length; Console.Write(getWord(str, n)); } } // This code has been contributed by 29AjayKumar |
Javascript
<script> // JavaScript implementation of the approach // Function that returns true if s1 // is equal to reverse of s2 function isReverseEqual(s1, s2) { // If both the strings differ in length if (s1.length != s2.length) return false ; let len = s1.length; for (let i = 0; i < len; i++) // In case of any character mismatch if (s1[i] != s2[len - i - 1]) return false ; return true ; } // Function to return the first word whose // reverse is also present in the array function getWord(str, n) { // Check every string for (let i = 0; i < n - 1; i++) // Pair with every other string // appearing after the current string for (let j = i + 1; j < n; j++) // If first string is equal to the // reverse of the second string if (isReverseEqual(str[i], str[j])) return str[i]; // No such string exists return "-1" ; } // Driver code let str = [ "Beginner" , "for" , "skeeg" ]; document.write(getWord(str, 3)); // This code is contributed by Surbhi Tyagi. </script> |
PHP
<?php // PHP implementation of the approach // Function that returns true if s1 // is equal to reverse of s2 function isReverseEqual( $s1 , $s2 ) { // If both the strings differ in length if ( strlen ( $s1 ) != strlen ( $s2 )) return false; $len = strlen ( $s1 ); for ( $i = 0; $i < $len ; $i ++) // In case of any character mismatch if ( $s1 [ $i ] != $s2 [ $len - $i - 1]) return false; return true; } // Function to return the first word whose // reverse is also present in the array function getWord( $str , $n ) { // Check every string for ( $i = 0; $i < $n - 1; $i ++) // Pair with every other string // appearing after the current string for ( $j = $i + 1; $j < $n ; $j ++) // If first string is equal to the // reverse of the second string if (isReverseEqual( $str [ $i ], $str [ $j ])) return $str [ $i ]; // No such string exists return "-1" ; } // Driver code $str = array ( "Beginner" , "for" , "skeeg" ); $n = count ( $str ); print (getWord( $str , $n )); // This code is contributed by mits ?> |
Beginner
Time Complexity: O(n3), as nested loops are used
Auxiliary Space: O(1), as no extra space is used
Efficient Approach: O(n) approach. This approach requires a Hashmap to store words as traversed. As we traverse, if reverse of current word found in the map, then reversed word is the first occurrence that is the answer. If not found at the end of traversal, return -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h> using namespace std; // Method that returns first occurrence of reversed word. string getReversed(string words[], int length) { // Hashmap to store word as we traverse map<string, bool > reversedWordMap; for ( int i = 0; i < length; i++) { string reversedString = words[i]; reverse(reversedString.begin(),reversedString.end()); // check if reversed word exists in map. if (reversedWordMap.find(reversedString) != reversedWordMap.end() and reversedWordMap[reversedString]) return reversedString; else // else put the word in map reversedWordMap[words[i]] = true ; } return "-1" ; } // Driver code int main() { string words[] = { "some" , "Beginner" , "emos" , "for" , "skeeg" }; int length = sizeof (words) / sizeof (words[0]); cout << getReversed(words, length); return 0; } // This code is contributed by divyesh072019 |
Java
import java.util.HashMap; import java.util.Map; public class ReverseExist { // Driver Code public static void main(String[] args) { String[] words = { "some" , "Beginner" , "emos" , "for" , "skeeg" }; System.out.println(getReversed(words, words.length)); } // Method that returns first occurrence of reversed word. private static String getReversed(String[] words, int length) { // Hashmap to store word as we traverse Map<String, Boolean> reversedWordMap = new HashMap<>(); for (String word : words) { StringBuilder reverse = new StringBuilder(word); String reversed = reverse.reverse().toString(); // check if reversed word exists in map. Boolean exists = reversedWordMap.get(reversed); if (exists != null && exists.booleanValue()) { return reversed; } else { // else put the word in map reversedWordMap.put(word, true ); } } return "-1" ; } } // Contributed by srika21m |
Python3
# Method that returns first occurrence of reversed word. def getReversed(words, length): # Hashmap to store word as we traverse reversedWordMap = {} for word in words: reversedString = word[:: - 1 ] # check if reversed word exists in map. if (reversedString in reversedWordMap and reversedWordMap[reversedString]): return reversedString else : # else put the word in map reversedWordMap[word] = True return "-1" # Driver Code if __name__ = = "__main__" : words = [ "some" , "Beginner" , "emos" , "for" , "skeeg" ] print (getReversed(words, len (words))) # This code is contributed by chitranayal |
C#
using System; using System.Collections.Generic; class GFG { // Method that returns first occurrence of reversed word. static string getReversed( string [] words, int length) { // Hashmap to store word as we traverse Dictionary< string , bool > reversedWordMap = new Dictionary< string , bool >(); for ( int i = 0; i < length; i++) { char [] reversedString = words[i].ToCharArray(); Array.Reverse(reversedString); // check if reversed word exists in map. if (reversedWordMap.ContainsKey( new string (reversedString)) && reversedWordMap[ new string (reversedString)]) return new string (reversedString); else // else put the word in map reversedWordMap[words[i]] = true ; } return "-1" ; } // Driver code static void Main() { string [] words = { "some" , "Beginner" , "emos" , "for" , "skeeg" }; int length = words.Length; Console.Write(getReversed(words, length)); } } // This code is contributed by divyeshrabadiya07 |
Javascript
<script> // Method that returns first occurrence of reversed word. function getReversed(words,length) { // Hashmap to store word as we traverse let reversedWordMap = new Map(); for (let word=0;word<words.length;word++) { let reverse = words[word].split( "" ); let reversed = reverse.reverse().join( "" ); if (reversedWordMap.has(reversed) && reversedWordMap.get(reversed)) return reversed; else // else put the word in map reversedWordMap.set(words[word] , true ); } return "-1" ; } // Driver code let words=[ "some" , "Beginner" , "emos" , "for" , "skeeg" ]; document.write(getReversed(words, words.length)); // This code is contributed by rag2127 </script> |
some
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Approach: “Iterative Reverse String Comparison”
One approach is to iterate through the array, and for each string, check if its reverse exists in the array. If it does, return that string as the answer. If none of the strings have a reverse that is also present in the array, return -1.
Steps:
- Iterate through the array using a for loop and a variable i that goes from 0 to n-1, where n is the length of the array.
- For each string str[i], find its reverse by using the reverse() function.
- Iterate through the array again using another for loop and a variable j that goes from 0 to n-1.
- Check if the reverse of str[i] is equal to any of the other strings in the array.
- If it is, return str[i] as the answer.
- If none of the strings have a reverse that is also present in the array, return -1.
C++
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; string findReverse(string s) { reverse(s.begin(), s.end()); return s; } string firstReverse(string str[], int n) { string rev; for ( int i = 0; i < n; i++) { rev = findReverse(str[i]); for ( int j = 0; j < n; j++) { if (i != j && str[j] == rev) { return str[i]; } } } return "-1" ; } int main() { string str[] = { "Beginner" , "for" , "skeeg" }; int n = sizeof (str)/ sizeof (str[0]); cout << firstReverse(str, n); return 0; } |
Java
import java.util.Arrays; public class Main { public static String findReverse(String s) { return new StringBuilder(s).reverse().toString(); } public static String firstReverse(String[] str) { String rev; int n = str.length; for ( int i = 0 ; i < n; i++) { rev = findReverse(str[i]); for ( int j = 0 ; j < n; j++) { if (i != j && str[j].equals(rev)) { return str[i]; } } } return "-1" ; } // Example Usage public static void main(String[] args) { String[] str = { "Beginner" , "for" , "skeeg" }; System.out.println(firstReverse(str)); // Output: Beginner } } |
Python3
def find_reverse(s): return s[:: - 1 ] def first_reverse(str_list): n = len (str_list) for i in range (n): rev = find_reverse(str_list[i]) for j in range (n): if i ! = j and str_list[j] = = rev: return str_list[i] return "-1" str_list = [ "Beginner" , "for" , "skeeg" ] print (first_reverse(str_list)) |
C#
using System; namespace GFG { class GFG { static string FindReverse( string s) { char [] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string (charArray); } static string FirstReverse( string [] str, int n) { string rev; for ( int i = 0; i < n; i++) { rev = FindReverse(str[i]); for ( int j = 0; j < n; j++) { if (i != j && str[j] == rev) { return str[i]; } } } return "-1" ; } static void Main( string [] args) { string [] str = { "Beginner" , "for" , "skeeg" }; int n = str.Length; string result = FirstReverse(str, n); Console.WriteLine(result); } } } |
Javascript
// JavaScript code for above approach // function to find reverse function findReverse(s) { return s.split( '' ).reverse().join( '' ); } // function to find first reverse function firstReverse(strList) { const n = strList.length; for (let i = 0; i < n; i++) { let rev = findReverse(strList[i]); for (let j = 0; j < n; j++) { if (i !== j && strList[j] === rev) { return strList[i]; } } } return "-1" ; } // Driver code const strList = [ "Beginner" , "for" , "skeeg" ]; console.log(firstReverse(strList)); |
Beginner
Time complexity: O(n^2) where n is the length of the array,
Auxiliary space: O(m) where m is the length of the longest string in the array.
Contact Us