Longest Common Prefix (LeetCode 14) | Full solution with animations and examples | Study Algorithms

  Рет қаралды 76,064

Nikhil Lohia

Nikhil Lohia

Күн бұрын

To see more videos like this, you can buy me a coffee: www.buymeacoffee.com/studyalg...
Most of the string based problems either revolve around a prefix or a suffix. A prefix is a character or a sequence of characters that occur in the beginning of a string. In this problem we try to find the longest common prefix in an array of strings. We first explore a naive and straight forward approach and then find an optimal solution using a neat little trick called sorting. Watch the video to learn how it makes the problem super easy to solve. All of this along with a dry-run of code in JAVA.
Chapters:
00:00 - Intro
01:03 - Problem statement and description
04:05 - Brute Force Method
07:10 - Efficient/Optimal solution
12:07 - Dry-run of Code
14:21 - Final Thoughts
Actual problem on LeetCode: leetcode.com/problems/longest...
📚 Links to topics I talk about in the video:
Brute Force Paradigm: • Brute Force algorithms...
Problems on Strings: • Strings
Quick Sort Algorithm: • Quick Sort super easy ...
Recursion based algorithm: • Recursion paradigms wi...
What is Big O?: • Big O Notation Simplif...
📘 A text based explanation is available at: studyalgorithms.com
Code on Github: github.com/nikoo28/java-solut...
Test-cases on Github: github.com/nikoo28/java-solut...
📖 Reference Books:
Starting Learn to Code: amzn.to/36pU0JO
Favorite book to understand algorithms: amzn.to/39w3YLS
Favorite book for data structures: amzn.to/3oAVBTk
Get started for interview preparation: amzn.to/39ysbkJ
🔗 To see more videos like this, you can show your support on: www.buymeacoffee.com/studyalg...
🎥 My Recording Gear:
Recording Light: amzn.to/3pAqh8O
Microphone: amzn.to/2MCX7qU
Recording Camera: amzn.to/3alg9Ky
Tablet to sketch and draw: amzn.to/3pM6Bi4
Surface Pen: amzn.to/3pv6tTs
Laptop to edit videos: amzn.to/2LYpMqn
💻 Get Social 💻
Follow on Facebook at: / studyalgos
Follow on Twitter at: / studyalgorithms
Follow on Tumblr at: / studyalgos
Subscribe to RSS feeds: studyalgorithms.com/feed/
Join fan mail: eepurl.com/g9Dadv
#leetcode #programming #interview

