⭐ Shop on Amazon to support me: [ Ссылка ]
⭐ NordVPN to protect your online privacy: [ Ссылка ]
⭐ NordPass to help manage all of your passwords: [ Ссылка ]
LeetCode 14. Longest Common Prefix
Problem link: [ Ссылка ]
Solution explained:
Solution 1: Horizontal scan
1. we can scan every single word in this given list, we assume the first word is the longest common prefix,
2. and then start checking from the second word in the list, we check if the current prefix candidate is a valid prefix for the current word that we are iterating on, if not, we'll just keep decrementing the current prefix length by 1 (trim the last character of it) until it becomes a valid prefix of the current word. Meanwhile, we could check if at any time, prefix.length() becomes zero, we could just return an empty string, this prune will help a lot in terms of time for some corner cases.
3. after we go through all words in the list, we can just return the final prefix string as the answer.
Solution 2: Vertical scan
1. we scan every single character of every single word by beginning from the first character of the first word, we'll use the first word as the possible longest common prefix candidate to start with;
2. in the inner for loop, we first check if the current character index i is equal to the current word length, if that's the case, we could simply break out of the loop and return the current prefix candidate as the result, or if the current word's character is not equal to the one that's at the same index from the first word, we should also break out and return;
3. if we could finish the two nested for loops until the end, that means, the very first word is our longest common prefix.
⭐ Support my channel and connect with me:
[ Ссылка ]
// TOOLS THAT I USE:
○ Memory Foam Set Keyboard Wrist Rest Pad - [ Ссылка ]
○ Electric Height Adjustable Standing Desk - [ Ссылка ]
○ Apple Magic Keyboard (Wireless, Rechargable) - [ Ссылка ]
○ Apple Magic Trackpad 2 (Wireless, Rechargable) - [ Ссылка ]
○ Apple MacBook Pro - [ Ссылка ]
○ All-In One Printer - [ Ссылка ]
○ Apple AirPods Pro - [ Ссылка ]
○ My new favorite Apple Watch - [ Ссылка ]
// MY FAVORITE BOOKS:
○ Introduction to Algorithms - [ Ссылка ]
○ Designing Data-Intensive Applications - [ Ссылка ]
○ Head First Java - [ Ссылка ]
○ Design Patterns - [ Ссылка ]
Coding interview made simple!
See the complete solutions to Leetcode problems: [ Ссылка ]
Support me on Patreon: [ Ссылка ]
Problem URL: [ Ссылка ]
My ENTIRE Programming Equipment and Computer Science Bookshelf:
[ Ссылка ]
And make sure you subscribe to my channel!
Your comments/thoughts/questions/advice will be greatly appreciated!
#softwareengineering #leetcode #algorithms #coding #interview #SDE #SWE #SiliconValley #programming #datastructures
Ещё видео!