Decode Ways Dynamic Programming | Total Ways to Decode a String | Count Encodings
Vložit
- čas přidán 2. 08. 2020
- Please consume this content on nados.pepcoding.com for a richer experience. It is necessary to solve the questions while watching videos, nados.pepcoding.com enables that.
NADOS also enables doubt support, career opportunities and contests besides free of charge content for learning. In this video, we discuss the Count Encodings problem where we are required to count and print all the encodings for a string as per the codes given in the question.
In this problem,
1. You are given a string str of digits. (will never start with a 0)
2. You are required to encode the str as per following rules
1 - a
2 - b
3 - c
..
25 - y
26 - z
3. You are required to calculate and print the count of encodings for the string str.
For 123 - there are 3 encodings. abc, aw, lc
For 993 - there is 1 encoding. iic
For 013 - This is an invalid input. A string starting with 0 will not be passed.
For 103 - there is 1 encoding. jc
For 303 - there are 0 encodings. But such a string maybe passed. In this case
print 0.
To submit this question, click here: www.pepcoding.com/resources/o...
For a better experience and more exercises, VISIT: www.pepcoding.com/resources/o...
#dp #decodeways #dynamicprogramming
Have a look at our result: www.pepcoding.com/placements
Follow us on our FB page: / pepcoding
Follow us on Instagram: / pepcoding
Follow us on LinkedIn: / pepcoding-education
when I was in college in 2012, there was no good content on the internet, Even the net was not so cheap at that time :P. but now I am seeing you guys putting this much effort into knowledge sharing is amazing. Today students are lucky to have instructors like you. Kudos, keep up the good work.
most under rated teacher on youtube
MOST Underrated Channel on CZcams!!
Very concise and informative video. That repetitive "chik hai" instead of "thik hai" though🤣
why did u point it out!! Now i cant avoid hearing it😂
Are bhai kya btaa diya bc bar bar ussi pe dhyan chala jata hai😂
I have not seen any teacher who is explaining so much except kj sir of mathematics for jee preparation in kota.I am from IIT Indore
Starting 5 mins gave me enough idea how to solve it. Thanks a lot. I refer to ur videos first.
Sir , amazing explaination !! Aap ek complex problem ko piece by piece aise explain kar dete ho jaise kuch ho hi nahi . Big fan Sumeet sir !
you are the best guy, making free tutorial
I am following your website and channel sir for data structures and algorithms. May be I am the luckiest guy to get this worldclass teaching free and hatsoff to your effort sir huge respect for you
This really means lot .Stay tuned and keep watching. For better experience visit on nados.pepcoding.com
Very nice explanation sir! Thankyou very much!
The way you teach is just amazing sir, you make every single line of code easy, Big Thank you.
Pepcoding is going to be a big brand in these coming days.
So nice of you!! aage bdtte rhiee and share as much as you can
thank you sir...u explained very well ❤
I would like to thank you for this question plus I was interviewed at one place where I explained the same way how you did and they were impressed, all because of you keep doing the good work. :)
Glad it helped!
Keep learning.
And for better experience, visit nados.io, where you will get well curated content and career opportunities.
Wow, the problem breakdown really helped to understand the question properly.
Thankyou beta!
I am glad you liked it. I hope that you are watching till the end and trying to understand what, how, and especially why of the problem.
If you like our efforts, will you like to write a few words about us here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )
always loved the way u teach us sir.......♥
Amazing explanation!
Great explanation.Really, hats off Sumit Sir.
The quality of the lessons when you are alone is much much better. You are a gifted teacher.
I hope someday you replace these videos.
I am glad. Keep learning. Keep supporting. Your kind words are the kind of motivation that truly help me in making more and more content. Especially, these days, not everybody is generous with motivating anybody either. It means a lot
great content sir....thank you so much
Thanks sir Amazing content .
Thanks a lot sir. bhut ache se sikhaya .
Thank you Sir!
Sir kamal ho gya sare questions hai apke pas jo companies m poochte h
thanks sir for such a good explanation
best explanation one can give in this problem, kudos to you. Thank you so much sir.
Thankyou beta!
I am glad you liked it. I hope that you are watching till the end and trying to understand what, how, and especially why of the problem.
If you like our efforts, will you like to write a few words about us here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )
@@Pepcoding sure sir
Thank You!
Amazing teaching Sir, I wish i had found this channel earlier. Thank you very much.
We also regret you found us so late. Can you help save some of your friends from this regret? We are dedicated to create top-notch content.
@@Pepcoding will definitely do
You are really hardworking and you are doing amazing work. One recommendation please, It would be more helpful if you could do this in recursion.
beta, DP ko tabulation se karenge. Recursion ki ek bhot fodu 50 questions ki alag playlist aaegi. Usme recursion itna ho jaega ki aap samjhenge kyun mai DP tabulation se pasand karta hun.
And maybe, I just got an idea. I will release a separate playlist for all DP questions, where all questions will be done via recursion (memoization)
@@Pepcoding yes sir
@@Pepcoding sir wo level2 hi hai na tagdi playlist recursion ke liye ,ya koi alag se aaegi
I am a noob in DSA and as a noob i can say that i loved this video and way of explanation and i understood clearly
Thank you! Cheers!
For better experience and well organised content visit on nados.pepcoding.com
Don't forget to follow us on Instagram instagram.com/pepcoding/
Great content sir 🙏🙏🙏 loved your explanation
I am glad you liked it. I also hope that you are watching till end and trying to understand the what, how and especially why of the problem.
If you like my efforts, I request a review
g.page/Pepcoding/review?rc
That is great sir
thanks a lot, quite helpful
Glad it helped and If you like our efforts, please upvote the comments written by the students about Pepcoding here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )
Thanku very much sirr :)
Great way of explanation.
Glad it was helpful! You can also check out nados.pepcoding.com for more such content and Free Resources✌️
Sir this dp series is very osm and understandable
Awesome sir🤩🤩
Well organized content
Thanks sir
Glad you liked it and If you like the content could you post something on LinkedIn about us? This will help us in reaching out to more people and help a lot of other students as well
Something like this
Sumeet Malik from Pepcoding is making all his content freely available to the community
You can check it out here - www.pepcoding.com/resources
/
Also, this is the youtube channel - czcams.com/users/Pepcodingplaylists?view_as=subscriber
I love the way you explained visually. Thanks a lot for your efforts. Keep it up.
I would like to add one point which make it bit simpler if we try to iterate values from last index.
Below solution is written in javascript as I'm not java guy :)
const solutionByDP=(s)=>{
const n=s.length;
if(n===0) return 0;
const dp=Array(n);
dp[n]=1;
for(let i=n-1; i>=0; i--){
if(s[i]==="0")
dp[i]=0;
else{
//add previous value for single chart/digit
dp[i]=dp[i+1];
//check double digit
if(i+1
Its fine if she is there as it becomes very abstract for a teacher to teach to a lifeless camera than to a human , it is a bit more easier.
thik hai
@@Sarojkumar-yh9uy chik hai
Sir really helpful, keep going.
Thank you, I will
@@Pepcoding TEST CASE : "06383" or "008834" is not covered :)
@@rahuljain5642 question mein diya hua hai , starting mein hamesha non zero hoga!
great explanation sir!
Glad it was helpful! and If you like our efforts, please upvote the comments written by the students about Pepcoding here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )
Nice sir 🥰
Me after looking at the final code:
Sochta hoon ki wo kitne masoom the...kya se kya ho gaye dekhte dekhte😂
Great explanation as always sir😊
wonderful explanation by sumeet malik sir
Keep watching and keep supporting us.
And for better experience and well curated content sign up on nados.io and start learning.
Thx u sir for this
Glad we helped you, for better experience and curated content sign up on nados.io, you can also post your queries on community tab of NADOS.
Sir but how do we identify a dp problem?
One test case is wrong sir.. I coded the same question on your website and failed a test case. It was for input (90), expected ans was gives as (0) but I don't get how? It should have been (1).. right?
Amazing
question tho maza agaya sir!!
Hope you like our explanation.☺️
For better experience and well-organized content visit - nados.pepcoding.com
"00".equals(any_string_variable); It helps in reducing NPE's. Just a programming practice.
Sir lovely explanation and if possible please make an option of adding questions as bookmarks on your site
There is a chrome extension by the name Geeks Assistant by Ronak Sakhuja for this purpose.
in case dp[i] = 0; Can't we directly return 0, instead of running the loop?
i was searching for this comment!!:)
Hello Sir, You are really explaining each topic in very depth... I'm loving your whole playlist. 😍 I'm just having 2 doubts so far:
1- Where should we take the array of "n" size? and where should we take it off "n+1"? because this is creating a lot of confusion in my mind.
2- How are we deciding ki 0 to 0 is the smaller problem? this can also be called the same for n to n is the problem?
And similarly, 0 to n is the bigger problem could also be said, n to 0 is a bigger problem.
Please elaborate this a bit, I've tried multiple ways and examples to clear this doubt but it's still there.
Thanks in Advance... 🤗
It depends on the problem and what the DP data structure is storing. A simple example of when n+1 would be necessary: let's say the DP array is storing computations where the index represents the length of a string. An array of size n will not have enough space for the case of an empty string (index 0), the case of the entire string (index n), as well as everything between. Size n does not allow indexing beyond n-1, while size n+1 allows indexing at n (which many problems call for).
In short if you represent index as a Value then the length of Array should be n+1 otherwise n
it depends upon the question
example : i am allowed to give you at max 3 rupees what are the possible coins i give you?
0,1,2,3 are the 4 possible answers
since 0 was also a possible solution u need a container of size 4 to store all the results
similarly in dp we have 2 options
a. to create a columns from 1 to n
b. to create columns from 0 to n , in this case we use n+1 sized container
Lets think about target sum subset , col 3 means can the array elements generate a target of sum 3 , if yes we place true otherwise false
In the same problem col 0 means can the array elements generate a target of sum 0
v1={1,2,3} v2={0,4,6} , note that v1 vector cant generate 0 as target so we push(false) but v2 vector can generate 0 so we push(true) i.e 0 is an important case and thus this problem belongs to type b.
problem2) count the number of possible outputs generated after decoding a string 123,
here
col 0=> number of possible outputs that can be formed by picking 0 elemnts from 1 bove string
Ans) obviously 0
col1=> number of outputs =1 i.e a
this questions belong to type a because 0th col will always be filled by 0 and col 1 is not dependent upon 0th col to get the answer so we omit it completly
in both the cases i have assumed empty subset as a solution is not allowed , otherwise v1={1,2,3} can also generate 0 as a target sum via an empty subset.
To sum up : we use 0th col in dp array if
1. it generates diff outputs for diff input array or
2. even if it generates the same output , the output is used as a base condition by col 1 or col 2 or any col in the right side
Otherwise we omit 0th column.
Hope this helps
why 1-D array, since supply are not unlimited, we should use 2d array right?
It is general suggestion that if you upload video of dp level up question then please make a new playlist that makes easy to learn...and diffrentiable ..thanx to make such a course..
Acknowledgement
Amazing explanation sir. Waiting for level up dp questions.
thank you beta. kal se shuru honge. next 17 days, 10 questions every day.
agar aapko content sahi lag rha hai to, please drop us a review
www.google.com/maps/place/PepCoding.com/@28.6993713,77.1360927,17z/data=!3m1!4b1!4m7!3m6!1s0x390d03d054d3e717:0x4fd0fdfc3f27ffaf!8m2!3d28.6993666!4d77.1382814!9m1!1b1
@@Pepcoding Done sir
sir can you please dry run it, cause i can't do it for this very question, I got the concept completely, but can't make a dry run for it
sir aap itna accha padhaate ho ki doubt hi nhi rahte kya doubt puche??
sir this dp series is undoubetely the best in india no paid or unpaid course can macth the level of this.
Great
1 case left. If str[0] == '0' then dp[0] = 0 else dp[0] =1
Sir i am adopting your technique feynman, but it take lot of hardwork
Keep it up
Sir jo qustn hm tabulation se kr rhe h kya hm unn questions ko memoization trick se kr skte h
Hanji beta, memoization se aap har recursive question ko kr skte ho. Aur memoization vala part aap logo k liye homework h, vo aap sbko khud krna h.
Great content sir .
I have a doubt regarding the above question.
We have solved all the cases but not of the type 013 which gives invalid input as we have taken dp[0] = 1 we have already considered it to be correct which cannot always be the case .
If you could help me out with this problem that would be great.
Actually this type of case is not given in the question itself and is considered invalid, that's why sir has taken dp[0]=1
leetcode decode ways solution:
Add up : string may contains leading zeroes.
class Solution {
public:
int numDecodings(string s) {
if(s.length()==1){
if(s[0]=='0')
return 0;
}
vector dp(s.size(),0);
dp[0]=1;
if(s.length()>=2){
if(s[0]=='0')
return 0;
}
for(int i=1;i=2?dp[i-2]:1);
else
dp[i]=0;
}
else if(s[i-1]!='0' && s[i]!='0'){
if(stoi(s.substr(i-1,2))=2?dp[i-2]:1);
else
dp[i]=dp[i-1];
}
}
return dp[s.length()-1];
}
};
No one can match sumit sir expalnation level....OP sumit sir
There should be a small change in the final solution where ever dp[i] = 0 replace it with dp[i] = dp[i-1] and in line 20 change it to dp[i] = (i >= 2 ? dp[i-2]+dp[i-1]: 1 ) rest of the logic is verified and correct
Isn't dp[i] = 0 is correct ? bco if number is >26 or =00 then 0 should be added and also dp[i] = (i >= 2 ? dp[i-2] : 1) bcoz we add [i-2] count there.
if 1st character is 0 then we need to return 0 and also if we encounter 00 then we also do the same.
Sir, how will you find count for 130 and 1304
Has anyone run this code in gfg
I don't think it works
Sumeet sir agar isme hum input 1201234 yeh le na toh ans ana chahiye 3 lekin is code ke hisab se 1 ara hai samaj nhi ara kyuki jabki humne charro case liye hai aur sir jab aap sabse pehle jab dp[0]=1 kare ho lekin agar sabse pehle no 0 hua toh us case ke liye hume condition lagani padegi agar pehle element 0 hai toh 0 warna 1 pr sir plz yeh btado yeh wale input ke liye galat kyu ara ans same yahi code likha hai.thanku in advance
3 hi aa raha hai answer... 1201234 ke liye... Shayad tumne code likhne mein koi mistake kar di hogi
Are you solving it using c++? If so, then are you using substr function, cause the 2nd parameter of that function is the length of the substring from the position. So you have to write s.substr(i-1,2) and it should work.
if str[0] = 0 then it prints 1 so you have to also add condition to check whether it is zero or non -zero
so that dp[0] = 0 or dp[0] = 1
U are right 👍
in the line dp[i]= i >=2? dp[i-2] : 1 , shouldn't 1 be replaced by dp[i-1]+1 . because we are counting ba and u . Also wouldn't line //19 work for 27 ,28,29 which is undesirable ..
Line 19 won't work for 27, 28, and 29 because we already stated that the second digit would always be equal to '0'.
@@suryanshyadav3423 Got it. Thanks!
sir ji , poora array kyu store karaya , last 2 elements ko store kara kar bhi to kam chal jayega or space bach jayegi
Bilkul sahi. Mai kai baar optimise nahi karta, khaaskar space. To aap agar better kar sakte hain to jaroor socha karie.
Damn 😍🔥🔥
Ye wala question Include Exclude Method se related nahi hai na sir??? Q ki previous video mein bola tha next 5-6 question same group ke hai.....ye ek dum alag hi method lag rha tha issliye
nhi ye uss group ka nahi hai
sir isme last m i-1,i+1
Sir what if the first charcter is zero ?
Why didn't we used 2D array here. Row represented as string and column represented as length of string?
Code is failing for this case : String Length = 2 and string starts with 0 (e.g. "06") because default value at dp[0] = 1. This needs to be checked if first character is 0 or not.
in question constraint is given string can not start with 0 so please read question again
sir the solution is wrong at 26th minute. Example : If the string is "29" , then for {2} -> we will store 1 in 0th index but at 2 index (with your code in video ) we will store 1 at 2nd index which is wrong as 29 >=2 :i-2:1 will evaluate to 1 only.
sir dont you think for 00 case, you should break the loop
btw great content !! :)
Thankyou beta!
I’ll go through it once again
@@Pepcoding and please correct me if i am doing it wrong
@@Pepcoding and after line no. 22 also we must add a break statement, basically we must break the loop once we get to add 0 to the DP array, I guess.
@@Pepcoding sir same in the case of target sum subset question agr ek baar bhi j = 10 pr true agaya to break the loop stop filling the dp array ......
Why sir do you not provide this content in c++
Sir is java developer aur language toh asan h maths algorithm seekho
11:35
sir : koi dikkat apko...
(see reaction on mam face)🤣🤣🤣🤣🤣🤣
What if the ending of the string is something like ......."001". At 1, we will be putting dp[i] = dp[i-1] = 0 but isn't that wrong ?
Bro This itself is a wrong string . Because if you have two zeros simultaneously , how you gonna decode it. Suppose I give you a string 11001 . How will you decode it .There is no way of decoding it .So the answer will be zero.
Full PRO
How to print all the string combinations ?
For better insight, visit nados.io, post your doubts, community will help you out there.
only fo 1 case,
remaining case ,you can do same way.
Kya ye ek better tareeka hota iss problem ko solve karne ka?
for(int i=1;i0)
{
dp[i]+=dp[i-1];
}
if(two>=10 && two2?dp[i-2]:1);
}
}
Visit nados.pepcoding.com and sign up to NADOS, for better experience, precisely arranged content and you can also post your query on community tab.
Don't forget to follow us on Instagram instagram.com/pepcoding/
Happy Coding!
Please note there is an edge case missing in this
if(s.charAt(0)=='0'){
dp[0]=0;
}else {
dp[0]=1;
}
if the first character is 0 than dp[0]= 0 else dp[0]=1
the question has stated that 0th index cannot be 0
For leetcode add this one case:
if(str.charAt(0) == '0'){
return 0;
}
Keep learning.
And for better experience, visit nados.io, where you will get well curated content and career opportunities.
what if initial characters are 0
Sir, please start graph(dfs, bfs) ☺
bhot jald. bass, 2-4 din mei.
Legend says that she is still saying 'chik haa '😂
keep motivating, keep learning and keep loving Pepcoding😊
you missed this case - "06" . for this answer should be 0 and your code will give 1. small correction --> dp[0] = s.charAt(0) != '0' ? 1 : 0;
you are right
Clarity X 1e16
For better experience, doubt support, career opportunities and well-organised content, visit - nados.pepcoding.com
Don't forget to follow us on Instagram
instagram.com/pepcoding/
2 3 1 akele akele agr rkhe to 3 bna skte h why this case is not considered
Sir, iss question ke test cases mein 21100, 21123 daldijiye. Galat result pe bhi submit horha h.
Thank you beta. Update kar dunga.
21100 vle ka ans 0 aayega?
@@aashishjha3223 haan bhai 0 ayega
we should use if else for dp[0], it can not we always 1 if s[0]==0 than dp[0] will be 0.
doubts ke liye yahi content nados.pepcoding.com pe consume karein
Memoized Dp sol
public static int numDecodings(String s) {
int dp[] = new int[s.length() + 1];
Arrays.fill(dp, -1);
return countEnc(s, dp);
}
public static int countEnc(String str, int dp[]) {
int n = str.length();
if (str.length() < 0 || str.equals("0")) return 0;
if (str.length() == 0 || str.length() == 1) return 1;
if (dp[n] != -1) return dp[n];
String one = str.substring(0, 1);
String two = str.substring(0, 2);
int ans1 = 0, ans2 = 0;
if (isCharacter(one)) {
ans1 = countEnc(str.substring(1), dp);
}
if (isCharacter(two)) {
ans2 = countEnc(str.substring(2), dp);
}
return dp[n] = ans1 + ans2;
}
private static boolean isCharacter(String str) {
if (str.length() == 1) {
int no = Integer.parseInt(str);
return no > 0;
} else {
if (str.charAt(0) != '0') {
int no = Integer.parseInt(str);
return no 0;
}
}
return false;
}
can someone please give the c++ code?? my code is giving wrong answer 🙏🙏😭
Visit - nados.pepcoding.com and sign up to NADOS.
You can ask your doubts on community tab. There are lots of programmers and mentors who can help you out with such doubts.
Don't forget to follow us on Instagram instagram.com/pepcoding/