smallest number greater than given number which is a palindrome - algorithm

This was asked in an interview. Given a number, say 900, output the smallest palindrome greater than the number, 909 in this case. I gave a brute force solution that checks every number but I'm assuming there's a better way to go about this

Just for fun, here's a simple implementation in Python (using essentially the same algorithm as described by Guntram Blohm).
def next_palindrome(n):
"""
Given a non-negative integer n, return the first integer strictly
greater than n whose decimal representation is palindromic.
"""
s = str(n + 1)
l = len(s)
if s[:l//2][::-1] < s[(l+1)//2:]:
head = str(int(s[:(l+1)//2])+1)
else:
head = s[:(l+1)//2]
return int(head + head[:l//2][::-1])
And some sample output:
>>> next_palindrome(123)
131
>>> next_palindrome(4321)
4334
>>> next_palindrome(999)
1001

Copy the first digit to the last, second digit to the second-last etc until you reach the center digit (or center 2 digits if there is an even number of digits).
If the resulting number is smaller than the original number, increase the center digit/center 2 digits by one. If they are 9, set them to zero and retry with the 2 digits next to them, moving outwards until you hit a non-9.
Edit:
If the loop that moves outwards never hits a non-9, prepend a 1 to the string, set all digits except the last one to 0, and the last one to 1. This is the same as adding 2 to the number.

Though what has been answered above is absolutely correct. Just to add more understanding :)
There can be three different types of inputs that need to be handled separately.
1) The input number is palindrome and has all 9s. For example “9 9
9″. Output should be “1 0 0 1″
2) The input number is not palindrome. For example “1 2 3 4″. Output
should be “1 3 3 1″
3) The input number is palindrome and doesn’t have all 9s. For example
“1 2 2 1″. Output should be “1 3 3 1″.
Solution for input type 1
is easy. The output contains n + 1 digits where the corner digits are 1, and all digits between corner digits are 0.
Now let us first talk about input type 2 and 3. Let us first define the following two terms:
Left Side: The left half of given number. Left side of “1 2 3 4 5 6″ is “1 2 3″ and left side of “1 2 3 4 5″ is “1 2″
Right Side: The right half of given number. Right side of “1 2 3 4 5 6″ is “4 5 6″ and right side of “1 2 3 4 5″ is “4 5″
To convert to palindrome, we can either take the mirror of its left side or take mirror of its right side. However, if we take the mirror of the right side, then the palindrome so formed is not guaranteed to be next larger palindrome.
So, we must take the mirror of left side and copy it to right side. But there are some cases that must be handled in different ways. See the following steps.
We will start with two indices i and j. i pointing to the two middle elements (or pointing to two elements around the middle element in case of n being odd). We one by one move i and j away from each other.
Step 1. Initially, ignore the part of left side which is same as the corresponding part of right side. For example, if the number is “8 3 4 2 2 4 6 9″, we ignore the middle four elements. i now points to element 3 and j now points to element 6.
Step 2. After step 1, following cases arise:
Case 1: Indices i & j cross the boundary.
This case occurs when the input number is palindrome. In this case, we just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side.
For example, if the given number is “1 2 9 2 1″, we increment 9 to 10 and propagate the carry. So the number becomes “1 3 0 3 1″
Case 2: There are digits left between left side and right side which are not same. So, we just mirror the left side to the right side & try to minimize the number formed to guarantee the next smallest palindrome.
In this case, there can be two sub-cases.
2.1) Copying the left side to the right side is sufficient, we don’t need to increment any digits and the result is just mirror of left side. Following are some examples of this sub-case.
Next palindrome for “7 8 3 3 2 2″ is “7 8 3 3 8 7″
Next palindrome for “1 2 5 3 2 2″ is “1 2 5 5 2 1″
Next palindrome for “1 4 5 8 7 6 7 8 3 2 2″ is “1 4 5 8 7 6 7 8 5 4 1″
How do we check for this sub-case? All we need to check is the digit just after the ignored part in step 1. This digit is highlighted in above examples. If this digit is greater than the corresponding digit in right side digit, then copying the left side to the right side is sufficient and we don’t need to do anything else.
2.2) Copying the left side to the right side is NOT sufficient. This happens when the above defined digit of left side is smaller. Following are some examples of this case.
Next palindrome for “7 1 3 3 2 2″ is “7 1 4 4 1 7″
Next palindrome for “1 2 3 4 6 2 8″ is “1 2 3 5 3 2 1″
Next palindrome for “9 4 1 8 7 9 7 8 3 2 2″ is “9 4 1 8 8 0 8 8 1 4 9″
We handle this subcase like Case 1. We just add 1 to the middle digit (or digits in ase n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side.
SOURCE: http://www.geeksforgeeks.org/given-a-number-find-next-smallest-palindrome-larger-than-this-number/

Related

Algorithms: Get final state of array after incrementing/decrementing elements based on neighbors

You're given an array of integers A. You keep doing iterations of the following until the array stops changing: if an element is larger than both of its adjacent neighbors, decrement it by 1. If an element is smaller than both of its adjacent neighbors, increment it by 1. Return the final state of the array (when it will not change any more). Note that the first and last elements do not have two neighbors, so they will never change.
Example: [1,2,7,4,6] -> [1,2,6,5,6] ->[1,2,5,6,6]
Example: [1,2,3,4] Does not change
Anyone have an idea of how to do this better than simulation? I feel like there should be an O(n) solution, but I can't think of it.
You can calculate teh differnce between all numbers. For your series:
1 , 2 , 7 , 4 , 6 you get
1 5 -3 2
you can conclude that a sign change from + to - means a decrease of the number and from - to + and increase
You also can conclude that 7 can be decreased min(abs(5), abs(-3)) = 3 times max before it "hits its boundry" what is 4. Problem is that 4 changes with the first iteration. This you can recognize by the 2 sequential sign changes. So when this is happening, your max before hitting the boudry for 7 becomes: min(abs(5), ceiling(abs(-3)/2)) = 2
as the max of hitting the boundy on 4 becomes min(ceiling(abs(-3)/2), abs(2)) = 2
With the knowledge above, you know you need to deduct: 7 - 2 = 5 and increase 4 + 2 = 6 to get your answer.

Determine given Sudoku is a magic square?

A magic square is a square in which:
1.There is one in the left upper cell.
2. There are no repeating numbers in any column.
3. There are no repeating numbers in any row.
4. There are no repeating numbers in any of the smaller squares.
5.If we swap two smaller squares having a common side, then we obtain square satisfying properties 2 to 4.
Ram has already written several numbers. Determine if it is possible to fill the remaining cells and obtain a magic square.
Example:
Given Matrix:
2 1 3 4
4 3 1 2
1 2 4 3
3 4 2 1
Step 1:
Swapping adjacent smaller squares
3 4 1 2
1 2 3 4
2 1 4 3
4 3 2 1
Step 2:
Swapping adjacent smaller squares(Finally obtaining the magic square)
1 2 3 4
3 4 1 2
2 1 4 3
4 3 2 1
Can anyone explain the logic behind this? Please do tell the easiest way to check whether the magic sudoku formation is possible or not for a given matrix?

Sort a deck of cards [duplicate]

This question already has answers here:
Sorting a deque using limited operations?
(3 answers)
Closed 6 years ago.
Given a deck of N cards. You have to sort them using following permissible operations:
You can see top 2 cards.
You can swap them.
You can insert top at the bottom.
Any ideas?
This seems to be a simple case of bubblesort, a very inefficient sorting algorithm that is described by smaller elements bubbling to the top (assuming that you are sorting in ascending order). The modified algorithm I'm about to present is very similar to the original bubblesort algorithm, so I am going to quickly explain the original first. Bubblesort (for ascending order) works as follows,
The first element in a list is marked.
If the element to the right of the marked element is less than the marked element, then the two elements are swapped.
The marker moves to the right one spot regardless of the outcome of step two
Steps two and three are repeated until the marked element becomes the last element in the list. Just for clarification, this means that when step 3 causes the last element to be marked, the iteration is over and a new iteration starts.
The four steps above are repeated until an iteration occurs where the marker goes through each element in the list without a single swap occurring. Here's an example from wikipedia, https://en.wikipedia.org/wiki/Bubble_sort#Step-by-step_example
So let's modify bubblesort so that a couple things change to fit the deck of cards scenario. Let's not think of the deck of cards as a deck, but more as a list. Yes, the first card in the deck will constantly be changing with each iteration of our modified bubblesort but can we make it so that cards are shifting while still maintaining the position of the first card in the deck? This question is to key to solving the problem. What I am saying is that moving the cards to the bottom of the deck will not change in the initial order of the cards, only swapping will. For example, consider this deck of cards where leftmost is the top and rightmost is the bottom:
NOTE: (*) signifies marked card
*5 3 1 2 6
In the algorithm that will later be explained, moving 5 to the bottom of the deck will make the deck look like this
3 1 2 6 *5
Notice how 5 is now at the bottom of the deck, but the order is still preserved. The * symbol signifies the first card in the list/deck, so if read from left to right, starting from 5 and looping back to 3, the order is preserved.
Now to the algorithm, how do we use what I just said to make this modified version of bubblesort as similar to the original? Simple, use this marking mechanism to make it so that we're not really sorting a deck, but rather a list of numbers. Before starting the algorithm, mark the top card in the deck. Here are the rest of the steps for each iteration of bubblesort:
Compare the top card with the card below it. If the top card is greater, then swap with the card below. If the marked card was swapped, then unmark the previously marked card and mark the new card at the top of the deck.
Place the top card of the deck to the bottom.
Steps 1 and 2 are repeated until the marked card resurfaces to being the second card in the deck (card below the top card)
Put the top card to the bottom of the deck, making the marked card the top card in the deck.
These steps are repeated for each iteration of the algorithm until an iteration occurs where no swaps were made. Here is an example to showcase the modified bubblesort:
NOTE: (*) signifies marked card
Iteration One:
5 3 1 2 6 //Mark the first card in the deck before starting
*5 3 1 2 6 //Compare 5(top card) with 3(card below it)
3 *5 1 2 6 //5 > 3 so swap
*3 5 1 2 6 //Since the marked card (5) was swapped, 3 becomes the new marked
//card to preserve original order of the deck
5 1 2 6 *3 //Top card is placed at the bottom
1 5 2 6 *3 //5 > 1 so swap
5 2 6 *3 1 //Put 1 at the bottom
2 5 6 *3 1 //5 > 2 so swap
5 6 *3 1 2 //Put 2 at the bottom
5 6 *3 1 2 //5 < 6 so no swap
6 *3 1 2 5 //Put 5 at the bottom
*3 1 2 5 6 //Marked card is second to top card, so put 6 at the bottom
//Marked card is now at the top, so new iteration begins
Before going into iteration two, I would like to point out that if you ran the original bubblesort, the resulting sequence from one iteration would be the same as the resulting sequence from one iteration of our modified algorithm.
Iteration Two:
*3 1 2 5 6 //3 > 1, so swap
*1 3 2 5 6 //Remark accordingly since the former marked card was swapped
3 2 5 6 *1 //Place 1 at the bottom
2 3 5 6 *1 //3 > 2, so swap
3 5 6 *1 2 //Place 2 at the bottom
3 5 6 *1 2 //3 < 5 so no swap
5 6 *1 2 3 //Place 3 at the bottom
5 6 *1 2 3 //5 < 6 so no swap
6 *1 2 3 5 //Place 5 at the bottom.
*1 2 3 5 6 //Since marked card is second to top card, place 6 at the bottom and end iteration
Iteration Three:
*1 2 3 5 6 //1 < 2 so no swap
2 3 5 6 *1 //Place 1 at the bottom
3 5 6 *1 2 //2 < 3 so no swap and place 2 at the bottom
5 6 *1 2 3 //3 < 5 so no swap and place 3 at the bottom
6 *1 2 3 5 //5 < 6 so no swap and place 5 at the bottom
*1 2 3 5 6 //Since marked card is second to top card, place 6 at the bottom and end iteration.
We now know to end the algorithm because an entire iteration has occurred without any swaps occurring, so the deck is now sorted. As for runtime, the worst case occurs, in terms of swaps, when the max number of iterations occurs which is n (size of the deck) times. And for each iteration, the worst case number of swaps occurs, which is also n times. So the big O is n*n or O(n^2).

Ascending Cardinal Numbers in APL

In the FinnAPL Idiom Library, the 19th item is described as “Ascending cardinal numbers (ranking, all different) ,” and the code is as follows:
⍋⍋X
I also found a book review of the same library by R. Peschi, in which he said, “'Ascending cardinal numbers (ranking, all different)' How many of us understand why grading the result of Grade Up has that effect?” That's my question too. I searched extensively on the internet and came up with zilch.
Ascending Cardinal Numbers
For the sake of shorthand, I'll call that little code snippet “rank.” It becomes evident what is happening with rank when you start applying it to binary numbers. For example:
X←0 0 1 0 1
⍋⍋X ⍝ output is 1 2 4 3 5
The output indicates the position of the values after sorting. You can see from the output that the two 1s will end up in the last two slots, 4 and 5, and the 0s will end up at positions 1, 2 and 3. Thus, it is assigning rank to each value of the vector. Compare that to grade up:
X←7 8 9 6
⍋X ⍝ output is 4 1 2 3
⍋⍋X ⍝ output is 2 3 4 1
You can think of grade up as this position gets that number and, you can think of rank as this number gets that position:
7 8 9 6 ⍝ values of X
4 1 2 3 ⍝ position 1 gets the number at 4 (6)
⍝ position 2 gets the number at 1 (7) etc.
2 3 4 1 ⍝ 1st number (7) gets the position 2
⍝ 2nd number (8) gets the position 3 etc.
It's interesting to note that grade up and rank are like two sides of the same coin in that you can alternate between the two. In other words, we have the following identities:
⍋X = ⍋⍋⍋X = ⍋⍋⍋⍋⍋X = ...
⍋⍋X = ⍋⍋⍋⍋X = ⍋⍋⍋⍋⍋⍋X = ...
Why?
So far that doesn't really answer Mr Peschi's question as to why it has this effect. If you think in terms of key-value pairs, the answer lies in the fact that the original keys are a set of ascending cardinal numbers: 1 2 3 4. After applying grade up, a new vector is created, whose values are the original keys rearranged as they would be after a sort: 4 1 2 3. Applying grade up a second time is about restoring the original keys to a sequence of ascending cardinal numbers again. However, the values of this third vector aren't the ascending cardinal numbers themselves. Rather they correspond to the keys of the second vector.
It's kind of hard to understand since it's a reference to a reference, but the values of the third vector are referencing the orginal set of numbers as they occurred in their original positions:
7 8 9 6
2 3 4 1
In the example, 2 is referencing 7 from 7's original position. Since the value 2 also corresponds to the key of the second vector, which in turn is the second position, the final message is that after the sort, 7 will be in position 2. 8 will be in position 3, 9 in 4 and 6 in the 1st position.
Ranking and Shareable
In the FinnAPL Idiom Library, the 2nd item is described as “Ascending cardinal numbers (ranking, shareable) ,” and the code is as follows:
⌊.5×(⍋⍋X)+⌽⍋⍋⌽X
The output of this code is the same as its brother, ascending cardinal numbers (ranking, all different) as long as all the values of the input vector are different. However, the shareable version doesn't assign new values for those that are equal:
X←0 0 1 0 1
⌊.5×(⍋⍋X)+⌽⍋⍋⌽X ⍝ output is 2 2 4 2 4
The values of the output should generally be interpreted as relative, i.e. The 2s have a relatively lower rank than the 4s, so they will appear first in the array.

Matrix, algorithm interview question

This was one of my interview questions.
We have a matrix containing integers (no range provided). The matrix is randomly populated with integers. We need to devise an algorithm which finds those rows which match exactly with a column(s). We need to return the row number and the column number for the match. The order of of the matching elements is the same. For example, If, i'th row matches with j'th column, and i'th row contains the elements - [1,4,5,6,3]. Then jth column would also contain the elements - [1,4,5,6,3]. Size is n x n.
My solution:
RCEQUAL(A,i1..12,j1..j2)// A is n*n matrix
if(i2-i1==2 && j2-j1==2 && b[n*i1+1..n*i2] has [j1..j2])
use brute force to check if the rows and columns are same.
if (any rows and columns are same)
store the row and column numbers in b[1..n^2].//b[1],b[n+2],b[2n+3].. store row no,
// b[2..n+1] stores columns that
//match with row 1, b[n+3..2n+2]
//those that match with row 2,etc..
else
RCEQUAL(A,1..n/2,1..n/2);
RCEQUAL(A,n/2..n,1..n/2);
RCEQUAL(A,1..n/2,n/2..n);
RCEQUAL(A,n/2..n,n/2..n);
Takes O(n^2). Is this correct? If correct, is there a faster algorithm?
you could build a trie from the data in the rows. then you can compare the columns with the trie.
this would allow to exit as soon as the beginning of a column do not match any row. also this would let you check a column against all rows in one pass.
of course the trie is most interesting when n is big (setting up a trie for a small n is not worth it) and when there are many rows and columns which are quite the same. but even in the worst case where all integers in the matrix are different, the structure allows for a clear algorithm...
You could speed up the average case by calculating the sum of each row/column and narrowing your brute-force comparison (which you have to do eventually) only on rows that match the sums of columns.
This doesn't increase the worst case (all having the same sum) but if your input is truly random that "won't happen" :-)
This might only work on non-singular matrices (not sure), but...
Let A be a square (and possibly non-singular) NxN matrix. Let A' be the transpose of A. If we create matrix B such that it is a horizontal concatenation of A and A' (in other words [A A']) and put it into RREF form, we will get a diagonal on all ones in the left half and some square matrix in the right half.
Example:
A = 1 2
3 4
A'= 1 3
2 4
B = 1 2 1 3
3 4 2 4
rref(B) = 1 0 0 -2
0 1 0.5 2.5
On the other hand, if a column of A were equal to a row of A then column of A would be equal to a column of A'. Then we would get another single 1 in of of the columns of the right half of rref(B).
Example
A=
1 2 3 4 5
2 6 -3 4 6
3 8 -7 6 9
4 1 7 -5 3
5 2 4 -1 -1
A'=
1 2 3 4 5
2 6 8 1 2
3 -3 -7 7 4
4 4 6 -5 -1
5 6 9 3 -1
B =
1 2 3 4 5 1 2 3 4 5
2 6 -3 4 6 2 6 8 1 2
3 8 -7 6 9 3 -3 -7 7 4
4 1 7 -5 3 4 4 6 -5 -1
5 2 4 -1 -1 5 6 9 3 -1
rref(B)=
1 0 0 0 0 1.000 -3.689 -5.921 3.080 0.495
0 1 0 0 0 0 6.054 9.394 -3.097 -1.024
0 0 1 0 0 0 2.378 3.842 -0.961 0.009
0 0 0 1 0 0 -0.565 -0.842 1.823 0.802
0 0 0 0 1 0 -2.258 -3.605 0.540 0.662
1.000 in the top row of the right half means that the first column of A matches on of its rows. The fact that the 1.000 is in the left-most column of the right half means that it is the first row.
Without looking at your algorithm or any of the approaches in the previous answers, but since the matrix has n^2 elements to begin with, I do not think there is a method which does better than that :)
IFF the matrix is truely random...
You could create a list of pointers to the columns sorted by the first element. Then create a similar list of the rows sorted by their first element. This takes O(n*logn).
Next create an index into each sorted list initialized to 0. If the first elements match, you must compare the whole row. If they do not match, increment the index of the one with the lowest starting element (either move to the next row or to the next column). Since each index cycles from 0 to n-1 only once, you have at most 2*n comparisons unless all the rows and columns start with the same number, but we said a matrix of random numbers.
The time for a row/column comparison is n in the worst case, but is expected to be O(1) on average with random data.
So 2 sorts of O(nlogn), and a scan of 2*n*1 gives you an expected run time of O(nlogn). This is of course assuming random data. Worst case is still going to be n**3 for a large matrix with most elements the same value.

Resources