Пікірлер: 211
@dhritiarora4147
@dhritiarora4147 2 жыл бұрын
All the 15 mins were worth it. Great job!
@nikoo28
@nikoo28 2 жыл бұрын
Thanks for the support and motivation
@user-kg6gu7re2w
@user-kg6gu7re2w 8 ай бұрын
You always provide the best, easiest, and simplest approaches. I watch your explanations and then try to write the code independently, and I succeed most of the time. Keep making such great content. It really helps us a lot.
@nikoo28
@nikoo28 7 ай бұрын
that is so nice to hear. I hope to keep bringing quality content for you guys.
@quantisticnumbers2633
@quantisticnumbers2633 Жыл бұрын
Definitely one of the easiest and best solutions that I came across. Thanks for the video!
@englishpopop7694
@englishpopop7694 10 ай бұрын
this breakdown made things much more clear and easy to comprehend
@candichiu7850
@candichiu7850 2 жыл бұрын
Thank you! The BEST on KZbin. Super explanation.Keep up the great work.
@sumanthpai4587
@sumanthpai4587 7 ай бұрын
Very Articulately explained . with proper animations etc , really good job
@tashi7316
@tashi7316 Жыл бұрын
So far one of the best solution I have seen
@CostaKazistov
@CostaKazistov 2 жыл бұрын
Great style of teaching algorithms. 10/10 👍
@subhamagarwal476
@subhamagarwal476 Ай бұрын
addicted to your channel. You explain so simple and in easy way. Thanks a lot
@enriquegrageda
@enriquegrageda 5 ай бұрын
My bro, you are a great teacher!
@himadripaul7332
@himadripaul7332 2 жыл бұрын
excellent this channel will grow gradually ..no bakwas straight forward explanation ..
@HY-eu4ei
@HY-eu4ei Жыл бұрын
tried a lot of videos and i would say this was the best explanation of all such a easy and elaborative explanation. thank you
@nikoo28
@nikoo28 Жыл бұрын
Glad you feel this way ♥️
@egm5081
@egm5081 5 ай бұрын
man, what amazing explanation, thank you so much!
@saiyamjain6099
@saiyamjain6099 Жыл бұрын
Excellent explanation 🔥 keep making more videos loved it
@kunalkheeva
@kunalkheeva 2 жыл бұрын
your videos seem like bit longer, but its really very productive, I couldnot even skip it for a sec, just great work!! Thank you!
@nikoo28
@nikoo28 2 жыл бұрын
I really try to go over the concept, rather than just giving away the code...the same you would be solving a problem in an interview. Thanks for your support. Much appreciated. 😄
@nginx.h
@nginx.h Жыл бұрын
bro i stuck at this problem and i dont understand how to solve this question but after watching some video i not getting it better but u solve this question with very simple approach. 👍👍 well done bro
@shivenderkumar4521
@shivenderkumar4521 2 жыл бұрын
Very Simple and clear explaination , Thank you ❤
@gopro12378
@gopro12378 Жыл бұрын
Crystal clear concept thank you sir!
@raghavkaushal7561
@raghavkaushal7561 2 жыл бұрын
Thank you so much brother!!! Your explanation is extremely simple to understand and follow. Wish I had a teacher like you.
@kirankutte7073
@kirankutte7073 2 жыл бұрын
Awesome explaination. I liked the slow and animated explainartion. Good job!
@nikoo28
@nikoo28 2 жыл бұрын
Glad you liked it
@user-ig2kt4jp8i
@user-ig2kt4jp8i 10 ай бұрын
You're such a good teacher. Thank you!
@nikoo28
@nikoo28 9 ай бұрын
Glad you think so!
@sharcodes
@sharcodes 11 ай бұрын
Love your Solution. Best Wishes for You. I Would Love to see your Channel Grow, why this is so Underrated.
@nikoo28
@nikoo28 10 ай бұрын
Thanks for your support and motivation. I really hope the youtube algorithm picks up the channel soon 😅
@PankajYadav-nz4gn
@PankajYadav-nz4gn Жыл бұрын
Oh My GOD!!! I can't imagine that someone can be this good in explanation. Amazing and super thanks.
@nikoo28
@nikoo28 Жыл бұрын
Wow, thanks!
@aparna5778
@aparna5778 3 ай бұрын
Thanks for the explanation. Was easy to follow.
@satyamgupta6030
@satyamgupta6030 Жыл бұрын
great teaching bhaiya. I always look for ur videos whenever I search for a solution of a leetcode question. No one comes close to you when it comes to explaining multiple approaches and finally solving with the most optimal approach . Thanks bhaiya.
@nikoo28
@nikoo28 Жыл бұрын
It's my pleasure
@d54nirajthakare69
@d54nirajthakare69 Жыл бұрын
The level of Explanation I saw today was amazing !!!
@nikoo28
@nikoo28 Жыл бұрын
So happy you felt that way
@aradhyashukla2813
@aradhyashukla2813 Жыл бұрын
Explained a complex problem very easily 💯👏
@Prince-fv8mb
@Prince-fv8mb 11 ай бұрын
loved the way you explained sir.....This channel is highly underrated
@nikoo28
@nikoo28 10 ай бұрын
Thanks for your support and motivation. I really hope the youtube algorithm picks up the channel soon 😅
@animationTip
@animationTip 2 жыл бұрын
I love the way of explanation.Thank u so much making such a video bhaiya .
@eyerahulk
@eyerahulk 10 ай бұрын
Nice explanation, thanks man.
@vm1662
@vm1662 Жыл бұрын
Great explanation! Thank you. :)
@nickjr9994
@nickjr9994 11 ай бұрын
Very good explanation brother. This solution was so precise and easy to understand. Thanks a ton
@nikoo28
@nikoo28 10 ай бұрын
glad you liked it.
@parulsaraogi6770
@parulsaraogi6770 Жыл бұрын
Woww explained so well.. just loved it 🥰❤️
@punamroy6639
@punamroy6639 7 күн бұрын
great explaination. Thank you
@salmarafiq7695
@salmarafiq7695 Жыл бұрын
Amazing explanation!!!
@curiousvaita
@curiousvaita Ай бұрын
Amazing Solution. Thanks a lot.
@mdrabby1259
@mdrabby1259 Жыл бұрын
Very good explanation ❤😊
@ChaitanyaPimparkar
@ChaitanyaPimparkar 2 жыл бұрын
keep them coming
@AvinashKumar-ps4tw
@AvinashKumar-ps4tw Жыл бұрын
Very Crisp and interesting explanation
@colveness9155
@colveness9155 Жыл бұрын
ty for video, great explanation!
@niteshpandey8207
@niteshpandey8207 11 ай бұрын
Esko dekh ye pta chala ki aise bhi question solve kr sakte hai.... keep posting
@nikoo28
@nikoo28 11 ай бұрын
😄
@amitarajput1153
@amitarajput1153 Жыл бұрын
Best Teacher. Please upload more videos. Super thanks
@abhijitbiradar
@abhijitbiradar Жыл бұрын
very nicely explained. thanks
@PranitKothari
@PranitKothari Жыл бұрын
You explain nicely!
@LuckyAndDad
@LuckyAndDad Жыл бұрын
Excellent narration
@SMARTRIXDbztttmods
@SMARTRIXDbztttmods Жыл бұрын
*Excellent Work 🔥Thanks Sir*
@AmeyBhogaonkar-vy2bx
@AmeyBhogaonkar-vy2bx 2 ай бұрын
Worth it !!
@SaumyaSharma007
@SaumyaSharma007 Жыл бұрын
Thank you brother 🙌
@karthikarthick5192
@karthikarthick5192 Жыл бұрын
great one bro keep making more and more u make learning so damn easy
@chakri2622
@chakri2622 Жыл бұрын
this video made to subscriber to never loss hope and don't give up u will grow
@voidcrs
@voidcrs 4 ай бұрын
This is a great solution.
@palashbharati8818
@palashbharati8818 Жыл бұрын
string longestCommonPrefix(vector& strs) { sort(strs.begin(), strs.end()); string st=strs[0], end=strs[strs.size()-1]; string ans; for(int i=0;i
@oncloudnine4334
@oncloudnine4334 3 ай бұрын
bro can you explain why we go with first and last and explain why can't we go with first and second string
@gauravsharma4994
@gauravsharma4994 Жыл бұрын
Man that was awesome
@atishyadavit1036
@atishyadavit1036 6 ай бұрын
Amazing!!!!
@anshikagarg9485
@anshikagarg9485 2 жыл бұрын
I can't think... Thanku for this optimal approch
@TemuriChitashvili
@TemuriChitashvili 3 ай бұрын
Really good.😉
@md.shimul4805
@md.shimul4805 Жыл бұрын
Thank you so much!!!
@simo_the_goat
@simo_the_goat 7 ай бұрын
nice job
@khushaldodeja8267
@khushaldodeja8267 9 ай бұрын
Thankyou soo much buddy ❤️
@rishabhjain7651
@rishabhjain7651 Жыл бұрын
love to way of explaination 😍
@siddhigolatkar8558
@siddhigolatkar8558 7 ай бұрын
Thank you
@kateach8056
@kateach8056 10 ай бұрын
Thanks for solution.
@DalisYn
@DalisYn Жыл бұрын
Thank you so much this one was a bit confusing
@Chhooso
@Chhooso 6 ай бұрын
Finally was able to understand it😭👍
@erenyeager4452
@erenyeager4452 Жыл бұрын
Hey, found a similar problem but no one had a good solution online. The idea is to find the longest palindromic prefix. Would help a lot if you can make a video on this. thanks for the videos. love them.
@zack176
@zack176 Жыл бұрын
Wow so you are finally tired of destroying world
@spongebobsquarepants4576
@spongebobsquarepants4576 25 күн бұрын
Interesting solution with sorting - but then you get n*log n. You can simply search the list for the shortest word and then compare it with all other words, thus making it O(n * k) where k is the length of the shortest word. Depending on the input you have in a real life scenario, your approach might be more efficient if the strings are very long, so if the length of the shoertest string k > n where n is number of values in the list, then your approach is more efficient. Anyway cool explanation thanks!
@salmarafiq7695
@salmarafiq7695 Жыл бұрын
Sooooo goood:⁠-⁠) keep going 👏
@huquea
@huquea 2 жыл бұрын
OMG, you took teaching algorithm to next level
@nikoo28
@nikoo28 2 жыл бұрын
So happy you feel this way 😄
@anshikagarg9485
@anshikagarg9485 2 жыл бұрын
Awesome👍👍
@kamleshkumarsingh5140
@kamleshkumarsingh5140 5 ай бұрын
SC will be O(n) right for using stringbuilder?? Great explanation though
@nikoo28
@nikoo28 4 ай бұрын
you are absolutely correct. My bad..the space complexity will be O(n)
@hemant8762
@hemant8762 9 ай бұрын
Thank you so much sir
@bivashroy2829
@bivashroy2829 10 ай бұрын
If the string contain a mixture of capital and small letter then sorting can't be the solution... string commonPrefix(vector& strs,int n){ string s1 = strs[0]; int ans_length = s1.length(); for(int i = 0 ; i< n ; i++){ int j = 0 ; while(j
@debasmitadash9974
@debasmitadash9974 8 ай бұрын
You are amazing. ❤
@nikoo28
@nikoo28 8 ай бұрын
You're the best!
@subee128
@subee128 7 ай бұрын
Thank you very much
@nikoo28
@nikoo28 6 ай бұрын
Any time
@mohdsameer2445
@mohdsameer2445 11 ай бұрын
very nicely explained bro
@nikoo28
@nikoo28 11 ай бұрын
🤝
@ahmedabdul9137
@ahmedabdul9137 9 ай бұрын
What is the time complexity of the brute force approach?
@B_Drive_2K
@B_Drive_2K Жыл бұрын
Nice Solution
@kaustavhalder7263
@kaustavhalder7263 10 ай бұрын
wow what an explanation
@sarthakbhargava3514
@sarthakbhargava3514 11 ай бұрын
Thanks
@kidoo1567
@kidoo1567 9 ай бұрын
Asusal nikil is on fire❤
@SnigdhaVerma-rc8zl
@SnigdhaVerma-rc8zl Жыл бұрын
nikhil , can we use two for loops for this question?
@bxp_bass
@bxp_bass 11 күн бұрын
That optimization only works in python or other interpreted languages, where sorting is much cheaper than a loop. In golang or c or c++ it's much faster to do loops, so you don't need to spend O(n log n) on sorting
@muskancreativity7
@muskancreativity7 Жыл бұрын
Best explanation 💜
@nikoo28
@nikoo28 Жыл бұрын
Glad that you feel this way :)
@VaibhavSingh-kh3jr
@VaibhavSingh-kh3jr 2 ай бұрын
Maza aayega ❤
@quartekstudio8127
@quartekstudio8127 5 ай бұрын
I was stucking this question for 4 days by watching many of videos but I can't find out the best way to answer this question. But you did and explain it really well. I know I'm not that good as problem solving but you are the one who can explain the concept from really hard to a really human can understanding really easy
@officialdreamplayz
@officialdreamplayz 4 ай бұрын
how many questions u have conquered till now i m on 4th (easy)
@quartekstudio8127
@quartekstudio8127 4 ай бұрын
@@officialdreamplayz just only 6-7. We are going slow because I think we are missing something or some concept to answer or design to answer the question. I think keep doing it will help us a lot. For me answering in Code war was really easy more than leetcode
@nikoo28
@nikoo28 4 ай бұрын
all the very best...and glad to see your progress
@user-fx1kt1ev2b
@user-fx1kt1ev2b Жыл бұрын
Great explanation, but I would add a check for potential issue where an Index error can occur if the first and last strings in the strs array have different lengths. Like this: min_length = min(len(first), len(last)) for i in range(min_length)
@nikoo28
@nikoo28 Жыл бұрын
Sure, you can do that
@kshiteeshmani1756
@kshiteeshmani1756 2 жыл бұрын
I tried implementing your code in c++, but I am getting an error on the test case when the input is [" "] in leetcode, how to handle this, because " " in strings would be an empty string.
@nikoo28
@nikoo28 2 жыл бұрын
Check the code in given link in video description. That should help you out.
@SouravCheck
@SouravCheck 2 ай бұрын
2:07, A is also a counted in prefix?
@denisgordiy5718
@denisgordiy5718 Жыл бұрын
Thank you for great explanation. IMHO more efficiently is not to use StringBulider but just return first.substring(0, index)
@nikoo28
@nikoo28 Жыл бұрын
The difference will be very minute. :)
@abhiramsathiraju6276
@abhiramsathiraju6276 9 ай бұрын
Can we optimize it further and make it O(N) ??? Help me if anyone know how to do that!!
@Atharva_kathiyawadi
@Atharva_kathiyawadi 2 жыл бұрын
wah bro amazing
@ashish4k07
@ashish4k07 7 ай бұрын
Can O(n) be possible like finding the max lengthed word and least lengthed word and compare them just the doubt
@nikoo28
@nikoo28 7 ай бұрын
Try writing a pseudo code for it
@amolgawai010
@amolgawai010 25 күн бұрын
Great Explanation, small correction: Space complexity is O(n)
@nikoo28
@nikoo28 22 күн бұрын
we aren't using any extra space to arrive at the solution
@CodingJourney-sz3og
@CodingJourney-sz3og 5 ай бұрын
i have a query , why we are comparing rhe first and the last string in the efficient solution after sorting the strings .. after sorting even first two strings can give the solution
@officialdreamplayz
@officialdreamplayz 5 ай бұрын
clever clue deliver now compare 1st and 2nd 😂
@rishidangi2978
@rishidangi2978 5 ай бұрын
first and the last string will have the maximum possible difference, while first and second will have the minimum difference as they're sorted
@keshavkaushlya8355
@keshavkaushlya8355 11 ай бұрын
if possible try to show the code for brute force approach also, this helps in understandig the problem in a much better way,btw doing great work,appreciated.
@nikoo28
@nikoo28 11 ай бұрын
thanks for your feedback and support :)...but usually coding for brute force is not desirable...i only do that in scenarios when you tweak a brute force approach to convert it to an optimal solution.
@saurabhsaxena8470
@saurabhsaxena8470 10 ай бұрын
In actual interviews, should we just explain the brute force solution and code only the optimal solution or try to code both?@@nikoo28
@amitshukla2268
@amitshukla2268 9 ай бұрын
Hey Bro really thanks, wanna give a suggestion, please use dark color in ppts.
@nikoo28
@nikoo28 8 ай бұрын
i prefer while, as it gives an experience with whiteboarding as well. You will be doing a lot of whiteboarding in any organization. 😄
@sahilbait2981
@sahilbait2981 10 күн бұрын
Please make a video on Repeated String Match question
@BljtKuntal
@BljtKuntal Жыл бұрын
thats great one, but you should also discuss optimised sol also
@nikoo28
@nikoo28 Жыл бұрын
The optimised solution starts at 07:10
@devxbasit
@devxbasit 9 ай бұрын
helpful, I just wanted to directly jump to the time complexity timestamp, but could not find it
@nikoo28
@nikoo28 8 ай бұрын
check the video description please.
@MaksymKondratiuk
@MaksymKondratiuk 5 ай бұрын
Thanks for the video. But in the end, it looks a bit confusing. The time complexity of the "brute force" approach should O(n * m) where m is the length of the string and in the case of the "efficient approach" we will have O(n * m * log n) which is slower than the previous one. Is it a case or did I miss something?
@Ishankulkarni
@Ishankulkarni 3 ай бұрын
You are correct
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 356 М.
ТАМАЕВ УНИЧТОЖИЛ CLS ВЕНГАЛБИ! Конфликт с Ахмедом?!
25:37
Эффект Карбонаро и нестандартная коробка
01:00
История одного вокалиста
Рет қаралды 9 МЛН
This is not my neighbor  Terrible neighbor! #funny #zoonomaly #memes
00:26
Scary Teacher 3D Nick Troll Squid Game in Brush Teeth White or Black Challenge #shorts
00:47
LeetCode 14. Longest Common Prefix Solution Explained - Java
6:33
Longest Common Prefix - Leetcode 14 - Python
6:31
NeetCode
Рет қаралды 157 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 261 М.
How To Solve Algorithms - Longest Common Prefix
9:31
Web Dev Simplified
Рет қаралды 30 М.
How Bugatti's New Electric Motor Bends Physics
9:25
Ziroth
Рет қаралды 75 М.
Doing LeetCode Be Like (Coding Interviews Be Like Pt. 2)
4:41
Nicholas T.
Рет қаралды 751 М.
ТАМАЕВ УНИЧТОЖИЛ CLS ВЕНГАЛБИ! Конфликт с Ахмедом?!
25:37