Linked List Palindrome
September 8, 2017
Today’s exercise is an Amazon interview question from Career Cup (this is the exact question asked):
There is a given linked list where each node can consist of any number of characters :- For example
a–>bcd–>ef–>g–>f–>ed–>c–>ba.
Now please write a function where the linked list will return true if it is a palindrome .
Like in above example the linked list should return true
Your task is to write a program to determine if a list of strings forms a palindrome. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
The following should run in time linear in the input size, and is a
bit more general than needed.
I was asked a palindrome question yesterday, but it explicitly excluded any solution that involved reversing or flattening, as it had to execute in O(1) space.
Note: it is possible to make it O(1) in space, but this will degrade into O(e^2)+O(n) instead of O(e)+O(n) in time since we will have to traverse the list several time, by index. (with e = (length list) and n = total number of characters). It will also be O(t^2) in programmer time, with t being the time the programmer took to implement the second version above… ;-)
Prompted by John Cowan’s comment above, here is a version that is
constant space, but quadratic time.
If using SRFI-135 is considered “cheating” then we could impagine we
have included code from portable implementation from that SRFI. (We
could also use “istrings” from SRFI 140 or Kawa, etc.)