Student
more
Question states that given a palindrome, create the next lexicographical string that turns it no longer into a palindrome.
Ex.
abccba
aaccba
To solve this, you convert the next letter which is not an ‘a’ to an ‘a’ so that it becomes the next string. This will always be the next lexicographical string.
For the case where all the letters are ‘a’
aaaaaaaa
aaaaaaab
You want the very last letter to be converted to ‘b’. This will be lexicographically next.
Finally, the last special case would be a single letter
a
Here, the output will be an empty string, because a single letter will always be a palindrome of itself.
function breakPalindrome
base case single letter
return empty string
iterate thru first half of the palindrome
when letter is not an 'a'
return palindrome with letter replaced as 'a'
return palindrome with last letter replaced as 'b' if it gets here
This is what the code would look like.
if(len(palindrome) == 1):
return ""
for i in range(len(palindrome)//2):
if(palindrome[i] != 'a'):
return palindrome[:i] + 'a' + palindrome[i+1:]
return palindrome[:-1] + 'b'
Success
Details
Runtime: 54 ms, faster than 47.20% of Python3 online submissions for Break a Palindrome.
Memory Usage: 13.9 MB, less than 13.13% of Python3 online submissions for Break a Palindrome.
Time: O(N)
Space: O(N)
where N is the size of palindrome
Middle of the Linked List Given the first node in a linked list, get the node which represents the middle of the list. If there are two middle nodes, ie when there is an even number of nodes, return the second node. To solve this, you use two iterators: one which moves +1 each iteration and another which moves +2. f(x) = x + 1, g(x) = x + 2....
read more
My Calender III Question states to create a class called my calendar III which has a function which adds bookings to the calendar. When you add a booking with a start and end time, which are integers, you have to return the max number of intersections between the bookings for the calender. Ex. Let’s say the bookings are as follows: [10, 20] [15, 30] [40, 50] [3, 18] The first...
read more