Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
/* ZoomBA
Note that sivapraneethalli is kind of correct.
A much better way to achieve this is to see this :
xy is a palindrome iff :
y = ( x ** -1 ) or
y = ( x[0:-2] ** -1 )
As an example :
1. x = abc
y = cba
2. x = abc
y = ba
Thus, a better algo is to store the potential y's as keys to
to a map, and value being that of x in a list.
Hence, we can get it done in two passes.
*/
def find_pair_palindromes( strings ){
map = fold( strings , dict() ) -> {
x = $.o
key = str( x ** -1 )
$.p[ key ] = $.i // store index
if ( size(x) > 1 ){
key = str( x[0:-2] ** -1 )
$.p[ key ] = $.i // store index
}
$.p // return
}
fold ( strings ) -> {
y = $.o
if ( y @ map ){ printf( '%s %s\n', strings[ map[y] ] , y ) }
}
}
listOfWords = list( "shiva" , "and" , "are" , "vihs" , "avihs" )
find_pair_palindromes( listOfWords )
namespace T2
{
class Program
{
static private string[] strings = { "one", "two", "three", "owt", "12345", "4321" };
private static bool IfPalindrom(string prototype)
{
char[] chproto = prototype.ToCharArray();
bool isproto = true;
for (int i=0; i<chproto.Length/2; ++i)
{
if (chproto[i] != chproto[chproto.Length - 1 -i])
{
isproto = false;
break;
}
}
return isproto;
}
static void Main(string[] args)
{
int n = strings.Length;
for (int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j)
{
char first = strings[i][0];
char last = strings[j][strings[j].Length - 1];
if (first == last)
{
string prototype = strings[i] + strings[j];
if (IfPalindrom(prototype))
{
Console.WriteLine(strings[i] + " " + strings[j]);
}
}
}
}
}
}
}
def check_any_concat_is_palindrome(list_strings):
def is_palindrome(s):
return s == s[::-1]
reversed_list = map(lambda x: x[::-1], list_strings)
for word in list_strings:
for rev in reversed_list:
if word.startswith(rev):
if len(word) == len(rev):
return True
if is_palindrome(word[-len(rev) + 1:]):
return True
return False
There exists a O(NM) solution. N is size of list and M is average size of each string in list.
M exist here because we need to reverse string and check if its palindrome. Here is my solution:
}
- sivapraneethalli November 24, 2016