I recently appeared for an interview where i was asked to write an algorithm for a problem. Later on during the interview i was asked to optimize the solution and provide alternate solution.
I found this practice of finding multiple/alternate solutions to a given problem worth learning. Thinking n approaching a problem from different directions gives a better grip over it.
Task: Given a pattern: "A1B3C7DE....", you need to print A '1' times followed by B '3' times and so on....
Diff Approaches: We will start by fetching character by character to be printed some x/y/z number of times. Each character fetched will be printed before fetching next character. We can optimize "printing a character some x number of times".
- Crude way: loop to print character x number of times
private static void crudePrinting(char ch,int times) { System.out.println(); for(int i = 0; i< times; i++){ System.out.print(ch); }
- StringBuilder way: keep appending character in stringbuffer and print stringbuffer. Faster way of printing characters. Though Extra memory occupied by StringBuilder object but it is reused to print different characters like A,B... Time efficiency is a larger gain than small memory overhead loss.
private static void stringBuilderPrinting(char ch,int times,StringBuilder str) { for(int i = 0; i< times; i++){ str.append(ch); } System.out.println(str); }
- String Format way: single line of code. Internally it uses StringBuilder to process format chunks. Memory and time wise better than crude way but not StringBuilder way.
private static void stringFormatPrinting(char ch,int times){ String repString = String.format(String.format("%%0%dd", times), 0).replace('0',ch); System.out.println(repString); }
Bench marking of alternatives
No comments:
Post a Comment