Ad
  • Custom User Avatar

    1- I was either careless about garbage filtering or instructions might have said not to worry about weird cases.Either way, I will be more careful it's good practice to handle those always.
    2-3-Should assigning frequently used expressions such as n-1 or n-2 to a variable be better?(int firstPrecedingIndex=n-1;)
    (I usually use Intellij to reformat the code and paste it back,but sometimes I have to use it because it interprets most of the faults unlike browser's editor).

  • Default User Avatar

    Glad to see your code - here are some thoughts:

    Nice clear indentation and consistent use of braces even for if() bodies with a single statement! This habit will save you from burning your mental cpu one day, trust me.

    Good that before doing work, you check for cases where you can quit the job early; e.g. if n is 1,2 or 3

    Ideas for Improvements:

    1. some more garbage filtering before you use input parameters e.g. n might be negative (-> crash) or s may be incomplete signature (so you coudl skip allocate a large array for nothing).
    2. if you set a constant to the value 3 and use that, you started to generalise your code AND get compiler help against accidentally typing 33 somewhere in your algorithm.
    3. Your use of (n-1) confused me, till I realised it was the max index in the result array. It would help to give it a meaningful name (e.g. maxDestIndex ?).

    In order to see your solution, I had to submit my own, so you can take a look at that if you want to see how Arrays.copyOf() can shorten your code a fair bit.

    PS TIP: You can setup an Intellij project to more easily code your solution and then paste it back into the browser. If you watch the clip from 5mins to 8.5mins here: https://www.youtube.com/watch?v=h8n2J1W-ajk&t=180s you can see how to setup a solution with unit tests - well worth doing that as standard practice.