Amazon Interview Question for Software Engineers


Country: United States
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
0
of 0 vote

Python

import sys
def make_palindrome(word):
	orig_word = word
	len_orig = len(orig_word)
	index = 0
	while index<len(orig_word):
		palindrome = check_palindrome(word)
		if not palindrome:
			word = word[0:len(word)-index] + orig_word[index] + word[len(word)-index::]
			palindrome = check_palindrome(word)
			index = index + 1
		else:
			print word
			return word
	

def check_palindrome(word):
	if word == word[-1::-1]:
		return True
	else:
		return False

		
		
if __name__ == "__main__":
	make_palindrome(sys.argv[1])

- Sharad Tulsyan December 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

wrong... the word must contain the whole original word with a suffix added.

- gen-x-s December 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It does contain the original word

- Sharad Tulsyan January 05, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import sys
def make_palindrome(word):
	orig_word = word
	len_orig = len(orig_word)
	index = 0
	while index<len(orig_word):
		palindrome = check_palindrome(word)
		if not palindrome:
			word = word[0:len(word)-index] + orig_word[index] + word[len(word)-index::]
			palindrome = check_palindrome(word)
			index = index + 1
		else:
			print word
			return word
	

def check_palindrome(word):
	if word == word[-1::-1]:
		return True
	else:
		return False

		
		
if __name__ == "__main__":
	make_palindrome(sys.argv[1])

- Sharad Tulsyan December 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java Solution

public static String createPalindrome(String str){

        if(isPalindrome(str)) return str;

        StringBuilder sb = new StringBuilder();

        for (char ch : str.toCharArray()) {

            sb.append(ch);
            sb.reverse();
            if(isPalindrome(str+sb)) break;
            sb.reverse();
        }

        return str+sb;

    }

    public static boolean isPalindrome(String s){

        StringBuilder sb = new StringBuilder(s);

        return s.equals(sb.reverse().toString());
    }

- abhay0609 December 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

nice try but it is not working. Ex: "test". it will return "testtset" (means adding 4 character) while the answer is 3.

- mehraz December 24, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Can please explain the question .I didn't get question

- Sravani K December 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can do it in O(n).
Basically, having s and reverse(s), we need to find to find reverse(s) in s.
Example:

offset=0
tests
stset - no match

offset=1
tests
 stset - no match

offset=1
tests
  stset - match of size 3

So we take reverse(s[:-3]) and append it to the resulting string.

Here is code, matching is done using KMP

def get_prefix_string(s):
    result = [0] * len(s)
    for i, c in enumerate(s):
        if i == 0:
            continue
        k = result[i - 1]
        while True:
            if s[i] == s[k]:
                result[i] = k + 1
                break
            if not k:
                break
            k = result[k - 1]
    return result

def shortest_palindrome(self, s):
    seek_in = s[::-1]
    prefix_string = get_prefix_string(s)
    matched_length = 0
    for compare_with in seek_in:
        while True:
            if s[matched_length] == compare_with:
                matched_length += 1
                break
            if not matched_length:
                break
            matched_length = prefix_string[matched_length - 1]
    return s[matched_length:][::-1] + s

- emb December 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is actually O(N^2). isn't it ?

- nberserk January 03, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def buildPalindrome(a):
        for j in reversed(a[:-1]):
                a+=j
	return a

- caf4 December 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

c# implementation.

static private string MakePalindrome( string str ) {

    var sb = new StringBuilder();
    for ( int i = str.Length - 1; i >= 0; i-- ) {
        sb.Append( str[ i ] );
    }
    var reverse = sb.ToString();

    int maxCnt = 0;
    // use KMP instead, I use simple brute force not to blow up the code
    for ( int i = 0; i < str.Length; i++ ) {
        if ( str[ i ] != reverse[ 0 ] ) { continue; }
        int tmpI = i;
        Func<int> f = () => tmpI - i;
        while ( tmpI < str.Length && str[ tmpI ] == reverse[ f.Invoke() ] ) {
            tmpI++;
        }
        if ( f.Invoke() > maxCnt ) { maxCnt = f.Invoke(); }
    }
    return str + reverse.Substring( maxCnt, reverse.Length - maxCnt );
}

