Reverse Words in a String | LeetCode 151 | C++, Java, Python

Поделиться
HTML-код
  • Опубликовано: 29 окт 2024

Комментарии • 112

  • @ashishupadhyay6881
    @ashishupadhyay6881 4 года назад +9

    If you need O(1) space sol:
    class Solution {
    public:
    void reverseword(string &s, int i, int j){ //reverse string from i to j
    while(i

    • @anusree8707
      @anusree8707 7 месяцев назад +1

      isnt the time complexity here O(n^2)?

  • @faisalrafi2078
    @faisalrafi2078 2 года назад +15

    Your vedios are really great. In this solution, we append and then copy result string in every iteration which is not optimal, TC will become O(n^2). It is better to start from end of input string, reverse each sub-string and then append it to result string, this will give us TC as O(n)

    • @Ishankulkarni
      @Ishankulkarni 2 года назад

      Great Idea!

    • @jayujain2647
      @jayujain2647 Год назад

      Reverse itself takes O(N) so if the avg length of a substring is m the total TC will be O(n*m)

  • @kiranmayeedobbali7216
    @kiranmayeedobbali7216 4 года назад +17

    The best video explanations I have seen so far.

  • @nishasao1881
    @nishasao1881 6 месяцев назад +1

    I CANT'T THANK YOU ENOUGH I WAS FRUSTRATED FROM AN HOUR OR SO, THANKYOU SO MUCH FOR IMPLEMENTING IT IN JAVA ASWELL😭😭😭😭😭😭

  • @rohansangodkar
    @rohansangodkar Год назад

    class Solution(object):
    def reverseWords(self, s):
    sp = s.strip().split()
    res = ""
    i,j=0,len(sp)-1
    while i

  • @sauravjha552
    @sauravjha552 Год назад +1

    best video i have found on how to reverse an word
    thank u sir...

  • @nagendrabommireddi8437
    @nagendrabommireddi8437 Год назад +1

    what is the point of writing 7th line python . when we placed a condition i

  • @Nick-j3e
    @Nick-j3e 3 месяца назад

    string reverseWords(std::string s) {
    int i = 0;
    int n = s.length();
    string ans;
    while (i < n) {
    while (i < n && s[i] == ' ') {
    i++; // skip spaces
    }
    if (i >= n) break;
    int j = i;
    while (j < n && s[j] != ' ') {
    j++; // find the end of the word
    }
    string word = s.substr(i, j - i); // extract the word
    if (ans.empty()) {
    ans = word; // if it's the first word, no need to add space
    } else {
    ans = word + " " + ans; // prepend the word
    }
    i = j; // move to the next word
    }
    return ans;
    }

  • @bostonlights2749
    @bostonlights2749 4 года назад +5

    Wow man... Quality content every time

  • @namangoyal7519
    @namangoyal7519 4 года назад +20

    sir, can u add time complexity of every problem in your video that's really help!!

  • @shrirangjoshi6568
    @shrirangjoshi6568 8 месяцев назад

    this is the only solution I found where internal methods are not used

  • @sahisharma8487
    @sahisharma8487 8 месяцев назад

    What a nice and a easy explanation .
    Thank you Sir.

  • @somratdutta
    @somratdutta 3 года назад +2

    I am wondering can we use stringtok in this question? Yes, it will be space O(n) but can be solved quicker I guess!

  • @MadlipzMarathi
    @MadlipzMarathi 3 года назад +1

    python
    class Solution:
    def reverseWords(self, s: str) -> str:
    return " ".join(list(filter(lambda x: len(x)>0,s.split(" ")))[::-1])

  • @riyazahemed5868
    @riyazahemed5868 4 года назад +7

    Excellent
    Thank you very much
    Changing the index value after spaces is like magic
    Really awesome 😎

  • @Nick-j3e
    @Nick-j3e 3 месяца назад

    in the solution, line #10 should be int j=i for a single character string.
    Also line #15 should be i=j if that falls true.

  • @mr.carguy6271
    @mr.carguy6271 Год назад +1

    Ultimate i would say hats off sir👌👌👏👏

  • @harsha171
    @harsha171 3 месяца назад

    For java users here is the code
    class Solution {
    public String reverseWords(String s) {
    char []str=s.toCharArray();
    String result="",w="";
    int n=s.length();
    int i=0,j=0;
    while(i

  • @stuti4076
    @stuti4076 Год назад +1

    While(i

    • @upendrachauhan5260
      @upendrachauhan5260 3 месяца назад

      give a space between the null character initialization.

  • @venugopal548
    @venugopal548 2 года назад

    Good video sir,
    Can you write this Java program too:
    Input: "This is, the most; particular example!"
    Output: "example particular, most the; is This!"

  • @vagabondfoodie5788
    @vagabondfoodie5788 Год назад +1

    Sir it is difficult for Me to understand the concept why we take subs from (i, j-i) why not from (i,j) in c++

    • @xboy2374
      @xboy2374 8 месяцев назад

      same

    • @uditagarwal4810
      @uditagarwal4810 8 месяцев назад

      because in c++, the second parameter takes the length of the substring and the length of word here is (j-i).

  • @laharishreddy4014
    @laharishreddy4014 Год назад +12

    commented using API.

    • @ytg6663
      @ytg6663 11 месяцев назад

      Which api

  • @Unv12sL
    @Unv12sL 4 года назад +4

    Time complexity should be
    O(n) We are still iterating through the array linearly, and when the j loop is activated,
    it still linearly searches in the same array but when it reaches a letter/nospace until it reaches '_' (_ is 1 space). , then continues from outer main loop again, the inner loop if it satisfies the condition all the way to the end of len(array).
    Space should be
    O(n) since we create a result array, it cannot be O(1) because we are not manipulating the input array in place.
    Please feel free to correct me if I'm wrong but I am thinking this is correct.

    • @manasakaleyanda3963
      @manasakaleyanda3963 4 года назад +2

      Space complexity will be O(1) as result is being stored to a constant and same constant gets updated on every iteration.

    • @MaxUP2
      @MaxUP2 3 года назад +3

      ​@@manasakaleyanda3963 Nope, it's O(n). Result is basically storing the original string in reverse so it's copying. it will be as long as the original words minus whitespaces.

  • @ishangujarathi10
    @ishangujarathi10 Год назад +1

    thanks for the explanation!!

  • @98_shubhamr.sharma78
    @98_shubhamr.sharma78 Год назад +7

    I REALLY LIKED THE PART WHERE HE EXPLAINED THE CODE IN C++ AND PYTHON

  • @avixka7751
    @avixka7751 Год назад

    This isn't working for me.
    The output is:
    "blue is sky the the"
    "world hello hello"
    "example good a a".
    The output always duplicate the last word.
    Edit*
    Never mind, I miss-placed the i = j + 1 into the final else statement

  • @amitsaurabh9948
    @amitsaurabh9948 4 года назад +1

    Really you are the best!. Especially those python solutions

    • @KnowledgeCenter
      @KnowledgeCenter  4 года назад

      Thanks.

    • @harrybhakt6020
      @harrybhakt6020 Год назад

      @@KnowledgeCenter Sir can you please explain what we are doing in s.substr(i,j-1) and result = w + " "+ result , IT should be result + " " + w -- right ?

  • @imranimmu4714
    @imranimmu4714 Год назад +1

    Thank you, was very helpful

  • @abeldaniel2245
    @abeldaniel2245 4 года назад +1

    Thank you. You did in a very clear way.

  • @laharishreddy4014
    @laharishreddy4014 Год назад +1

    video are very helpful.

  • @vikramreddy6219
    @vikramreddy6219 2 года назад +2

    Hi @Abhishek the video is very good, but I am thinking can we split the string using spaces and rearranging in the reverse order it will do our requirement right.

    • @KnowledgeCenter
      @KnowledgeCenter  2 года назад +1

      Yes. That should work. May be a little more space will be required to store all the words after splitting, and then creating the result string from that.

  • @shivanktripathi4661
    @shivanktripathi4661 4 года назад +1

    even if I am able to solve the question by myself , I watch your videos because your solution is always better than mine :-)..... I didnt see the O(1) space code.....can you comment it

    • @DmitrySerkin
      @DmitrySerkin 4 года назад +6

      O(1) or reverse in place is quite easy. you will need to reverse entire string first and then reverse every word in reversed string.
      def reverse_characters(m, i, j):
      while i < j:
      m[i], m[j] = m[j], m[i]
      i += 1
      j -= 1
      def reverse_words(message):
      l = len(message)
      i = 0
      reverse_characters(message, 0, len(message) - 1)
      for j in range(l+1):
      if j == l or message[j] == " ":
      reverse_characters(message, i, j - 1)
      i = j + 1
      return message

    • @KnowledgeCenter
      @KnowledgeCenter  4 года назад +3

      @Dmitry That's an excellent idea. Thanks for sharing.

    • @abhishek_vancedyoutube5935
      @abhishek_vancedyoutube5935 4 года назад +3

      Nice approach. But strings are immutable in python. Solution works if you have list of char

    • @aravindajayakumar8854
      @aravindajayakumar8854 3 года назад

      wil your code work if there are spaces in the start ,end and extra spaces un the middle??

    • @lingyuhu4623
      @lingyuhu4623 2 года назад

      @@abhishek_vancedyoutube5935 So, is there any solutions for python with space O(1)? I cannot find one😭

  • @sahajpareek6352
    @sahajpareek6352 2 года назад

    I don't understand why we can't just use trim in java and strip in python to get rid of the leading and trailing spaces.

  • @rutwikmore7462
    @rutwikmore7462 Год назад

    Awesome explaination !!

  • @rajatverma7936
    @rajatverma7936 3 года назад +2

    Thank You Sir.

  • @bijendersingh5771
    @bijendersingh5771 4 года назад +1

    sir you r the best sir!

  • @mohdareeb3541
    @mohdareeb3541 9 месяцев назад

    Thanks a lot Sir..

  • @AkshyaSingh-ff1fe
    @AkshyaSingh-ff1fe 3 месяца назад

    Learn by Doing

  • @MilanMVlogs
    @MilanMVlogs 4 месяца назад

    At 3:12 'i' variable is looking for space and 'j' variable is looking for non space. Anybody Correct me if i am wrong?

  • @sharandeepkaur5302
    @sharandeepkaur5302 2 года назад

    can anyone tell what is the significance of writing if(i>=n)break; here?
    it will be really helpful

    • @HomeDevVlog
      @HomeDevVlog Год назад

      if you notice the next line is int j = i + 1; so if we dont catch i>= n, j will be out of range of the string by this line charAt(j).

  • @ehsanhosseini5861
    @ehsanhosseini5861 4 года назад +1

    Excellent explanation

  • @consistentthoughts826
    @consistentthoughts826 4 года назад +2

    Sir so far shortest video from you 😛😛

  • @AkshyaSingh-ff1fe
    @AkshyaSingh-ff1fe 3 месяца назад

    Nice Video!

  • @rakshitkoli6697
    @rakshitkoli6697 3 года назад +1

    C++ Code is not working

  • @Karol-123
    @Karol-123 Год назад

    s = sentence.split()[::-1]
    l = []
    for i in s:
    l.append(i[::-1])
    print('-'.join(l))

  • @sweetthirty2
    @sweetthirty2 3 года назад

    please provide the desired code in description box

  • @TYCOC_HarshilHuda
    @TYCOC_HarshilHuda Год назад

    Code for no extra space
    class Solution {
    public:
    string reverseWords(string s) {
    int k=s.size();
    int n=k;
    s+=" ";
    while(n>=0)
    {
    while(n>=0 && s[n]==' ')
    {
    n--;
    }
    if(n=0 && s[j]!=' ')
    {
    j--;
    }
    s+=s.substr(j+1,n-j)+" ";
    n=j-1;
    }
    s=s.substr(k+1,s.size()-(k+2));
    return s;
    }
    };

  • @Mnv_Sadiwala
    @Mnv_Sadiwala Год назад

    How to skip last two words in sentence?
    My input string is: Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.
    Expected output is: Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.

  • @GM-rw5fl
    @GM-rw5fl 2 года назад +1

    thanks.........

  • @ramialdarkazly1163
    @ramialdarkazly1163 3 года назад +1

    Thanks

  • @hideme420
    @hideme420 2 года назад

    always try to show runtime speed and space after code is submitted

  • @kwakukusi4094
    @kwakukusi4094 2 года назад +1

    thank you bro, your explanations are so clear

  • @shubhankarmane3172
    @shubhankarmane3172 3 года назад +1

    Nice explanation

  • @techstuff9830
    @techstuff9830 3 года назад

    Code is not reversing , please help

  • @dantenero7835
    @dantenero7835 2 года назад +1

    this code is not working in leetcode

    • @KnowledgeCenter
      @KnowledgeCenter  2 года назад

      Just now checked. It works. In C++, Java, Python3. All the three languages. Can you retry.

  • @shubhanshusingh742
    @shubhanshusingh742 4 года назад +1

    Sir, there's no doubt that you make a problem look very easy but it will be great if you write code in C language also...plzzzzz

    • @KnowledgeCenter
      @KnowledgeCenter  4 года назад +4

      Without STLs, life would become tough. Need to implement whichever container we want to use.

  • @sagrika7096
    @sagrika7096 2 года назад +1

    Thanku sir

  • @subhamagarwal476
    @subhamagarwal476 3 года назад

    Perfect

  • @vgopal001
    @vgopal001 2 года назад

    In Leetcode, it gives error for Python3
    Time Limit Exceeded

    • @sahajpareek6352
      @sahajpareek6352 2 года назад

      Use strip to get rid of leading and trailing spaces.

  • @sidhantraghav7749
    @sidhantraghav7749 4 года назад

    This code is useful for Umar the Akmal🤣

  • @abhisheksuryavanshi9675
    @abhisheksuryavanshi9675 3 года назад

    Jaduu!

  • @aflatoon5374
    @aflatoon5374 2 года назад

    How to write complext code 101

  • @yannlilgrass5010
    @yannlilgrass5010 Год назад

    I write a main method after your code. and it doesn't work. It only returns one word of my sentence.
    public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the sentence:");
    String sentence = keyboard.next();
    String result = reverseWords(sentence);
    System.out.println(result);
    }
    Did I do anything wrong with my main method?

  • @partheshsoni6421
    @partheshsoni6421 3 года назад

    Nice explanation. Although I was expecting in-place solution.

  • @Nick-j3e
    @Nick-j3e 3 месяца назад

    string reverseWords(std::string s) {
    int i = 0;
    int n = s.length();
    string ans;
    while (i < n) {
    while (i < n && s[i] == ' ') {
    i++; // skip spaces
    }
    if (i >= n) break;
    int j = i;
    while (j < n && s[j] != ' ') {
    j++; // find the end of the word
    }
    string word = s.substr(i, j - i); // extract the word
    if (ans.empty()) {
    ans = word; // if it's the first word, no need to add space
    } else {
    ans = word + " " + ans; // prepend the word
    }
    i = j; // move to the next word
    }
    return ans;
    }