Time complexity of longest palindrome finding algorithm - java

Can some one help me out on this algorithm time complexity? It`s a leetcode task to find the longest palindromic substring (https://leetcode.com/problems/longest-palindromic-substring/). I belive this is O(n³), but how to count this? My approach was: for loop goes s.length times (call it n), inner loop, in a worse case where string consist of equal chars, will expand the window n times, hence O(n²). But working time seems to be to big for O(n^2).
Here's code:
public String longestPalindrome(String s) {
if (s.length() == 1) {
return s;
}
String max = "";
for (int i = 0; i < s.length() - 1; i++) {
int lpointer = i;
int rpointer = i + 1;
while (rpointer < i + 3) {
int t = rpointer;
System.out.println(lpointer + " " + rpointer);
while (lpointer >= 0 && rpointer < s.length() && s.charAt(lpointer) == s.charAt(rpointer)) {
lpointer--;
rpointer++;
}
String temp = s.substring(lpointer + 1, rpointer);
max = max.length() < temp.length() ? temp : max;
rpointer = t + 1;
lpointer = i;
if (rpointer == s.length()) {
break;
}
}
}
return max == "" ? String.valueOf(s.charAt(0)) : max;
}
Much appreciate any help!

I’d say your algorithm is an O(n²) even though you have three loops:
The time-complexity of the for loop is quite easy: You have n iterations for a n long string. The inner while loops are a bit more complex:
I noticed that outside the inner while loop the both cursers have always the difference from 1 or 2. I guess that’s because you want to check for even and uneven palindromes. That means that the inner while loop is only running twice for every iteration of the for loop. In addition, the inner while loop can max run the half the length of the string because it searches in both directions. This leads to both while loops having a complexity of 2 * n/2 which equals n. So n*n leads to O(n²).
Still, besides the time-complexity, your code runs very slow (>700ms) compared to the average submissions.
With some optimization I was able to reproduce an O(n²) algorithm with only 15ms running time. It uses pretty much your attempt. The only major difference is that instead of having the two inner while loops to differentiate between even and uneven numbers it uses two different separate loops:
public static String longestPalindrome(String s) {
if (s.length() <= 0) return "";
char[] chars = s.toCharArray();
int longest = 0;
int iLongest = 0;
for (int i = 0; i < chars.length; i++) { //position to start from
if (longest == chars.length || (chars.length - 1 == longest && ((chars.length % 2 != 0 && longest % 2 == 0) || i - 1 > longest / 2))) break; //skip useless iterations
//uneven
for (int j = 0; j <= (chars.length - 1 - i < i ? chars.length - 1 - i : i); j++) { //max length possible in both directions
if (chars[i+j] == chars[i-j]) {
int nLongest = j*2+1;
if (nLongest > longest) {
longest = nLongest;
iLongest = i;
}
} else break;
}
//even
for (int j = 0; j <= (chars.length - 1 - i < i ? chars.length - 1 - i : i - 1); j++) {
if (chars[i+j] == chars[i-j-1]) {
int nLongest = (j+1)*2;
if (nLongest > longest) {
longest = nLongest;
iLongest = i;
}
} else break;
}
}
int start = iLongest - ((longest % 2 == 0 ? longest : longest - 1) / 2);
int stop = iLongest + ((longest - 1) / 2);
return s.substring(start, stop + 1);
}
Hope that answeres your question.

Related

How would I calculate big-O for this Algorithm

I have got this algorithm
int count = 0;
for(int i = n; i >= 1; i = i/2) {
for ( int j = 1; j <= i; j++) {
count++;
}
}
Am I right in saying that the Big-O for this would be n/2?
TL;DR The time complexity is O(n).
More details
Am I right in saying that the BigO for this would be n/2?
No that is accurate, in big-O notation you drop the constant part so (1/2)n simplifies to O(n).
I am not sure where that n/2 comes from because only the outer loop
for(int i = n; i >= 1; i = i/2) {
...
}
is log2n not n/2.
And with both loops together:
int count = 0;
for(int i = n; i >= 1; i = i/2) {
for ( int j = 1; j <= i; j++) {
count++;
}
}
the count would vary between N and 2N.
Let us go through the calculations:
int count = 0;
for(int i = n; i >= 1; i = i/2) {
for ( int j = 1; j <= i; j++) {
count++;
}
}
The inner loop will execute N iterations then N/2, then N/4 ... until N/N.
In another words we have (N + N/2 + N/4 ... N/N) which can be simplified to N * (1/2 + 1/4 + .. + 1/2^L)), with L = Log2 N.
This (1/2 + 1/4 + .. + ) series is well-known for being 1. Therefore, we can simplified N * (1/2 + 1/4 + .. + 1/2^L)) to O(N).
You are correct! This is basically a geometric progression with a quotient of 2 and the number of elements is lg(n) as we divide i by 2 each iteration of the outer loop.
1, 2, 4, ..., n
Using a known formula to calculate the sum, we get:
The reason we have lg (n) elements, is because we divide i each iteration by 2, thus we need to solve for the number of iterations k:

What is the role of temp = 0 in finding primes?

I have the following code to print all prime numbers from 2 to 100:
int number1 = 2, number2 = 100, temp = 0;
System.out.println("prime numbers between" + number1 + "and" + number2 + "are :");
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp = 0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
What is the role of temp = 0 in the very beginning?
If I modify it to, lets say 1, I get a different output. The code then prints all primes starting from 5 instead of 2. Why are the other numbers skipped?
Explanation
Have a close look at your loop logic flow:
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp=0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
i starts as 2 and increments. The inner loop is:
for (int j = 2; j <= i / 2; j++) {
Inner loop is skipped
That means that for the first iterations of the outer loop, for example i = 2 the condition of the inner loop evaluates to:
j <= i / 2
// which is
2 <= 2 / 2
// which is
2 <= 1
Hence the inner loop does not even enter at all and is skipped. So we directly reach
if (temp == 0) {
System.out.println(i);
}
The same is true for the iterations, i = 3.
i = 4 is the first iteration that actually enters the inner loop and starts overwriting temp with either 0 or 1.
Meaning of temp == 0
So during the first iterations of the outer loop (i = 2, i = 3), the initial state of temp plays a role, since it determines whether i will be printed or not.
So you need it to start as 0 to have the first values, for which the inner loop is not even entered, included in the output.
Notes
That said, using temp in such a way is overly complicated. It would be better if it would be moved to the place where it is actually needed, inside the loop, given a better name and also changed to a boolean. All in all, you may simplify the code as follows:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i);
}
}
And if you are willing to introduce a helper method like:
public static boolean isPrime(int candidate) {
for (int i = 2; i <= candidate / 2; i++) {
if (candidate % i == 0) {
return false;
}
}
return true;
}
Your code will heavily simplify and be very easy to read:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
you need to understand, what is the role of the variable temp in this code.
The variable temp is behaving like a flag, means whenever the number found to be divisible by another number, temp variable is setting as 1 and the code stops checking.
if we scan all the number upto i/2 and the variable temp is still 0, means we didn't find any number j which can divide current number i, then the current number is prime.
edit:
the role of temp=0 at the very beginning assumes all the number is prime. if found later number is divisible then we are assigning temp=1 and we get to know that the number is not prime.
The role in temp is to simply indicate if a prime was or was not found. Then use that value to control printing of the value under test. But it is not really needed (and as already stated in the comments, should have been a boolean).
Here is one way you could improve your effort without using that value.
Other than dividing by already found primes, you can make it somewhat more efficient by doing the following:
If the first prime is even, check to make certain it isn't 2.
if it is, print it.
if even, increment number1 by 1 to make it odd.
then starting iterating by both candidates and divisors by two to get just the odd numbers.
don't divide by any number > the square root of the candidate. Otherwise you are wasting time. Example, if 97 is not divisible by any of 3,5,7,11 then it must be a prime because any larger divisor would return a quotient < 11 which has already been checked.
you don't need a temp value. Just continue to the outer loop if the number is divided. Otherwise, print the number.
int number1 = 2, number2 = 100;
System.out.println("prime numbers between" + number1 + "and"
+ number2 + "are :");
if (number1 % 2 == 0) {
if (number1 == 2) {
System.out.println(2);
}
number1++;
}
outer:
for (int i = number1; i <= number2; i += 2) {
int max = (int)Math.sqrt(i);
for (int j = 3; j <= max; j += 2) {
if (i % j == 0) {
// try next candidate
continue outer;
}
}
// must be a prime so print it.
System.out.println(i);
}
A better approach is to use the Sieve of Erastosthenes. A BitSet is perfect for this. The idea is to:
mark every bit that is not a prime.
This eliminates composite numbers since it eliminates all their prime factors from the composite positions in the bitset.
The unset bit positions in the bitset are then primes.
as the list is being built, the first unset (clear) bit in the list is as prime.
BitSet bits = new BitSet();
bits.set(0,2); // set bits 0 and 1
initialize nextBit to the first prime
int nextBit = 2; // essentially bitSet.nextClearBit(0);
Continue the loop while the next bit is less than the square root of the terminal value.
while (nextBit <= Math.sqrt(number2)) {
// mark every prime position after this one.
for (int i = 2*nextBit; i < number2; i += nextBit) {
bits.set(i);
}
// the next clear bit after the previous prime must be a prime
// since it is next unset bit
nextBit = bits.nextClearBit(nextBit+1);
}
Now display them
// This is done by simply printing all the bit positions
// that are clear up to the terminal value.
int i = bits.nextClearBit(0);
while (i < number2) {
System.out.println(i);
i = bits.nextClearBit(i+1);
}

What's the effect of changing this condition in this Java function to find palindromes?

I am wondering how changing this condition will change the way the function works:
public static boolean palindrome(String str) {
int i = 0;
int j = str.length() - 1;
while(i < j) { // This condition
if(str.charAt(i) != str.charAt(j)) {
return false;
}
i = i + 1;
j = j - 1;
}
return true;
}
Changing it as follows:
public static boolean palindrome(String str) {
int i = 0;
int j = str.length() - 1;
while(i <= j) { // Change is here
if(str.charAt(i) != str.charAt(j)) {
return false;
}
i = i + 1;
j = j - 1;
}
return true;
}
They seem to both detect palindromes. The second one takes one more step. I don't see how this changes anything.
Thank you!
Between while(i < j) and while(i <= j) The difference is that the second one has one additional step because in the end, you are comparing i with j as suppose just everything less than j
Example with input abcba:
// First Code Indices Checked (i and j)
0 < 4
1 < 3
2 < 2 //fails, done
// Second Code Indices Checked (i and j)
0 <= 4
1 <= 3
2 <= 2 //passes, continues
3 <= 1 //fails, done, unneeded comparison
And just like #azurefrog said : "You don't have to check past the
midpoint in palindrome detection"

beginner whats wrong with my method

public class assignment6part3 {
public static void main(String[] args) {
int q = 0;
for ( int count=1; count <= 10000; count++) {
if (Prime(count)) {
q = q + 1;
}
}
System.out.println("It comes out " + q + " times.");
}
public static boolean Prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 1; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
I'm trying to get the number of prime numbers between 0 and 10000, but when I run this, it says there are 0 prime numbers. What part of the code is causing this error?
Inside your function Prime your for loop runs like ::
for(int i = 1; i < Math.sqrt(n); i++), starting from i = 1 and every number is divisible by 1 and hence 0 prime numbers.. :P
Initialization condition for i shall be i = 2
Other things you might consider changing ::
for (int i = 1; i < Math.sqrt(n); i++) shall be changed to
for (int i = 1; i <= Math.sqrt(n); i++)
NOTE :: A more optimal way to find Primes would be https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
The code is returning false before it actually checks the numbers, because every number is divisible by 1. Also, in some cases such as 25 and 49, the factors are not less than the square root. Try this:
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}

Review an answer - Decode Ways

I'm trying to solve a question and my question here is why doesn't my solution work?. Here's the question and below's the answer.
Question taken from leetcode: http://oj.leetcode.com/problems/decode-ways/
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The number of ways decoding "12" is 2.
My solution:
The point with my solution is going backwards and multiplying the number of options if a split is found. By split I mean that digits can be interpreted in two ways. For example: 11 can interpreted in two ways 'aa' or 'k'.
public class Solution {
public int numDecodings(String s) {
if (s.isEmpty() || s.charAt(0) == '0') return 0;
int decodings = 1;
boolean used = false; // Signifies that the prev was already use as a decimal
for (int index = s.length()-1 ; index > 0 ; index--) {
char curr = s.charAt(index);
char prev = s.charAt(index-1);
if (curr == '0') {
if (prev != '1' && prev != '2') {
return 0;
}
index--; // Skip prev because it is part of curr
used = false;
} else {
if (prev == '1' || (prev == '2' && curr <= '6')) {
decodings = decodings * 2;
if (used) {
decodings = decodings - 1;
}
used = true;
} else {
used = false;
}
}
}
return decodings;
}
}
The failure is on the following input:
Input:"4757562545844617494555774581341211511296816786586787755257741178599337186486723247528324612117156948"
Output: 3274568
Expected: 589824
This is a really interesting problem. First, I will show how I would solve this problem. We will see that it is not that complicated when using recursion, and that the problem can be solved using dynamic programming. We will produce a general solution that does not hardcode an upper limit of 26 for each code point.
A note on terminology: I will use the term code point (CP) not in the Unicode sense, but to refer to one of the code numbers 1 though 26. Each code point is represented as a variable number of characters. I will also use the terms encoded text (ET) and clear text (CT) in their obvious meanings. When talking about a sequence or array, the first element is called the head. The remaining elements are the tail.
Theoretical Prelude
The EC "" has one decoding: the CT "".
The EC "3" can be destructured into '3' + "", and has one decoding.
The EC "23" can be destructured as '2' + "3" or '23' + "". Each of the tails has one decoding, so the whole EC has two decodings.
The EC "123" can be destructured as '1' + "23" or '12' + "3". The tails have two and one decodings respectively. The whole EC has three decodings. The destructuring '123' + "" is not valid, because 123 > 26, our upper limit.
… and so on for ECs of any length.
So given a string like "123", we can obtain the number of decodings by finding all valid CPs at the beginning, and summing up the number of decodings of each tail.
The most difficult part of this is to find valid heads. We can get the maximal length of the head by looking at a string representation of the upper limit. In our case, the head can be up to two characters long. But not all heads of appropriate lengths are valid, because they have to be ≤ 26 as well.
Naive Recursive Implementation
Now we have done all the necessary work for a simple (but working) recursive implementation:
static final int upperLimit = 26;
static final int maxHeadSize = ("" + upperLimit).length();
static int numDecodings(String encodedText) {
// check base case for the recursion
if (encodedText.length() == 0) {
return 1;
}
// sum all tails
int sum = 0;
for (int headSize = 1; headSize <= maxHeadSize && headSize <= encodedText.length(); headSize++) {
String head = encodedText.substring(0, headSize);
String tail = encodedText.substring(headSize);
if (Integer.parseInt(head) > upperLimit) {
break;
}
sum += numDecodings(tail);
}
return sum;
}
Cached Recursive Implementation
Obviously this isn't very efficient, because (for longer ETs), the same tail will be analyzed multiple times. Also, we create a lot of temporary strings, but we'll let that be for now. One thing we can easily do is to memoize the number of decodings of a specific tail. For that, we use an array of the same length as the input string:
static final int upperLimit = 26;
static final int maxHeadSize = ("" + upperLimit).length();
static int numDecodings(String encodedText) {
return numDecodings(encodedText, new Integer[1 + encodedText.length()]);
}
static int numDecodings(String encodedText, Integer[] cache) {
// check base case for the recursion
if (encodedText.length() == 0) {
return 1;
}
// check if this tail is already known in the cache
if (cache[encodedText.length()] != null) {
return cache[encodedText.length()];
}
// cache miss -- sum all tails
int sum = 0;
for (int headSize = 1; headSize <= maxHeadSize && headSize <= encodedText.length(); headSize++) {
String head = encodedText.substring(0, headSize);
String tail = encodedText.substring(headSize);
if (Integer.parseInt(head) > upperLimit) {
break;
}
sum += numDecodings(tail, cache); // pass the cache through
}
// update the cache
cache[encodedText.length()] = sum;
return sum;
}
Note that we use an Integer[], not an int[]. This way, we can check for non-existent entries using a test for null. This solution is not only correct, it is also comfortably fast – naive recursion runs in O(number of decodings) time, while the memoized version runs in O(string length) time.
Towards a DP Solution
When you run above code in your head, you will notice that the first invocation with the whole string will have a cache miss, then calculate the number of decodings for the first tail, which also misses the cache every time. We can avoid this by evaluating the tails first, starting from the end of the input. Because all tails will have been evaluated before the whole string is, we can remove the checks for cache misses. Now we also don't have any reason for recursion, because all previous results are already in the cache.
static final int upperLimit = 26;
static final int maxHeadSize = ("" + upperLimit).length();
static int numDecodings(String encodedText) {
int[] cache = new int[encodedText.length() + 1];
// base case: the empty string at encodedText.length() is 1:
cache[encodedText.length()] = 1;
for (int position = encodedText.length() - 1; position >= 0; position--) {
// sum directly into the cache
for (int headSize = 1; headSize <= maxHeadSize && headSize + position <= encodedText.length(); headSize++) {
String head = encodedText.substring(position, position + headSize);
if (Integer.parseInt(head) > upperLimit) {
break;
}
cache[position] += cache[position + headSize];
}
}
return cache[0];
}
This algorithm could be optimized further by noticing that we only ever query the last maxHeadSize elements in the cache. So instead of an array, we could use a fixed-sized queue. At that point, we would have a dynamic programming solution that runs in *O(input length) time and O(maxHeadSize) space.
Specialization for upperLimit = 26
The above algorithms were kept as general as possible, but we can go and manually specialize it for a specific upperLimit. This can be useful because it allows us to do various optimizations. However, this introduces “magic numbers” that make the code harder to maintain. Such manual specializations should therefore be avoided in non-critical software (and the above algorithm is already as fast as it gets).
static int numDecodings(String encodedText) {
// initialize the cache
int[] cache = {1, 0, 0};
for (int position = encodedText.length() - 1; position >= 0; position--) {
// rotate the cache
cache[2] = cache[1];
cache[1] = cache[0];
cache[0] = 0;
// headSize == 1
if (position + 0 < encodedText.length()) {
char c = encodedText.charAt(position + 0);
// 1 .. 9
if ('1' <= c && c <= '9') {
cache[0] += cache[1];
}
}
// headSize == 2
if (position + 1 < encodedText.length()) {
char c1 = encodedText.charAt(position + 0);
char c2 = encodedText.charAt(position + 1);
// 10 .. 19
if ('1' == c1) {
cache[0] += cache[2];
}
// 20 .. 26
else if ('2' == c1 && '0' <= c2 && c2 <= '6') {
cache[0] += cache[2];
}
}
}
return cache[0];
}
Comparision with your code
The code is superficially similar. However, your parsing around characters is more convoluted. You have introduced a used variable that, if set, will decrement the decode count in order to account for double-character CPs. This is wrong, but I am not sure why. The main problem is that you are doubling the count at almost every step. As we have seen, the previous counts are added, and may very well be different.
This indicates that you wrote the code without proper preparation. You can write many kinds of software without having to think too much, but you can't do without careful analysis when designing an algorithm. For me, it is often helpful to design an algorithm on paper, and draw diagrams of each step (along the lines of the “Theoretical Prelude” of this answer). This is especially useful when you are thinking too much about the language you are going to implement in, and too little about possibly wrong assumptions.
I suggest that you read up on “proofs by induction” to understand how to write a correct recursive algorithm. Once you have a recursive solution, you can always translate it into an iterative version.
So here is some what simpler way out for your problem. This is pretty close to calculating Fibonacci, with the difference that there are condition checks on each smaller size subproblem.
The space complexity is O(1) and time is O(n)
The code is in C++.
int numDecodings(string s)
{
if( s.length() == 0 ) return 0;
int j = 0;
int p1 = (s[j] != '0' ? 1 : 0); // one step prev form j=1
int p2 = 1; // two step prev from j=1, empty
int p = p1;
for( int j = 1; j < s.length(); j++ )
{
p = 0;
if( s[j] != '0' )
p += p1;
if( isValidTwo(s, j-1, j) )
p += p2;
if( p==0 ) // no further decoding necessary,
break; // as the prefix 0--j is has no possible decoding.
p2 = p1; // update prev for next j+1;
p1 = p;
}
return p;
}
bool isValidTwo(string &s, int i, int j)
{
int val= 10*(s[i]-'0')+s[j]-'0';
if ( val <= 9 )
return false;
if ( val > 26 )
return false;
return true;
}
Here is my code to solve the problem. I use DP , I think it's clear to understand.
Written in Java
public class Solution {
public int numDecodings(String s) {
if(s == null || s.length() == 0){
return 0;
}
int n = s.length();
int[] dp = new int[n+1];
dp[0] = 1;
dp[1] = s.charAt(0) != '0' ? 1 : 0;
for(int i = 2; i <= n; i++){
int first = Integer.valueOf(s.substring(i-1,i));
int second = Integer.valueOf(s.substring(i-2,i));
if(first >= 1 && first <= 9){
dp[i] += dp[i-1];
}
if(second >= 10 && second <= 26){
dp[i] += dp[i-2];
}
}
return dp[n];
}
}
Since I struggled with this problem myself, here is my solution and reasoning. Probably I will mostly repeat what amon wrote, but maybe someone will find it helpful. Also it's c# not java.
Let's say that we have input "12131" and want to obtain all possible decoded strings.
Straightforward recursive solution would do iterate from left to right, obtain valid 1 and 2 digits heads, and invoke function recursively for tail.
We can visualize it using a tree:
There are 5 leaves and this is number of all possible decoded strings. There are also 3 empty leaves, because number 31 cannot be decoded into letter, so these leaves are invalid.
Algorithm might look like this:
public IList<string> Decode(string s)
{
var result = new List<string>();
if (s.Length <= 2)
{
if (s.Length == 1)
{
if (s[0] != '0')
result.Add(this.ToASCII(s));
}
else if (s.Length == 2)
{
if (s[0] != '0' && s[1] != '0')
result.Add(this.ToASCII(s.Substring(0, 1)) + this.ToASCII(s.Substring(1, 1)));
if (s[0] != '0' && int.Parse(s) > 0 && int.Parse(s) <= 26)
result.Add(this.ToASCII(s));
}
}
else
{
for (int i = 1; i <= 2; ++i)
{
string head = s.Substring(0, i);
if (head[0] != '0' && int.Parse(head) > 0 && int.Parse(head) <= 26)
{
var tails = this.Decode(s.Substring(i));
foreach (var tail in tails)
result.Add(this.ToASCII(head) + tail);
}
}
}
return result;
}
public string ToASCII(string str)
{
int number = int.Parse(str);
int asciiChar = number + 65 - 1; // A in ASCII = 65
return ((char)asciiChar).ToString();
}
We have to take care of numbers starting with 0 ("0", "03", etc.), and greater than 26.
Because in this problem we need only count decoding ways, and not actual strings, we can simplify this code:
public int DecodeCount(string s)
{
int count = 0;
if (s.Length <= 2)
{
if (s.Length == 1)
{
if (s[0] != '0')
count++;
}
else if (s.Length == 2)
{
if (s[0] != '0' && s[1] != '0')
count++;
if (s[0] != '0' && int.Parse(s) > 0 && int.Parse(s) <= 26)
count++;
}
}
else
{
for (int i = 1; i <= 2; ++i)
{
string head = s.Substring(0, i);
if (head[0] != '0' && int.Parse(head) > 0 && int.Parse(head) <= 26)
count += this.DecodeCount(s.Substring(i));
}
}
return count;
}
The problem with this algorithm is that we compute results for the same input string multiple times. For example there are 3 nodes ending with 31: ABA31, AU31, LA31. Also there are 2 nodes ending with 131: AB131, L131.
We know that if node ends with 31 it has only one child, since 31 can be decoded only in one way to CA. Likewise, we know that if string ends with 131 it has 2 children, because 131 can be decoded into ACA or LA. Thus, instead of computing it all over again we can cache it in map, where key is string (eg: "131"), and value is number of decoded ways:
public int DecodeCountCached(string s, Dictionary<string, int> cache)
{
if (cache.ContainsKey(s))
return cache[s];
int count = 0;
if (s.Length <= 2)
{
if (s.Length == 1)
{
if (s[0] != '0')
count++;
}
else if (s.Length == 2)
{
if (s[0] != '0' && s[1] != '0')
count++;
if (s[0] != '0' && int.Parse(s) > 0 && int.Parse(s) <= 26)
count++;
}
}
else
{
for (int i = 1; i <= 2; ++i)
{
string head = s.Substring(0, i);
if (head[0] != '0' && int.Parse(head) > 0 && int.Parse(head) <= 26)
count += this.DecodeCountCached(s.Substring(i), cache);
}
}
cache[s] = count;
return count;
}
We can refine this even further. Instead of using strings as a keys, we can use length, because what is cached is always tail of input string. So instead of caching strings: "1", "31", "131", "2131", "12131" we can cache lengths of tails: 1, 2, 3, 4, 5:
public int DecodeCountDPTopDown(string s, Dictionary<int, int> cache)
{
if (cache.ContainsKey(s.Length))
return cache[s.Length];
int count = 0;
if (s.Length <= 2)
{
if (s.Length == 1)
{
if (s[0] != '0')
count++;
}
else if (s.Length == 2)
{
if (s[0] != '0' && s[1] != '0')
count++;
if (s[0] != '0' && int.Parse(s) > 0 && int.Parse(s) <= 26)
count++;
}
}
else
{
for (int i = 1; i <= 2; ++i)
{
string head = s.Substring(0, i);
if (s[0] != '0' && int.Parse(head) > 0 && int.Parse(head) <= 26)
count += this.DecodeCountDPTopDown(s.Substring(i), cache);
}
}
cache[s.Length] = count;
return count;
}
This is recursive top-down dynamic programming approach. We start from the begining, and then recursively compute solutions for tails, and memoize those results for further use.
We can translate it to bottom-up iterative DP solution. We start from the end and cache results for tiles like in previous solution. Instead of map we can use array because keys are integers:
public int DecodeCountBottomUp(string s)
{
int[] chache = new int[s.Length + 1];
chache[0] = 0; // for empty string;
for (int i = 1; i <= s.Length; ++i)
{
string tail = s.Substring(s.Length - i, i);
if (tail.Length == 1)
{
if (tail[0] != '0')
chache[i]++;
}
else if (tail.Length == 2)
{
if (tail[0] != '0' && tail[1] != '0')
chache[i]++;
if (tail[0] != '0' && int.Parse(tail) > 0 && int.Parse(tail) <= 26)
chache[i]++;
}
else
{
if (tail[0] != '0')
chache[i] += chache[i - 1];
if (tail[0] != '0' && int.Parse(tail.Substring(0, 2)) > 0 && int.Parse(tail.Substring(0, 2)) <= 26)
chache[i] += chache[i - 2];
}
}
return chache.Last();
}
Some people simplify it even further, initializing cache[0] with value 1, so they can get rid of conditions for tail.Length==1 and tail.Length==2. For me it is unintuitive trick though, since clearly for empty string there is 0 decode ways not 1, so in such case additional condition must be added to handle empty input:
public int DecodeCountBottomUp2(string s)
{
if (s.Length == 0)
return 0;
int[] chache = new int[s.Length + 1];
chache[0] = 1;
chache[1] = s.Last() != '0' ? 1 : 0;
for (int i = 2; i <= s.Length; ++i)
{
string tail = s.Substring(s.Length - i, i);
if (tail[0] != '0')
chache[i] += chache[i - 1];
if (tail[0] != '0' && int.Parse(tail.Substring(0, 2)) > 0 && int.Parse(tail.Substring(0, 2)) <= 26)
chache[i] += chache[i - 2];
}
return chache.Last();
}
My solution is based on the idea that the arrangement of items(char/digit) within a particular substring is completely independent of the same within a different substring.
So we need to multiply each of those independent ways to get the total number of ways.
// nc is the number of consecutive 1's or 2's in a substring.
// Returns the number of ways these can be arranged within
// themselves to a valid expr.
int ways(int nc){
int n = pow(2, (nc/2)); //this part can be memorized using map for optimization
int m = n;
if (nc%2) {
m *= 2;
}
return n + m - 1;
}
bool validTens(string A, int i){
return (A[i] == '1' || (A[i] == '2' && A[i+1] <= '6'));
}
int numDecodings(string A) {
int ans = 1;
int nc;
if ((A.length() == 0)||(A[0] == '0')) return 0;
for(int i = 1; i < A.length();i++){
if(A[i] == '0' && validTens(A, i-1) == false) return 0; //invalid string
while(i < A.length() && validTens(A, i-1)) {
if(A[i] == '0'){
//think of '110' or '1210', the last two digits must be together
if(nc > 0) nc--;
}
else nc++;
i++;
}
ans *= ways(nc);
nc = 0;
}
return ans;
}
Java solution with space and time complexity O(n)
public int numDecodings(String s) {
int n = s.length();
if (n > 0 && s.charAt(0) == '0')
return 0;
int[] d = new int[n + 1];
d[0] = 1;
d[1] = s.charAt(0) != '0' ? 1 : 0;
for (int i = 2; i <= n; i++) {
if (s.charAt(i - 1) > '0')
d[i] = d[i] + d[i - 1];
if (s.charAt(i - 2) == '2' && s.charAt(i - 1) < '7')
d[i] = d[i - 2] + d[i];
if (s.charAt(i - 2) == '1' && s.charAt(i - 1) <= '9')
d[i] = d[i - 2] + d[i];
}
return d[n];
}
Here is an O(N) C++ DP implementation.
int numDecodings(string s) {
if(s[0] == '0') return 0; // Invalid Input
int n = s.length();
// dp[i] denotes the number of ways to decode the string of length 0 to i
vector<int> dp(n+1, 0);
// base case : string of 0 or 1 characters will have only 1 way to decode
dp[0] = dp[1] = 1;
for(int i = 2; i <= n; i++) {
// considering the previous number
if(s[i-1] > '0') dp[i] += dp[i-1];
// considering the previous two numbers
if(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] < '7')) dp[i] += dp[i-2];
}
return dp[n];
}

Categories

Resources