- zr.roman December 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Any string s can be made into a palindrome by reversing s and appending it to the end. It seems they don't want double ending letters though, so the last letter of s should be removed before (or after) reversing it. In haskell:

createPalindrome = ap (++) (tail . reverse)

- Anonymous December 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

not only the last letter.
It you are given input "testse", then your solution will create output "testsestset", but this is incorrect, it should be "testset".

- zr.roman December 22, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think you are missing the casses when you have something like 12343 and you only need to append 21 or 123432 and need to append 1.
What if you are trying to find the middle and keep checking values to the left and right if they match until there is a missmatch and concatenate what's left unchecked to the end of the string?

- erik December 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think you're missing the cases when you have 12343 and you have to append 21 or
123432 and have to append only 1.
My solution would be to find the middle and try to check left and right until there's a missmatch. If I find a missmatch, it means the middle is incorrect so I increment it with 1 till I find the correct middle (both to the left and right I have the same values) or I hit the end (when none of the values match).

- erikseulean December 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PalindromeMinString {

	private static boolean isPalindrome(char[] s1, int newCharIndex) {
		for (int i = 0; i < newCharIndex; i++) {
			if (i == newCharIndex) {
				break;
			}
			if (s1[i] == s1[newCharIndex--]) {
				continue;
			}
			return false;
		}
		return true;
	}

	private static char[] shiftChar(char[] c1, char[] c2, int idx) {
		int len = c1.length;
		for (int i = idx; i >= 0; i--) {
			c2[len++] = c1[i];
		}
		return c2;
	}

	private static int addCharsToStr(String s) {
		char[] c1 = s.toCharArray();
		char[] c2 = new char[c1.length * 2];
		int len = c1.length;
		for (int j = 0; j < s.length(); j++) {
			c2[j] = c1[j];
		}

		if (isPalindrome(s.toCharArray(), s.length() - 1)) {
			return -1;
		}
		int i = 0;
		while (i < len) {
			char[] c = shiftChar(c1, c2, i);
			if (isPalindrome(c, len + (i))) {
				return (len + i);
			}
			i++;
		}

		return -1;

	}

	public static void main(String[] args) {
		String str = "test";
		int i = addCharsToStr(str);
		for (int j = i - str.length(); j >= 0; j--) {
			System.out.print(str.toCharArray()[j]);
		}
	}

}

- Suresh Patel December 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java

public static String makePalindrome(String str) {
        // test
        //    tset

        // java
        //  avaj

        // scala
        //   alacs

        // dvd
        // dvd

        StringBuilder origin = new StringBuilder(str);
        StringBuilder reversed = new StringBuilder(str).reverse();

        if (reversed.toString().equals(str)) {
            return str;
        }

        for (int i = 1; i < origin.length() - 1; i++) {
            if (origin.substring(i).equals(reversed.substring(0, reversed.length() - i))) {
                return origin.append(reversed.substring(reversed.length() - i)).toString();
            }
        }

        return origin.append(reversed.substring(1)).toString();
    }

- teru December 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Ruby version

def is_palindrome?(s) ; s == s.reverse; end
def min_palin(s) 
  sol = "" 
  r = s.reverse
  j = 0
  (0..s.length).each do |i|
     if is_palindrome? r[j..i]
      j = i
      sol = "" 
    else
      sol = r[j+1..i]
    end
  end
  puts sol
  puts sol.length
end

min_palin "test"

- Sandeep January 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Ruby

def is_palindrome?(s) ; s == s.reverse; end
def min_palin(s) 
  sol = "" 
  r = s.reverse
  j = 0
  (0..s.length).each do |i|
     if is_palindrome? r[j..i]
      j = i
      sol = "" 
    else
      sol = r[j+1..i]
    end
  end
  puts sol
  puts sol.length
end

min_palin "test"

- NekDil January 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def is_palindrome?(s) ; s == s.reverse; end
def min_palin(s)
sol = ""
r = s.reverse
j = 0
(0..s.length).each do |i|
if is_palindrome? r[j..i]
j = i
sol = ""
else
sol = r[j+1..i]
end
end
puts sol
puts sol.length
end

