Reverse a String - Java Interview Coding Challenge #3 [Java Brains]

  Рет қаралды 114,863

Java Brains

Java Brains

Күн бұрын

Пікірлер: 101
@Java.Brains
@Java.Brains 5 жыл бұрын
Thanks for all the great comments: Couple of things: 1. Yes, using character array is an option. You can use that instead of StringBuffer to save from creating a gazillion strings 2. Don't go for recursion unless asked. My suggestion is to mentally evaluate which is the simpler option. Recursion adds a cognitive load to whoever will read code in the future. So, use it only if it makes the solution simpler and more elegant than the iterative approach.
@lxerlx2890
@lxerlx2890 5 жыл бұрын
A straightforward implementation iterating through individual characters of the string will fail if the string contains an Unicode supplementary character (with code points U+10000 to U+10FFFF), which is encoded as a pair of _char_ values in Java. The implementation with *StringBuilder(str).reverse().toString()* should be preferred because it will work even if the string has an Unicode supplementary character. One can see the difference between two methods by trying with the string "s𝕋u" which contains a supplementary character (U+1D54B) in the middle of the string. Because all of these, it is not recommended to use _char_ type in the programs unless the intent is to actually manipulate UTF-16 code units.
@etric89
@etric89 5 жыл бұрын
1. char[] chars = str.toCharArray(). 2. Traverse chars[] array from 0 to n/2 swapping elements from first half with ones from second: chars[idx] chars[n-1-idx]. 3. Create new string: new String(chars).
@soumyajitdey5720
@soumyajitdey5720 5 жыл бұрын
Exactly what I had in mind
@antmakov
@antmakov 5 жыл бұрын
You can actually set character individually in a string by calling setCharAt(int index, char c) function and you basically don't need to create char [] array
@etric89
@etric89 5 жыл бұрын
@@antmakov java.lang.String is an immutable class
@antmakov
@antmakov 5 жыл бұрын
@@etric89 my bad, setCharAt exists only in string builder class not in string. And as you mentioned it's pointless to set character on string if it's immutable.
@AjinkyaRane
@AjinkyaRane 5 жыл бұрын
Hey Koushik nice way to explain. simultaneous explanation on writing pad is helping to understand concepts quickly. I would request you to do video on 1. String pool & immutability. Diff new String() & String literal 2. Writing immutable classes. 3. Internal working of HashMap 4. Dutch National Flag problem. If these are already in pipeline..👍
@PramriDesigns
@PramriDesigns 5 жыл бұрын
One thing I always remember your one line u mention in first SOAP Sample program "Writing a SOAP web services is very difficult, so Please pay attention to that then when you write @webservice then u said job done. then u mention that u were just kidding :) then I watch your all SOAP videos in 2 days and learned complete concept within 2 days. " I always remember this line :)
@dhanushkakumarage1889
@dhanushkakumarage1889 5 жыл бұрын
Hes also kidding with angular series.. quantum physics and relativity 😁😁😁
@phanindraitika5609
@phanindraitika5609 5 жыл бұрын
Just another thought... we can loop thru the string and instead of appending it to another string...store each character in a character array and at the end create one new string with the character array... Also I believe to test our Java 8 features knowledge, interviewers may ask a solution using lambda expression...!! Good one... A pretty good refresher... These days I need a dose of your videos daily 😄 keep doing good work .. thanks for the videos again !!
@tusharkshirsagar611
@tusharkshirsagar611 5 жыл бұрын
You are not just teacher, but an incredible teacher... Thanks Kaushik...!!!
@edgieacepojadas6700
@edgieacepojadas6700 4 жыл бұрын
Back in my college days, all I did with this kind of problem is that I just put the string on an array and call the array in reverse, well I don't know if it's efficient thou, but it works and got some grade for it. lol
@uma_r
@uma_r 5 жыл бұрын
I know one person with 8+ years of experience, when asked this question, left the interview hall saying it's too basic.
@Java.Brains
@Java.Brains 5 жыл бұрын
This is probably not a good interview question for someone with 8 years of experience. Having said that, the important thing is not the question itself- it’s the discussions around it. I’d ask the experienced candidate to explore time and space complexities with extremely large data sets. Example: what if the incoming string is larger than the available memory capacity? There are tons of opportunities to explore complexity even in the simplest of interview questions. :)
@uma_r
@uma_r 5 жыл бұрын
@@Java.Brains wonderful. I never had such thoughts :)
@amirthasaha
@amirthasaha 5 жыл бұрын
Thank you very much Koushik sir. you just rock in your teaching style. Please make courses on Core java concepts, Design patterns, Data Structure/Algorithms sir. Java Brains will become one stop for every Java Programmer from the beginner till whatever is the highest level. Thank you so so much sir.
@pushpesh82
@pushpesh82 4 жыл бұрын
I would love to see this series going for solving 50 such questions...
@sebastianmendoza2005
@sebastianmendoza2005 5 жыл бұрын
Nice explanation. Some other ways I think this could be done is recurssion going from both ends to the center O(n/2). Another really easy way is to just use a stack, it would automatically return anything in it in reverse order once it is emptied.
@vivekbhadauria2130
@vivekbhadauria2130 3 жыл бұрын
Infact this recursion based approach helps in dynamic programming problems related to palindromic strings
@sleepy_Dragon
@sleepy_Dragon 5 жыл бұрын
Did you check if this is working with upper Unicode characters? I think one would have to use code points. Otherwise emoticons and such would break.
@nikhilraut6820
@nikhilraut6820 5 жыл бұрын
For life -abdul kalam ji....for java- Kaushik ji...salute both of u.... thanks make me better 😊🙏
@arunabhhejib1136
@arunabhhejib1136 5 жыл бұрын
Hi Kaushik, how about making videos on currently hot topics like Kafka, Rabbit MQ, Cassandra. Messaging frameworks and NoSQL databases? That would be really helpful. Thanks!
@howtoed3116
@howtoed3116 5 жыл бұрын
We could also have reduced the complexity by interchanging value at 0 to value at n-1, and then doing the same for all chars till I=n/2.
@wiper123ful
@wiper123ful 5 жыл бұрын
Hi Koushik, Can you do a video on hash map implementation??
@asankaishara
@asankaishara 5 ай бұрын
This method can do it with O(n/2) complexity. Else it will be O(n) private static String reverseString(String s) { char[] charArray = s.toCharArray(); int start = 0; int end = charArray.length - 1; while (start
@uppunu1
@uppunu1 5 жыл бұрын
It would be great if you could also mention the BigO for the solution. Thanks so much
@Finn-jp6pn
@Finn-jp6pn 5 жыл бұрын
You're an amazing teacher .❤️ Please continue this series with frequent uploads.
@samwilgost1143
@samwilgost1143 5 жыл бұрын
Please Please more of these interview questions, I love the way you explain them!!!
@hemsagarpatel8992
@hemsagarpatel8992 5 жыл бұрын
sir please make videos for various ds questions
@VickieEB
@VickieEB 5 жыл бұрын
I just get excited when I see a notification from Java Brain. Thanks for this explanation. Clear
@ajay-pg8ok
@ajay-pg8ok 5 жыл бұрын
Bro ur explanation makes everything easy to understand.
@parvezmd6455
@parvezmd6455 5 жыл бұрын
Sir your way of explaining using pictorial diagram is super .
@yuvaraj9740
@yuvaraj9740 5 жыл бұрын
sir can you upload more questions asked on interviews in java please! thanks!
@sisisisi6
@sisisisi6 5 жыл бұрын
These interview questions are soo helpful. So helpful that I landed an offer from Amazon! Thank you!! So much.
@ascar66
@ascar66 4 жыл бұрын
How is it going in Amazon?
@amirthasaha
@amirthasaha 5 жыл бұрын
Thank you sir, can you please add a video explaining how Hashmap works in storing name value pairs and also the equals and hashcode method concepts around it. Thank you!
@mukundpatel1768
@mukundpatel1768 5 жыл бұрын
This is really nice sir.
@saddamahmad2310
@saddamahmad2310 5 жыл бұрын
thank you very much sir for this video
@rashmir193
@rashmir193 4 жыл бұрын
Hi Koushik Cold you please add a tutorial to write a program that reverses a sentence. Ex: Hello World to World Hello
@GenjaOrigins
@GenjaOrigins 3 жыл бұрын
and how to check if they are palindrome foe example Anna and Reversed Anna is the same thing how to check this.. maybe with str1.equals(str2) something like this?
@RANJANJHA95
@RANJANJHA95 5 жыл бұрын
Expected to discuss most efficient approach
@NANDANKAUSHIK
@NANDANKAUSHIK 3 жыл бұрын
How are you able to write like pen on paper , on whiteboard which seems to be running on your system ?
@abarag8
@abarag8 5 жыл бұрын
Hi Kaushik sir. Nice video. Keep up the good work. I am inspired from you and learned to love coding because of you :)
@HungNguyen-nd6tz
@HungNguyen-nd6tz 3 жыл бұрын
Thanks, it's perfect explanation
@amitdeshpande2548
@amitdeshpande2548 5 жыл бұрын
When reference pointing to modified version of string literal then previous string would be collected by GC as it is not referred by any reference variable or it would remain in string pool without reference. In below code "Sachin" would be taken by GC or remains in string pool? class Testimmutablestring1{ public static void main(String args[]){ String s="Sachin"; s=s.concat(" Tendulkar"); System.out.println(s); } }
@MetinCloup
@MetinCloup 5 жыл бұрын
This is more practical package reverse; public class reversAString { public static void main(String[] args) { String a= "hello"; for (int i=a.length()-1; i >= 0; i--) { char c = a.charAt(i); System.out.print(c); } } }
@pradiptalekar7545
@pradiptalekar7545 5 жыл бұрын
Hi Kaushik, really appreciate your work. Thank you!! Expecting more in this series - coding challenges
@Paul-ry3jq
@Paul-ry3jq 5 жыл бұрын
These are really awesome, thanks for the good videos.
@Tridib_Tinkel
@Tridib_Tinkel 5 жыл бұрын
String str = "Hello World"; String f = ""; for(int i = 0; i < str.length(); i++) { f = str.charAt(i)+f; } System.out.printf("Reversed String: %s", f);
@theblindprogrammer
@theblindprogrammer 3 жыл бұрын
Good vid, keep up the good work.
@aoshi2552
@aoshi2552 5 жыл бұрын
Excellent video. Here’s my like 👍🏼
@maheshgowthamt
@maheshgowthamt 5 жыл бұрын
Hi sir, thanks for uploading videos for us....I need junit testing for controller and service classes in rest api using mockito..plz upload with explanation..
@toufiqurrahman7025
@toufiqurrahman7025 5 жыл бұрын
please continue this series
@explorerfl007
@explorerfl007 5 жыл бұрын
I think we can have solution using recursive method call. What are disadvantages of recursive calls?
@Java.Brains
@Java.Brains 5 жыл бұрын
Good point. Please refer to my pinned comment.
@darylphuah
@darylphuah 5 жыл бұрын
Recursions are memory intensive in non-functional languages like Java. Not sure I agree with Java Brain's assertion that recursion is a cognitive load, if anything its normally simpler and easier to understand vs iteration. Tree traversals for example are better expressed recursively vs iterative.
@balaramnayak9948
@balaramnayak9948 5 жыл бұрын
Can we use character[] to hold the character and construct the String at the end?
@theblindprogrammer
@theblindprogrammer 3 жыл бұрын
String first = "First"; char[] chars = new char[first.length()]; for (int i =(first.length()-1); i>=0;i--){ chars[i] = first.charAt(i);; System.out.println("Character: " + chars[i]); }
@ritesh_b
@ritesh_b 5 жыл бұрын
Nice code sir👌
@praveenj3112
@praveenj3112 5 жыл бұрын
Such a easiest problem in interview
@ariel-jc5ug
@ariel-jc5ug 5 жыл бұрын
Please make a Java course
@DeepsWar
@DeepsWar 3 жыл бұрын
Couldnt we also use stack and just print out the reversed string?
@narimo2773
@narimo2773 5 жыл бұрын
Also possible option is: private static String reverseString(String str) { StringBuilder builder = new StringBuilder(); for (int i = str.length(); i > 0; i--) { builder.append(str.substring(i - 1, i)); } return builder.toString(); }
@vignesh4352
@vignesh4352 5 жыл бұрын
Hi Koushik, I am becoming a sincere student of your tutorials. Your logical explanation makes us to understand the concept clearly....I've been searching for DS and Algorithms tutorial for very long time. Even joined online tutorials on Geeks for Geeks, but its only waste of money. I know its very big concept to make ready, but at least give us planning how we can start learning it.
@mahdighribi4151
@mahdighribi4151 2 күн бұрын
Thank you
@SuperYouthful
@SuperYouthful 4 жыл бұрын
Int[] StringArray = String.toArray(numString); String revString = new String(""); For(int I = StringArray.length -1, I--, I >=0) { RevString += ("" + StringArray[i] ); } Return RevString;
@malinmalindic8582
@malinmalindic8582 4 жыл бұрын
Very nice way to find out , is a String a palindrome
@sidharthk.burnwal2044
@sidharthk.burnwal2044 5 жыл бұрын
keep making these kinds of videos brother :-)
@davidparker5530
@davidparker5530 4 жыл бұрын
Your manual solution is incorrect and it stems from a common misunderstanding of how strings are represented in Java. In Java, Strings are encoded using UTF-16, so you should preserve the relative ordering of UTF-16 surrogate pairs, i.e. this method fails to correctly reverse a string of code points outside of the basic multilingual plane, for example, emoji characters. In Java, the StringBuilder class already accounts for this if you use the reverse() method, so you should compare its output to your manual reverse on a string of emoji characters, or perhaps Egyptian hieroglyphs.
@Vithal_Nivargi
@Vithal_Nivargi 3 жыл бұрын
thank u sir
@gs-rc3eq
@gs-rc3eq 5 жыл бұрын
Thank you, Sir!!!!
@dhanushkakumarage1889
@dhanushkakumarage1889 5 жыл бұрын
Thank you very much 😎
@khadijabensaid2901
@khadijabensaid2901 5 жыл бұрын
Thanks a lot
@vinitkatti7998
@vinitkatti7998 5 жыл бұрын
public String reverse(String str){ if(str.length()==0){ return str; }else{ return reverse(str.substring(1)) + str.charAt(0); } }
@MrRadebg
@MrRadebg 3 жыл бұрын
String reverse(String s){ if(s.length() == 0) return ""; else { return reverse(s.substring(0)); } }
@vegahimsa3057
@vegahimsa3057 3 жыл бұрын
StringBuilder.reverse is about 10x faster than String += charAt(). StringBuilder is only a bit faster than StringBuffer on my computer. StringBuilder.reverse: (200 - 512 - 4041) ns StringBuffer.reverse: (230 - 566 - 4442) ns char[] reversing outer to inner: (422 - 1325 - 8646) ns String += charAt() for end to 0: (1277 - 5667 - 29 834) ns
@ngonimugandani4504
@ngonimugandani4504 Жыл бұрын
private static String reverseString(String s){ char [] n = new char[s.length()]; int counter = 0; for (int i = s.length()-1; i > -1 ; i--) { n[counter++]=s.toCharArray()[i]; } return new String(n); }
@TomarSahab
@TomarSahab 3 жыл бұрын
Swap char from 0 to length -1
@manu-g21-mx
@manu-g21-mx 5 жыл бұрын
Now with recursive :D
@katiesun1533
@katiesun1533 5 жыл бұрын
👍👍👍
@kvelez
@kvelez Жыл бұрын
My solution? package javaapplication21; import java.util.Scanner; public class JavaApplication21{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("WORD: "); String word = scan.nextLine(); StringBuilder sb = new StringBuilder(); System.out.println(sb.append(word).reverse()); } }
@danteastudillo6123
@danteastudillo6123 5 жыл бұрын
return "oso" == new StringBuilder("oso").Reverse().toString()? true : false
@aliali-uf9yp
@aliali-uf9yp 4 жыл бұрын
I would use recorgen🤔 much faster
@asashish905
@asashish905 5 жыл бұрын
As usual, I can die to watch your tutorials.. ❤️
@vegahimsa3057
@vegahimsa3057 3 жыл бұрын
Create a char[] .
@chiranjeevisaride
@chiranjeevisaride 5 жыл бұрын
Lol which tech company asks String Reverse in coding interview then interviewer is dumb
@onestepahead4507
@onestepahead4507 5 жыл бұрын
I think as Indian u should also speak hindi,
@nareshbalabathula6062
@nareshbalabathula6062 5 жыл бұрын
Can we use StringBuffer instead of StringBuilder ?
@SushilKumarBhaskar
@SushilKumarBhaskar 5 жыл бұрын
Actually StringBuffer class having synchronized methods, that`s why it is slower than StringBuilder. you may use but think a case where size of string is about 10000+ char or more?
@nareshbalabathula6062
@nareshbalabathula6062 5 жыл бұрын
@@SushilKumarBhaskar got it.. Thanks
@monkpintoo
@monkpintoo 5 жыл бұрын
😔
@Java.Brains
@Java.Brains 5 жыл бұрын
Why the sad face?
@monkpintoo
@monkpintoo 5 жыл бұрын
@@Java.Brains I am waiting for array and stack video.
@rohitmehta3812
@rohitmehta3812 5 жыл бұрын
@@Java.Brains How to append using String???
@explorerfl007
@explorerfl007 5 жыл бұрын
@@rohitmehta3812 use '+' operator. result = result + str.charAt(i);
@alemayehuaklilu7694
@alemayehuaklilu7694 5 жыл бұрын
@@monkpintoo a
БУ, ИСПУГАЛСЯ?? #shorts
00:22
Паша Осадчий
Рет қаралды 2,9 МЛН
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 5 МЛН
Don't underestimate anyone
00:47
奇軒Tricking
Рет қаралды 16 МЛН
Reversing a String | JAVA INTERVIEW QUESTIONS
7:13
CYDEO
Рет қаралды 4,4 М.
Detect Capital - LeetCode Interview Coding Challenge [Java Brains]
25:09
What is JWT? JSON Web Tokens Explained (Java Brains)
14:53
Java Brains
Рет қаралды 1 МЛН
Top 25 Microservice Interview Questions Answered - Java Brains
39:54
БУ, ИСПУГАЛСЯ?? #shorts
00:22
Паша Осадчий
Рет қаралды 2,9 МЛН