Length of Last Word - Leetcode 58 - Python

  Рет қаралды 43,889

NeetCode

NeetCode

Күн бұрын

Пікірлер: 49
@NeetCode
@NeetCode 3 жыл бұрын
✅ EASY PLAYLIST: kzbin.info/www/bejne/gX3PiXZ8fJqHpKM
@chiraagpala3243
@chiraagpala3243 3 жыл бұрын
will you be making a hard playlist as well?
@aNoobLikeSaibot
@aNoobLikeSaibot 2 жыл бұрын
I answered this question by myself with no help and it was pretty awesome. I finally did a problem without help. I used a for loop and started from the end of the string to the beginning. The conditions were, if my counter variable is zero and next character is a space, continue, else if, increment counter variable by one and else is break. Hope that makes some senses but it worked!
@marztianpapi3419
@marztianpapi3419 2 жыл бұрын
my code was new = s.strip(“ “).split(“ “) return len(new[-1])
@amra-dev
@amra-dev 3 жыл бұрын
If you are interested in Solving Python Builtin Functions, this might help. stip() will remove all covering spaces from string split(" ") will split string into array separated by " " len(res[-1]) will return length of last word res = s.strip().split(" ") return len(res[-1])
@gayan1742
@gayan1742 3 жыл бұрын
But then it would be 10x slower.
@venkatasundararaman
@venkatasundararaman 2 жыл бұрын
@@gayan1742 Actually it is faster than the solution in the video. Runtime: 28 ms, faster than 91.49% of Python3 online submissions for Length of Last Word. I feel it is ok to use the built in function as we are going to only use them in real world scenario.
@gayan1742
@gayan1742 2 жыл бұрын
@@venkatasundararaman ​ Maybe it's because the solution in the video uses two iterations, which is not really necessary. Iterating from the last character to the left until a space is found, then returning the length does also work. The last time I tried, it took only 0 ms. Not sure if it is because I used Java or not.
@lambdadelta_witch
@lambdadelta_witch Жыл бұрын
Splitting needs to be done only once, so s.rsplit(maxsplit=1)
@mufaddalmotiwala8672
@mufaddalmotiwala8672 Жыл бұрын
better still, you can just do return(len(s.split()[-1]))
@swimmingshi
@swimmingshi 3 жыл бұрын
strip() and split() string will also do. but watching your video I find sometimes algorithmic solutions might not be intuitive at first but your solution is really clever. I will keep watching your videos
@leeroymlg4692
@leeroymlg4692 2 жыл бұрын
don't need to .strip(). split() removes all the whitespace
@user-nq7nt1rq9b
@user-nq7nt1rq9b 3 жыл бұрын
Hey man one personal question for you from where did you have learned the basic of Data structure and algorithm and your video are pretty much helpful to me Thanks a Ton
@shivarajbandaru2216
@shivarajbandaru2216 Жыл бұрын
class Solution: def lengthOfLastWord(self, s: str) -> int: x="1" y=[] for i in reversed (s): if i>x: y.append(i) if len(y)>0: if i
@everyontech2716
@everyontech2716 Жыл бұрын
easy class Solution: def lengthOfLastWord(self, s: str) -> int: temp = "" # using strip method we are actually remove whitespace from lefft and right side string = s.strip() for i in string: if i.isspace(): temp = "" else: temp = temp + i return len(temp)
@rajarajan1338
@rajarajan1338 11 ай бұрын
A very simple method class Solution: def lengthOfLastWord(self, s: str) -> int: count = 0 for i in s[::-1]: if i == " ": if count >= 1: return count else: count += 1 return count
@GfoxSim
@GfoxSim 8 ай бұрын
I solved this in one line using Python3 built-in functions and it's fast and efficient. return len(s.strip().split()[-1])
@QuantumVortex17
@QuantumVortex17 2 жыл бұрын
I have submitted this: class Solution(object): def lengthOfLastWord(self, s): array = s.split(' ') x = array[len(array)-1] count = 0 while x == '': count += 1 x = array[len(array) - count] if x != '': counter = 0 for i in x: counter += 1 return counter
@mutaherkhan2161
@mutaherkhan2161 2 жыл бұрын
This code is not working on leedcode compiler. I getting time out errror
@KrutiDugade
@KrutiDugade 3 ай бұрын
This is because he forgot to decrement "i" by 1 in next while loop. This works: def lengthOfLastWord(self, s: str) -> int: i, length = len(s) - 1, 0 while s[i] == " ": i -= 1 while i >= 0 and s[i] != " ": length += 1 i -= 1 return length Or you can use other solution in the comments using strip function.
@dasshrs
@dasshrs 2 жыл бұрын
My solution: At first we go trough every spaces from the end of the array. Once we reach not space element, this is a word start. After we add elements when non-space character is present. If we have more then one word_symbols saved it's the word that has already started and if we reach other space chracter it's actually an end. class Solution: def lengthOfLastWord(self, s: str) -> int: word_symbols = 0 for i in range(len(s) - 1, -1, -1): if s[i] == ' ' and word_symbols != 0: break if s[i] == ' ': word_symbols = 0 else: word_symbols += 1 return word_symbols
@unknownboy8174
@unknownboy8174 19 күн бұрын
class Solution: def lengthOfLastWord(self, s: str) -> int: words=s.split() if words: return len(words[-1]) else: return 0
@lamedev1342
@lamedev1342 2 жыл бұрын
My solution: I used extra memory but tried to reduce the time by implementing a hashmap. def lengthOfLastWord(self, s: str) -> int: length = 0 values = {} s += " " for i in s: if i != " ": length += 1 else: if length > 0: values[i] = length length = 0 return values.get(' ')
3 жыл бұрын
For C#, it's quite similar; var count = 0; var end = s.Length - 1; while(s[end] == ' ') { end--; } for(var i = end; i >= 0 && s[i] != ' '; i--) { count++; } return count;
@scottwarner9856
@scottwarner9856 Жыл бұрын
Instead of iterating through the entire string char by char in C# (which could take much longer the lengthier the end of the string is), you can just use built in string methods .Trim() and .Split() to solve this more quickly in just 3 lines of code: string trimmed = s.Trim(' '); //removes given whitespace chars from ends of s string[] words = trimmed.Split(' '); //splits words in trimmed into separate strings return words[words.Length - 1].Length; //returns length of last word in arr words
@suhelmakkad
@suhelmakkad 2 жыл бұрын
class Solution: def lengthOfLastWord(self, s: str) -> int: length, prevLength = 0, 0 for char in s: if char == " ": if length != 0: prevLength = length length = 0 else: length += 1 return length if length != 0 else prevLength
@Famelhaut
@Famelhaut Жыл бұрын
1 liner solution: class Solution: def lengthOfLastWord(self, s: str) -> int: return len(s.split()[-1])
@lollollollol1622
@lollollollol1622 3 жыл бұрын
im a newb but this is my solution class Solution: def lengthOfLastWord(self, s: str) -> int: s = ' '.join(s.split()) last = s[::-1] count = 0 last = last + " " for c in last: if c == " ": return(count) break count +=1
@muneerak1833
@muneerak1833 10 ай бұрын
class Solution(object): def lengthOfLastWord(self, s): strr=s.strip() str=strr.split(" ") l=str[-1] return len(l)
@abdulhalimabdullahi9907
@abdulhalimabdullahi9907 Жыл бұрын
s = " fly me to the moon " l = s.split() last_word = l[-1] print(len(last_word))
@razapanjwani-z2s
@razapanjwani-z2s Ай бұрын
why not just strip() and convert the string into array and get the last word from the array and then just return its length?
@venkatrushivanga1025
@venkatrushivanga1025 2 жыл бұрын
class Solution: def lengthOfLastWord(self, s: str) -> int: endIdx=len(s)-1 strIdx=0 while endIdx>=0: if s[endIdx]==" " and strIdx!=0: return strIdx-endIdx if s[endIdx]!=" " and strIdx==0: strIdx=endIdx endIdx-=1 return strIdx-endIdx
@kiraqueenyt5161
@kiraqueenyt5161 9 ай бұрын
wow i got the exact same solution
@sophearyrin
@sophearyrin Ай бұрын
In Java code solution: class Solution { public int lengthOfLastWord(String s) { int count =0; s = s.trim(); int n = s.length(); for(int i=n-1; i>=0; i--){ if(s.charAt(i) != ' '){ count++; }else{ break; } } return count; } }
@vatsalsharma5791
@vatsalsharma5791 3 жыл бұрын
Hey can you please make a video on “matrix block sum”
@paragsarkar8258
@paragsarkar8258 3 жыл бұрын
def lengthOfLastWord(s): i , length = len(s) - 1, -1 while i >= 0: if s[i] == ' ' and length != -1: return length - i if s[i] != ' ' and length == -1: length = i i -= 1 return length + 1 if length != -1 else 0 I did it like this
@user-vm8yk9ic2c
@user-vm8yk9ic2c 2 ай бұрын
i love you sooo much dude
@stutipatel1059
@stutipatel1059 Ай бұрын
I used the same method, but seems to be exceeding time limit
@lasredchris
@lasredchris 3 жыл бұрын
Question for you Neetcode - do you think doing these problems improve your ability as a software engineer at all?
@sancho608
@sancho608 Жыл бұрын
No. They are just silly questions. Just like common entrance exams for high school. They don't really help you out in high school
@sabu4539
@sabu4539 Жыл бұрын
i used trim() and split(" "). think that's ok
@harrisamin
@harrisamin 2 жыл бұрын
Hey Neet, I think I brute forced this with 1 for loop, but leetcode doesn't like my solution. Could you or anyone else help me evaluate my solution? and its efficiency in big o notation? class Solution: def lengthOfLastWord(self, s: str) -> int: maxStr = '' for i in range(len(s)): if s[i] != ' ': maxStr += s[i] continue if s[i:] == ' '*len(s[i:]): return len(maxStr) maxStr = '' return len(maxStr) Thanks in advance! -Harris
@vinaydeshpande
@vinaydeshpande 11 ай бұрын
How's about? class Solution: def lengthOfLastWord(self, s: str) -> int: return (len((s.split())[len(s.split())-1]))
@gamesandsoftwares1441
@gamesandsoftwares1441 2 ай бұрын
my answer : arr=s.split() return(len(arr[-1])) beats 100%
@sabarishnarayanan4818
@sabarishnarayanan4818 3 жыл бұрын
return len(s.split()[-1])
@techno-tronics4946
@techno-tronics4946 3 жыл бұрын
Sir how do I start with DP?
@9eyeKnight
@9eyeKnight 4 ай бұрын
just tried to do with beginner knowledge but it only beats 5% lol var lengthOfLastWord = function(s){ s = s.toLowerCase() let a = '' let c = '' let alpha = 'qwertyuioplkjhgfdsazxcvbnm' for(i=s.length-1;i>-1;i--){ a = a + s[i] } for(let i=0;i-1){ break } } for(let i=0; i-1){ c = c+ a[i] }else if (a[i]==' '){ return c.length } } return c.length }
@ridhwana2331
@ridhwana2331 4 ай бұрын
return len(s.strip().split(" ")[-1]) this would work too
@user-nm2wc1tt9u
@user-nm2wc1tt9u 11 ай бұрын
class Solution: def lengthOfLastWord(self, s: str) -> int: new = s.split() req = new[-1] return len(req) Done with built in functions
Remove Element - Leetcode 27 - Python
9:05
NeetCode
Рет қаралды 109 М.
Ozoda - Alamlar (Official Video 2023)
6:22
Ozoda Official
Рет қаралды 10 МЛН
Single Number - Leetcode 136 - Python
7:09
NeetCode
Рет қаралды 108 М.
Add Binary - Leetcode 67 - Python
8:01
NeetCode
Рет қаралды 67 М.
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 848 М.
Intersection of Two Linked Lists - Leetcode 160 - Python
8:13
The Absolute Best Intro to Monads For Software Engineers
15:12
Studying With Alex
Рет қаралды 679 М.
Reverse Words in a String - LeetCode 151 - Python #leetcode75
4:16
DEEPTI TALESRA
Рет қаралды 1,4 М.
Rotting Oranges - Leetcode 994 - Python
12:19
NeetCode
Рет қаралды 117 М.
Ransom Note - Leetcode 383 - Hashmaps & Sets (Python)
8:34
Greg Hogg
Рет қаралды 10 М.
Python's Walrus Operator??
2:39
b001
Рет қаралды 126 М.
Learn Python OOP in under 20 Minutes
18:32
Indently
Рет қаралды 170 М.