min_palin "test"

- NekDil January 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def is_palindrome?(s) ; s == s.reverse; end
def min_palin(s) 
  sol = "" 
  r = s.reverse
  j = 0
  (0..s.length).each do |i|
     if is_palindrome? r[j..i]
      j = i
      sol = "" 
    else
      sol = r[j+1..i]
    end
  end
  puts sol
  puts sol.length
end

min_palin "test"

- NekDil January 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//string s = "test";
string s = "abccdcc";
Console.WriteLine(string.Format("Palindrome of {0} is {1}", s, CompletePalindrome(s)));


public string CompletePalindrome(string s)
{
	int minIndex = s.Length - 1;
	for (int i = s.Length - 1; i > 0; i--)
	{
		int index = GetPalindrome(s, i, i);
		if (index != -1 && index < minIndex)
			minIndex = index;

		index = GetPalindrome(s, i-1, i);
		if (index != -1 && index < minIndex)
			minIndex = index;
	}

	var sb = new StringBuilder();
	sb.Append(s);
	for (int i = minIndex - 1; i >= 0; i--)
		sb.Append(s[i]);

	return sb.ToString();
}

private int GetPalindrome(string s, int left, int right)
{
	int n = 0;
	while (left - n > 0 && right + n < s.Length && s[left - n] == s[right + n])
		n++;

	return (right + n == s.Length) ? left - n + 1 : -1;
}

- hnatsu January 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Time complexity o(n) and space complexity max o(2) . Used extra for loops for display logic which may be avoided..

public class Palindrome {
	char[] a={'r','a','b','c','p','p','q','x','q','p'};
	public static void main(String[] args){
	   Palindrome pl = new Palindrome();
	   pl.getPalindrom();
	}
	public  void getPalindrom(){
		int pivot =searchPalindrome(a.length-1, 0, 0);
		for(char c : a){
			System.out.print(" "+c);
		}
		for(int i=pivot-1;i>=0;i--)
			System.out.print(" "+a[i]);
		
	}
	public int searchPalindrome(int endLoc, int startLoc,int startPivot){
		if(a[endLoc]==a[startLoc]){
			if(endLoc==startLoc)
				return startPivot;
			else
				return searchPalindrome(endLoc-1,startLoc+1,startPivot);
		}
		else{
			if(startLoc!=(a.length-1))
				return searchPalindrome(a.length-1,startPivot+1,startPivot+1);
			else
				return a.length-1;
		}
			
	}
}

- Anonymous January 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Palindrome {
	char[] a={'r','a','b','c','p','p','q','x','q','p'};
	public static void main(String[] args){
	   Palindrome pl = new Palindrome();
	   pl.getPalindrom();
	}
	public  void getPalindrom(){
		int pivot =searchPalindrome(a.length-1, 0, 0);
		for(char c : a){
			System.out.print(" "+c);
		}
		for(int i=pivot-1;i>=0;i--)
			System.out.print(" "+a[i]);
		
	}
	public int searchPalindrome(int endLoc, int startLoc,int startPivot){
		if(a[endLoc]==a[startLoc]){
			if(endLoc==startLoc)
				return startPivot;
			else
				return searchPalindrome(endLoc-1,startLoc+1,startPivot);
		}
		else{
			if(startLoc!=(a.length-1))
				return searchPalindrome(a.length-1,startPivot+1,startPivot+1);
			else
				return a.length-1;
		}
			
	}
}

- Anonymous January 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Palindrome {
	char[] a={'r','a','b','c','p','p','q','x','q','p'};
	public static void main(String[] args){
	   Palindrome pl = new Palindrome();
	   pl.getPalindrom();
	}
	public  void getPalindrom(){
		int pivot =searchPalindrome(a.length-1, 0, 0);
		for(char c : a){
			System.out.print(" "+c);
		}
		for(int i=pivot-1;i>=0;i--)
			System.out.print(" "+a[i]);
		
	}
	public int searchPalindrome(int endLoc, int startLoc,int startPivot){
		if(a[endLoc]==a[startLoc]){
			if(endLoc==startLoc)
				return startPivot;
			else
				return searchPalindrome(endLoc-1,startLoc+1,startPivot);
		}
		else{
			if(startLoc!=(a.length-1))
				return searchPalindrome(a.length-1,startPivot+1,startPivot+1);
			else
				return a.length-1;
		}
			
	}
}

