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[] = {“neveropen”, “for”, “skeeg”}
Output: neveropen
“neveropen” 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++
#include<bits/stdc++.h>
using namespace std;
bool isReverseEqual(string s1, string s2)
{
if (s1.length() != s2.length())
return false ;
int len = s1.length();
for ( int i = 0; i < len; i++)
if (s1[i] != s2[len - i - 1])
return false ;
return true ;
}
string getWord(string str[], int n)
{
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++)
if (isReverseEqual(str[i], str[j]))
return str[i];
return "-1" ;
}
int main()
{
string str[] = { "neveropen" , "for" , "skeeg" };
cout<<(getWord(str, 3));
}
|
Java
class GFG {
static boolean isReverseEqual(String s1, String s2)
{
if (s1.length() != s2.length())
return false ;
int len = s1.length();
for ( int i = 0 ; i < len; i++)
if (s1.charAt(i) != s2.charAt(len - i - 1 ))
return false ;
return true ;
}
static String getWord(String str[], int n)
{
for ( int i = 0 ; i < n - 1 ; i++)
for ( int j = i + 1 ; j < n; j++)
if (isReverseEqual(str[i], str[j]))
return str[i];
return "-1" ;
}
public static void main(String[] args)
{
String str[] = { "neveropen" , "for" , "skeeg" };
int n = str.length;
System.out.print(getWord(str, n));
}
}
|
Python3
def isReverseEqual(s1, s2):
if len (s1) ! = len (s2):
return False
l = len (s1)
for i in range (l):
if s1[i] ! = s2[l - i - 1 ]:
return False
return True
def getWord( str , n):
for i in range (n - 1 ):
for j in range (i + 1 , n):
if (isReverseEqual( str [i], str [j])):
return str [i]
return "-1"
if __name__ = = "__main__" :
str = [ "neveropen" , "for" , "skeeg" ]
print (getWord( str , 3 ))
|
C#
using System;
class GFG
{
static bool isReverseEqual(String s1, String s2)
{
if (s1.Length != s2.Length)
return false ;
int len = s1.Length;
for ( int i = 0; i < len; i++)
if (s1[i] != s2[len - i - 1])
return false ;
return true ;
}
static String getWord(String []str, int n)
{
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++)
if (isReverseEqual(str[i], str[j]))
return str[i];
return "-1" ;
}
public static void Main(String[] args)
{
String []str = { "neveropen" , "for" , "skeeg" };
int n = str.Length;
Console.Write(getWord(str, n));
}
}
|
Javascript
<script>
function isReverseEqual(s1, s2)
{
if (s1.length != s2.length)
return false ;
let len = s1.length;
for (let i = 0; i < len; i++)
if (s1[i] != s2[len - i - 1])
return false ;
return true ;
}
function getWord(str, n)
{
for (let i = 0; i < n - 1; i++)
for (let j = i + 1; j < n; j++)
if (isReverseEqual(str[i], str[j]))
return str[i];
return "-1" ;
}
let str = [ "neveropen" , "for" , "skeeg" ];
document.write(getWord(str, 3));
</script>
|
PHP
<?php
function isReverseEqual( $s1 , $s2 )
{
if ( strlen ( $s1 ) != strlen ( $s2 ))
return false;
$len = strlen ( $s1 );
for ( $i = 0; $i < $len ; $i ++)
if ( $s1 [ $i ] != $s2 [ $len - $i - 1])
return false;
return true;
}
function getWord( $str , $n )
{
for ( $i = 0; $i < $n - 1; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
if (isReverseEqual( $str [ $i ], $str [ $j ]))
return $str [ $i ];
return "-1" ;
}
$str = array ( "neveropen" , "for" , "skeeg" );
$n = count ( $str );
print (getWord( $str , $n ));
?>
|
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;
string getReversed(string words[], int length)
{
map<string, bool > reversedWordMap;
for ( int i = 0; i < length; i++)
{
string reversedString = words[i];
reverse(reversedString.begin(),reversedString.end());
if (reversedWordMap.find(reversedString) !=
reversedWordMap.end() and reversedWordMap[reversedString])
return reversedString;
else
reversedWordMap[words[i]] = true ;
}
return "-1" ;
}
int main()
{
string words[] = { "some" , "neveropen" , "emos" , "for" , "skeeg" };
int length = sizeof (words) / sizeof (words[0]);
cout << getReversed(words, length);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class ReverseExist {
public static void main(String[] args) {
String[] words = { "some" , "neveropen" , "emos" , "for" , "skeeg" };
System.out.println(getReversed(words, words.length));
}
private static String getReversed(String[] words, int length) {
Map<String, Boolean> reversedWordMap = new HashMap<>();
for (String word : words) {
StringBuilder reverse = new StringBuilder(word);
String reversed = reverse.reverse().toString();
Boolean exists = reversedWordMap.get(reversed);
if (exists != null && exists.booleanValue()) {
return reversed;
} else {
reversedWordMap.put(word, true );
}
}
return "-1" ;
}
}
|
Python3
def getReversed(words, length):
reversedWordMap = {}
for word in words:
reversedString = word[:: - 1 ]
if (reversedString in reversedWordMap and reversedWordMap[reversedString]):
return reversedString
else :
reversedWordMap[word] = True
return "-1"
if __name__ = = "__main__" :
words = [ "some" , "neveropen" , "emos" , "for" , "skeeg" ]
print (getReversed(words, len (words)))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static string getReversed( string [] words, int length)
{
Dictionary< string , bool > reversedWordMap =
new Dictionary< string , bool >();
for ( int i = 0; i < length; i++)
{
char [] reversedString = words[i].ToCharArray();
Array.Reverse(reversedString);
if (reversedWordMap.ContainsKey( new string (reversedString)) &&
reversedWordMap[ new string (reversedString)])
return new string (reversedString);
else
reversedWordMap[words[i]] = true ;
}
return "-1" ;
}
static void Main()
{
string [] words = { "some" , "neveropen" , "emos" , "for" , "skeeg" };
int length = words.Length;
Console.Write(getReversed(words, length));
}
}
|
Javascript
<script>
function getReversed(words,length)
{
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
reversedWordMap.set(words[word] , true );
}
return "-1" ;
}
let words=[ "some" , "neveropen" , "emos" , "for" , "skeeg" ];
document.write(getReversed(words, words.length));
</script>
|
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[] = { "neveropen" , "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" ;
}
public static void main(String[] args) {
String[] str = { "neveropen" , "for" , "skeeg" };
System.out.println(firstReverse(str));
}
}
|
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 = [ "neveropen" , "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 = { "neveropen" , "for" , "skeeg" };
int n = str.Length;
string result = FirstReverse(str, n);
Console.WriteLine(result);
}
}
}
|
Javascript
function findReverse(s) {
return s.split( '' ).reverse().join( '' );
}
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" ;
}
const strList = [ "neveropen" , "for" , "skeeg" ];
console.log(firstReverse(strList));
|
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!