Amazon Interview Question


Country: India
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
2
of 4 vote

A recursive approach.
call isPalindrome(&root,root);

bool isPalindrome(struct node **left, struct  node *right)
{
   /* stop recursion here */
   if (!right)
      return true;
 
   /* If sub-list is not palindrome then no need to
       check for current left and right, return false */
   bool isp = isPalindrome(left, right->next);
   if (isp == false)
      return false;
 
   /* Check values at current left and right */
   bool isp1 = (right->data == (*left)->data);
 
   /* Move left to next node */
   *left = (*left)->next; /* save next pointer */
 
   return isp1;
}

- john.matheus July 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

intially where left and right pointer points to ??

- cobra July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

both pointing to root.

- john.matheus July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

good approach!.. but left(1 traversal) and right pointers(2 traversal.. totally 3 traversal) are traversing whole list... stop your traversing when left and right pointers point to the same node or right pointer is next to the left ..

- cobra July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Beautiful.

- Anonymous July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good approach.
The best way to traverse a linked list in reverse order is to put the items in a stack while traversing list in normal order. Once all the items are on stack then whenever we pop the items from stack we get the linked list items in reverse. Here John has used the JVM functionality to store recursive function data in a stack.

- Mario July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@mario: space complexity O(1)

- cobra July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Please can you elaborate the algorithm with example?

- Ani July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Using recursion is considered using extra space. No, the proper approach to do this is to find the middle node, reverse the linked list in place from the middle to the end, and traverse from the beginning and the end simultaneously, comparing characters that occur. Then you repair the original input by again reversing from the middle node to the end.

- eugene.yarovoi July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes I thought about both the approach.
But this approach internally build a stack. Not sure but explicitly we are not declaring any variable/stack, so its fine according to the question.

1 suggestion why don't use static node *left instead of node **left ?

- Sanjay Kumar July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No it's not fine according to the question. Extra space is extra space, whether it's declared implicitly or explicitly.

- eugene.yarovoi July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The only problem here is that at the end, root pointer will be modified. Memory leak.

- Victor July 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Keep another node pointer. While till the middle, keep adding to the head of the other pointer. After middle, start the comparison. But the problem here is that the list will be split since we can't have additional memory. After the algo is done, we need to merge the list back.

- Victor July 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nice approach. Though it takes o(n) internal stack space. (Using recursion)

- Psycho August 30, 2012 | Flag
Comment hidden because of low score. Click to expand.
2
of 4 vote

1、 find the middle node of LL to divide LL in two half lists.
2、reverse the nodes of the list before the middle node(time O(N) space O(1)).then we get two lists
3、test if these two lists are the same

- notbad July 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Not bad if you only care about the complexities but having an extra traversal would be time consuming if you have a huge data stored as a linked list.

- Vick July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

That's the way to do it.

I would add 4) Reverse the nodes before the middle node again to repair the original input.

You also need to be careful how you treat the middle node if there's an odd vs. if there's an even number of nodes.

@Vick: it's not possible to do this with only one pass. How would you do it? If you put entries into a stack and then use that, you are 1) using extra space; and 2) still making a second pass, through the stack instead of the linked list in this case.

- eugene.yarovoi July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

i wld like to include this is a link list
applying reversal to first half would be a mess.....

- shreyans July 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does anyone tell me the reason for reversing the first half instead of traversing with two pointers(one from the beginning and one from the middle) simultaneously?

- gfam July 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Oh forget about it. misunderstood question

- gfam July 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Well, that's a logical approach and meets the space constraint (hope you are suggesting using slow and fast pointers to identify the middle of the LL). Just would like to add some notes:
1. At the end, the reversed part of the LL would most probably need to be reverted;
2. When finding the middle, make sure that you take care of both cases when the LL may have either odd or even count of elements;

- ashot madatyan July 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public static void main(String [] args){
				
		LinkedList<String> ll = new LinkedList<String>();
		ll.addAll(Arrays.asList("M A L A Y A L A M".split(" ")));
		System.out.println(ll);
		Iterator<String> forward = ll.iterator();
		Iterator<String> reverse = ll.descendingIterator();
		System.out.println(isPalindrome(forward, reverse, ll.size()/2));
		
	}
		
	public static Boolean isPalindrome(Iterator<String> forward, Iterator<String> reverse, int limit){
		int count = 0;
		System.out.println(limit);
		while(forward.hasNext() && reverse.hasNext() && count <=limit){
			System.out.println("Processed\n");
			count++;
			if(!forward.next().toString().equals(reverse.next().toString())){
				return false;
			}
		}
		return true;
	}

- VS July 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

can be calculated in two parse..
for the first parse.....we find the no. of elements
if even first n/2 int are inserted in stack
and for next n/2 they are popped if same element is encountered else not a palindrom

for odd n/2 floor are inserted
and n+1/2 element is ignored and same as for even popping starts for same element
else not a palindrom

- shreyans July 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

inserting into a stack uses extra space. The constraint here is to not use extra space.

- eugene.yarovoi July 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Lets try this
Time: worst case 3*n, O(n)
Space: O(1)

void linkedList::reverse() {
            int i;
            int len = length();                               //order n, 1 depends on implementation
            node *l = getNodeAtIndex(len - 1); //order n
            for(i = 0 ; i < len - 1 ; i++)
            insertAtPtr(l,removeAtIndex(0));     //order n
       }

- amit July 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I hope if we can reverse this in o(n), comparison will not be any issue...

- memyselfamit July 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int GetLength(Node *head)
{
	int count = 0;
	while(head != NULL)
	{
		count ++;
		head = head->next;
	}

	return count;
}

bool IsPalindrome(Node *root, Node *current, int len, int cl)
{
	bool b = true;
	
	if (len > 0 && cl != len/2 + 1)
	{
		b = IsPalindrome(root, current->next, len, cl + 1);
	}

	while (cl-- > 0) root = root->next;

	bool b1 = root->c == current->c;
	return b1 && b;

}

- Victor July 17, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

IsPalindrome(head, head, GetLength(head), 0);

- Victor July 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

There is another approach to it. Keep another node pointer. While till the middle, keep adding to the head of the other pointer. After middle, start the comparison. But the problem here is that the list will be split since we can't have additional memory. After the algo is done, we need to merge the list back.

- Victor July 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

LinkedList<String> ll = new LinkedList<String>();
		ll.addAll(Arrays.asList("M A L A Y A L A M".split(" ")));
		
		boolean noPalind = false;
		for(int i=0,j=ll.size()-1; i<(ll.size()/2)+1 || j>((ll.size()/2)+1); i++, j--)
		{
			if(!(ll.get(i).equals(ll.get(j))))
			{
				noPalind = true;
				break;
			}				
		}
		System.out.println(!noPalind);

- Raj July 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Reach the middle of the LL
ptr = head and middle

write a recursive print_reverse(middle)

on every print check with head and move head till middle is reached.
use flag. set flag to false the moment there is mismatch

- neer300 July 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

how about this one:
1. Start from the beginning, Push all charters to the stack
2. While stack is not empty, traverse the list again and compare the characters.
Runtime is O(n) in success case where n is number of characters.
Also, small optimization can be done where push last half of he list to the stack in step 1 above.
Space requirement is bit more. :)

- Victor July 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

That wouldn't be O(1) space complexity implementation

- Vineet July 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

I am simply adding a characters to a string and then checking if the string is palindrome or not

- codingAddicted July 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

you are using extra space!

- cobra July 16, 2012 | Flag


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