- Anonymous January 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

space complexity -- O(2) max in case no palindrome
timecomplexity -- O(2n) maz in case no palindrome
correct me if m wrong above...

public class Palindrome {
	//char[] a={'r','a','b','c','p','p','q','x','q','p'};
	 StringBuffer sb = new StringBuffer("harry");
	public static void main(String[] args){
	   Palindrome pl = new Palindrome();
	   pl.getPalindrom();
	   
	}
	public  void getPalindrom(){
		int pivot =searchPalindrome(sb.length()-1, 0, 0);
		
		for(int i=pivot-1;i>=0;i--)
			sb.append(sb.charAt(i));
		
		System.out.println(sb);
		
	}
	public int searchPalindrome(int endLoc, int startLoc,int startPivot){
		if(sb.charAt(endLoc)==sb.charAt(startLoc)){
			if(endLoc==startLoc)
				return startPivot;
			else
				return searchPalindrome(endLoc-1,startLoc+1,startPivot);
		}
		else{
			if(startLoc!=(sb.length()-1))
				return searchPalindrome(sb.length()-1,startPivot+1,startPivot+1);
			else
				return sb.length()-1;
		}
			
	}
}

- Harry January 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) Python

def checkPalindrome(string):
    if string == string[::-1]:
        return True
    else:
        return False
    
def makeMinimumPalindrome(string):
    stack = []
    index = 0
    print string
    while(index<len(string)):
        if string[index] !=string[-1]:
            stack.append(string[index])
        else:
            if checkPalindrome(string[index+1:-1]):
                break
            else:
                stack.append(string[index])
        index = index +1
    
    pal = string
        
    while(True):
        if stack == []:
            break
        pal = pal + stack.pop()
    
    print pal


if __name__ == '__main__':
    makeMinimumPalindrome('satas')

- simplyankush February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{

static String createPalindrome(String word){

String newWord = word;
//not the last char because it is same in palindrome
int index = word.length()-2;

while( !checkPalindrome(newWord) ){
newWord = newWord + word.charAt(index);
System.out.println("word: "+newWord);
index--;
}

return newWord;
}

private static boolean checkPalindrome(String word){
//reverse the word
//check if they are equal
StringBuilder str = new StringBuilder(word);
String reversedWord = str.reverse().toString();
if(reversedWord.equals(word)){
return true;
}
else{
return false;
}
}

}}

- thatMongol March 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function create(str) {
  var midway = Math.ceil(str.length/2)
  for(var i = midway; i >= 0; i--) {
    str += str.charAt(i)
  }
  console.log(str);
}

- Jordan April 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function create(str) {
  var midway = Math.ceil(str.length/2)
  for(var i = midway; i >= 0; i--) {
    str += str.charAt(i)
  }
  console.log(str);
}

- Jordan April 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Heres a small quick solution in javascript
Sorry for the duplicates, I dont know how to use this site yet.

function create(str) {
  var midway = Math.ceil(str.length/2)
  for(var i = midway; i >= 0; i--) {
    str += str.charAt(i)
  }
  console.log(str);
}

- JJN2009 April 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Solution
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    
    System.out.println(createPalindrome("test"));
  }
  
  public static String createPalindrome(String str){
  	if(isPalindrome(str)) return str;
    
    for(int i=1; i<str.length(); i++){
      if(isPalindrome(str.substring(i))) {
        StringBuilder sb = new StringBuilder(str.substring(0,i));
        return str + sb.reverse().toString();
      }
    }
    return "";
  }
       
  private static boolean isPalindrome(String str) {
    if(str==null) return true;
        int left = 0;
        int right = str.length() - 1;
        while (left <= right) {
            if (str.charAt(left++) !=  str.charAt(right--)) return false;
        }
        return true;
    }
}

- caofang0429 October 13, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More