The other day I came across the following question:
Write a simple program for a Turing machine that can identify if a string of 0's and 1's on the tape is a palindrome or not.
I was discussing this with my friend who is an electronics engineer and who works with state machines a lot. Soon, our conversation turned into how would one solve the problem if the numbers were in a linked list.
I went home and thought about the problem.
There is the obvious O(n^2) solution:
- Read the head
- Go all the way to the tail
- Compare.
- Read the second item
- Go all the way to tail - 1
- Compare
- And so on
Now, one fact that we didn't use is that the values in the linked list are 0's and 1's. Can this be used to our advantage?
I guess we can - if we encode the string into an integer.
So here is the revised algorithm:
- Find the number of elements in the linked list - O(n)
- Read half the number of elements and find the number (n) represented by the 1's and 0's
- Read the remaining elements and pop the digits from n and compare the values
Now what if the linked list could have any kind of values?
No comments:
Post a Comment