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.
@lxerlx28905 жыл бұрын
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.
@etric895 жыл бұрын
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).
@soumyajitdey57205 жыл бұрын
Exactly what I had in mind
@antmakov5 жыл бұрын
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
@etric895 жыл бұрын
@@antmakov java.lang.String is an immutable class
@antmakov5 жыл бұрын
@@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.
@AjinkyaRane5 жыл бұрын
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..👍
@PramriDesigns5 жыл бұрын
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 :)
@dhanushkakumarage18895 жыл бұрын
Hes also kidding with angular series.. quantum physics and relativity 😁😁😁
@phanindraitika56095 жыл бұрын
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 !!
@tusharkshirsagar6115 жыл бұрын
You are not just teacher, but an incredible teacher... Thanks Kaushik...!!!
@edgieacepojadas67004 жыл бұрын
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_r5 жыл бұрын
I know one person with 8+ years of experience, when asked this question, left the interview hall saying it's too basic.
@Java.Brains5 жыл бұрын
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_r5 жыл бұрын
@@Java.Brains wonderful. I never had such thoughts :)
@amirthasaha5 жыл бұрын
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.
@pushpesh824 жыл бұрын
I would love to see this series going for solving 50 such questions...
@sebastianmendoza20055 жыл бұрын
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.
@vivekbhadauria21303 жыл бұрын
Infact this recursion based approach helps in dynamic programming problems related to palindromic strings
@sleepy_Dragon5 жыл бұрын
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.
@nikhilraut68205 жыл бұрын
For life -abdul kalam ji....for java- Kaushik ji...salute both of u.... thanks make me better 😊🙏
@arunabhhejib11365 жыл бұрын
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!
@howtoed31165 жыл бұрын
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.
@wiper123ful5 жыл бұрын
Hi Koushik, Can you do a video on hash map implementation??
@asankaishara5 ай бұрын
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
@uppunu15 жыл бұрын
It would be great if you could also mention the BigO for the solution. Thanks so much
@Finn-jp6pn5 жыл бұрын
You're an amazing teacher .❤️ Please continue this series with frequent uploads.
@samwilgost11435 жыл бұрын
Please Please more of these interview questions, I love the way you explain them!!!
@hemsagarpatel89925 жыл бұрын
sir please make videos for various ds questions
@VickieEB5 жыл бұрын
I just get excited when I see a notification from Java Brain. Thanks for this explanation. Clear
@ajay-pg8ok5 жыл бұрын
Bro ur explanation makes everything easy to understand.
@parvezmd64555 жыл бұрын
Sir your way of explaining using pictorial diagram is super .
@yuvaraj97405 жыл бұрын
sir can you upload more questions asked on interviews in java please! thanks!
@sisisisi65 жыл бұрын
These interview questions are soo helpful. So helpful that I landed an offer from Amazon! Thank you!! So much.
@ascar664 жыл бұрын
How is it going in Amazon?
@amirthasaha5 жыл бұрын
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!
@mukundpatel17685 жыл бұрын
This is really nice sir.
@saddamahmad23105 жыл бұрын
thank you very much sir for this video
@rashmir1934 жыл бұрын
Hi Koushik Cold you please add a tutorial to write a program that reverses a sentence. Ex: Hello World to World Hello
@GenjaOrigins3 жыл бұрын
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?
@RANJANJHA955 жыл бұрын
Expected to discuss most efficient approach
@NANDANKAUSHIK3 жыл бұрын
How are you able to write like pen on paper , on whiteboard which seems to be running on your system ?
@abarag85 жыл бұрын
Hi Kaushik sir. Nice video. Keep up the good work. I am inspired from you and learned to love coding because of you :)
@HungNguyen-nd6tz3 жыл бұрын
Thanks, it's perfect explanation
@amitdeshpande25485 жыл бұрын
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); } }
@MetinCloup5 жыл бұрын
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); } } }
@pradiptalekar75455 жыл бұрын
Hi Kaushik, really appreciate your work. Thank you!! Expecting more in this series - coding challenges
@Paul-ry3jq5 жыл бұрын
These are really awesome, thanks for the good videos.
@Tridib_Tinkel5 жыл бұрын
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);
@theblindprogrammer3 жыл бұрын
Good vid, keep up the good work.
@aoshi25525 жыл бұрын
Excellent video. Here’s my like 👍🏼
@maheshgowthamt5 жыл бұрын
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..
@toufiqurrahman70255 жыл бұрын
please continue this series
@explorerfl0075 жыл бұрын
I think we can have solution using recursive method call. What are disadvantages of recursive calls?
@Java.Brains5 жыл бұрын
Good point. Please refer to my pinned comment.
@darylphuah5 жыл бұрын
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.
@balaramnayak99485 жыл бұрын
Can we use character[] to hold the character and construct the String at the end?
@theblindprogrammer3 жыл бұрын
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_b5 жыл бұрын
Nice code sir👌
@praveenj31125 жыл бұрын
Such a easiest problem in interview
@ariel-jc5ug5 жыл бұрын
Please make a Java course
@DeepsWar3 жыл бұрын
Couldnt we also use stack and just print out the reversed string?
@narimo27735 жыл бұрын
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(); }
@vignesh43525 жыл бұрын
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.
@mahdighribi41512 күн бұрын
Thank you
@SuperYouthful4 жыл бұрын
Int[] StringArray = String.toArray(numString); String revString = new String(""); For(int I = StringArray.length -1, I--, I >=0) { RevString += ("" + StringArray[i] ); } Return RevString;
@malinmalindic85824 жыл бұрын
Very nice way to find out , is a String a palindrome
@sidharthk.burnwal20445 жыл бұрын
keep making these kinds of videos brother :-)
@davidparker55304 жыл бұрын
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.
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 Жыл бұрын
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); }
@TomarSahab3 жыл бұрын
Swap char from 0 to length -1
@manu-g21-mx5 жыл бұрын
Now with recursive :D
@katiesun15335 жыл бұрын
👍👍👍
@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()); } }
@danteastudillo61235 жыл бұрын
return "oso" == new StringBuilder("oso").Reverse().toString()? true : false
@aliali-uf9yp4 жыл бұрын
I would use recorgen🤔 much faster
@asashish9055 жыл бұрын
As usual, I can die to watch your tutorials.. ❤️
@vegahimsa30573 жыл бұрын
Create a char[] .
@chiranjeevisaride5 жыл бұрын
Lol which tech company asks String Reverse in coding interview then interviewer is dumb
@onestepahead45075 жыл бұрын
I think as Indian u should also speak hindi,
@nareshbalabathula60625 жыл бұрын
Can we use StringBuffer instead of StringBuilder ?
@SushilKumarBhaskar5 жыл бұрын
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?
@nareshbalabathula60625 жыл бұрын
@@SushilKumarBhaskar got it.. Thanks
@monkpintoo5 жыл бұрын
😔
@Java.Brains5 жыл бұрын
Why the sad face?
@monkpintoo5 жыл бұрын
@@Java.Brains I am waiting for array and stack video.
@rohitmehta38125 жыл бұрын
@@Java.Brains How to append using String???
@explorerfl0075 жыл бұрын
@@rohitmehta3812 use '+' operator. result = result + str.charAt(i);