Sorry, it should be "the sky is blue" -> "blue is sky the"!
@abdelrhmankamal1370
5 ай бұрын
You're still doing great! I really like all your videos; they keep helping me learn more about code interview questions.
@GregHogg
5 ай бұрын
@@abdelrhmankamal1370Thank you so much, I really do appreciate it!! ❤
@yogeshvanzara5553
5 ай бұрын
Hey can you give us where can we learn DSA?
@tomasruzicka9835
4 ай бұрын
I would have used bash sed replace ` +` for ` ` everywhere, another sed delete `(^ )|( $)` then rev then xargs
@The-KP
4 ай бұрын
@@tomasruzicka9835 , or \s ?
@AngryEgg6942
4 ай бұрын
Bro is taking 3 left turns instead of 1 right
@AverageSensei
3 ай бұрын
Bro the type of guy to park the furthest from the grocery store
@danielhaveman5675
4 ай бұрын
That code is waaaay too complicated. You only need to do 4 steps: - split on spaces - reverse the array - filter the array for any empty strings (the null between the two spaces, at the beginning and at the end) - join the array with a space again so: " hi there ".split(" ").reverse().filter(a=>a).join(" "); no need to trim separately, or to track things manually in a loop
@shapelessed
4 ай бұрын
The point there was to make it as little CPU-intensive as possible. It does technically achieve this, since built-in methods hook in to pure C++ code, but the side effect is that you end up allocating memory for 5 different copies of that string before you reach the results.
@danielhaveman5675
4 ай бұрын
@@shapelessed then that sounds like you have a severe case of premature optimization there. Sure you should understand what happens so you can write optimized code if there's a case for it. But there are many cases where legibility, simplicity, using native C++ optimized code, maintainability, preventing possibility of memory-leaks, etc. etc. is worth more than a slightly optimized memory-footprint that wasn't asked for in the initial question
@shapelessed
4 ай бұрын
@@danielhaveman5675 That's literally exactly not what I said.
@pantherdddjvdgx
4 ай бұрын
You got to love the noobs making videos while being unemployed
@gustavo9758
4 ай бұрын
@@shapelessed how would you make it more performant? Regex to get the words? Individual trimming?
@sophiophile
5 ай бұрын
I think a more elegant (and memory efficient) solution is to iterate over the chars backward and while char != ' ', add the chars to a string rev_word. Each time the loop breaks, ans += ' ' + rev_word[::-1] and rev_word = '' (also, add on the termination of the for loop if rev_word isn't empty). Same time complexity, but lower memory complexity. Plus no extra logic necessary to handle weird extra whitespaces. Memory complexity for your solution is O(k) where k is the number of words, this is O(1).
@shapelessed
4 ай бұрын
Memory is plenty in modern systems, while the CPU might be more of a bottleneck, and since it's probably either node or chromium, it's generally better to use builtin methods as they offload all the logic to much faster, lower-level underlying C++ code. So while splitting and joining is more memory-intensive, GC will generally get rid of it right away and might just as well be faster. That's why it's generally better to use builtin methods and only optimise and write your own helpers when truly needed.
@darknight3613
4 ай бұрын
It wouldnt be smart to look at k as the number of words, if i have only 4 words but each of them is 10,000 chars long then it's around 40,000 iterations while you are saying O(4). And going through each letter in a word and keeping it will cost you the length of the longest word in the string, which is potentially the length of the string so O(n) memory
@sophiophile
4 ай бұрын
@@darknight3613 I agree with you about calling it O(k). It was just to help make clear that he was duplicating the entire string *and* creating a list structure that stores the entire thing piece-wise, when you could just have a variable hold a single word at a time, while making a solution that didn't need to create any extra logic to handle extra/weirdly placed white spaces. Both solutions need to iterate over the whole string once (the split and join is iterating over each character in the word). The absolute best solution memory complexity wise, is to just do the whole thing in-place on the input string, and not create any extra variables whatsoever. But that makes for some really hard to read code when you handle the whitespace problem. This struck a balance between the two.
@RockuHD
4 ай бұрын
@sophiophile yeah but doing it in place is scary. In real life (not a code interview) they might be using that string for something else and then you just changed it on them... some languages string are immutable and for good reason... 100% agree though, looping backwards and added each char to a char buffer pre sized to the original string length +1 (for the null terminator) is the best way to go about this one.
@sophiophile
4 ай бұрын
@@RockuHD 100%
@merveillevaneck5906
4 ай бұрын
Dude. Strip + reverse loop + character buffer using a stack + store resulting words in the buffer in an array every time you find a whitespace. Then join the array at the end. 2n runtime
@salism2
4 ай бұрын
Thanks. This is an accepted answer in Python: ' '.join(s.split()[::-1])
@user-zt8gg8rs6w
4 ай бұрын
yeah, even i put this directly in return statement and this solution passed all leetcode test case. I do not understand why go long when it can be done in a shorter way or probably with just one-line code.
@edudictivecoder4644
23 күн бұрын
@@user-zt8gg8rs6w well you can but remember the single line would not help you track your Intermediates thus right multiple line is good in many cases where you might have to read the intermediates it can be for other func or debugging for your own with print func
@antonivanov1351
4 ай бұрын
You can do it with no additional memory by just reversing the whole string first and then reversing each word(using two pointers technic)
@thescientist4668
4 ай бұрын
normal people: Just use split() or the equivalent in your language... solved in one minute. me with arm assembly without any libraries : "this little maneuver is gonna cost us 51 years!!" ya ik using asm is stoopid for coding interviews.
@NishitMishra96
3 ай бұрын
Reversing the array and finding a word Using two pointers and then reversing the word makes it a medium category of problem. Using library functions is easy. But coming up with a solutions without using them is the actual skill.
@TonyFarley-gi2cv
4 ай бұрын
Honey even the conversation to the wording is mathematically aligned together
Master Data Structures & Algorithms For FREE at AlgoMap.io!
5 ай бұрын
If you use .split() or .split(None) instead of .split(' ') then you don't need for-loop nor .strip(' ') def rev(txt): return ' '.join(txt.split()[::-1]) And if you really need to use space (or other char) in .split(' ') then you may use filter(None, list) to remove empty strings from list def rev(txt): return ' '.join(filter(None, txt.split(' ')[::-1]))
@musicb5202
5 ай бұрын
Right? I swear this guy seems to go at each of these challenges in the most beginner way possible, cause split is like the most trivial of functions. Yet he somehow can't understand how it works. Maybe like finish a python course first before doing leetcodes lol.
@niaei
4 ай бұрын
@musicb5202 it's a codding challenge. You must have a logic that work on all languages. Split in all languages does not have the same functionality as it has in python. If it was a python codding challenge. Then you would be right.
@prodmatze
4 ай бұрын
thats only for python tho, most languages dont have that many pre built functions
@madghostek3026
4 ай бұрын
@@prodmatzethe solution is in python so you should know and utilise the language, writing C calque in python is always possible but will be inefficient
@jeansimonlavoie
4 ай бұрын
@@niaeiim a c# dev . And when I have to solve problems in a interview they usually forbid us to use any LINQ
@corbinfonville1012
5 ай бұрын
I think the for loop is overkill. Just: str.split(' ').filter(s => !!s).reverse().join(' ')
@pknepps
5 ай бұрын
Even better, string.split("//s+")
@Keyakina
4 ай бұрын
what is s => !! s?
@norbertkis-szabo5053
4 ай бұрын
This oneliner does everything that is needed for the solution. Although its in javascript I believe. S => !!s is checking the truthiness of the string and its only False if the string is ‘’. Code should be something like this in python, but I didn’t check it, wrote it from phone: “ “.join(reversed(filter(lambda s: s, text.split(‘ ‘))))
@mathe42
4 ай бұрын
Using .filter(Boolean) is more readable
@MadpolygonDEV
4 ай бұрын
And what do you think those functions do under the hood 😂
@FakeDumbDummy
3 ай бұрын
the sky is blue blue is the sky bro failed test cases in dry run
@GregHogg
3 ай бұрын
Yeah ikr
@Eknoma
4 ай бұрын
You don't need a custom for loop to do a super common operation... "...".split() does exactly what you would expect, removing all whitespace, so e.g. " this is a \t string ".split() Gives you ["this", "is", "a", "string"] So the way to do this task in Python is just " ".join(reversed(inp.split()))
@Eknoma
4 ай бұрын
Or of course if you want to use an actual programming language instead, you could just do solution :: String -> String solution = unwords . reverse . words
@Torbeng
4 ай бұрын
@@Eknoma Boo no one wants haskell, but looks nice actually
@Phrozends
3 ай бұрын
Without using so much memory for large inputs, we could use a the regular stack tecnique that gets flushed on spaces. You do it in O(n) time too.
@jjpaq
4 ай бұрын
Regex replace all `\s.*?` matches with ` ` and then trim() would work for the spacing issues, no?
@chacelow2438
4 ай бұрын
Or \s+ might work too
@jjpaq
4 ай бұрын
@@chacelow2438 you're right.
@The-KP
4 ай бұрын
`\s.*?` would replace all chars following a space, the dot star matches everything
@jjpaq
4 ай бұрын
@@The-KP yeah, he's right, I was zonked when I wrote that lol.
@MasterQuestMaster
3 ай бұрын
This language doesn’t have a „remove empty entries“ option for split? Damn…
@daa82
4 ай бұрын
Just use a stack, put all elements in and pop them out. Voila!!
@SAL404w
3 ай бұрын
Me with my reg expression: 🗿
@prasadsawant7
3 ай бұрын
Even though if we don't provide the separator to split, still it splits the string as expected without including those spaces in the list. I did it in one line: return " ".join(s.split()[::-1]).strip()
@alexwolters1164
4 ай бұрын
In python its easy, try doing it in c with pointers and dynamic memory allocation.
@gvenkatesh8935
3 ай бұрын
We can do this in one loop by using two pointers
@MytvvvMovies
3 ай бұрын
We can use space as a delimmetter in that case
@henryjubeda7617
4 ай бұрын
Spaces are characters too
@RemoteAccessGG
4 ай бұрын
Split, reverse, join - Wise Man And if you’re a nerd, you should do list(filter(lambda a: a != “”, splitted_list))
@usemayonaise
4 ай бұрын
I doubt microsoft would hire you if you gave that as a solution
@babatundetaiwo5184
3 ай бұрын
I got asked a question similar to this 2 weeks ago
@davidgillies620
4 ай бұрын
Run it through a whitespace-contraction regex before split/reverse/join.
@BitbenderM
3 ай бұрын
if you are gonna use python, then maybe actually use python? def reverseWords(words: str) -> str: return ' '.join([word for word in words.split(' ') if word != ''][::-1]) can change to r.split() if you want to split by regex to split better or to split easier with multiple types of delimiters but this one line requires no imports
@GregHogg
3 ай бұрын
Sounds good to me haha
@eXAt33
4 ай бұрын
I remember having this question for an interview with dell for an internships position. I had to do it in a “c-like” language. Luckily enough I had just finished a final for a class that asked the same question in risc-v assembly so I managed to get the position
@briandavis6898
4 ай бұрын
Can you use split and join? Then maybe a trim instead of all that parsing
@pound9799
5 ай бұрын
can you use the split function ? btw I love your content!
@Triplicata
4 ай бұрын
"I solved it right away" >Everyone in the comments talks about how shit the code is
@kartirnium
4 ай бұрын
Or just use split(' ') with the option to remove empty strings. Then iterate backwards while adding a space in between .
@borisv7357
4 ай бұрын
when using split without any parameters, so just .split() it remoces all whitespaces, which means that for this solution you dont need to iterate in anyway, just not use the split.(' ') and the strip(' '). Which leaves new_s = ' '.join(s.split()[::-1])
@keyboardbasher5769
4 ай бұрын
def reverseWords(self, s: str) -> str: # Split the string into words s_split = s.split() # Reverse the order of words reversed_words = s_split[::-1] # Join the reversed words with a single space return ' '.join(reversed_words)
@jackpaice
4 ай бұрын
I hate this kind of test, cause irl I’d just use lodash
@jjferman2587
3 ай бұрын
This runtime is terrible. You can propose this solution but at what cost? Follow up, can you do it without using as much memory or time?
@masomahboob
4 ай бұрын
Why don’t you write a lambda function inside the filter function to filter out any whitespaces. In the end, you could join the words back into a string with a space. Or, you could use regex as well. Using regex: import re # Original string with multiple whitespaces original_string = "This is an example string" # Step 1: Use re.findall() to find all non-whitespace sequences words = re.findall(r'\S+', original_string) # Step 2: Reverse the list of words reversed_words = words[::-1] # Step 3: Join the reversed list back into a string with single spaces reversed_string = " ".join(reversed_words) print(reversed_string)
@wong_tai_ming
5 ай бұрын
Can be solved with two pointers as well
@oferron4894
4 ай бұрын
SHOULD be solved with two pointers is more accurate.. This dude didn't get what coding interviews are all about
@Eknoma
4 ай бұрын
What would you need two pointers for?
@tgr5588
4 ай бұрын
@@Eknomaone points to the beginning of the current word, and the other one to the end of it. You can then reverse the word in-place
@Eknoma
4 ай бұрын
@@tgr5588 You are not asked to reverse each word... you are asked to reverse the order of the words. "I am a human" -> "human a am I". And why would you every write out an algorithm like reverse by hand, instead of using a library?
@Tldr205
4 ай бұрын
@@Eknomain coding interview the goal is often to make or show your own implementation and solution and optimize it. You need to know a library really well, to be sure it's not doing something funky.
@pcriged
4 ай бұрын
Why not strip the spaces. Split on space into an array and then move any non space elements in to a new concatenated string. Seems like less code and less processor cycles.
@jpmiguel
4 ай бұрын
In typescript with any amount of spaces: "The Sky is Blue ".split(' ').reverse().filter(i=> i).join(' ')
@Imbalanxd
4 ай бұрын
does anyone notice that the questions that rely on knowing long established decades old algorithms are classed as easy, and anything requiring even the slightest amount of nuance and original thinking is medium or hard?
@gregbugaj
4 ай бұрын
just because you solved does not mean it is good. However you did get the job.done
@chandings
4 ай бұрын
sir what about , or . or any other punctuation. ususally there is no space between words n punctuation
@MartinBarker
4 ай бұрын
one line and no manual loops: String.Join(" ", s.Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToArray().Reverse()); This is MS use C# they built it. if you can't you can do the same thing is most langs including VB since it has all of .Net inside it
@mykevelli
4 ай бұрын
Or just add StringSplitOptions.RemoveEmptyEntries to your Split and you don't need the Where()
@AbhishekGupta-qv7ig
4 ай бұрын
They will rejext it or fail you , they want a DSA answer always
@vigneshreddy1213
3 ай бұрын
java 3 steps StringTokenizer deli=" " call recursively till no more tokens add the token to stringBuilder before returning from function and return
@midophriya3657
4 ай бұрын
in Php implode(‘ ‘, array_reverse(array_filter(explode(‘ ‘, $str))))
@darkoplax7688
4 ай бұрын
.trim.split(" ").reverse().join("")
@Nikhil-ty3rk
4 ай бұрын
This is literally 3 lines in C#
@RalfNieuwenhuijsen
5 ай бұрын
You are joking right? str => str.trim().split(/\s+/g).reverse().join(' ')
@ankitroy8567
3 ай бұрын
L=s.split() L=l.sort(reverse=True)
@theabshow7318
4 ай бұрын
Bro can't we use just trim function
@balavikashkandukuri6139
11 күн бұрын
return " ".join(reverse(s.split()))
@n_fan329
3 ай бұрын
Ret = s.split(‘ ‘).reverse().join(‘’)
@GregHogg
3 ай бұрын
Beauty
@GeroldH
4 ай бұрын
This isn't quite the right problem. The constraint making this interesting is to do it in place, you can't allocate memory. Then you get the classic Microsoft question :)
@GregHogg
4 ай бұрын
In many languages strings are immutable though?
@lucnguyen5553
4 ай бұрын
@@GregHoggNot in all languages. If you were to do this interview question in a language where strings are immutable (e.g. Java or Python), then imagine the input was an array of chars instead, similarly to low-level languages like C where strings are just pointers to sequences of chars. So "hi there" would be ['h', 'i', ' ', 't', 'h', 'e', 'r', 'e']. The goal is to reverse the order of the words without allocating any extra memory. The trick is to reverse the whole array, and then reverse each word individually, all in-place. For example: ['h', 'i', ' ', 't', 'h', 'e', 'r', 'e'] -> ['e', 'r', 'e', 'h', 't', ' ', 'i', 'h'] -> ['t', 'h', 'e', 'r', 'e', ' ', 'h', 'i'] Note: I agree that the solution in your video is cleaner and would usually be better in an actual code base. But that's just how coding interviews go, they force harsh constraints because they want to see a particular clever solution. In this case, the pretext is that this is a low mem device and so allocating memory is a no-no, which can be a real constraint, but most of the time your solution is easier for everyone to read and understand.
@KejriwalBhakt
3 ай бұрын
Do it using C. Using python is itself a hack.
@GregHogg
3 ай бұрын
Haha fair, it's a hack that's usually allowed in coding interviews, and I feel we deserve all the help we can get 😂
@rahuldwivedi4758
5 ай бұрын
This is not the kind of logic they’d be looking for though. They’d be looking for the logic. How about this? var newStr = ‘’; str=str.trim(); temp=‘’; for(var i=str.length-1; i>0; i-){ if(str[i]==“”){ newStr += temp.revers(); temp = “”; } temp +=str[i]; }
@Gennys
4 ай бұрын
Can't you pass in a regex to split by instead of splitting by single space? Split by greedy white space character in regex. Or you can sanitize the string before doing the standard method.
@alexjenkins8026
4 ай бұрын
Or just don't specify a single space in your split: ' '.join(s.split()[::-1])
@muhammad.hameem
4 ай бұрын
Do this using C language without including sny library
@user-vs5rh1oz3w
2 ай бұрын
we can solve via stringstream as well
@GregHogg
2 ай бұрын
What's that
@user-vs5rh1oz3w
2 ай бұрын
@@GregHogg it breaks words into tokens.
@aniketmahangare8333
3 ай бұрын
I don’t think you’re allowed to use split and all here.
@GregHogg
3 ай бұрын
You might, you could ask the interviewer! I try to use built ins where possible to simplify things
@casperhansen826
4 ай бұрын
A one liner i C#: return string Join(" ", input.Split(' ', StringSplitOptions.RemoveEmptyEntries).Reverse());
@MadpolygonDEV
4 ай бұрын
The point of these is to show how you come up with your own algorithms and problem solving.
@mohammedfarookabdul3387
4 ай бұрын
heck to use regex pattern that's pro do
@antoniong4380
4 ай бұрын
``....=my_string.trim().split(' ').rev().collect();`` this should be about right, right?
@NOKIA5593
3 ай бұрын
Damn thats a bad solution... I would not hire you with this.
@arsenypogosov7206
3 ай бұрын
You are supposed to solve it in O(1) space...
@GregHogg
3 ай бұрын
You'll have to generate a new (immutable) string so I'm not sure if this is completely possible
@arsenypogosov7206
3 ай бұрын
@@GregHogg You are allowed to do it "inplace". You need to reverse the whole string and then each word individually. "hello world" -> "dlrow olleh" -> "world hello". Also sometimes people exclude the space needed for the answer from space complexity (like with the space for the input), but it's really depends on the interviewer. It's always better to ask him directly.
@opaligodzilla417
3 ай бұрын
it should not be "blue is the sky" it should be "blue is sky the"
@GregHogg
3 ай бұрын
Yes sorry about that
@opaligodzilla417
3 ай бұрын
@@GregHogg 👍
@AkshatPandey
4 ай бұрын
w=s.split() w.reverse return ' '.join(w)
@nabilfannane7217
5 ай бұрын
return s.split(' ').reverse().join(' ')
@low-key-gamer6117
4 ай бұрын
Do it in C
@strategistaow3520
4 ай бұрын
How did you do blue is the sky? When it should be blue is sky the?
@salism2
4 ай бұрын
He corrected it at the pinned comment above
@SelvaKarthik07
4 ай бұрын
Just use .split() ?
@bxshaped27_79
4 ай бұрын
Now do it in C
@aziz0x00
4 ай бұрын
Hey thanks!, why is the "i += 1" in the for loop
@StripesOO7
4 ай бұрын
Its totally useless since its this is python and „i“ gets overwritten nonetheless each loop.
@prangbod
4 ай бұрын
‘ ‘.join([word for word in string.split(‘ ‘) if word != ‘’].reverse())
@user-vr9dz8yd5n
4 ай бұрын
Do it in c
@lootusmaximus9776
4 ай бұрын
even i could probably do that
@sujanedwin504
5 ай бұрын
Trim?
@mufasum
4 ай бұрын
a cool one-liner I came up with, although I'm not sure if it's the most memory-efficient. return ' '.join(s.split()[::-1])
@MadpolygonDEV
4 ай бұрын
Shocking how many people here over engineer this a simple problem
@davidahgren9037
3 ай бұрын
Que?
@ajgamerpro1356
3 ай бұрын
c# remove empty entries
@GregHogg
3 ай бұрын
Lol yeah built in functions are great
@abhinavmishra9323
4 ай бұрын
Don't know why people solve coding problems in python. Its so stupid
@user-yb4dz7pl2h
4 ай бұрын
regex moment
@DrCognitive
4 ай бұрын
What practical use could this knowledge bring to the table? When are you going to do this in a real program?
@quokka_yt
4 ай бұрын
In python, it's just: " ".join(s.split(" ")[::-1])
@AkellaBosch
4 ай бұрын
return " ".join([word for word in string.strip().split()[::-1] if len(word) > 0)
@salism2
4 ай бұрын
This is accepted, split takes care of strip and empty words: ' '.join(s.split()[::-1])
@user-je1nh6qq7x
3 ай бұрын
Now do it in C++
@GregHogg
3 ай бұрын
Nah
@user-je1nh6qq7x
2 ай бұрын
@@GregHogg hehe , I did this in C++ it was much line of code
@oferron4894
5 ай бұрын
You are getting these questions the wrong way.. Naive solutions are easy to find, and might be even one liners, but they are not the way to go. These questions are aiming for optimizing time and space complexities, not for actually solving the problem or having a short code.
@Ooze74
4 ай бұрын
Yeah, if so, why then language creators made all those native functions and methods?
@oferron4894
4 ай бұрын
@@Ooze74 it's useful in most cases, for small enough inputs, where time and space complexities are negligible. But when you come to an interview, they expect you to notice hard problems, such as enormous inputs. They look for the computer science concepts, not the syntax of some language.
@raphaelamorim
4 ай бұрын
too complicated, the problem is much easier
@17ashishemmanuel
5 ай бұрын
Does python not support regex?
@PavankumarPattar-bs5lv
5 ай бұрын
The Python "re" module provides regular expression support.
@17ashishemmanuel
5 ай бұрын
@@PavankumarPattar-bs5lv ah I see
@AngryEgg6942
4 ай бұрын
It does but you don’t need it
@maervo4179
3 ай бұрын
Dude just iterate, collect word as long there is not " " and put it on stack. O(n) congrats 😂
@DZX5000
4 ай бұрын
if your getting asked to code in an interview, your being looked at as a clown. find something else.
@kajoma1782
4 ай бұрын
Single responsibility function. The name should have been "reverseWordsAndTrim"
@hello_there79
5 ай бұрын
I think there is no need of using if statement and i+=1, its 'for' loop
Пікірлер: 201